Disclaimer: I'm not actually very familiar with C#. I'll also refrain from the style review and let someone more familiar with common practices take a crack.

You can prepend 0 and append line.Length to your array, simplifying the logic. There's probably a better way, but I got it working with a List:

List<int> list = new List<int>();
list.Add(0);
list.AddRange(markers);
list.Add(line.Length);

for (int i = 0; i < list.Count - 1; i++)
{
    string value = line.Substring(list[i], list[i + 1] - list[i]);
    Console.WriteLine(value);
}


There can be three ways to enhance this code, it mostly depends what you aim to create.

Very flexible HTML and CSS,
Flexible CSS, less flexible HTML,
Minimal HTML, CSS and class names (as a result minimum flexibility).

Minor change summary

CSS cleanup,
CSS animation  -  to make it more readable,
Class names - to make the logic evident,
HTML- to make it modular and reusable,

CSS cleanup

.element, .elem-1, .elem-2, .bounce, .bounce-2, .bounce-3 {
    position: absolute;
    width: 20px;
    height: 20px;
    top: 50%;
    left: 50%;
    opacity: .6;
    background-color: #ffffff;
    border-radius: 50%;
    animation: big 2s infinite ease-in-out;
}
.elem-1, .bounce-2 {
    position: absolute; /*Already has position attribute*/
    width: 20px; /*Already has width attribute*/
    height: 20px; /*Already has height attribute*/
    top: 6%;
    left: 80%;
    background-color: #fff; /*Already has background-color attribute*/
}
.elem-2, .bounce-3 {
    position: absolute; /*Already has position attribute*/
    width: 20px; /*Already has width attribute*/
    height: 20px; /*Already has height attribute*/
    top: 6%;
    left: 20%;
    background-color: #fff; /*Already has background-color attribute*/
}
.elem-1{
    animation-delay: -0.5s;
}
.elem-2{
    animation-delay: -.75s;
}
.bounce{
    animation-delay: -1s;
}
.bounce-2{
    animation-delay: -1.5s;
}
.bounce-3{
    animation-delay: -1.75s;
}

@keyframes big {
    0%, 100%{transform: scale(0.0)}
    50% {transform: scale(1.75)}
}

CSS animation

Instead of

@keyframes big {
    0%, 100%{transform: scale(0.0)}
    50% {transform: scale(1.75)}
}

can be used

@keyframes big {
    0% { transform: scale(0);}
    100% {transform: scale(1);}
}

There is animation-direction which can have alternate value, this reverses the animation and gets the back effect this means there is no need for 50% key-frame, as one way animation can be altered beck.

Also when you use transform: scale() with greater than 1 value can cause element blurring in some browsers. to avoid this issue I multiplicated  20px height and width of the element with 1.75 and put 35px instead in order to use scale(1) instead of scale(1.75).

Classnames - to make the logic evident

As element, elem-1, elem-2, bounce, bounce-1, bounce-2 class names can be misleading. The meaning of these 6 classes is the animation states of each circle. in this case they can be bounceIn and bounceOut states and these states can be given to any element (in this case to any circle).
Also each circle has its own position and that's why I have created  pos-0,pos-1,pos-2 classes.

Centering

For centering elements there are many methods, the one that you used is a classic way and can be fully legitimate for this case (it will work even on IE6).

.cont {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 50%;
    left: 50%;
    margin: -50px 0 0 -50px;
}

HTML

Instead of

Can be used

Or

Or

Which are much more readable and maintainable.

Solution 1: Very flexible HTML and CSS

You can add separate bouncing circles with different positions and different delays, or reuse same classes. or you can add 3-rd effect too (e.g. bounceIn, bounceOut, bounceLeft... etc.)

body {background: #0BCCCA;}

.cont {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 50%;
    left: 50%;
    margin: -50px 0 0 -50px;
}

.circle {position: absolute;}

.pos-0 {
    top: 50%;
    left: 50%;
}
.pos-1 {
    top: 6%;
    left: 80%;
}
.pos-2 {
    top: 6%;
    left: 20%;
}

.bounceIn, .bounceOut {
    position: absolute;
    width: 35px;
    height: 35px;
    background-color: rgba(255, 255, 255, .6);
    border-radius: 50%;
    transform-origin: center center;
    animation: ease-in-out 1s infinite big alternate;
}

.bounceIn {animation-delay: 1000ms;}

.delay-0 .bounceIn {animation-delay: .75s;}
.delay-0 .bounceOut {animation-delay: -1.75s;}

.delay-1 .bounceIn {animation-delay: -0.5s;}
.delay-1 .bounceOut {animation-delay: -1.5s;}

.delay-2 .bounceIn {animation-delay: 0s;}
.delay-2 .bounceOut {animation-delay: -1s;}

@keyframes big {
    0% {transform: scale(0);}
    100% {transform: scale(1);}
}

Solution 2: Flexible CSS, less flexible HTML

This solution uses only :before and :after instead of bounceIn and bounceOut classes to minimize HTML.

body {background: #0BCCCA;}

.cont {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 50%;
    left: 50%;
    margin: -50px 0 0 -50px;
}

.circle {position: absolute;}

.pos-0 {
    top: 50%;
    left: 50%;
}
.pos-1 {
    top: 6%;
    left: 80%;
}
.pos-2 {
    top: 6%;
    left: 20%;
}

.circle:after, .circle:before {
    content: '';
    position: absolute;
    width: 35px;
    height: 35px;
    background-color: rgba(255, 255, 255, .6);
    border-radius: 50%;
    transform-origin: center center;
    animation: ease-in-out 1s infinite big alternate;
}

.circle:after {animation-delay: 1000ms;}

.delay-0.circle:after {animation-delay: .75s;}
.delay-0.circle:before {animation-delay: -1.75s;}

.delay-1.circle:after {animation-delay: -0.5s;}
.delay-1.circle:before {animation-delay: -1.5s;}

.delay-2.circle:after {animation-delay: 0s;}
.delay-2.circle:before {animation-delay: -1s;}

@keyframes big {
    0% {transform: scale(0);}
    100% {transform: scale(1);}
}

Solution 3: Minimal HTML, CSS and class names

In addition to Solution 2 this one adds all necessary styles to one class.

body {
  background: #0BCCCA;
}

.cont {
  position: absolute;
  width: 100px;
  height: 100px;
  top: 50%;
  left: 50%;
  margin: -50px 0 0 -50px;
}

.circle-0,
.circle-1,
.circle-2{
  position: absolute;
}

.circle-0{
  top: 50%;
  left: 50%;
}

.circle-1{
  top: 6%;
  left: 80%;
}

.circle-2{
  top: 6%;
  left: 20%;
}

.circle-0:after,
.circle-0:before,
.circle-1:after,
.circle-1:before,
.circle-2:after,
.circle-2:before{
  content:'';
  position: absolute;
  width: 35px;
  height: 35px;
  background-color: rgba(255,255,255, .6);
  border-radius: 50%;
  transform-origin: center center;
  animation: ease-in-out 1s infinite big alternate;
}

.circle-0:after,
.circle-1:after,
.circle-2:after{animation-delay: 1000ms;}

.circle-0:after{animation-delay: .75s;}
.circle-0:before{ animation-delay: -1.75s;}

.circle-1:after{animation-delay: -0.5s;}
.circle-1:before{animation-delay: -1.5s;}

.circle-2:after{animation-delay: 0s;}
.circle-2:before{animation-delay: -1s;}

@keyframes big {
  0% { transform: scale(0); }
  100% { transform: scale(1);}
}


Deserialize with LINQ query code in PageModel or PageView

I find you should keep the library code in the model and only parts that are relevant to views inside them.

In your case there is actually a third option. Let OnGet only handle the file. Remove OrderBy as this is a view's matter how it's displayed. Additionally initialize itemListReportages to an empty list if a file was empty. It'll save you the trouble of null checks later.

public void OnGet()
{
    PageSettings = (PagesSettings)HttpContext.Items["pagesettings"];

    if (PageSettings == null)
    {
        return;
    }

    var fileContent = _fileService.GetFileContentCached(PageSettings.DataFile);

    itemListReportages =
        fileContent?.Length > 0
            ? JsonConvert.DeserializeObject<List<Reportage>>(fileContent).Where(l => l.Published).ToList()
            : new List<Reportage>();
}

We don't see whether you initialize itemListReportages but this view could crash because you don't use the null propagation operator here: ?.Count

@for (var i = 0; i < Model.itemListReportages.Count; i++)
{

            @Model.itemListReportages[i].Text

}

With a non-null list you can turn this into a foreach loop and put OrderBy here. It'll make the code shorter too as you now have an item variable and no longer have to acces them by index like Model.itemListReportages[i]:

@foreach (var item in Model.itemListReportages.OrderBy(x => x.Name))
{

            @item.Text

}


When describing lists, always consider using DCGs. In this case, try for example:

sum(Xs0, Ys0, Ls) :-
    reverse(Xs0, Xs),
    reverse(Ys0, Ys),
    phrase(sum(Xs, Ys, 0), Ls0),
    reverse(Ls0, Ls).

sum([], [], Carry) -->
    (   { Carry > 0 } -> [Carry]
    ;   []
    ).
sum([X|Xs], [Y|Ys], Carry0) -->
    { N0 is X + Y + Carry0,
      (  N0 > 9 ->  N is N0 - 10, Carry = 1
      ;  N = N0, Carry = 0
      ) },
    [N],
    sum(Xs, Ys, Carry).

Exampe queries and their results:

?- sum([1,9,9], [0,9,9], Ls).
Ls = [2, 9, 8].

?- sum([8,1,9], [1,8,2], Ls).
Ls = [1, 0, 0, 1].


Using os.scandir to get all txt files in subfolders

There are (at least) two ways to easily achieve this. The first one is what @Ludisposed suggested in the comments, glob. It can also recurse down into subdirectories with ** (in Python 3):

import glob

def get_txt_files(base_dir):
    return glob.iglob(f"{base_dir}/**/*.txt", recursive=True)

Or, if you are using Windows, which uses different delimiters for paths:

def get_txt_files(base_dir):
    return glob.iglob(rf"{base_dir}\**\*.txt", recursive=True)

The other one is basically what @Mast suggested, also in the comments, make this a fully recursive function:

def get_txt_files(base_dir):
    for entry in os.scandir(base_dir):
        if entry.is_file() and entry.name.endswith(".txt"):
            yield entry.name
        elif entry.is_dir():
            yield from get_txt_files(entry.path)
        else:
            print(f"Neither a file, nor a dir: {entry.path}")

Both functions return iterators. You can print all names with a simple for loop:

for name in get_txt_files("foo"):
    print(name)

If your directory X also contains txt files, they will be yielded from these functions. You can avoid this with glob by making the depth level explicit:

def get_txt_files(base_dir):
    return glob.iglob(f"{base_dir}/*/*.txt")

A third, very similar, way is to use pathlib.Path (Python 3 only), which also has a glob method (that directly returns an iterator). This way you can be sure that this works both on UNIX and Windows:

from pathlib import Path

def get_txt_files(base_dir):
    return Path(base_dir).glob("*/*.txt")


Handling errors in potentially incomplete responses

Some suggestions:

Don't use exceptions for flow control unless you have to for TOCTOU or other reasons. "Tell, don't ask" is a useful guideline when requesting something from a piece of state the current code has no control over, but it's not a law. In your code there is no chance of res.country.names changing while running res.country.names.get('en', "-1"), and that is much clearer than using exception handling to set a default.
You almost always want to catch specific exceptions.
When retrieving values from a dict you can use my_dict.get("key", default) to get a default value if the key does not exist.
Use f-strings rather than + to create formatted strings.


The warning

The warning you are seeing is because the switch feature that gives you the given and when keywords is experimental. That means it's there in this specific Perl version, and possible future ones, but that is not clear. Sometimes experimental features make it into the core part of the language itself, but sometimes they get removed. With switch it's not clear yet which one it's going to be.

If you are use you are only going to use your specific Perl version, you can simply turn off the warnings.

use feature 'switch';
no warnings 'experimental';

Now you don't see any warnings any more. But if your code will be run on an older version that doesn't have the feature yet, or on a later version in the future where it has might have been changed or removed, your code will break.

I would not use experimental features in long-living production code. Instead, I would use either of the following two approaches, based on how complex your program is.

Using a bunch of ifs and elsifs

The most simple approach is to just replace the given/when with a couple of if statements. Your do { ... } while ( $ch != 5 ) approach is good, so we keep it. But because it's not really a loop, but rather a block with a postfix condition, we cannot use next to jump out, so we need to use an elsif construct.

my $ch;
do {
    $ch = <>;
    chomp $ch;

    if ( $ch == 1 ) {
        # new item ...
    }
    elsif ( $ch == 2 ) {
        # search ...
    }
    elsif ( $ch == 3 ) {
        # display ...
        next;
    }
    elsif ( $ch == 4 ) {
        # max price ...
    }
} while ( $ch != 5 );

We don't even need to use an elsif because we can just use next to skip to the next iteration.

Using a dispatch table

This is way more advanced, and a bit overkill for your situation, but it's very nicely extensible. A dispatch table is essentially a hash with code references that you call depending on your input.

my %dispatch = (
    1 => sub {
       # new item ...
    },
    2 => sub {
       # search ...
    },
    3 => sub {
       # display ...
    },
    4 => sub {
       # max price ...
    },
);

my $ch;
do {
    # read input ...

    if ( exists $dispatch{$ch} ) {
        $dispatch{$ch}->();
    }
} while ( $ch != 5 );

But as I said, this is an advanced technique and possibly a bit overkill for this program.

Telling the user they gave wrong input

If you enter another number than 1 to 5, your program does not complain. It just reiterates the same output. If you enter a letter, it will issue a warning.

Input validation up front

You could check the input first, issue a warning and then redo the loop.

do {
    # read input ...

    if ( $ch !~ m/^[1-5]$/ ) {
        print "Invalid input.\n";
    }
    elsif ( $ch == 1 ) {

    # ...
} while ( $ch != 5 );

Don't use numerical operators

Or you could replace all your == and != with eq and ne, which work on strings as well as numbers, and move the warning to the end of the loop.

my $ch;
do {
    $ch = <>;
    chomp $ch;

    if ( $ch eq 1 ) {
        # new item ...
    }
    elsif ( $ch eq 2 ) {
        # search ...
    }
    elsif ( $ch eq 3 ) {
        # display ...
        next;
    }
    elsif ( $ch eq 4 ) {
        # max price ...
    }
    else {
         print "Invalid input.\n";
    }
} while ( $ch ne 5 );

Both of those approaches work.

Self-explaining variable names

Your variable names $b, $c, $p and $ch do not speak for themselves. The program is very hard to read because of that. Instead of on-letter names, name them for what they represent.

$ch could be $selection, $c could be $category, $b the $brand and $p could be $price.

Smaller scope

You are already using strict and lexical variables with my, which is very good. But you should not declare your vars at the top like in a C program. In Perl you should always use the smallest possible scope.

For example, your $c is declared outside the loop (I'll continue to say loop, although it's not a loop structure), but you use it in multiple places where you assign new values in different branches of your code.

Instead, you should declare a new, lexical version in each of those branches, which are individual from each other. That helps to protect from bugs. Right now you could easily introduce a bug, if you for example accidentally put == instead of =. Because the variable is already declared in a higher scope, Perl won't tell you that that's possibly wrong. But if you instead declare it freshly, it will complain.

print "Enter the category you want to add";
my $category = <STDIN>;
chomp $category; # no need for parenthesis here
if ( exists( $grocery{$category} ) ) {
    print "Enter brand\n";
    my $brand = <STDIN>;
    chomp $brand;
    print "Enter price\n";
    my $price = <STDIN>;
    chomp $price ;
    $grocery{$category} = { $brand => $price };

    print "\n";
}
# ...

You should do that throughout the code.

Autovivification

When you create a new entry, you check if the category exists, and then branch the code. You don't need to do that. Right now you have duplicated all the code for getting the brand and price from the user, but you only need to write that once.

elsif ( $selection == 1 ) {
    print "Enter the category you want to add\n"; # you forgot a \n here
    my $category = <>; # <> is the same as <STDIN>

    print "Enter brand\n";
    my $brand = <STDIN>;

    print "Enter price\n";
    my $price = <STDIN>;
    chomp( $category, $brand, $price );
    $grocery{$category}->{$brand} = $price;
}

The above code sums both cases up into one. The assignment $grocery{$category}->{$brand} = $price works because Perl will automatically create a hash reference inside $grocery{$category} if it sees the ->{$brand} part. That's called autovivification and is explained in the perlglossary.

I also moved the chomp into one line so make the code more concise, as chomp can take a list of variables. In that case you need the parenthesis so it knows it's a list.

Use say instead of print "...\n"

You can enable the say builtin that works like print, but includes a newline at the end of each invocation. It will make your code more concise. To enable it, you need to

use feature 'say';

at the top of your program. You can then use it throughout the code.

if ( $selection !~ m/^[1-5]$/ ) {
    say "Invalid input.";
}

Use a HERE doc for blocks of output

HERE docs are useful for multi-line output. You can use one for the main menu that lists your options.

do {
    print <<'EOTEXT';
________________MENU_________________
1.ADD ITEM
2.SEARCH
3.DISPLAY
4.FIND THE MAX PRICE
5.EXIT
enter your choice
EOTEXT

    $selection = <>;

The delimiter EOTEXT can be chosen freely. It should be all-caps and I like to start it with EO, which means end of. The semicolon goes at the end of that same line. The single quotes '' mean that there is no interpolation. If you want to include variables in the text, use "EOTEXT" instead. The delimiter has to be placed in the line after the text, and needs to be preceded by an empty line. As of Perl 5.24, HERE docs cannot be indented. Perl 5.26 will include a new feature that allows this.


Finding the comic ID of the last XKCD comic published

I'm not sure it's much shorter than what you wrote, but finding stuff in any tree-like data structure is what I created the tupelo.forest library for.

Here is a solution for your problem:

(dotest
  (when false ; manually enable to grab a new copy of the webpage
    (spit "xkcd-sample.html"
      (slurp "https://xkcd.com")))
  (with-forest (new-forest)
    (let [doc         (it-> (xkcd)
                        (drop-if #(= :dtd (:type %)) it)
                        (only it))
          root-hid    (add-tree-enlive doc)
          >>          (remove-whitespace-leaves)
          ;>>          (spyx-pretty (hid->bush root-hid))
          hid-keep-fn (fn [hid]
                        (let [node       (hid->node hid)
                              value      (when (contains? node :value) (grab :value node))
                              perm-link? (when (string? value)
                                           (re-find #"Permanent link to this comic" value))]
                          perm-link?))
          found-hids  (find-hids-with root-hid [:** :*] hid-keep-fn)
          link-node   (hid->node (only found-hids)) ; assume there is only 1 link node
          value-str   (grab :value link-node) ; "\nPermanent link to this comic: https://xkcd.com/1988/"
          result      (re-find #"http.*$" value-str)]
     ;(spyx-pretty link-node)  ;=> {:tupelo.forest/khids [],
                                  ; :tag :tupelo.forest/raw,
                                  ; :value "\nPermanent link to this comic: https://xkcd.com/1988/"}
     ;(spyx result) ; => "https://xkcd.com/1988/"
    )))

Documentation is ongoing, but you can see a lightning talk from the Clojure Conj 2017.


Transaction handling for multiple SQL statements

Naming

Constants in .NET should be named using PascalCase. See c-sharp-naming-convention-for-constants
Your const string selectSatement = @"INSERT INTO Payment..." should be better named InsertStatement to also reflect that it is an INSERT and not a SELECT.

var first = 0;
var payInfo = list[first];

As the value of var first won't be changed, you should change it to a const with a meaningful name.

Refactoring
Before using the first item in the list, a check to see if the list is null or empty should take place.

const int NoRowsAffected = 0;
if (list == null || !list.Any()) { return NoRowsAffected; }

int result= 0;

won't be used, except for assigning the affetced rows of the update command. we should just remove it.

if (result == +1)
    affectedRecords = 1;

Using curly brackets {} should be a have to everytime, at least if written on separate lines.

sqlCommand.CommandText = updateStatement;

should be placed outside of the for loop. Ther is no need to assign the const to the CommandText property for each iteration.

Result

public int InsertPaymentDetails(List<PaymentInfo> paymentInfos, int totalRecords, decimal totalAmount)
{
    const string InsertStatement = @"
        INSERT INTO Payment (payment_type, reference, payment_date, total_records, total_amount)
        VALUES(@type, @reference, @date, @totalRecords, @totalAmount )
        ";

    const string UpdateStatement = @"
        UPDATE SalaryTrans
        SET payment_id = (SELECT TOP 1 id FROM Payment ORDER BY Payment.id DESC)
        WHERE SalaryTrans.employee_id = @employeeID
        AND SalaryTrans.reference = @reference
        ";

    const int NoRowsAffected = 0;
    const int FirstListIndex = 0;

    if (paymentInfos == null || !paymentInfos.Any()) { return NoRowsAffected; }

    var payInfo = paymentInfos[FirstListIndex];

    //To get the affected rows following variables are declared

    int affectedRecords = NoRowsAffected;

    using (SqlConnection sqlConnection = new SqlConnection(db.ConnectionString))
    {
        sqlConnection.Open();
        using (SqlTransaction sqlTrans = sqlConnection.BeginTransaction())
        using (SqlCommand sqlCommand = new SqlCommand(InsertStatement, sqlConnection, sqlTrans))
        {
            sqlCommand.Parameters.Add("@type", SqlDbType.VarChar).Value = payInfo.PaymentType;
            sqlCommand.Parameters.Add("@date", SqlDbType.Date).Value = payInfo.PaymentDate;
            sqlCommand.Parameters.Add("@reference", SqlDbType.VarChar).Value = payInfo.Reference;
            sqlCommand.Parameters.Add("@totalRecords", SqlDbType.Int).Value = totalRecords;
            sqlCommand.Parameters.Add("@totalAmount", SqlDbType.Decimal).Value = totalAmount;

            sqlCommand.ExecuteNonQuery();

            SqlParameter paramEmployeeID = new SqlParameter("@employeeID", SqlDbType.Int);
            sqlCommand.Parameters.Add(paramEmployeeID);
            sqlCommand.CommandText = UpdateStatement;

            foreach (PaymentInfo paymentInfo in paymentInfos)
            {
                paramEmployeeID.Value = paymentInfo.EmployeeID;
                //If at least one recored was inserted then the recordsAffected should be +1
                if (sqlCommand.ExecuteNonQuery() == 1) { affectedRecords = 1; }
            }
            sqlTrans.Commit();
        }
    }
    return affectedRecords;
}


Adding, removing, and changing user names and passwords in .htpasswd with PHP

Here is my version based on two personal preferences: I hate scroll bars and I hate repititions. Hence I prefer everything typed once and also I like my code being fully visible in the default code area on Stack Overflow.

for this reason I removed that double spacing which just hurts my eyes
also I removed the try catch which is a cargo cult code that makes no sense. I was never able to understand what's the point in writing a try catch that's the only job is to echo the error message when without a try catch PHP will do exactly the same - echo the error message
also I removed the code repetitions such as mentioning the filename in a dozen places
also I changed the algorithm, to make it add a user line only once
I also removed that uncertainty when we can't make our mind whether we are working with an array or with a text
I also changed the function name as it doesn't only add a user
and some other improvements such as following the HTTP guidelines and the ability to choose the hashing algorithm without using inline comments

here it goes
<?php
$filename = ".htpasswd";
if (isset($_POST['user'])) {
    manage_htpasswd($_POST['user'], $_POST['pass'], $filename);
    header("Location: ".$_SERVER['REQUEST_URI']);
    exit;
}
function manage_htpasswd($user, $pass, $filename, $algo = 'crypt_apr1_md5')
{
    $lines = file($filename);
    foreach ($lines as $i => $line) {
        $existing_user = explode(':', $line);
        if ($existing_user[0] === $user) {
            unset($lines[$i]);
            break;
        }
    }
    if ($pass) {
        $lines[] = "$user:" . $algo($pass) . PHP_EOL;
    }
    file_put_contents($filename, $lines);
}
?>
<form method="post">
    User: <input type="text" name="user">

    Pass:<input type="text" name="pass">

    <input type="submit">
</form>

<?= $filename ?>:

<?= file_get_contents($filename) ?>


Test whether a string representing an object n-levels deep is available

This maybe a matter of taste, but I'm not a big fan of slicing arrays.
I find this alternative implementation using a for loop and without array slicing a bit simpler:

function isAvailable(s,context) {
    var aSplit, ob, i;

    if (s === undefined || s === null) {
        return false;
    }

    aSplit = s.split('.');
    ob = context;
    for (i = 0; ob !== undefined && i < aSplit.length; ++i) {
        ob = ob[aSplit[i]];
    }
    return typeof ob === "object";
}


find_value_from_key
The core method find_value_from_key looks functional for the limited specification you have given. I am not a great fan of the specification though, I think the function should try to be a bit smarter about identifying values in the input strings. The two items I find most concerning are:

It will successfully find key1 =  and value1 in "ThisIsSubkey1 = value1"
it does not successfully find value1 in "key1 =  value1" (note two spaces after =)

These are both items related to the context-naive usage of the find(...) method.
Still, as far as the specification goes, your code looks like it does the job.
There is one improvement that can/should be done to make it more readable. You reuse the value pos_start+key.length() four times. Performance-wise this may be sorted out by a compiler, but it does not help the readability at all...
I would prefer the function written as:
bool find_value_from_key(const string& source, const string& key, string& value, const string& endmarkers) {
   bool ret = false;
   size_t key_start = source.find(key);
   size_t val_start = key_start + key.length();
   if(key_start != string::npos) {
      size_t val_end = source.find_first_of(endmarkers, val_start);
      if(val_end == string::npos && source.length() > val_start)
         val_end = source.length();

      if(val_end != string::npos) {
         value = source.substr(val_start, val_end - val_start);
         ret = true;
      }
   }
   return ret;
}

Note how there is no pos_start variable... it was being reused for different purposes in different places. It was confusing. Renaming the variables to self-document makes the code easier to understand. The compiler will sort out any optimizations in the same ways as before.
There is one additional item in that method... why the CamelCase parameter EndOfValueMarker? I have renamed it endmarkers.
main
The main method has a couple of issues I think must just be an artifact from testing.
You set up the loop to check each input string, but, you do not use i (the loop variable) as an index to the actual data you check... you have the code:

   for(int i = 0; i < elements; ++i) {
     cout << "processing: " << test_strings[i] << endl;
     string value;
     if(find_value_from_key(test_strings[0], keys[0], value, ", \t\n"))
        cout << value << endl;
   }

This code prints each test_strings[i] just fine, but the input to the function is always index 0... so you only actually test the first input.
The second item is that you only test for key1. The other keys are not tested.
The loop code should look like:
for(int i = 0; i < elements; ++i) {
    cout << "processing: " << test_strings[i] << endl;
    string value;
    for (int k = 0; k < 3; k++) {
        if(find_value_from_key(test_strings[i], keys[k], value, ", \t\n"))
            cout << keys[k] << " -> " << value << endl;
    }
}

I know, it has the magic number 3 for the k loop, but at least it checks each key....
Ideone
I have put my recommendations in to this ideone... take it for a spin


I want to take away WebService call from UIViewController

I would recommend looking into MVVM architecture. You can see a simple example in this repo.
One problem with it is that its author declares and assigned view models directly in a ViewController which can be a bit problematic when writing tests. A better approach would be to inject view model so it can be easily replaced with mock. To improve that approach you can take a look at coordinators patterns, a bit more advanced example can be found here
In most cases the WebService should go in the ViewModel in the MVVM pattern. Services can be injected to ViewModels, which are responsible for managing data provided by these services. Then when they perform all logical transformations (filtering, ordering, multiplying etc.) they provide this information to a view (ViewController in our case) which just consumes it. It allows us to easily write mocks and tests. There are of course more approaches like state machine, but ViewModel as content provider and meeting point for services is most common and most universal one in my opinion.


Extension Method for Creating Types from Regular Expression Match Groups

If you are doing reflection magics the caller of your method may be as well. If that person already has a Type it can be a bit of a pain in the butt to call your generic method. Since you are already working against a Type offering an overload for it should not be too much work. Perhaps extracting the following code into its own method may help:

PropertyInfo[] properties = type.GetProperties();
IEnumerable<string> groupNames = regEx.GetGroupNames().Skip(1); //First Group is always 0
if (matchCollection.Count >= 1) {
    SetPropertyValuesFromGroupMatches<T>(groupNames, regEx, obj, matchCollection[0].Groups, properties);
}


Removing numbering gaps in a series of filenames

This is actually a very tricky function to write well, especially for a beginner.

Bugs

Be careful whenever you do string interpolation: escaping is often needed.  Here, you have plopped prefix directly into your regex, without considering whether there might be characters within the prefix that might have special significance in the regex language.  Here, you need to call re.escape().

if fileList is empty, you'll get stuck in an infinite loop, since Completed will never be set to True.

You probably want to require all of the filenames to start with the prefix.  Instead, you do re.search(), which performs an search that is not anchored at the beginning of the string.  You should use either re.match() or include a ^ at the beginning of your regex.

You zero-pad the numbers so that they are all the same width, based on the width of the number in the smallest-numbered file.  If the numbers are all the same width, then that's fine.  However, if they might not all be the same width, then it makes more sense to go with the width of the largest-numbered file.

Also, it's not obvious what the right behaviour is if spam1.txt and spam001.txt both exist.  Maybe that isn't a concern for you, but I thought I should mention it.

Algorithm

Your strategy works well enough for small numbers.  I wouldn't recommend it for a files named like photo_2016022235959.jpg — it could take a while to count that high!  Sorting might be a better strategy than counting up from 0.

The nested while True: for filename in fileList: loops are cumbersome.  You can often avoid loops in Python by using list comprehensions and generator expressions.  An additional benefit of using comprehensions and generator expressions is that you can "say what you mean" instead of specifying what to do step-by-step.

There is some repetition of the string-analysis code in the two loops.  I recommend performing the regex match once and storing the match results instead of the filenames.

Implementation details

I don't see any reason for converting folder to an absolute path.

os.path.isfile(…) involves a system call, and is much more expensive than a regex test.  Therefore, you should reorder the tests to do the quick test first:

if prefixRegex.search(item) and os.path.isfile(os.path.join(folder, item)):

However, since Python 3.5, you can use os.scandir() instead of os.listdir() if you also want information about the entries such whether it is a regular file (thus rendering the previous point moot).  os.scandir() produces os.DirEntry objects as results, such that you can retrieve the entry.name of the file and test entry.is_file() efficiently.

Instead of zero-padding numbers by concatenating strings yourself…

# New number including prefixed zero's
subNumber = '0' * (length - len(str((Number)))) + str(Number)
# New filename with updated number
newFileName = prefixRegex.sub(r'%s%s\4' % (prefix, subNumber), filename)

… use str.format():

'{}{:0{width}}.{}'.format(prefix, n, extension, width=width)

That means, basically, prefix + str(n) + '.' + extension.  A :05 format spec makes the number zero-padded to five digits; writing it as :0{width} makes it take the width from the parameter named width.

Counting loops are often better written using enumerate().

PEP 8 is the official Python style guide.  The naming conventions say that you should use lower_case_with_underscores for function and variable names.  Following some other capitalization convention is allowable if you need to interoperate with existing code, but is not recommended.

Suggested solution

import os, re, shutil

def fill_gaps(folder, prefix):
    filename_re = re.compile(r'{}(\d+)\.(.*)'.format(re.escape(prefix)))
    name = lambda match: match.group(0)
    number = lambda match: int(match.group(1))
    ext = lambda match: match.group(2)

    # A list of regular expression matches for all filenames that fit the
    # pattern, sorted numerically. filter(None, ...) eliminates false values,
    # namely the failed re.match(...) calls that returned None.
    matches = sorted(filter(None, (
        filename_re.match(entry.name)
        for entry in os.scandir(folder)
        if entry.is_file()
    )), key=number)

    if not matches: return

    first_num = number(matches[0])
    width = max(len(match.group(1)) for match in matches)

    for n, match in enumerate(matches, first_num):
        old_name = os.path.join(folder, name(match))
        new_name = os.path.join(
            folder,
            '{}{:0{width}}.{}'.format(prefix, n, ext(match), width=width)
        )
        if new_name != old_name:
            if os.path.exists(new_name):
                raise FileExistsError(new_name)
            # print('mv {} {}'.format(old_name, new_name))
            shutil.move(old_name, new_name)

I'd rather have the operation fail than risk overwriting an existing file, so I've added the test if os.path.exists(new_name): raise FileExistsError(new_name).


Synchronization of remote files download

If you change _retrieveFile to return a Task that's already started, you could simplify the whole Get() into just:

return _progress.GetOrAdd(key, _retrieveFile).Result;

Also, it seems that Downloader with empty map doesn't make sense, so you should check for that in your constructor, instead of using ??.


Keeping code DRY is a noble goal, even for test code, but it's less important for tests. Our first priority when writing test code is being precise and clear. The tests are the specs and the specs are the tests. It's important that it be immediately clear what the state of the mocked object is. We can expect to duplicate a certain amount of code.

Looking at your test, in isolation from your extension, it's difficult to tell exactly what is going on here.

bool isDirty = false;
var product = new Mock<IProduct>();

product.As<ISku>().SetupDirtyProperty(x => x.Price, x => x.Price= It.IsAny<decimal?>(), () => isDirty = true);

If you need to create this same Moq for many tests, it would be better to use the [TestInitialize] attribute and have it set up prior to each test method being run. See this for more information.


Memory ordering problem
This line:

        if (first == m_last.load(std::memory_order_relaxed))
            return false;

should be:
        if (first == m_last.load(std::memory_order_acquire))
            return false;

Otherwise, on the next line you may load the wrong value out of m_buffer due to the load being reordered before the load to m_last.  I spotted this because I noticed a memory_order_release without a corresponding memory_order_acquire.  The pop() function also needs a load of m_last with memory_order_acquire.
You have the same problem in push().  If you don't load m_first with memory_order_acquire, you run the risk of writing to the buffer when it is full, thus overwriting some element.  Even the assertion won't help because you could have overwritten the buffer and then loaded a modified value for m_first.
Example of failure
Since your comment indicated that I didn't explain thoroughly enough, I will give an example of how the pop could go wrong.

The queue is empty, with m_first = m_last = 0.
The consumer calls try_pop().
In try_pop(), m_first is loaded as 0.
Now, the cpu speculatively loads m_buffer[0], even though you haven't reached that line yet.
The producer calls push().
The producer writes m_buffer[0], and then increments m_last to 1, in that order.
The consumer reads m_last as 1.
The consumer uses the value speculatively loaded in step 4 as the value for m_buffer[0], but this value is wrong.

By adding the memory_order_acquire, you prevent the load of m_buffer[0] from happening until after step 7.


.map is only for the construction of new arrays - for example, arr.map(num => num / 2), to transform every element of one array into another array. If you aren't returning anything from the .map callback, or if you aren't using the resulting array, then .map isn't appropriate. If all you're interested in is something that can be accomplished with side-effects, use a generic iteration method like for..of or forEach (like with your second snippet).
But:
Select the proper iteration method - forEach can be used to accomplish pretty much any task while iterating over an array, but that's somewhat of a weakness, because it makes the intent of the code somewhat less clear. In this case, your logic is:

If CERTIFICATEPRINT showing is off, remove any Certificate items from the candidateColumns array.

There's no need for a nested loop, which will increase the computational complexity to O(n ^ 2) (a big jump). This can easily be accomplished by putting a .filter inside an if, O(n):
if (!this.showControlsBasedOnPrivileges('CERTIFICATEPRINT')) {
  this.candidateColumns = this.candidateColumns.filter(item => item !== 'Certificate')
}

performance oriented considering an array would have atleast 1.5k or even larger

With thousands of elements, O(n ^ 2) would indeed be a problem, but the O(n) operation should be quite reasonable; a few thousand operations is next to nothing on modern hardware.
Is reassignment necessary? You assign the result of the filter to this.candidateColumns. Is that required? Could you, for example, allow the filtered array to be used by returning it instead, or by passing it along to whatever needs the data? If possible, consider doing so, if it doesn't make the code convoluted - code is generally easier to make sense of when mutations are only done when necessary.


First thing I would consider is using functions so that it becomes easier readable.

function hasAllowedExtension($filename); // returns bool
function isAllowedType($filetype); // returns bool

That way you can shorten the first lines to

$file = $_FILES["file"];
if (hasAllowedExtension($file["name"]) && isAllowedType($file["type"]) && $file["size"] < 20000) {

which is much more readable.

$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

There are better and easier ways:

$extension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);

Also consider making all of this into a function which you only either hand the name of the file $_FILES[$filename] or the file (from $_FILES) directly.

echo "Invalid file";

A die might be appropriate here. die will also print a message but has the added bonus that it immediately stops execution and it is easier to understand that this is really a stopper.

die("Invalid file.");

I couldn't see any gaping holes in it except for only one thing: I can't remember and couldn't find out if $_FILES["file"]["name"] is safe or not. So check if this value can contain path separators or not. And by check I mean, read the documentation carefully.

Also it seems like you're checking for the file in a different location/under a different name than you actually save it as.

if (file_exists("upload/" . $_FILES["file"]["name"]))
...
move_uploaded_file($_FILES["file"]["tmp_name"],
  "images.example.com/" . randomName() .$_FILES["file"]["name"]);


First, I'll go on about how the code looks, since it displays the most obvious issues.

You have redundant comments all over the place.

// Rectangle drawing function
Function DrawRect

The name DrawRect makes it clear enough that you're drawing a rectangle in there. No need for the comment.

Similarly for:

// Define Y2
y2 := TextHeight(fLinesText.strings[count])*2;

And in the case of:

// Define Y1,Y2
x2 := Width - Width div 20;
y1 := Width div 20;

it's not only redundant, but also misguiding, since you're not setting the value of Y2 anywhere in there.

Code should be self-documenting, comments should not explain what you're doing, at most they should explain why you're doing what it is that you're doing. Otherwise, they're just cluttering the file, requiring extra work to maintain and looking ugly.

You should work towards improving the names of your variables.

// Define Link Rectangle
Lrect := Rect(x1, y1, x2, y2*(i+1));

By calling Lrect LinkRectangle or at least LinkRect, you can also discard the comment above the assignment. LinkRect := Rect(...); makes it clear enough that you're setting up a link rectangle.

chR and clR are some awfully confusing names, and unless you look at what parameters are being passed to the function in an actual call, it's pretty hard to understand what they're supposed to do. Consider chosenRect, and clickedRect instead.

bttn_dwn could become button_down (if this is the style you decided to apply to what seem to be unsigned integer constants). txts could become text.

count is more often used to represent the number of items in a particular collection. For a loop counter, consider using a more common and appropriate name. In your particular case, there should be no issue to rename count to i.

And so on...

There is some inconsistency in the way you use the casing for your names.

Although Lrect is a parameter like all the others, it's being cased differently.

You chose to use Function while also using procedure. This sort of stands out, consider changing Function to function or procedure to Procedure, depending on how you want to be consistent. Personally, I prefer to not start with an uppercase character. Mainly because I don't start the rest of the keywords with one either, and I see you've also done that.

You should try to keep these things consistent throughout your code. Choose a way to name your things, and keep it throughout your project.

You could improve the way your code behaves.

if fLinesText.Count = 0 then exit
  else

could well become if fLinesText.Count > 0 then.

However, this too is redundant because for count := 0 to fLinesText.Count - 1 do begin will do nothing if Count is less than 1.

Consider extracting

if (chosenRect = i) and (clickedRect = -1) then
  Brush.color := stateColor[bttn_on]
else if (chosenRect = i) and (clickedRect = i) then
  Brush.color := stateColor[bttn_dwn]
else
  Brush.color := stateColor[bttn_off];

into a function that returns values of the type the stateColor elements have. Then call it from TOC_MenuPanel.Paint, and pass the result as parameter to DrawRect. This will ease the burden caused by the many parameters on DrawRect (you'll be able to get rid of chosenRect and clickedRect). It will also remove the responsibility of knowing that there are chosen and clicked rectangles, from DrawRect.

In the case of:

Lrect := Rect(x1, y1, x2, y2 * (i + 1));

You seem to be altering the rectangle's size based on the rectangle's index in the menu. There is no reason for DrawRect to even know that there's a menu and that the rectangle being drawn has an index in it. The raw value of y2 is not used anywhere else, so consider passing y2 * (i + 1) as parameter (from within MenuPanel.Paint), and getting rid of i as parameter. If you extract the color choosing bit in a separate function, and call it from Paint, doing this too should be trivial.

Consider wrapping up x1 x2 y1 y2 into some higher level abstraction (a record for example) or at least name them appropriately. (x, y, width, height) would go a long way towards making your code more understandable. Right now you have to carefully analyze how the code is written to find out if you're working exclusively with coordinates or if x2 and y2 somehow represent the width and height of the rectangle.

Using a higher level abstraction will also reduce the number of parameters you pass around, so I'd do that myself.

  What methods could I use to increase the amount of encapsulation used in the drawing routine so I'm not defining variables in the Paint routine? The y2 variable in particular is irritating.

Follow the steps above to improve the way DrawRect works. As for the variables showing up in Paint, it depends on how far you want to go with your refactoring. In some form or another, the logic you used there has to exist. I do agree that it's probably better to take it out of the drawing routines.

Personally, I'd extract everything about positioning into some higher level structure that describes the whole layout. My drawing routines would receive the given layout and show it on the screen.


Optimizing multiple if-else from static class with LINQ

One solution would be to encapsulate the logic into a method. A problem with that is that there is no simple way to pass a property to the method.

If the case where the key is not in the dictionary means that the value is null, then you could write an extension method for IDictionary that returns the value, if it's present, or null:

public static string GetValueOrDefault(this IDictionary<string, string> dict, string key)
{
    string result;
    dict.TryGetValue(key, out result);
    return result;
}

You would then use it like this:

ConfigurationDetails.SharepointServer = configValues.GetValueOrDefault("SharepointServer");

Another option (assuming the names of properties and keys always match) would be to use reflection to set all the properties at the same time. Something like:

var properties = typeof(ConfigurationDetails).Getproperties();
foreach (var property in properties)
{
    string value;
    if (configValues.TryGetValue(property.Name, out value))
    {
        property.SetValue(null, value);
    }
}


Faster way of converting a 1-d table to predefined userdata in Lua

You have a duplication of the allocation and init part in the 2 functions, instead you can create a helper that will create the usertable, return a pointer to it and leave it on top of the stack:

static FloatArray *create_array(lua_State *L, int n) {
  size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
  FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
  a->size = n;
  return a;
}

static int new_array(lua_State *L) {
  int n = luaL_checkint(L, 1);
  create_array(L, n);
  return 1;
}

When accessing parameters in the C api it's easier to always index them from the bottom of the stack. That wat you won't end up being mistaken about the state of the stack and try to use the wrong value by accident (like you did in your attempt).

static int new_array_from_table(lua_State *L) {
  luaL_argcheck(L, lua_type(L, 1) == LUA_TTABLE, 1, "'1-d array' expected");

  // get the length of input table
  int n = lua_objlen(L, 1);

  // create new userdata
  FloatArray *a = create_array(L, n);
  //leaves the new table at the top of the stack

  // fetch data and use it to fill the array
  int index;
  for (index = 1; index <= n; index++) {
    lua_rawgeti(L, 1, index);
    a->values[index-1] = (float)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
  return 1;
}

With the creation bit in a single place you can now add a metatable to it so the script can access the values using the indexing syntax.

luaL_Reg[] floatArrayFuncs = { {"__index", get_array_value},
         {"__newindex", set_array_value},
         //...
         {NULL, NULL},};

//call on initialization
static void init_FloatArray(lua_State *L){
    luaL_newmetatable (L, "FloatArray");
    luaL_setfuncs(L, floatArrayFuncs , 0);
    lua.pop(1);
}

static FloatArray *create_array(lua_State *L, int n) {
  size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
  FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
  luaL_setmetatable (L, "FloatArray", -1);
  a->size = n;
  return a;
}

The metatable also allows you an easy way to type check the userdata from lua using

FloatArray *a = (FloatArray *)luaL_testudata (L, arg, "FloatArray");

Also you can overload the creation function by doing

static int new_array(lua_State *L) {
  switch(lua_type(L, 1)){
  case LUA_TNUMBER:
      int n = luaL_checkint(L, 1);
      create_array(L, n);
      return 1;
  case LUA_TTABLE:
      return new_array_from_table(L);
  case LUA_TUSERDATA:
      return duplicate_array(L);  //exercise for the reader
  default:
      luaL_argcheck(L,0, 1, "expected number, 1D array or FloatArray");
  }
  return 0; //never reached
}


Converting pseudocode for max subarray into working Java code

Your translation is pretty faithful to the already low-level pseudocode but you could:

The pseudocode talks about an array of numbers and not integers, but that is just a simple type change, and doesn't affect the logic at all
copy array.length into variable n near the top, and use n throughout as the original code does,
remove the initial filling of S with 0's, since your first loop will overwrite them anyway (and that was not in the original code)
change max to m, and array to A, but you could argue this makes your code more readable

This probably isn't the point of the exercise, but it is possible to solve this problem with a single loop that scans through the array just once, for a more efficient solution.


You should separate the computation code from the input/output code. As you have written it, the factorial computation code will never be reusable in any other program. To be specific, you should define an unsigned long long factorial(int n) function.

You have a formatting bug in the special case:

!0 = 1

In fact, you should structure your code to avoid the need for special cases altogether.

unsigned long long factorial(int n) {
    unsigned long long result = 1;
    while (n > 1) {
        result *= n--;
    }
    return result;
}


The class name, why template? Template is much better and follows the naming convention in all sane languages (oook, i know it's PHP :()

Where are $db and $functions? You missed to declare them in the class

class template
{
   private $db;
   private $functions = [];

Your

$query = $this->db->connection->prepare( 'SELECT id FROM ' . $this->functions->prefix( 'pages' ) . ' where id = ?' );

You use prepared statement for where id = ? but now for $this->functions->prefix( 'pages' ) it makes the prepared statement useless.

The same for fetchPage, getTheme.

As user45891 said, your $query->close() will never be executed due to the return. You can improve this with:

$query->close();
return $query->numRows > 0;

This block

if ( ! $query )
{
    throw new Exception( $query->error(), 1 );
}

Great, i love Exceptions but what about a more specific exception? When i write PHP code i check this list to know which exceptions php have. What about UnexpectedValueException or LogicException. LogicException should be used when the error in your code, if $query is false it means you DB is OFF or your question is wrong so the problem should be in your code.

Anyway, your check should go before you use $query! because it will fails with

 $query->bind_param( 's', $theme );

while ( $query->fetch() )
{
   return $result;
}

You need only the first value? Well, what about

$query->fetch();
return $result;

?

Anyway, you don't close $query in every function.

Your handlePageLoad don't return everytime, only if it joins $this->pageExist( $id ) path. Maybe you want to add return false;?

You could improve the this code with this:

public function handlePageLoad( $id )
{
    if ( $this->pageExist( $id ) )
    {
        $this->fetchPage( $id );
        $this->loadPage();
        $this->parseParameters();
        return true;
    }

    $this->fetchPage( 404 );
    $this->loadPage();
    $this->parseParameters();
    //header('Location: index.php?page=404');
    echo '! <br /> He\'s a true genius.';
    return false;
}

The indentation of parseParameters is not coerent with the other code (and ugly :()

As i said above, you missed to declare fields in your class. Do it! You will need to remember what fields you use and what fields your class have (and your IDE will help you more!)

How you handle the case where someone uses the same name for lang and template data?

Your parseParameters feels to be very slow with many arguments... what about RegEx?

Why you use three different arrays parameter, langParameters and templateData (except this which is filled by another method) ? They do the same thing? What about only one array?

You need it separate?

I don't use PHP everyday (only when i need to) so i'm not sure, so don't take it serious:

In getTheme you used $theme = 'theme'; because bind_param wants references ok, but what about &"theme"? I'm not sure, but you could try

Anyway, good luck!


I don't have a tool here to count, so I don't know how the numbers will
play out.  That said, I agree with the interpretation since there's a
lot of things going on here and it makes sense to detangle the function
into smaller bits.

The big if block immediately suggests that some kind of
short-circuiting or decomposing into functions would be useful.  E.g. if
workInfo is not an object, call persistWOrkDetails and just return;
the other branch will continue afterwards and also persists the object.

Then again, I'd rather split a function off in this case, though I have
no idea what to call it.

function addGenresAndThemesFromWork(work) {
    let workDetails = {workId: work.$.id, genres: [], themes: []};

    if (typeof work.info === 'object') {
        fillInWorkDetails(work.info, workDetails);
    }

    if (!_.has(workDetails, 'picture')) {
        workDetails.picture = {src: '/default.jpg', temporary: true};
    }

    persistWorkDetails(workDetails);
}

Next up are the genres and themes, which exhibit a common pattern, so
again, move that into a separate function.  Sounds like that is a
function that might already exist in a library anyway.

function pushNew(thing, name) {
    let value = {name: name};

    if (thing.findOne(value) === undefined) {
        thing.insert({name: name});
    }
}

...

case 'genres':
    workDetails.genres.push(workInfoValue);
    pushNew(Genres, workInfoValue);
    break;
case 'themes':
    workDetails.themes.push(workInfoValue);
    pushNew(Themes, workInfoValue.toLowerCase());
    break;

For "objectionable content" (I wonder) the if can be replaced with an
or, that is:

workDetails.mature = workDetails.mature || workInfoValue.toLowerCase() === 'ma';

The syntax is a bit longer, but a temporary variable could be used to
deal with that.

Is there a particular reason to use Object.keys instead of for
... in on the workInfo object?
The nested else { if ... } can just be written as else if in this
case.
workInfo[key] appears way too often, just assign it to a shorter
name.
Since you create workDetails yourself, you probably don't have to
use _.has, but just plain in.
The picture default value can be moved into the workDetails
initialisation since the loop will always overwrite the existing
value.  That also takes care of any possible issues with undefined.
If a function (like findOne) only returns a false value if couldn't
find something, then the comparison can also simply be if
(!findOne(...)) - I'm assuming that that's done for a reason though.

With all that in mind I'm arriving at the following, which, depending on
the exact format and semantics of the objects could be further
distilled, but I think this is good enough for now and for you to
continue on it later.

I'd also suggest that the workDetails object is filled in with more
defaults so it's actually clear that e.g. a missing mature field
actually means the same as mature: false in the initialisation (or
not, in which case the code below is slightly wrong).

function pushNew(thing, name) {
    let value = {name: name};

    if (thing.findOne(value) === undefined) {
        thing.insert(value);
    }
}

function pictureValue(img) {
    if (img[1] !== undefined) {
        return img[1].$;
    } else if (img[0] !== undefined) {
        return img[0].$;
    }
    return undefined;
}

function fillInWorkDetails(workInfo, workDetails) {
    for (let key in workInfo) {
        let value = workInfo[key];
        let workInfoValue = workInfo[key]._;

        switch (value.$.type.toLowerCase()) {
            case 'genres':
                workDetails.genres.push(workInfoValue);
                pushNew(Genres, workInfoValue);
                break;
            case 'themes':
                workDetails.themes.push(workInfoValue);
                pushNew(Themes, workInfoValue.toLowerCase());
                break;
            case 'main title':
                workDetails.name = workInfoValue;
                break;
            case 'plot summary':
                workDetails.plot = workInfoValue;
                break;
            case 'objectionable content':
                workDetails.mature = workDetails.mature || workInfoValue.toLowerCase() === 'ma';
                break;
            case 'picture':
                workDetails.picture = pictureValue(value.img) || workDetails.picture;
                break;
            case 'alternative title':
                if (value.$.lang.toLowerCase() === 'ja') {
                    workDetails.alternativeTitle = workInfoValue;
                }
                break;
        }
    }

    return workDetails;
}

function addGenresAndThemesFromWork(work) {
    let workDetails = {
        workId: work.$.id,
        genres: [],
        themes: [],
        picture: {src: '/default.jpg', temporary: true}
    };

    if (typeof work.info === 'object') {
        fillInWorkDetails(work.info, workDetails);
    }

    persistWorkDetails(workDetails);
}


Squashing multiplication identity in an expression

You are doing both too much work and not enough.

You are doing too much work because you don't need to repeatedly squash units in case the first pass has returned a modified expression.
You are not doing enough work because you are not squashing the units coming from MulId rather than Lit mulId

Here is a solution which one could argue is more idiomatic as well as dealing with the two shortcomings I pointed out earlier:

We start by implementing the recursion pattern first; it is a quite common thing to do in Haskell as it helps make it easier to understand from first sight how a function works (what does this function do? Oh! It goes by recursion on the structure! Let's see what the different cases are...).

To do that, you define a function fold taking one argument per constructor of the datatype and having a given return type (here b). The arguments are functions taking the same arguments as the constructors they correspond to except that the recursive occurences of RingExpr a have been replaced by the return type b (i.e. we assume we already know the result for the recursive subcomputations!)

fold :: (a -> b)      -> -- Lit    :: a -> RingExpr a
        b             -> -- AddId  :: RingExpr a
        (b -> b)      -> -- AddInv :: RingExpr a -> RingExpr a
        b             -> -- MulId  :: RingExpr a
        (b -> b -> b) -> -- Add    :: RingExpr a -> RingExpr a -> RingExpr a
        (b -> b -> b) -> -- Mul    :: RingExpr a -> RingExpr a -> RingExpr a
        RingExpr a -> b
fold litb addIdb addInvb mulIdb addb mulb = go
  where go (Lit a)    = litb a
        go AddId      = addIdb
        go (AddInv e) = addInvb $ go e
        go MulId      = mulIdb
        go (Add e f)  = go e `addb` go f
        go (Mul e f)  = go e `mulb` go f

The function you are looking to define is now a simple instance of the recursion pattern we just described: for the cases which are not Mul, we simply use the corresponding constructor but in the case of Mul we do the squashing:

squashMulId :: (Ring a, Eq a) => RingExpr a -> RingExpr a
squashMulId = fold Lit AddId AddInv MulId Add squashing
  where
    squashing a b
      | a == Lit mulId || a == MulId = b
      | b == Lit mulId || b == MulId = a
      | otherwise                    = Mul a b


This will not reduce time complexity, just space complexity; as well as spending less time in the interpreter, most of the work being done in C.

The key idea is to make use of generators to avoid building lists that you only iterate once; reducing your need for memory management, thus increasing the overall speed.

Since you are already importing itertools, I’ll just import the relevant parts to save on typing a bit, feel free to use the long names if you see fit:

from itertools import product, permutations

in case you are using Python 2, I'd use:

from itertools import product, permutations, imap as map

Now we transform each list into a generator expression:

def _compare_names_with_combinations(name_1,name_2):
    join = ' '.join
    name_1 = name_1.lower().split()
    name_2 = name_2.lower().split()
    distances = []
    for name1 in map(join, permutations(name_1)):
        for name2 in map(join, permutations(name_2)):
            distance = _compare_names(name1,name2)
            distances.append(distance)
    return max(distances)

Then product lets us merge the two loops:

def _compare_names_with_combinations(name_1,name_2):
    join = ' '.join
    name_1 = name_1.lower().split()
    name_2 = name_2.lower().split()
    distances = []
    for name1, name2 in product(map(join, permutations(name_1)), map(join, permutations(name_2))):
        distance = _compare_names(name1,name2)
        distances.append(distance)
    return max(distances)

An other improvement is to not build the list of all distances since we are only interested in the maximum value: let's put this max call out of the function and turn it into a generator:

def _compare_names_with_combinations(name_1,name_2):
    join = ' '.join
    name_1 = name_1.lower().split()
    name_2 = name_2.lower().split()
    for name1, name2 in product(map(join, permutations(name_1)), map(join, permutations(name_2))):
        yield _compare_names(name1,name2)

def score_names(name_1, name_2):
    return max(_compare_names_with_combinations(name_1, name_2))

Well, we’re just mapping _compare_names over the product. Maybe we could have that max call in the function after all:

def _compare_names_with_combinations(name_1, name_2):
    join = ' '.join
    name_1 = name_1.lower().split()
    name_2 = name_2.lower().split()
    return max(
        map(
            _compare_names,
            product(
                map(join, permutations(name_1)),
                map(join, permutations(name_2))
            )
        )
    )

But this will require that we modify _compare_names to accept a tuple of two names as parameter instead of two names as two separate parameters:

def _compare_names(names):
    a, b = names
    return SequenceMatcher(None, a, b).ratio()


The way that you find rows and columns is good. You can't iterate through the lists so this approach is good.
However using them for your comprehensions is bad.

The name a_list is not descriptive, and quite poor.
table whilst generic is much better.

Your comprehensions and loops are actually rather poor.
Your comprehensions are used as if you are initialize an array in say C.
But this is Python, not C.

You should also use the builtins. The way you find the longest in a list can be changed to use max instead.
And if you use a comprehension to change all the strings to their length then you could make column_widths a comprehension.

column_widths = [max(len(cell) for cell in column) for column in table]

Your print row is also quite strange.
Instead of print_row[a] = print_row[a] + you should use print_row[a] += but this can be done in a list comprehension too.
As you're joining the items by nothing you can 'wrap' the comprehension with ''.join.
And the comprehension would just be the indexing the table and justifying you're already doing.
This can result in:

print_row = ["" for i in range(rows)]
for row in range(rows):
    print_row[row] = ''.join(
        table[col][row].rjust(column_widths[col])
        for col in range(columns)
    )

for item in print_row:
    print(item)

From this you should notice that there is not much point in adding to a list, if you're just going to print it later anyway.
And so you can merge these two loops together and remove the print_row comprehension.

Also I'd change the rjust call to not add 4 spaces, as that indents the table, which looks kinda ugly.
And you can add a space between each column by using ' '.join instead.
This can result in the function:

def print_table(table):
    rows, columns = len(table[0]), len(table)

    column_widths = [max(len(cell) for cell in column) for column in table]
    for row in range(rows):
        print(' '.join(table[col][row].rjust(column_widths[col]) for col in range(columns)))


Recording options selected from dropdown menu

Your indentation is a little funky. I can understand not indenting after $(function () { (though I would do so myself), but the change handler's body really should be indented
You've got everything in one function, though it'd probably be more readable to separate things. For instance, addRecord, removeRecord (with further specialized functions for adding/removing a row, and adding/removing an option.
Use jQuery to build the HTML; don't type it out as a long string. Doing so is error-prone
I don't know how modalMsg works, but I imagine that the result you receive in the callback can have at least 2 different values. What happens if the user says "No, I don't want to delete that resource"? It looks like it gets removed anyway...
Moreover, the wording of that modal seems a bit severe considering you can just add the resource back in a moment later. The word "Delete" can scare the pants of people.
I have to wonder why your ajax call is a POST. I'm guessing you're updating something server-side when a record is added to the table, but in that case, shouldn't there also be a POST or DELETE call when the user removes something from the table?
You don't have any error handling, so if the ajax call should fail for any reason, the option is already gone, and the record isn't in the table either.
It'd be easy to add a little bit of caching, just in case someone changes their mind twice (adds, removes, adds again)
The hidden input should be in a td, rather than floating around inside a tr.
There's no need to create unique class names for every row. The idea of class names is that they can be applied to several elements. If you want to uniquely identify something, use an ID attribute - it's what they're for. However, in this case, we don't even need that, as we can use closures instead.
Rather than add and remove the no-resources row and the "No more contacts available" alert, it'd be easier to have these in the HTML already, and simply show/hide them as needed. The less HTML you have to build in JS, the better.
There's the issue of sorting the records, too. Not so much in the table, but rather in the dropdown. If I were to select the 3rd option out of, say, 10, and then change my mind, I'd expect it to behave like "undo": That's the option is back in the dropdown, as the 3rd option. But tackling this is a bit beyond the scope of this review.

I'd do something like this (assuming that the 1st option - the do-nothing option - has its value attribute set to an empty string). I haven't looked at error handling because I don't know how you'd prefer to do that.

Haven't tested this, but the general idea should be apparent

$(function () {
  var dropdown = $("#addResource"),
      table = $("#resourcesTable tbody"),
      noResourcesRow = table.find(".no-resources"),
      noContactsAlert = dropdown.parent().find(".alert"),
      url = "/admin/contacts/json",
      recordsCache = {};

  function fetchRecord(id) {
    if(recordsCache[id]) {
      addTableRow(records[id]); // use cache if possible
    } else {
      $.post(url, {id: id}, function (record) {
        recordsCache[id] = record; // add to cache
        addTableRow(record);
      });
    }
  }

  function addTableRow(record) {
    var row = $("

").addClass("resource").data("record", record),
        removeLink = $("", {
          "href": "#",
          "class": "remove-resource",
          "title": "Remove resource"
        }).append($("", { "class": "icon-trash" }));

    row.append($("	").text(record.name)).append($("<input></input>", {
      type: "hidden",
      value: record.id
    }));

    // this could be done with a loop too
    row.append($("	").text(record.phone));
    row.append($("	").text(record.email));
    row.append($("	").text(record.rate));

    row.append($("	").append(removeLink));

    removeLink.on("click", function (event) {
      event.preventDefault();
      modalMsg("Are you sure you wish to remove " + record.name + " as a resource?", "", function (result) {
        // FIXME: Add proper checking of the result
        if(...) {
          removeTableRow();
        }
      });
    });

    table.append(row);
  }

  function removeTableRow(row) {
    var record = row.data("record");
    row.fadeOut(function () {
      row.remove();
      if(!table.children.length) {
        noResourcesRow.show(); // or fadeIn() maybe
      }
      addOption(record.id, record.name); // add the option back in
    }
  }

  function addOption(id, name) {
    dropdown.append($("<option></option>", { value: id }).text(name));
    noContactsAlert.hide();
    dropdown.show();
  }

  function removeOption(option) {
    option.remove();
    if(dropdown.children.length === 1) { // includes the do-nothing option
      dropdown.hide();
      noContactsAlert.show();
    }
  }

  dropdown.on("change", function (event) {
    if(!this.value) {
      return; // ignore event if the do-nothing option is selected
    }

    fetchRecord(this.value);
    removeOption(dropdown.children(":selected"));
    this.value = ""; // set the do-nothing option
  });
});


Show that sum and product are both examples of accumulation

Since the only parameter that changes in your recursive definition is a, you can write an inner definition like so:

(define (accumulate combiner null-value term a next b)
  (define (rec a)
    (if (> a b)
        null-value
        (combiner (term a) (rec (next a)))))
  (rec a))


"Suspicious comparison of integer references" while checking for a monotonically increasing sequence

You should only use == if you work with elementary data types (boolean, byte, char, short, int, long, float, long).
If you use == on instances of classes like Integer you check if it is the same instance of the class not if the value is the same. You hardly ever want to check if two references refer to the same instance. That is especially true for the primitive wrappers.
So as a rule of thump:

use == for boolean, byte, char, short, int, long, float, long
use equals(..) otherwise

For little values of wrapper types == might work, but this totally depends on the VM implementation. JLS 5.1.7 Boxing Conversion:

Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly. For other values, this formulation disallows any assumptions about the identity of the boxed values on the programmer's part. This would allow (but not require) sharing of some or all of these references.
This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.


In a sense, your function does produce the right numbers.  However, the termination condition is not quite right.  For example, fibb(3) and fibb(4) produce identical output: each prints six numbers.  Why six?  The most natural interpretation of the parameters would be that $limit should specify the number of items in the sequence to be printed.

The root of the problem is that each call to fibb() prints two lines, which means that output will always be printed in pairs.  Normally, you would want to print just one number per call.

In addition, your naming is unconventional.  Why fibb() with two bs?  Also, $first_numer is misspelled.

function fibonacci($limit, $first_number=0, $second_number=1) {
    if ($limit <= 0) {
        return;
    }
    echo "$first_number\n";
    fibonacci($limit - 1, $second_number, $first_number + $second_number);
}


I want to check neighborhoods of cell in two dimensional array in C++

You can use 8 bit memory (char in c/c++) to precompute possible direction of movement for each of the cells and use bitwise operation to improve performance:

//bit1: top direction, bit2: topright directon, bit3: rigth, and so on....
std::array<char, 1000000> c;    //array, this will be our playground
c.assign(255);                  //to set all ones in all cells
c[0] = c[0] & 0x38;             //top left cell representing 00111000
c[999] = c[999] & 0xE;          //top right cell
c[900000] = c[900000] & 0xE0;   //bottom left cell
c[999999] = c[999999] & 0x83;   //bottom right cell

for(int i=1; i<999; i++)               //all top edge cells except corners
   c[i] &= 0x3E;
for(int i=1999; i<999999; i += 1000)   //all right edge cells except corners
   c[i] &= 0x8F
for(int i=9999000; i<999999; i ++)     //all bottom edge cells except corners
   c[i] &= 0xE3
for(int i=1000; i<999000; i += 1000)   //all left edge cells except corners
   c[i] &= 0xF8

then you can use these hex values to quickly determine if your cell is at corners, edges or in the middle
    example:

  if(! c[i] ^ 0x38){
       //this cell is left corner
    }

Because bitwise operators are very fast, you will see great improvement in performance.


No, the Second Query won't Delete anything.

In the statement prior to the delete you change the oldID to the newID so there aren't any records with the oldID in that table.

Difference between the two Queries

The first Query, inserts new records into the table, then deletes the records with the oldID

The Second Query, updates all the records removing the oldID's and replacing it with the newID's, so instead of inserting and then deleting the old records, it updates the old records UniqueID column

These both do very different things.


3-stack implementation with a single array

Compiler errors:

You code did not compile under Clang! It would not compiler anywhere for that matter, as it has a few syntax errors:

In method is_empty(), pointer is not declared. It should be pointers (plural).
In both pop() and top() methods, this line is broken:

if (is_empty(stack_num) {
//                    ^-------- Missing a `)` here!

Compiler warnings:

Always compile with warnings turned on and set them to the highest level practical.
If you have the habit of ignoring warnings, try compiling with "warnings as errors" (-Werror for Clang and GCC) to force yourself into fixing them.

That said, your code only produced one warning, after the errors above where fixed:

array[get_top_position(stack_num)] = NULL;
//                                   ^^^^--------- implicit conversion of NULL constant to 'int'

NULL is not the same as int. In fact, an implementation is free to define NULL to whatever, so don't assume it will be convertible to an integer on all compilers/platforms.

Code review:

Now if I get the idea behind your code, you intend to have a single array with several stack
sharing this array. Your implementation doesn't seem to be doing that correctly. I could not test it thoroughly, but the helper array pointers, which doesn't store pointers by the way, seems questionable. The method get_top_position() also seems a bit contrived to me. print_stack() is broken, so I couldn't print the stacks to validate the state of the structure.

I would suggest that you attempt to simplify this by storing actual pointers (or indexes) to the sub-array inside the main array. Then you won't need any additional offset calculation once pushing/poping. You also have the advantage that all stacks share the same size.

               main array of ints:
    +--+--+--+--+--+--+--+--+--+--+--+--+----
    |  |  |  |  |  |  |  |  |  |  |  |  | ...
    +--+--+--+--+--+--+--+--+--+--+--+--+----
    |           |           |           |
    V           V           V           V
    +-----------+-----------+-----------+----
    |  stack 0  |  stack 1  |  stack 2  | ...
    +-----------+-----------+-----------+----
    |           |           |           |
    V           V           V           V
pointer[0]  pointer[1]  pointer[2]  pointer[N] ...

Overall code improvements:

sizeof misuse: This is not doing what you expect:

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

sizeof is a compile-time operator, so it cannot infer the size of dynamically allocated arrays, only arrays in which the size is known at compile-time (e.g.: char buf[128]) can have the size inferred with sizeof. You must keep a member variable with the size of the stacks and another with the main array's.
top() only inspect data, so it should also be a const method.
Simplify if-else logic where it is not needed. Example:

if (is_empty(stack_num)) {
    throw std::runtime_error("Stack is empty");
} else {
    return array[get_top_position(stack_num)];
}

No need to keep the if-else when both paths will exit the function.

if (is_empty(stack_num)) {
    throw std::runtime_error("Stack is empty");
}
return array[get_top_position(stack_num)];

Instead of hardcoding cout in print_stack(), you could take the output parameter as an std::ostream &. However, such function is asking to become an output stream operator.
Manual memory management (with new/delete) is a dated practiced in C++. Even for custom containers, the use of smart pointers is strongly advised. I would replace the raw pointers by at least a std::unique_ptr or even better a std::vector.


This is what you have, cleaned a little

foreach ($data['test'] as $value) {

    if ($value == '__d') {
        $sql .= 'NOW()';
    } else {
        $sql .= "'" . $value . "'";
    }
    $i++; // add before the comparisson
    // make the comparrison at one place
    // if the number != total, then we need a comma.
    if($i != $numItems) $sql .= ',';
}
// always end with a close paren.
$sql .= ')';

But you are better off using implode and replace:

// implode using the quotes and commas.
$values = "'".implode("', '", array_values($values))."'";
// swap out __d for NOW
$sql .= str_replace("'__d'",'NOW()',$values);

Of course, you really need to make sure that you've cleaned all of those values with mysql_real_escape_string.


This is very close to what AutoMapper is for. Though it doesn't directly support bidirectional maps, so you'll have to write a simple class that builds two mappers at the same time:

public class TwoWayMapper<TSource, TDestination>
{
    private readonly IMappingExpression<TSource, TDestination> m_sourceMapping =
        Mapper.CreateMap<TSource, TDestination>();
    private readonly IMappingExpression<TDestination, TSource> m_destinationMapping =
        Mapper.CreateMap<TDestination, TSource>();

    public TwoWayMapper<TSource, TDestination> ForMember(
        Expression<Func<TSource, object>> sourceMember,
        Expression<Func<TDestination, object>> destinationMember)
    {
        m_sourceMapping.ForMember(destinationMember, opt => opt.MapFrom(sourceMember));
        m_destinationMapping.ForMember(sourceMember, opt => opt.MapFrom(destinationMember));
        return this;
    }
}

You can then set up your mapping like this (maybe in a static constructor of ProjectOwnerDataFields?):

new TwoWayMapper<ProjectOwnerDataFields, T_PROJECT>()
    .ForMember(f => f.Id, p => p.proj_owner_id)
    .ForMember(f => f.CompanyName, p => p.proj_owner)
    .ForMember(f => f.ContactPerson, p => p.proj_owner_contact)
    .ForMember(f => f.CountryIsoLetter, p => p.proj_owner_country);
    // etc.

With that, your methods simplify to:

public ProjectOwnerDataFields(T_PROJECT project)
{
    Mapper.Map(project, this);
}

public void UpdateToModel(T_PROJECT project)
{
    Mapper.Map(this, project);
}


Now assuming you simply just want to use standard APIs and ES6 (because from a cross-browser point of view, this code isn't guaranteed to work)...

onClick is unnecessarily pulled out. You can just inline it. Also, I believe return false are unnecessary when you already have preventDefault. You wouldn't want to prevent bubbling as something else might be delegating their handlers.

document.addEventListener('DOMContentLoaded', () =>  {
    document.querySelector('#foo').addEventListener('click', e => {
      event.preventDefault();
      scroll(400);
    }, false);
});

Variable declarations are also unnecessarily separated. It's not like they're defined somewhere in the middle (where you sometimes need to pull them up for visibility).

var start = performance.now();
var travelled = 0;
var html = document.querySelector('html');

Pull out your move function from your scroll. What happens is that every call to scroll, you're creating move.
I also suggest you schedule you call requestAnimationFrame first thing in the callback. That's so your code won't hold up the scheduling of the next frame. Should you want to bail out, you can always use cancelAnimationFrame.
Math.floor can be substituted by | 0 (bitwise or). Under the hood, it transforms the number from float to int, dropping the decimals. It's fast one some engines, but your mileage may vary.
Your "bail out" conditions can simply be combined:

if((1 - fractionDone) <= 0 || window.scrollY + window.innerHeight === html.offsetHeight) return


Detecting which properties have been changed from two objects

I did a bit of testing on jsperf which seems to indicate that it would be marginally faster for you to delete the properties you don't need rather than create a new object and replace it. Obviously, your mileage may vary. My test was objects with 6 properties, 3 of which were different.

EDIT : Delete is faster on IE. The new object version is faster on Chrome and FF.

_deltaProperties: function (cmd) {
    var prop;
    for (prop in cmd.properties) {
        if (cmd.properties[prop] === this.xxx.properties[prop]) {
            delete cmd.properties[prop];
        }
    }
    return cmd;
},

If you decided to keep your current code, there are some improvements you could make in terms of styling:

// I personally dislike underscores in variable names
deltaProperties: function (cmd) {
    // JavaScript only has function scope, a lot of developers define all
    // variables at the top of the function - can help with subtle scope bugs
    var dataBefore = this.xxx.properties,
        newData = {},
        prop,
        newValue,
        oldValue;

    for (prop in cmd.properties) {
        newValue = cmd.properties[prop],
        oldValue = dataBefore[prop];
        if (newValue !== oldValue) {
            // Use newValue rather than accessing member again
            newData[prop] = newValue;
        }
    }
    cmd.properties = newData;
    return cmd;
},


Compute spherical distance matrix from list of geographical coordinates

With numpy and its meshgrid functions, you don't have to do any looping at all, although under the hood looping similar to yours is going on (but in C, and thus much faster).

Here's a numpy version of your function:

import numpy as np

def distance_on_sphere_numpy(coordinate_array):
    """
    Compute a distance matrix of the coordinates using a spherical metric.
    :param coordinate_array: numpy.ndarray with shape (n,2); latitude is in 1st col, longitude in 2nd.
    :returns distance_mat: numpy.ndarray with shape (n, n) containing distance in km between coords.
    """
    # Radius of the earth in km (GRS 80-Ellipsoid)
    EARTH_RADIUS = 6371.007176

    # Unpacking coordinates
    latitudes = coordinate_array[:, 0]
    longitudes = coordinate_array[:, 1]

    # Convert latitude and longitude to spherical coordinates in radians.
    degrees_to_radians = np.pi/180.0
    phi_values = (90.0 - latitudes)*degrees_to_radians
    theta_values = longitudes*degrees_to_radians

    # Expand phi_values and theta_values into grids
    theta_1, theta_2 = np.meshgrid(theta_values, theta_values)
    theta_diff_mat = theta_1 - theta_2

    phi_1, phi_2 = np.meshgrid(phi_values, phi_values)

    # Compute spherical distance from spherical coordinates
    angle = (np.sin(phi_1) * np.sin(phi_2) * np.cos(theta_diff_mat) +
           np.cos(phi_1) * np.cos(phi_2))
    arc = np.arccos(angle)

    # Multiply by earth's radius to obtain distance in km
    return arc * EARTH_RADIUS

In addition to changing things to be compatible with numpy, there were several other stylistic and efficiency notes:

I renamed the function to eliminate the unit word from its name, which was misleading: you are multiplying the Earth's radius, so the result is not distances on a unit sphere but rather on an Earth-sized sphere.
I added docstrings to explain the function.
Rather than have the "magic number" 6371.007176 in the bottom of the code, I moved it to the top, defined it as a variable with an all-caps name.  This make it more apparent that the function relies on this value and is consistent with recommended Python PEP8 style best practices.  The units (km) in particular may not be apparent to users of the code.
It is obviously inefficient to compute every distance twice, as my version currently does.  However, your version also double-counted, which would be difficult to avoid without storing a copy of the keys in your dictionary in a list or tuple, so you could enumerate() them and then make the second loop go only from the index of the outer loop on up.
For easy array-based trigonometry, I switched the calls to math.cos() and math.acos() to np.cos() and np.arccos().  After that the only import I needed from math was pi, but as Jaime pointed out that is available from numpy, so I just used that version and eliminated all imports of anything from math.

This function is usable like this:

coordinates_dict = {u'YALE UNIVERSITY': [41.3111, -72.9267],
                    u'YONSEI UNIVERSITY': [37.5664, 126.939],
                    u'YORK UNIVERSITY': [43.7731, -79.5036],
                    u'YUAN ZE UNIVERSITY': [24.9697, 121.267],
                    u'ZHEJIANG UNIVERSITY': [30.2636, 120.121],
                    u'ZHONGNAN UNIVERSITY OF ECONOMICS AND LAW': [30.4752, 114.394]}

coordinates_array = np.array([(val[0], val[1]) for key, val in coordinates_dict.iteritems()])

distance_on_sphere_numpy(coordinates_array)
Out[2]:
array([[  1.34258937e-04,   1.20828584e+04,   1.16387852e+04,
          1.15437577e+04,   1.05861981e+04,   6.04128344e+02],
       [  1.20828584e+04,   0.00000000e+00,   9.11965962e+02,
          5.99372703e+02,   1.50000489e+03,   1.25010601e+04],
       [  1.16387852e+04,   9.11965962e+02,   0.00000000e+00,
          5.49877343e+02,   1.39741343e+03,   1.19974669e+04],
       [  1.15437577e+04,   5.99372703e+02,   5.49877343e+02,
          0.00000000e+00,   1.02655483e+03,   1.19442021e+04],
       [  1.05861981e+04,   1.50000489e+03,   1.39741343e+03,
          1.02655483e+03,   0.00000000e+00,   1.10150349e+04],
       [  6.04128344e+02,   1.25010601e+04,   1.19974669e+04,
          1.19442021e+04,   1.10150349e+04,   0.00000000e+00]])

By adding your code into its own function, I was able to compare timing between the numpy version and your version:

import math
from collections import OrderedDict
import numpy as np

def distance_on_unit_sphere(coord1, coord2):
    lat1 = coord1[0]
    long1 = coord1[1]
    lat2 = coord2[0]
    long2 = coord2[1]
    # Convert latitude and longitude to spherical coordinates in radians.
    degrees_to_radians = math.pi/180.0
    phi1 = (90.0 - lat1)*degrees_to_radians
    phi2 = (90.0 - lat2)*degrees_to_radians
    theta1 = long1*degrees_to_radians
    theta2 = long2*degrees_to_radians
    # Compute spherical distance from spherical coordinates.
    cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
           math.cos(phi1)*math.cos(phi2))
    arc = math.acos( cos )
    # Multiply with radius of the earth in km (GRS 80-Ellipsoid)
    distance = arc * 6371.007176
    return distance

def compute_distance_mat(coordinates_dict):
    distance_dict = {}
    for university in coordinates_dict.keys():
        distance_dict[university] = OrderedDict()
        coord1 = coordinates_dict[university]
        for other_university in coordinates_dict.keys():
            coord2 = coordinates_dict[other_university]
            distance = distance_on_unit_sphere(coord1, coord2)
            distance_dict[university][other_university] = distance
    return distance_dict

coordinates_dict = {u'YALE UNIVERSITY': [41.3111, -72.9267],
                    u'YONSEI UNIVERSITY': [37.5664, 126.939],
                    u'YORK UNIVERSITY': [43.7731, -79.5036],
                    u'YUAN ZE UNIVERSITY': [24.9697, 121.267],
                    u'ZHEJIANG UNIVERSITY': [30.2636, 120.121],
                    u'ZHONGNAN UNIVERSITY OF ECONOMICS AND LAW': [30.4752, 114.394]}

import timeit
%timeit compute_distance_mat(coordinates_dict)

%timeit distance_on_sphere_numpy(coordinates_array)
10000 loops, best of 3: 125 µs per loop
10000 loops, best of 3: 40.8 µs per loop

So numpy is already three times faster for this small test case.


Optimization of code for searching in db

var test = (from x in myDb.myTable
            where (x.name == tmp || x.name == tmp2 || x.name == tmp3)
            select x)
           .AsEnumerable()
           .OrderBy(x => x.unit == u ? 0 : 1)
           .FirstOrDefault();

I removed the x.unit == u condition. Instead I sort the items to make the ones where
this condition would be met to appear first. FirstOrDefault then makes the rest.

I split the EF part from the LINQ-to-objects part with AsEnumerable() as I am not sure if EF can translate the order by to SQL. If it can, you can try this

var test = (from x in myDb.myTable
            where (x.name == tmp || x.name == tmp2 || x.name == tmp3)
            orderby x.unit == u ? 0 : 1
            select x)
           .FirstOrDefault();


Overview
Sure this is one way to represent a Matrix.
typedef vector<vector<double> > Matrix;

The problem here is that there is no enforcement that these are rectangular. Your code makes the assumption they are rectangles and things will go very wrong if the assumption is wrong.
You don't use encapsulation.
Matrix add(Matrix a, Matrix b)
Matrix subtract(Matrix a, Matrix b)
Matrix multiply(Matrix a, double b)
Matrix multiply(Matrix a, Matrix b)
Matrix dotProduct(Matrix a, Matrix b)

All these are standalone methods. Not an absolute no-no but using classes correctly you can enforce the rectangular size requirements (preferably at compile time) but you could do it at runtime. If you use these methods then these would normally be member functions.
Also these functions are just wrong:
Matrix multiply(Matrix a, Matrix b)
Matrix dotProduct(Matrix a, Matrix b)

Neither of these functions do what they advertise. You should check out wikipedia for the definitions.


Preliminary draft of a data structure for a goodies tracker

It's weird that your get_capacity() returns a string.  I'm guessing that it's to facilitate string concatenation in the print() statement in main(), but that is not a good justification for the weirdness.  A better solution would be to use str.format() rather than string concatenation.

Those get_…() methods look like an awkward translation of Java code.  In Python, it is often customary to just access the member variables directly.  If you did want to write a getter method (to help enforce read-only access, for example), you could write a @property instead.

Going further, it seems like your StampCard is mostly a structure to hold a bunch of read-only properties.  You could just use or inherit from collections.namedtuple.

# -*- coding: utf-8 -*-
from collections import namedtuple
from tabulate import tabulate

class StampCard(namedtuple('StampCard', 'name description capacity symbol redeemable_location')):
    def __str__(self):
        stamps_per_row = self.capacity // 2  # hardcoded rows for now
        stamps = [[self.symbol] * stamps_per_row] * 2
        return tabulate(stamps, tablefmt='grid')

def main():
    oasis = StampCard('Oasis', 'Bubble Tea', 10, u'', 'University District')
    print('Name: {card.name}, Capacity: {card.capacity}'.format(card=oasis))
    print(unicode(oasis))

if __name__ == '__main__':
    main()


Put /path/to/dir/ in a variable to avoid writing it repeatedly.

Instead of running the command and checking $? after,
you can put the command inside an if.

The script would become shorter, for example:

path=/path/to/dir

if find $path -daystart -type f -mtime 1 -name "*.log" -print | zip $path/"logbackup-$yest.zip" -@
then
    find $path -daystart -type f -mtime 1 -name "*.log" -exec rm -f {} \;
fi

In my tests, it seems that simply dropping -daystart will have the desired effect of matching the right files. For example:

touch -d yesterday a
touch -d '2014-11-19 00:00:00' b
touch -d '2014-11-18 00:00:00' c
touch -d '2 days ago' d
ls -l

Gives:

-rw-r--r-- 1 janos users 0 Nov 19 12:35 a
-rw-r--r-- 1 janos users 0 Nov 19 00:00 b
-rw-r--r-- 1 janos users 0 Nov 18 00:00 c
-rw-r--r-- 1 janos users 0 Nov 18 12:38 d

And then:

$ find . -daystart -mtime 1 -type f
./a
$ find . -mtime 1 -type f
./a
./b


It looks fine to me.  My only real criticism is your checkCar implementation.  It ought to be written out as:

self.checkCar = ko.computed(function(){
    return !self.other();
});

On a minor note, you should case your view model name in PascalCase.  By making constructors like that, they stand out better.  Everything else should be in camelCase.

Other than that, you've made great use of the computed observables.  A big mistake I see a lot on Stack Overflow IMHO is when I see people putting all that logic in the view.

I might change the name of the properties however to be more descriptive of what they represent.  In particular, change checkCar to isSelectedCarOverridden.

Personally, I'd change it around a bit.  I'd add an "Other" option in the cars list and make the Other car input enabled/visible based on that value.

Also, consider making cars not observable. If this is going to be a fixed list and you won't be dynamically adding to it, making it observable may be unnecessary.  In fact, I'd pull that array out of the view model as it appears to be a constant value.  That way if you have multiple view models instantiated in the future, they all can share the same instance.

var constants = {
    cars: ["Chrysler", "Chevrolet", "Ford", "Lincoln"]
};

function ViewModel() {
    var self = this;
    self.cars = constants.cars;
    // ...
}