Print distinct car names with count in descending order

I'm sure that someone who knows more Python than me will be able to provide more feedback, but I see a couple of issues.

The first is that the core of this functionality is implemented by collections.Counter. We can just write this:

def frequency(lst):
    counter = Counter(lst)
    return reversed(sorted(counter.items(), key=lambda x:x[1]))

The second issue is with these lines:

item_list = [item.lower() for item in item_list]
item_list = [item.strip() for item in item_list]

We can just write

item_list = [item.lower().strip() for item in item_list]

Or as @janos suggested,

item_list = [item.lower().strip() for item in data.splitlines()]


Calculating the ranks of classmates' exam grades

in your checkRelativePrime method you have

static boolean checkRelativePrime(int a, int b) {
    int i = 2;
    while (a > 1) {
        if (a % i == 0) {
            {
                if (b % i == 0)
                    return false;
            }
            a = a / i;
        } else
            i++;
    }

    return true;
}

you have an extra set of brackets
you have a statement in purgatory.

a = a / i;

it sits in-between the ending bracket of your if statement and the else statement that is supposed to be attached to the if statement
if you use brackets for one part of an if statement, you should use them for the entire if statement. I recommend using brackets even for one-liners no matter what, it's cleaner and leaves less room for mistakes.

I think you wanted to keep that if statement separate from the declaration to the a variable, but you don't need to do that(especially if you are using brackets properly)

like this

while (a > 1) {
    if (a % i == 0) {
        if (b % i == 0) {
            return false;
        }
        a = a / i;
    } else {
        i++;
    }
}

if you enter that if statement and return false then a = a /i; will never happen and your boolean method will return false


csv is meant to store rows of data, not a simple dictionary. You can use json for that:

import json

# writing
json.dump(yourdict, open(filename, 'w'))

# reading
yourdict = json.load(open(filename))


Formatting date depending on current date

It's neatly formatted and follows standard naming-conventions. I found it easy to follow the logic.

I'm not sure why you switched from a String to a StringBuilder. It doesn't buy you anything, and makes the code more verbose. (If you did it as an optimization, the effort is misplaced. These days, Java compilers turn simple String concatenations into StringBuilder appends behind the scenes. In any case, even if you were doing this trillions of times in a tight loop, the possible savings from StringBuilder would be negligible compared to the time to format dates and whatever I/O you're doing).

Rather than using a static method, you could create an interface (e.g. DateRenderer) and one or more implementations. This would be a bit more object-oriented and more future proof. You wouldn't have to add the alwaysShowTime flag (or whatever future formatting options might be needed) to the interface, but have that knowledge in a specific implementation.

What is the foreign character string when daysDiff == 1? If it's not a typo, it might be worth writing a comment to explain, for people who can't read that language.

I'm not sure that TIME_TEMPLATE_TODAY is the right name, nor whether it is necessary. You don't use a constant for the other date/time formats in the method.


Convert carry-add loop to a map or reduce to one-liner

Your code has a lot of copying in it. In the default case (where direction is left) you copy the array three times. This seems like a lot. There are various minor improvements you can make, for example instead of

v = v[::-1]

you can write

v.reverse()

which at least re-uses the space in v.

But I think that it would be much better to reorganize the whole program so that you store your bignums the other way round (with the least significant word at the start of the list), so that you can always process them in the convenient direction.
The parameters direction and word_size are part of the description of the data in z. So it would make sense to implement this code as a class to keep these values together. And then you could ensure that the digits always go in the convenient direction for your canonicalization algorithm.

class Bignum(object):
    def __init__(self, word_size):
        self._word_size = word_size
        self._mod = 2 ** word_size
        self._digits = []

    def canonicalize(self, carry = 0):
        """
        Add `carry` and canonicalize the array of digits so that each
        is less than the modulus.
        """
        assert(carry >= 0)
        for i, d in enumerate(self._digits):
            carry, self._digits[i] = divmod(d + carry, self._mod)
        while carry:
            carry, d = divmod(carry, self._mod)
            self._digits.append(d)

Python already has built-in support for bignums, anyway, so what exactly are you trying to do here that can't be done in vanilla Python?

Edited to add: I see from your comment that I misunderstood the context in which this function would be used (so always give us the context!). It's still the case that you could implement what you want using Python's built-in bignums, for example if you represented your key as an integer then you could write something like:

def fold(key, k, word_size):
    mod = 2 ** (k * word_size)
    accum = 0
    while key:
        key, rem = divmod(key, mod)
        accum += rem
    return accum % mod

but if you prefer to represent the key as a list of words, then you could still implement the key-folding operation directly:

from itertools import izip_longest

class WordArray(object):
    def __init__(self, data = [], word_size = 8):
        self._word_size = word_size
        self._mod = 1 << word_size
        self._data = data

    def fold(self, k):
        """
        Fold array into parts of length k, add them with carry, and return a
        new WordArray. Discard the final carry, if any.
        """
        def folded():
            parts = [xrange(i * k, min((i + 1) * k, len(self._data)))
                     for i in xrange((len(self._data) + 1) // k)]
            carry = 0
            for ii in izip_longest(*parts, fillvalue = 0):
                carry, z = divmod(sum(self._data[i] for i in ii) + carry, self._mod)
                yield z
        return WordArray(list(folded()), self._word_size)


Looking for meta data which matches certain criteria and was created after a certain date

Suggest staring with this:

AND `meta_id` IN
        (SELECT SUBSTRING_INDEX(`meta_value`, '!', 1)
         FROM `wp_postmeta`
         WHERE `meta_key`
         LIKE 'wpcf-post-like-date-link'
         ORDER BY `meta_id`
         DESC)

LIKE text searching, sorting with the ORDER, additional subquery on the same wp_postmeta table are sources of the lengthy query execution. Rewriting subqueries as joins


Querying nearest city with a given shop using latitude and longitude is slow

I think there's three big things you might be able to do to improve the performance of this.

Write your query such that it doesn't need to execute the subquery for each line and/or have a HAVING clause by using an inner join which will automatically exclude those with no match.
Use ST_Distance_Sphere(POINT(:longitude, :latitude), POINT(cities.longitude, cities.latitude) to get the distance using a built in function that'll probably be faster than anything you can calculate outside of one.
If you're looking for the singular closest entry it may be worth using half of the maximum distance between two points as a cut off and excluding anything by default where the long or lat is outside of the given range and would thus never be the closest entry.
For example if the largest distance between two cities is 1,600 km you know for sure that no city outside of 800 km in any direction can ever be the closest; At 70N about the north end of Canada that equates to ~21 points of longitude anything outside of your passed in longitude +- 22 can be immediately ignored. The same rule can be applied to latitude to ignore everything outside of +/- 7.

You'll still have to check everything in those ranges, but it'll be very quick to run and if it reduces the amount of slow work required to be run it's worth it.

SELECT
    cities.id,
    cities.city,
    cities.city_url,
    COUNT(DISTINCT shops.id) AS totalshops,
    ST_Distance_Sphere(POINT(:longitude, :latitude), POINT(cities.longitude, cities.latitude) AS distance
FROM cities
JOIN shops
    ON
    shops.city_id = cities.id
JOIN shop_categories
    ON
    shop_categories.shop_id = shops.id
WHERE
    shop_categories.category_id = :catId
    AND
    cities.longitude BETWEEN :longitude - :max_long_distance AND :longitude + :max_long_distance
    AND
    cities.latitude BETWEEN :latitude - :max_lat_distance AND :latitude + :max_lat_distance
GROUP BY
    cities.id
ORDER BY
    distance ASC
LIMIT 1
;

PS: I assumed for the GROUP BY clause you're not running with the strict grouping mode enabled. If that's not the case you'll need to add the other columns from cities that are references like the cities.city, cities.city_url, cities.longitude and cities.latitude.


Does this class-adding slow page rendering?

It's slow for the following reasons:

You're using find() which is a descendant lookup. jQuery will look for all descendants under an element and see if it's a match. If the DOM under that element is huge... you get the picture.
Additionally, you aren't really specific here. You just give it div, which makes it all the more so generic. There could be lots of <div> under that element.

What you can do:

If these elements you have are just children of #menu, then use children() which is just  searches one level down.
If the set you have contains the elements you want plus siblings, and they are in order, then you can do slice() instead. Slice is zero-indexed by the way.

$('#menu').children('div').slice(1,6).addClass("menuDivs");

Here's a demo


Find all combinations of a number sequence which is first increasing then decreasing

Bug

Input : 500000003
Output: 18446744073709551615

The problem is that the result of your power() call could be 0 or 1.  Then when you subtract 2, you get a negative number.  Given the input constaint of \$n ≤ 10^9\$, 500000003 is the only bad input, but in general this happens when n is any multiple of 500000003.  To correct this, you could change this:

temp--;
temp--;

to:

temp = (temp + m - 2) % m;

This ensures that temp will remain positive.  Time complexity wise, your program is great at \$O(\log n)\$.


Find the shortest & best starting move in Mancala (Kalah)

Kind of surprised no one else has offered constructive criticisms.  Let's get the ball rolling.  Keep in mind I don't know anything about Mancala.

Overall code organization could be better.  Rather than static methods in Program2 class, I would go with separate class(es).  I suggest you review posts on Tic-Tac-Toe, where multiple classes are used for the board versus players versus moves.

There are a lot of magic numbers in the code: 5, 6, 12, 13, and 24 to name a few.  I'd suggest using named constants or else change the code a bit, e.g. if 6 is a named constant, sometimes use < Constant instead of 5, and <= Constant for 6.  As it is, it gets confusing for someone to follow your logic.

initialState.ToArray() is totally unnecessary, unless you are trying to have a independent clone.  Your intent is not apparent from the code.  And I find that true about much of your code.  It's hard to follow your intent.

You may consider using List instead of the combination of arrays and IEnumerable.

The ValueTuple pair named (seq, count) has a few issues.  I think the spelling should be Pascal-cased, with seq spelled out as Sequence.  Plus, count seems confusing.  It's not the count of the associated sequence but rather seems to the the point tally of the sequence.  Thus I would rename count to Points.

I would rather use a class than ValueTuple.  You can have a variety of constructors, plus:

Override ToString() to simplify the 2 times you use it in Main.
Create specific methods to compare 2 instances for shorter sequence length or higher point tally.  This may require implementing IEquatable or IComparable.


First of all, Welcome to CodeReview!

Let's analyse the code to see what could be improved here.

current_Time = strftime("%H")
print current_Time
# convert str to number
cTime = int(current_Time)

A few things could be improved here:

Too many calls! current_Time = int(strftime("%H")) would have sufficed
the comment # convert str to number adds no real value to the code readability

s = smtplib.SMTP('smtp.gmail.com', 587)

Use better names, s does not make it clear what it does.
Avoid "magic" numbers-- it would have been better to have these as named constants

f = open('Readme.md', 'r')

Use context managers (with open ... as ...), see the docs

Some random thoughts

Use guards-- that way your script can be imported by other modules. Might not need it here, but I think it is good practice to always use them.
Consider upgrading your python-2.7 to python-3 and port all your code, since the Python 2 End Of Life is just 2 years away!


Building on the comments made by h.j.k., you forgot to handle one case in your implementation: the case when the bigger list has a count of a number n that is less than the count for that number n for the smaller list. For example, if you consider the following:

public static void main(String[] args) {
    List<Integer> all = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 4, 5, 5));
    List<Integer> incomplete = new ArrayList<>(Arrays.asList(1, 1, 1, 2));
    System.out.println(identifyMissingNumbers(all, incomplete));
}

It will print with your current code [3, 4, 5] disregarding 1 as a missing number although it should be missing since it does not appear with the same frequency in both lists.

The reason is that you're iterating on the number in the bigger list, removing them from the smaller list as you encounter them and adding them to the missing number when you finally don't find a match. But if the smaller list as a bigger count for that number, it won't be taken into account.

There are a couple of possibilities to tackle this: you could introduce a new loop that would have the same logic but iterating on the smaller list instead and removing elements from the bigger list.

I find a better approach would be the following:

Sort each input list in ascending order
Create an empty Map<Integer, Integer> that will store the count for each number
Iterate over the first list. If the number if not in the Map, add it with a value of 1. Else, increment the current count by 1.
Iterate over the second list. If the number if not in the Map, add it with a value of -1. Else, decrement the current count by 1.
At this point, all values in the map that are different than 0 are missing numbers: since we added 1 when encountered in the first list and subtracted 1 when encountered in the second list, the result must be 0 if that number is not missing. Hence, we remove all entries in the map where the value is 0.
Finally, we return the keys of the map in ascending order.

Assuming Java 8, an implementation would be the following:

public static Set<Integer> identifyMissingNumbers(List<Integer> list1, List<Integer> list2) {
    Map<Integer, Integer> count = new HashMap<>();
    for (Integer number : list1) {
        count.merge(number, 1, Integer::sum);
    }
    for (Integer number : list2) {
        count.merge(number, -1, Integer::sum);
    }
    count.values().removeIf(i -> i == 0);
    return new TreeSet<>(count.keySet());
}


In my opinion, Maybe is too cumbersome here.  I'd consider fib (-1) to be ill-defined, and I'd let it just crash with an error.

By your convention, the Fibonacci sequence is

  1, 2, 3, 5, 8, 13, …

I would prefer to see it start earlier, such that fib 0 is 0:

  0, 1, 1, 2, 3, 5, 8, 13, ….

The outputs can get pretty big.  I suggest using Integer instead of Int.

You're using a very convoluted way to extract the nth item from a list.

Suggested solution

import Data.List (iterate)

fib :: Int -> Integer
fib n = fst $ sequence !! n
  where
    sequence = iterate (\(x, y) -> (y, x + y)) (0, 1)

You could also use the point-free style:

fib :: Int -> Integer
fib = (!!) $ map fst $ iterate (\(x, y) -> (y, x + y)) (0, 1)

For that matter, you could just define the infinite sequence

fibonacciSequence = map fst $ iterate (\(x, y) -> (y, x + y)) (0, 1)

… and let the caller do whatever they want with it, including extracting specific entries using !!.

Behaviour

*Main> fib (-1)
*** Exception: Prelude.!!: negative index
*Main> fib 0
0
*Main> fib 1
1
*Main> fib 2
1
*Main> fib 3
2
*Main> fib 4
3
*Main> fib 5
5


This isn't a bad approach - simple, effective, and gets the job done. It could be ever-so-slightly better, though.

First, string concatenation (str1 & str2, str1 + str2) in .NET has been known to be extremely slow at times, due to extra allocations. (Basically, str1 + str2 + str3 + str4 creates a temp string str12, then creates another temp string str123 and then creates a final string str1234. Doing this in a loop means that it creates a temp string returnStringStr1234 then sets returnString to that, and then repeats all four of these new allocations for each iteration, at a minimum.) There's something in the framework called StringBuilder, and I'd like to recommend you look into it.

I should also mention that we also use StringBuilder from a semantics point of view: instead of wondering what returnString does (is it a bunch of sub-strings, is it just one string being set by a certain loop iteration, etc.) we have something that indicates that our return value should be building a string. Everything starts to make sense.

Essentially, the StringBuilder has a sort of internal buffer that, instead of creating a new copy of the strings, it just adds the strings together. This also exposes a few useful properties, one of which being Length, which can be increased or decreased, removing the need for Left(...).

Dim result As New StringBuilder()
For Each kvp in oParameters
    result.Append(kvp.Key).Append("="c).Append(kvp.Value).Append("&"c)
Next
result.Length -= 1
Return result.ToString()

This is only one line-of-code longer than your version, but it should perform more quickly and is also clearer about what the last step is (remove the last character). Of course, an alternative implementation that avoids manipulating the StringBuilder like that might look like:

Dim result As New StringBuilder()
For Each kvp In oParameters
    If result.Length > 0 Then result.Append("&"c)
    result.Append(kvp.Key).Append("="c).Append(kvp.Value)
Next
Return result.ToString()

In this situation we test if the Length is > 0 to see if it already has an element. If so, we append the ampersand ("&"c) and continue on. Now we don't need to worry about the last character being an ampersand at all.

I've used a couple constructs that may be unfamiliar to you:

The If expression Then statement is a single-line If statement. It must be on one line (unless in a line-continuation context) and will do the same thing as If expression Then <NEWLINE> statement <NEWLINE> End If, but is much more succinct. I use them for guard-clauses like this a lot.
The "_"c construct creates a character literal from the specified string (which should be one character only). The c is the magic bit, you can remove it from everything if you like.

I would also recommend adding the explicit type for your kvp:

For Each kvp As KeyValuePair(Of String, String) In oParameters
    ...
Next

This makes it much more clear to the compiler as to what type you expect, and tells future programmers that you do know what you're doing.

Overall, good work. Hopefully this is somewhat educational for you and not just a bunch of random nonsense. :)


Measuring a given method's execution time

The thing you're timing is:

while (watch.Elapsed.Milliseconds < precision*(100-error))
{
    action();
    ++iterations;
}

The problem is that if action takes a very short time, then most of what you're timing is the time it takes to call the watch.Elapsed.Milliseconds property.

A more accurate timer would be something like:

int iterations = 1000;
watch.Restart();
while (iterations--)
{
    action();
}
watch.Stop();

You would then need to do something to ensure you pick a suitable number of iterations (e.g. try again with 10 times as many iterations if the measured time is too short to be accurate).


Defining the same connection multiple times can be avoided, and also, putting everything in try/catch serves no purpose if the only thing you do in the catch is displaying the message which would be displayed anyway with the error reporting mode you set on the $conn

I also find that naming PDOStatements can help a bit for readability, instead of always using $stmt. Here it all happens in few lines, but sometimes, using a prepared statement far away in the code can be easier if they have significant names.

Doing this, I noticed your clockIn PDOStatement is done twice. Since the if prevents it from happening twice, it's OK, but perhaps you could find some use in preparing your PDOStatements outside of loops, then executing them in the loops.

<?php

session_start();
//require 'functions.php';
//require 'DB.php';
$employeeID = $_SESSION['employeeID'];
$clockIn = $_GET['clockIn'];
$clockOut = $_GET['clockOut'];
$timeToday = date("g:i a");
$dateToday = date("m/d/y");
$jobDescription = $_GET['jobDesc'];
$equipType = $_GET['equipTypeRan'];
$unitNumber = $_GET['unitNumber'];
$unitHours = $_GET['unitHours'];

$conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$putClockIn = $conn->prepare('INSERT INTO timeRecords (employeeID, date, timeIn) VALUES (:employeeID, :dateToday, :timeIn)');

if (isset($clockIn)) {
    echo "You clocked in at: " . $timeToday . " on " . $dateToday;
    $putClockIn->execute(array(
        ':employeeID' => $_SESSION['employeeID'],
        ':dateToday' => $dateToday,
        ':timeIn' => $timeToday
    ));
    $conn = null;
} else {
    if (isset($clockOut)) {
        $putClockOut = $conn->prepare('UPDATE `timeRecords` SET `timeOut`= :timeOut WHERE `date`= :dateToday AND `employeeID`= :employeeID');
        $putClockOut->execute(array(
            ':employeeID' => $_SESSION['employeeID'],
            ':dateToday' => $dateToday,
            ':timeOut' => $timeToday
        ));
        $getTimeIn = $conn->prepare('SELECT `timeIn` FROM `timeRecords` WHERE `date`= :dateToday AND `employeeID` = :employeeID');
        $getTimeIn->execute(array(':employeeID' => $_SESSION['employeeID'], ':dateToday' => $dateToday));
        //$getTimeIn->setFetchMode(PDO::FETCH_BOTH);
        $results = $getTimeIn->fetch(PDO::FETCH_BOTH); // no need to set a mode for stmt if you ain't using it anywhere else, pass it directly in fetch()
        $timeInDB = $results[0];
        $time_one = new DateTime($timeInDB);
        $time_two = new DateTime($timeToday);
        $difference = $time_one->diff($time_two);
        echo "You clocked in at: " . $timeInDB . "
";
        echo "You clocked out at: " . $timeToday . "
";
        echo $difference->format('Total working time %h hours %i minutes');
    } else {
        $getCurrentSessions = $conn->prepare("SELECT COUNT(*) FROM timeRecords WHERE `timeOut` IS NULL AND `employeeID`= :employeeID AND `date`= :dateToday");
        $getCurrentSessions->execute(array(':employeeID' => $employeeID, ':dateToday' => $dateToday));
        if ($getCurrentSessions->fetchColumn() > 0) {
            $closeSession = $conn->prepare('UPDATE `timeRecords` SET `jobDescription`= :jobDescription, `equipType`= :equipType, `unitNumber`= :unitNumber, `unitHours`= :unitHours,
                                `timeOut`= :timeOut WHERE `employeeID`= :employeeID AND `date`= :dateToday AND `timeOut` IS NULL');
            $closeSession->execute(array(
                ':employeeID' => $employeeID,
                ':timeOut' => $timeToday,
                ':dateToday' => $dateToday,
                ':jobDescription' => $jobDescription,
                ':equipType' => $equipType,
                ':unitNumber' => $unitNumber,
                ':unitHours' => $unitHours
            ));
            $putClockIn->execute(array(
                ':employeeID' => $employeeID,
                ':dateToday' => $dateToday,
                ':timeIn' => $timeToday
            ));
            echo "There was an update";
        } else {
            echo "There was no Match";
        }
    }
}

require 'summary.php';


You can get rid of the redundancy by using the EntityState. You first try to get the SaveCount. Then based on this value you set the State either to Added or Modified. Something like this should work:

    var companySaveCount = await con.Companies.SingleOrDefault(x => x.ID == model.ID)?.SaveCount ?? 0;

    var company = new Company
    {
        ...
        SaveCount = saveCount + 1
    };

    var companyExists = companySaveCount > 0;
    con.Entry(company).State =
        companyExists
            ? EntityState.Modified;
            : EntityState.Added;
    }

    await con.SaveChangesAsync();

Alternatively the first query could be just:

var companySaveCount = await con.Companies.Where(x => x.ID == model.ID).Select(x => x.ID).SingleOrDefult();

so that you don't have to get the entire object.


Comments and good docstrings would go a long way. Obviously if I was familiar with the algorithm I'd understand easier, but you're not helping a lot with your naming. Why are you using _cur and cur? Do you just want to use the same name twice without clashing? If so you should do it another way, because _var is the Python style of indicating a variable that should be treated as private and not modified externally. It's an idiom for classes and looks out of place here.

Even still, cur, nex mean current and next, right? As you noted you shouldn't use next because it's a builtin name, but using next_branch or something more descriptive is better than stripping away a letter. Also if I've got the wrong end of the stick and nex is something else, that also just means you need a better shortened word or a comment explaining what nex is.

Also more whitespace will make the flow of your code easier to read than a solid block of text:

def sub(visited, _cur, graph):
    if not graph:
        return visited + [_cur]

    for i, edge in enumerate(graph):
        cur, nex = edge
        if _cur not in edge:
            continue

        _graph = graph[:]
        del _graph[i]

        if _cur == cur:
            res = sub(visited + [cur], nex, _graph)
        else:
            res = sub(visited + [nex], cur, _graph)

        if res:
            return res

Even before adding code and more readable names, this breaks up what's happening so a reader can parse it easier.


Even though the difference is minimal, there IS a difference. So you'll need to make a minimal distinction, depending on the button that was pressed.

What you could do is create a general event for all the buttons and in that event you'll determine the index to be passed to the AddItem() method. The code might look like this:

private void ButtonClick(object sender, EventArgs e)
{
    Button b = (Button)sender;

    switch(b.Name)
    {
        case "button9" : AddItem(buttonNames[0], prices[0]); break;
        case "button14" : AddItem(buttonNames[1], prices[1]); break;
        case "button5" : AddItem(buttonNames[2], prices[2]); break;
        //other buttons...
    }
}

Another solution is to pre-assign the index to the Tag property of your button:

button9.Text = buttonNames[0];
button9.Tag = 0;
//Same for other buttons

This way you can also use a general method like before and use the tag to call the AddItem() method. Like this:

private void ButtonClick(object sender, EventArgs e)
{
    Button b = (Button)sender;
    int index = Convert.ToInt32(b.Tag);
    AddItem(buttonNames[index], prices[index]);
}

Lastly, if you name your buttons in a different way, it will become even more easy to do this. Place the index to be used in the name of the button and get it from the name in the general event. Example:

//Assignment of the buttons:
button0.Text = buttonNames[0];
button1.Text = buttonNames[1];
button2.Text = buttonNames[2];

//Event:
private void ButtonClick(object sender, EventArgs e)
{
    Button b = (Button)sender;
    int index = Convert.ToInt32(b.Name.Replace("button", ""));
    AddItem(buttonNames[index], prices[index]);
}

Hope this helps!


Updating an offset in a buffer after each read

I tend to agree with your colleague - magic numbers are nearly always bad. In this case, it is clear why you are adding 4, but only once I've done 32/8 in my head.

Extracting this constant into a bytesIn32Bits would certainly be helpful for me and other developers who don't work on the byte level very often.

However, I don't believe this is the ideal solution. Though the code itself isn't really that repetitive, the logic is.

Read data
Advance offset by length of data

Unfortunately Node does not have a built in Buffer alternative which can keep track of an offset for you. You could do this with functions as shown in the edit, but it would be better to handle at the class level as you can then completely forget about the offset in most cases.

Ideally, the function should read something like this:

function readMessage(data: OffsetTrackingBuffer) {
    let firstLen = data.readInt32LE();
    let firstPieceOfMessage = data.readString(firstLen);
    let secondLen = data.readInt32LE();
    let secondPieceOfMessage = readString(secondLen);

    let finalMessage = firstPieceOfMessage + secondPieceOfMessage;
    return finalMessage;
}

The outer loop would also be slightly changed:

let data = new OffsetTrackingBuffer(rawData, 0);
while (data.offset < data.length) {
    let message = readMessage(data);
    console.log(message);
}

I'm not normally one to recommend adding libraries to your project, but in this case, all this logic has already been implemented in the smart-buffer npm package. According to the readme it also comes with TypeScript typings built in. I haven't used it, but it seems to be rather popular.


One possible inefficiency is that you are copying the array when you call the function.  If you pass parameters by reference, then you could avoid allocating and copying the array.  See the difference in these two functions that just perform one swap:

function f($a) {
    $swap = $a[0];
    $a[0] = $a[1];
    $a[1] = $swap;
    return $a;
}

function g(&$a) {
    $swap = $a[0];
    $a[0] = $a[1];
    $a[1] = $swap;
}

$xyz = array('x', 'y', 'z');
print_r($xyz);                  # array { [0] => x  [1] => y  [2] => z }
$yxz = f($xyz);
print_r($xyz);                  # array { [0] => x  [1] => y  [2] => z }
print_r($yxz);                  # array { [0] => y  [1] => x  [2] => z }
g($xyz);
print_r($xyz);                  # array { [0] => y  [1] => x  [2] => z }

That aside, there is not that much you can do to optimize your two sorting algorithms.  You could try obtaining the length count($sort_array) just once, before the loop, to see if makes any difference.

The important thing to note, though, is that both insertion sort and selection sort are O(n2) algorithms.  That means that if you double the size of the array, it will take approximately quadruple the amount of time to complete the sort.  If you care about performance when sorting large lists, you don't use insertion sort or selection sort.  You pick a more efficient algorithm that tends to work in O(n log n) time, such as quicksort.

Comparing performance across languages is not a very useful way to judge the quality of your code.  To make a comparison that is at least somewhat fair, try racing against PHP's own array_sort() function.


Working on key-value disk cache written in plain C. Is there any errors?

size_t pathLength = strlen(cache->path) + strlen(key);
char *path = malloc(pathLength);
strcpy(path, cache->path);
strcat(path, key);

Try this instead:

size_t path_len = strlen(cache->path);
size_t key_len = strlen(key);
size_t total_len = path_len + key_len + 1;

char *path = malloc(total_len);
if (!path) { /* TODO: handle error */ }

mempcy(path, cache->path, path_len);
memcpy(path + path_len, key, key_len + 1);

This is better for the following reasons:

Your malloc call does not account for the extra 0 byte (also called NUL terminator) that must end C strings.  You repeat this mistake in a bunch of other places.  (To reiterate: if your string is size len, allocate len + 1 and set the last byte to 0.)
strcat will recompute the length of the string at runtime, by searching for that NUL character.  This is bad.  Every concatenation will lead to another traversal, leading to an O(n2) kind of curve when concatenating lots of strings.  I see the use of strcat in pretty much any code as a sort of red flag.
malloc can fail.  Check your return codes.  A large part of writing good C code is being able to answer the question: "how does this code fail?"  I feel like a lot of higher-level coders (usually Java and C#, but these days also objC) seem to fail to grasp this and code rather "optimistically" instead.

Error handling in C looks very ugly when done poorly, but if there is a general approach to coding style it can work elegantly..  The trick I like to use is to make your failure paths mostly the same as your success cases.  This typically means that there's a part of each function that does "cleanup" - deallocates everything you've allocated, releases whatever's been acquired, etc.  Kind of like the RAII pattern in C++ where your locally-declared quantities will do their cleanup in a destructor.  This would get run regardless of success or failure.  If some allocation or resource acquisition outlives the function, then make the success case be the special case, because this will ultimately allow you to make more fluid code modifications vis-a-vis complex error handling.  In case I'm writing too abstractly, an example of this would be:

void *frob(int num_frobs)
{
   void *buf = malloc(/* ... */);
   void *r = buf;   /* Let's say this will be non-null on success cases. */

   if (r && !do_frobbing(buf, num_frobs))
   {
      /* do_frobbing failed! */
      r = NULL;
   }

   if (r && !additional_frobs(buf))
   {
      /* more failure! */
      r = NULL;
   }

   if (r)
   {
      /* success, make sure not to free the buffer on the way out */
      buf = NULL;
   }

   /* clean up*/
   free(buf);

   return r;
}

OK, that's a really goofy-looking example...  But here you see that these blocks inside if (r) are really composable.  In between each of them you can add and remove more operations that can potentially fail, and your cleanup block handles releasing resources in event of either success or failure.  If you're working in C++ this would be done via RAII wrappers, i.e. in destructors of classes and possibly with throw or an early return.  But C has no such features to make that easy and correct...

Moving on to other code:

return (CacheRef)cache;

This cast is suspicious.  If I read your typedef correctly, all this does is adds an extra const.  This means the cast is totally unnecessary.  (Another general rule for anal-retentive types such as myself, by the way: casts are suspicious, especially with pointer types.  If you can make your code work without casts it's always better.)  I would say in general you don't need this typedef.

 FILE *_FileForKey(CacheRef cache, const char *key, const char *access)

Technically the C standard says you can't name things with leading underscores.  In practice your compiler will let you get away with it anyway.  But personally I think it looks weird.  If your intention is to hide internal functions from the outside would I suggest you declare them with static and/or add some prefix to their names.

Speaking of names, this brings me to another point...  I would work on better and consistent naming conventions.  Overall I would strive to have someone be able to read the header, as well as code that calls your library, and have some clue what the functions do.  In C it's common to prefix functions from a given library or module with some common name, i.e. having to do with the type.


What you did well

Storing sensitive information, such as the database connection parameters, separately from the source code is a good idea.
You used parameterized queries with placeholders, which are not vulnerable to SQL injection.

Things to work on

Your indentation is inconsistent.
tryconn() should not echo 'ok' on success, as that pollutes the output.
$a is a horrible name for your database handle.  It's conventionally called $db or something like that.


Returning a NumPy array (or list) of strings of words repeated N times

It would seem you're doing it the right way. One thing though: you might want to replace the following piece of code:

[[x[i]]*b[i] for i in range(len(x))]

A few points as to how you could improve this:

I suggest you use zip to iterate over two arrays simultaneously.
Also, prefer using () over [], since it creates a generator expression, rather than a list.
A similar argument holds with the construct join([ ... ]). Simply use join( ... ) instead, which would avoid creating the list in memory.
Better variable names will also help with clarity.

([s] * count for s, count in zip(strings, counts))

Finally, formatting can make loads of difference:

import numpy as np

strings = ['yugoslavia', 'zealand', 'zimbabwe', 'zip', 'zone']
counts_array = np.array([[2,1,0,0,5], [0,0,1,3,0]])
result = np.apply_along_axis(
    lambda counts: ' '.join(item for sublist in
                                ([s] * count for s, count in zip(strings, counts))
                            for item in sublist),
    1, counts_array)

An equally ugly alternative might involve using two join statements:

result = np.apply_along_axis(
    lambda counts: ' '.join(filter(None,
                  (' '.join([s] * count) for (s, count) in zip(strings, counts)))),
    1, counts_array)

Note how I've had to use filter, as per this question, in order to remove the extra spaces emanating from the empty strings.


Method to read the number of lines in a web page

There are a bunch of things which you should consider revising, including the basic concept itself.

Here your concept is to read each line from the URL, count it, and throw it away. Your code does nothing with the data? What's the point?

Regardless, even if the sole purpose of the code is to count a URL's lines, the code should be revised to take advantage of Java Best practices.

First up, it's a cheap shot to treat the new URL(...) constructor the way you do. Yes, it throws a MalformedURLException, and yes, that is a subclass of an IOException, but they really should not be lumped together.

Your method is listed as throwing an IOException anyway, so why handle the exception inside the method and throw nothing? The calling code will need to handle the IOException anyway. Just throw the exception and be done.... but also throw the MalFormedURLException.

Next try-with-resources is your friend. Resources treated that way will not need the finally block at all.

Finally, Java 8 does have some fantastic InputStream-to-Stream methods, use them. Specifically, the BufferedReader.lines() method:

Your code could be something like:

private static int countPageLines(String url) throws IOException {
    URL page = new URL(url);
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(page.openStream()))) {
        long count = reader.lines().count();
        return count > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)count;
    }
}

As a side note, you have tagged your question with performance. The limiting factor here in terms of performance is your network... I cannot suggest a way to make your code above improve the performance of your network without knowing more about your setup ;-)


Fuzzy Humanize date using Moment.js for datatable searching

What if you have three functions that each calculate the string on its own? Therefore:

function days_diff(daydiff) {
  if (daydiff==0) return 'Today'
  if (daydiff==1) return 'Tomorrow'
  if (daydiff==-1) return 'Yesterday'
  return null
}
function weeks_diff(daydiff) {
  if (daydiff > 0 && daydiff < 7) return 'Thisweek'
  if (daydiff < 7) return 'Nextweek'
  return null
  ...

Then you can have your one aggregate function that calls the three of them...

Here's the much more complicated one from Rails that might provide guidance/inspiration: https://github.com/rails/rails/blob/2c97fbf6503c9199f3fe5ed06222e7226dc6fcd9/actionview/lib/action_view/helpers/date_helper.rb#L104


Checking and returning Xml from a byte array

Why not verify if a root node exists rather than check for a '<' ?

    public bool GetRootNode(XmlReader reader)
    {
        bool isValid;
        try
        {
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    isValid = true;
                    break;
                }
            }
        }
        catch (XmlException x)
        {
            throw new XmlException(x.Message);
        }

        return isValid;
    }

You could also use the chain of responsibilities pattern to determine which parser you want to use.

EDIT

Not sure if this will work, but here is an example on using the above code:

protected bool TryGetXElement(byte[] body, out XElement el)
{
    el = null;
    // if there is no data, this is not xml :)
    if (body == null || body.Length == 0)
    {
        return false;
    }

    try
    {
        // Load the data into a memory stream
        using (var ms = new MemoryStream(body))
        {
            using (var sr = new StreamReader(ms))
            {
                XmlReaderSettings settings = XmlReaderSettings { CheckCharacters = true; };
                using(XmlReader reader = XmlReader.Create(ms, settings))
                {
                    if (!GetRootNode(reader))
                    {
                        return false;
                    }
                    else
                    {
                        // ultimately, we try to parse the XML
                        el = XElement.Load(sr);
                        return true;
                    }
                }
            }

        }
    }
    catch
    {
        // if it failed, we suppose this is not XML
        return false;
    }
}


I think that you are going about this the wrong way. Rather than thinking of what you should remove, you should think of what you should match.

You are only allowing zero to two digits before a decimal place and so you can use the pattern \d{0,2}.

To include a decimal place you can use the pattern \.?.

And finally you can include zero to four numbers after the decimal place with the pattern \d{0,4}.

If you were to merge these together you will end up with \d{0,2}\.?\d{0,4}.
This has the problem of matching both fullstops, and numbers 6 digits long.

To amend this you can can use the or operator (i.e. |) but you will need to duplicate your regex.
And can result in \d{0,2}\.\d{0,4}|\d{0,2}.?|.?\d{0,4}.

As an alternate to this you can thank that you only include the second half if there is a decimal, and limits the input to two numbers rather than four. Via \d{0,2}(\.\d{0,4})?.

Both the above patterns have their pros and cons. Now you want to match these and so you don't want to use replace. This gives you the option of exec or match. I'd use match due to the simplicity. As you always want the first match and this will always return a match you can simply use something like str.match(//)[0].

This can result in:

$(function() {
  $('input').on('input', function() {
    this.value = this.value.match(/\d{0,2}(\.\d{0,4})?/)[0];
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

This has the problem that, if you enter 12.1234 and then change it to 123.1234 it'll be replaced to 12.
This is as you want it to ignore all numbers after the first two and match the decimal and the last four.
To explain this with the demonstration of capture groups you want (12)3(.1234) and then you'd just join them together.
To achieve this you will want to add capture groups to the above, and use a non-capture group to get empty strings, so (\d{0,2})((?:\.\d{0,4})?).
This doesn't capture the 3, and so to add this we'll need to capture everything apart from a decimal point. [^.]*.
Put this in the above function and you should get what you want. (\d{0,2})[^.]*((?:\.\d{0,4})?).
To properly use this we'll need to use exec rather than match too.

The other problem with the above is as 200_success says:

  For example, if you type 12 into the text field, then place the cursor before the 1, and press x, your code is able to discard just the x.
  Joe's answer, on the other hand, discards the x and everything after it.

You can change the single regex to account for this input x12.
But it won't work with 1x2 either.
To account for this we can use your first replace to limit the input to just numbers and decimals.

And, without adding 200_success' position stuff, should result in:

$(function() {
  $('input').on('input', function() {
    match = (/(\d{0,2})[^.]*((?:\.\d{0,4})?)/g).exec(this.value.replace(/[^\d.]/g, ''));
    this.value = match[1] + match[2];
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

This as far as I can tell works exactly as yours does.
But there is one difference, that I don't think you really want.
If you copy and paste 1234.12345678 into both my input and yours they're different.

Mine results in 12.1234, where yours results in 124.1234678.


Generate 2D array with set amount entries

boolean finished = false;
while (!finished) {
    finished = true;

    // check columns
    for (int x = 0; x < width; x++) {
        if (generateTargetColumn(x, width, height, targetNumbers)) {
            finished = false;
        }
    }

    // check rows
    for (int y = 0; y < height; y++) {
        if (generateTargetRow(y, width, height, targetNumbers)) {
            finished = false;
        }
    }
}

We're working with booleans here. I can directly assign the result to the variable...

boolean finished = false;
while (!finished) {
    finished = true;

    // check columns
    for (int x = 0; x < width; x++) {
        finished = !generateTargetColumn(x, width, height, targetNumbers) && finished;
    }

    // check rows
    for (int y = 0; y < height; y++) {
        finished = !generateTargetRow(y, width, height, targetNumbers) && finished;
    }
}

There's a lot of negations in here, so maybe we can flip the variable's meaning and get clearer code?

boolean busy = true;
while (busy) {
    busy = false;

    // check columns
    for (int x = 0; x < width; x++) {
        busy = generateTargetColumn(x, width, height, targetNumbers) || busy;
    }

    // check rows
    for (int y = 0; y < height; y++) {
        busy = generateTargetRow(y, width, height, targetNumbers) || busy;
    }
}

Sure, but "busy" is not really what we're looking for, after all, you say that

@return returns true if the column/row is regenerated.

So we should change the name to "gridChanged" or something like that.

boolean gridChanged = true;
while (gridChanged) {
    gridChanged = false;

    // check columns
    for (int x = 0; x < width; x++) {
        gridChanged = generateTargetColumn(x, width, height, targetNumbers) || gridChanged;
    }

    // check rows
    for (int y = 0; y < height; y++) {
        gridChanged = generateTargetRow(y, width, height, targetNumbers) || gridChanged;
    }
}

But now you have this weird thing where at the start, you say "I had changes", which seems wrong... and you always want to go in the loop at the start. So convert it to a do-while:

boolean gridChanged = true;
do {
    gridChanged = false;

    // check columns
    for (int x = 0; x < width; x++) {
        gridChanged = generateTargetColumn(x, width, height, targetNumbers) || gridChanged;
    }

    // check rows
    for (int y = 0; y < height; y++) {
        gridChanged = generateTargetRow(y, width, height, targetNumbers) || gridChanged;
    }
} while(gridChanged);


Simple application in Python using OpenCV for face

Some notes only:

Instead of

(_, im) = webcam.read()

is more common not to use parentheses:

_, im = webcam.read()

(and similarly in other places of your code).

Too many blank lines. In the PEP 8 - Style Guide for Python Code repeatedly occurs the word "sparingly" for the Blank Lines usage.

(Correcting English only):

Instead of

print("Webcam is open? ", webcam.isOpened())

use

print("Is the webcam open? ", webcam.isOpened())

Magic numbers in your code, as in this statement

if key == 27:

Why not use names for such constants, e. g.

ESC_KEY = 27               # Near the start of your code
...
...
if key == ESC_KEY:


Use callback style to start a worker thread and receive result in Qt

This answer seems to be what you are looking for. I copy it here for reference:

There is this library that is highly integrated with Qt and implements javascript-like promises:

https://github.com/juangburgos/QDeferred

It allows to create a thread-safe async API as follows:

multiplyNumbersInThread(3, 4)
.fail([](int res) {
    Q_UNUSED(res);
    qDebug() << "multiplyPositiveNumbers failed!";
})
.done([](int res) {
    qDebug() << "multiplyPositiveNumbers succeded! Result :" << res;
});


Help optimizing a function to count the rows in a textarea

What kind of performance are you getting?  Is it acceptable.  If it's not, then I'd look for changing your algorithm, and not minor tweaks.  In particular, I'd look into NOT splitting the string and recalclating each time.  Instead keep track of the state (what line and the number of characters on that line, whether it's a paste or a delete), and do the right thing based upon that.  Adding an additional character at the end of a 5k block of text, adds one more line at most, if the last line was 1 character long, then unless the key being pressed is the enter key, it doesn't even do that.

But before doing anything, sit down and see how well your existing function works, for your typcial data, and then for some extreme data.


Using itertools.groupby
What you are looking for is itertools.groupby. When there is an odd number of groups then we use try-except block here.
from itertools import groupby

get_grp_len = lambda grp: len([*grp])

def transform(b):
    if len(b) == 0:  # if not b wouldn't work since your `b` is ndarray
        return []
    it = groupby(b)
    out = []
    for _, grp in it:
        try:
            t_size = get_grp_len(grp)
            f_size = get_grp_len(next(it)[1])
            out.append([t_size, f_size])
        except StopIteration:
            out.append([t_size, 0])
    return out

print(transform(b)) # `b` taken from the question itself.
# same output as expected output posted in question.

NumPy has a lot of vectorized operations
NumPy has many vectorized operations, you have to find the correct ones. Not an expert but the below approach should do good.
The idea here is to find the index of the first value from each group and then take the difference.

We check if ith element is not equal to i+1th element.
Now use np.ndarray.cumsum to give each group a unique sequential number.
Then use np.unique to get first index of value from each group.
Find the difference between i+1th value and ith to get size of each grp. We can use np.diff

m = b != (np.r_[np.nan, b[:-1]])
_, c = np.unique(m.cumsum(), return_index=True)
#print(c)
# array([ 0,  3,  4,  8, 10, 11, 13, 14, 18, 19, 22, 26, 28, 29, 35, 37, 38,
#        40, 42, 43, 45, 46, 48, 49, 50, 51, 52, 53, 54, 57, 58, 59, 60, 64,
#        66, 67, 68, 74, 75, 77, 78, 80, 82, 83, 84, 85, 87, 91, 96])

# np.unique gives the index of the first occurrence, our `b` len is 100
# and `c` stopped at 96. we need to add the last index + 1 to it.

out = np.diff(np.r_[c, len(b)])

# Now, reshape your array, if it's of odd length add a 0 at end.
if len(out) % 2:
    out = np.r_[out, 0].reshape(-1, 2)
out = out.reshape(-1, 2)
print(out)
# same output mentioned in the question.

Using Pandas's GroupBy
A lot of times pandas and NumPy are used together so might as well post pandas code too.
import pandas as pd
s = pd.Series(b)
g = s.ne(s.shift()).cumsum()
out = s.groupby(g).size().to_numpy()
# repeat same step as we did in above solution add a 0 if len is odd.

if len(out)%2:
    out = np.r_[out, 0].reshape(-1, 2)
out = out.reshape(-1, 2)
print(out)

Code Review
Everything's good as far as I can see, well-named variables, proper indentation but too many if :p


Python is not C. You don't need to declare variables at the beginning and you don't need to set them to empty values if the first thing you do in your code is set them to sensible values.

Python is also unlike C in the sense that you don't need () around statements. while expression is perfectly valid (no need for while (expression) and so is if expression.

Python is unlike C in that it does not need ; at the end of lines. While it is not a SyntaxError, it is only needed when you absolutely have to put multiple statements on the same line (e.g. sometimes when using the commandline). This is basically never the case when writing a script in a file.

Python is like C in the sense that it has sensible operator preferences. Instead of while (cur_guess < max_guess) and guessed == False you can write while cur_guess < max_guess and not guessed and the < expression will be evaluated before the and.

A second thing I did there was removing the direct comparison with False. This is almost never needed (same as direct comparison with True), because the value itself is already a bool (and if not, most types have truthy and falsy values which behave just like bools, e.g. for strings the empty string "" is falsy, every other string is thruthy).

Your letter_bank would be better suited for a set, which has fast membership tests (since you do a lot of if letter_guess not in letter_bank. And since you are using the whole lowercase alphabet, why not use the built-in module string to save yourself some typing (next time):

import string
letter_bank = set(string.ascii_lowercase)

You don't even need to change letter_bank.remove(letter_guess), because it is the same for a set.

The same is true for word_chars.

Python has an official style-guide, PEP8, that recommends using lower_case_with_underscores for variables and functions. So your findOccurences would become find_occurences.

To increase readability, I would put more of your functionality into functions. At least have a setup() and a game() function to separate these two parts of logic.

With these (rudimentary) recommendations, your code would become:

import string

def find_occurences(s, ch):
    return [i for i, letter in enumerate(s) if letter == ch]

def game(word, max_guess):
    letter_bank = set(string.ascii_lowercase)
    word_chars = set(word)
    if word_chars - letter_bank:
        print("Words can only contain ascii letters!")
        return False
    word_guess = list(" ".join("-" * len(w) for w in word.split()))
    cur_guess = 0  # Current count of Guesses.

    while cur_guess < max_guess:
        print(''.join(word_guess))
        if word == ''.join(word_guess):
            return True

        letter_guess = input(
            "Please enter your guess (%i remaining):" % (max_guess - cur_guess)).lower()
        if len(letter_guess) != 1:
            return letter_guess == word
        elif letter_guess not in letter_bank:
            print("You have already used that letter or it is not a valid letter!")
        elif letter_guess in word_chars:
            print("%s is in the word!" % letter_guess)
            letter_bank.remove(letter_guess)
            for each in find_occurences(word, letter_guess):
                word_guess[each] = letter_guess
        else:
            print("%s is not in the word!" % letter_guess)
            letter_bank.remove(letter_guess)
            cur_guess += 1
        print()
    return False

def main():
    print('Welcome to Hangman! Simplified version of the original Hangman.')

    word = input("Please enter a word: ").lower()
    max_guess = int(input("Maximum Guess: "))

    print("\n" * 50)
    print('You are now ready to play.')

    if game(word, max_guess):
        print('You have successfully guessed the word!')
    else:
        print('You have lost the game! :(\nThe word was %s' % word)

if __name__ == "__main__":
    main()


Power menu (Shutdown, Reboot, Sleep) in ELISP

Disclaimer: Total beginner here too. So take everything with a grain of salt.
That being said this looks perfectly fine. However, I suggest you to use completing-read instead of ivy-completing-read as it will provide more flexibility. Don't worry, if you use ivy-mode (or customize completing-read-function to ivy-completing-read), then completing-read will use ivy-completing-read.This is especially helpful if you want to copy your snippet to another Emacs configuration where ivy isn't installed.
Other than that, I guess you want to introduce action before you setq it. However, I'm not really sure whether it's necessary.
Note that I will probably use your db/power-menu in my configuration. Well done :)


Don't add meaningless comments.
#include <iostream>  // allows program to output data to the screen

There is a real issue with code and comment rot. So your comments should always be meaningful as you have to maintain them with the code. It is best to reserve comments to "WHY" you are doing something. The code will explain "HOW".

Don't do this:
using namespace std;

There are definitely issues with pulling the whole standard namespace into the global namespace.
See: Why is “using namespace std;” considered bad practice?
In my opinion the best answer is the second one: sbi though the first one is good.

If Base does no real work you can make the virtual functions abstract:
struct Base {
    virtual void do_something() {};
    virtual ~Base(){};
};

// If the user should not be able to instantiate a `Base` then do this:

struct Base {
    virtual void do_something() = 0;
    virtual ~Base() {}
};

If your functions do not alter the standard behavior then don't include them:
struct Derived1 : public Base {
    Derived1():Base(){}
    virtual void do_something() {
        std::cout << "Derived1!!!" << std::endl;
    }
    virtual~Derived1(){};
};

Here the constructor and destructor are useless. Do not bother to specify them
struct Derived1 : public Base {
    virtual void do_something() {
        std::cout << "Derived1!!!" << std::endl;
    }
};

Don't use std::endl.
        std::cout << "Derived2!!!" << std::endl;

This is the major cause of C++ code running slowly. The problem is that std::endl forces the stream to flush. The stream will automatically flush when it is need and any extra flushes are likely to be inefficient (humans are bad at working out when to flush the stream).
It is better simply to use "\n"
        std::cout << "Derived2!!!" << "\n";

From C++11 we introduced the override specifier.
In the derived class you should mark any overridden methods with it.
struct Derived1 : public Base {
    virtual void do_something() override;
};

struct Derived2 : public Base {
    virtual void do_something() override;
};

The advantage here is that if in the future somebody changes the Base class and renames or alters the virtual functions in the base the compiler will not warn you that these functions no longer align with the base class version.


Find maximum number in a nested array using recursion

Your solution is much too complicated.  There is no point (pardon my pun) in splitting the array in the middle.

If you just want to demonstrate your knowledge of recursion, then apply recursion to nested lists.  You can then use the max() built-in function with a generator expression.

Instead of long comments and assert statements, write docstrings with doctests.

# Credit: https://www.linkedin.com/pulse/ask-recursion-during-coding-interviews-identify-good-talent-veteanu/
def max_number(array):
    """
    Find the maximum number in a jagged array. Each element of the
    array can be a number or an array of other numbers on indefinite
    number of levels.

    >>> max_number([1, [3, 9], 5])
    9
    >>> max_number([2, 4, 10, [12, 4, [100, 99], 4], [3, 2, 99], 0])
    100
    >>> max_number([-5])
    -5
    """
    return max(
        max_number(e) if isinstance(e, list) else e
        for e in array
    )


From your bash script, I assume that you expect a proper (no junk) input. In that case, you can just do

while ((c = getchar()) != '\n') {
    ungetc(c, stdin);
    scanf("%lf%*c", &x);
    printf("x = %g\n", x);
}

Of course, you'll replace printf with memory (re)allocation.

If you stick to your solution, I think that

if (sscanf(line, "%lf", &input))
{
    new_data = realloc(data_set, (size+1) * sizeof(double));
    ...

makes a bit more sense. The way you're doing it now, you (re)allocate the memory even if the input is not a real number. This can lose you all your old data, if realloc has to move the block (so new_data != data_set) in the same step in which input is not a real number.

Edit: As requested in the comments, I'll elaborate why and how the original code could lose the data. So, I'm talking about this code:

while(fgets(line, sizeof(line), stdin))
{
    if(line[0] == '\n') break;

    new_data = realloc(data_set, (size+1) * sizeof(double));

    if(sscanf(line, "%lf", &input))
    {
        if(new_data == NULL)
        {
            free(data_set);
            puts("Error (re)allocating memory");
            exit(1);
        }
       data_set = new_data;
       data_set[size++] = input;
   }
}

There are two things to consider:

The sole purpose of the line

if(sscanf(line, "%lf", &input))

is to make sure that line contains a real number (and to put it in input, as a number). If we were sure that line contains a double, we wouldn't use if.
The line

new_data = realloc(data_set, (size+1) * sizeof(double));

tries to reallocate the memory pointed to by data_set so that it would fit size+1 doubles. However, this may not be possible if the memory right behind the block pointed to by data_set is occupied.

In that case, another memory block of the required size will be allocated, the data will be copied there, and its address will be returned as the return value of realloc, which we save in new_data. The old memory is freed

So, what happens if both of these things happen, i.e., if we don't input a number and the occupation of the memory is such that realloc cannot simply expand the occupied memory?

First, we do realloc:

new_data = realloc(data_set, (size+1) * sizeof(double));

Now, our memory old memory (the one pointed to by data_set) is freed, a new memory is allocated and pointed to by new_data, and the data is copied to this new memory.

But, since we didn't input the number, this if will have a false condition:

if(sscanf(line, "%lf", &input))

So, we do not enter this block and, among other things, we don't do

data_set = new_data;

Hence, for the next step, our data_set points to some freed memory (where our data used to be), while the pointer new_data will be lost, either with the next new_data = realloc(...) command, or when we exit the function. In both cases, our data is unreachable, and any action on data_set will have unpredictable (most probably wrong) results.

It is not very probable that this will happen, but it might, and the solution is simply to reallocate the memory if and only if we're going to work with it. Hence, my suggestion above.


Counting the number of digits with a recursion algorithm in c

I unfortunately cannot comment (not enough reputation), but in terms of performance and generated assembly code both variants are exactly same:

int countDigitsSane (int n){
  int digits=1;
  for(int i=n; i>9; i/=10)
  {
    digits++;
  }
  return digits;
}

int countDigits(int n){
  if(n<10){
    return 1;
  }
  else{
    return 1+countDigits(n/10);
  }
}

Pay attention, I have removed the redundant check in the recursive snippet.With that correction, the code generated by the compiler is almost 100% same, save for different choice of registers.

Having said that, it is indeed, better to avoid recursion in imperative languages (such as C++), however in functional languages (Haskell, OCaml etc.) , recursion is a normal thing, and the compiler guarantees it can optimise tail-recursive calls.


(Apologies in advance for any bad F# syntax in this answer)

One issue is that you're doing things statefully. In a functional style, you want functions to be pure, as much as possible- i.e. their purpose is to return something, not to change state. Whereas you have global collections like sieve and bigPrimes, and functions whose purpose is to modify those collections.

Taking the last part in particular, you do:

smallPrimes
|> Seq.map(fun a -> (int (number/(int64 a))))
|> Seq.iter(addBigPrime)

let answer = smallPrimes |> Seq.append(bigPrimes) |> Seq.max

Instead, you want to be able to do something like:

let answer = smallPrimes
             |> getBigPrimes
             |> Seq.max

In this case getBigPrimes would just calculate the big primes from the small ones, probably using a recursive inner function. A useful technique to allow you to do this without any state mutation is to have an accumulator collection as a parameter to your recursive function (often called acc). Then instead of having some list you repeatedly add results to, you pass a new acc to each call of the recursive function, created by prepending the result to the previous one acc.

So as an example, instead of:

let primesUpTo n =
    let primes = new List<int>()
    let rec loop i =
        if isPrime n primes then primes.Add(n)
        if i = n then primes else loop i+1
    loop 2

You'd do:

let primesUpTo n =
    let rec loop i acc =
        if i = n then acc
        elif isPrime i acc then loop i+1 i::acc
        else loop i+1 acc

Notice that by replacing iteration with this tail recursive style, you no longer have to have mutable state in the form of a collection which gets updated. This (and the fact that recursive algorithms often read as more declarative than iterative ones), mean that tail recursion is generally preferred over iteration in F#.

As you already said in your question, your algorithm is a bit strange. Your alternative algorithm is much better. Writing it in the same recursive style, an outline would look something like:

let rec largestFactor n primes =
    let factor = smallestFactor n primes
    if factor = n then factor else largestFactor n/factor primes

let answer = primesUpTo n |> largestFactor n

You'd then just need to implement primesUpTo (which you'd want to make lazy, so that you don't calculate primes higher than you need) and smallestFactor


Is this a correct way to use Factory Pattern?

Some design considerations:

Returning Null: Your factory method createFromString returns a null creator if the column is unknown. It's good practice to note this in the javadoc or perhaps throw an IllegalArgumentException if a column you can't handle is passed in.
Date Abstraction: ProjectDateCreatorlooks like it could use either its own factory or two separate implementations based on the second constructor argument. That class isn't included here, but it appears CREATION and UPDATED are some sort of public static final type constants. Those would be better expressed as an enum:

// A factory can use this instead!
public enum ProjectDateOption {
    CREATION, UPDATED;
}

Interface Naming: Interfaces in Java aren't typically prefixed with an I, but if it's consistent through your code then that's a minor quibble.
Column Strings: Your TODO mentions this, but the column strings could also be placed into an enum, and then the checking could occur there.


C++ rudimentary bitmap image edge detection

I'm just going to rattle off the things I see as I find them.

header.getBytesAhead() should return a void *
pointer_ahead should be a unsigned char const *
small_ahead should be a unsigned char *
Loop x over the pixels (width) not the bytes.
for (unsigned int x = 0; x < width; x += 2)
starting_position = x * 6 + y * ( width * 3 + padding_bytes )
int difference = abs(first_av - second_av)
small_position = x / 8 + y * ( small_width + small_padding_bytes )
small_bit_position = x % 8
small_ahead[ small_position ] |= 3 << small_bit_position
Use std::vector so header.deleteBytes is unnecessary.

Edit:

small_position = x / 8 + y * ( ( width + 7 ) / 8 + small_padding_bytes )
To handle an odd width: for (unsigned int x = 0; x + 1 < width; x += 2)


I guess correctness is the most important aspect - as I mentioned in a comment, isCyclicObject returns false positives for references to the same substructure.

I don't know if you intended to directly return null if a value is null (in the flattenObject function). Seems a little harsh to scrap the whole object if any one of its properties has a null value. I would have assumed the behavior should have been to skip pushing the property to the flattened array.

Performance-wise there is some room for improvement:

the function isCyclicObject is called every time the flattenObject function is called. This is not necessary - you only need to perform the check for cycles once.
an array is not the ideal data structure to use for seenObjects. I'd pick the native Set - don't worry, even IE (11) supports it. Read about it on MDN. Plus, to check if something is part of a set you get the neat set.has(something) method which is far better looking than array.indexOf(something) !== -1.
for ... in is not very optimizable by JavaScript engines and what's more it will cause the whole function it's part of to not be optimized. You can read about this here. The other argument against for ... in is that it needs to be accompanied by hasOwnProperty. I see you're doing that for isCylicObject but not for flattenObject. Instead of for ... in you could use Object.keys(obj) which returns an array of the object's own properties directly.

Style-wise:

don't expose seenObjects to the user. If the user accidentally types in a second parameter to seenObjects then strange things will happen and debugging it is going to be unpleasant. Instead you can initialise it in a closure like so:

function isCyclicObject(object) {
  var seenObjects = []

  // let's shadow the original function
  function isCyclicObject(object) {
    // check every property or and call traverse recursively
    // your original logic, except for the `seenObjects` initialization
  }

  return isCyclicObject(object)
}

This way you also eliminate that check which occurs every time, making the traversal faster.

prefer to use const and let over var unless you're targeting old browsers
prefer the more functional forEach/map/some in your case instead of for loops

EDIT:

Don't use ... instanceof Object to verify if something is an object. Objects with a null prototype will fail that test. Instead use `typeof ... === 'object' && ... !== null


Structure

I don't really like returning a magic array. The caller has to guess or read up on the keys, which is annoying. I know that this is often done in PHP, but I think a better approach would be to move the retrieving of information to the constructor, store the result in class fields, and then access those fields with explicit getter (or if you don't want to completely rewrite your class, store the array as field, and add getters for each key of the array).

This could be used like this:

$userInfo = new UserInfo($userId, $dbConnection);

Name: <?php echo htmlentities($userInfo->getName()); ?>

Email: <?php echo htmlentities($userInfo->getEmail()); ?>

[...]

For debug purposes you could still add a toString method with returns a string of all array values.

If you do it like this, not only is your class a lot easier to use (without having to read the documentation and/or knowing of the inner workings of the class), the class now actually is more than a wrapper for a method that could just as well be a static function.

Misc

You bind a result to $admin which never exists.
your fields should be private.
naming: oConni could be pdo or database, cSQL could be query, and grav_url gravatarUrl (you are using camelCase everywhere else).
your indentation and spacing is sometimes off, you can use an IDE to fix this easily.


A few general things from a quick scan:

declare all your variables at the top in one var statement rather than using it throughout the script
use somearray.push(x) rather than somearray[somearray.length]=x, as its shorter and means you don't have to look up the .length property every time in your loop
in general, avoid with; there are many reasons why e.g. http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/
string concatenation is slow; instead of many += operators, create an array, use .push() as above to add strings to the array, then use .join('') to merge them together.

And yes, XPath would be a better approach to extract data from XML.


Printing all possible sums of two n-sided dice rolls

As @BenC mostly put a code dump, I'll explain ways that your code could have improved.

reverseIt

Programming this is just wrong in Python.
This is as there are two ways to do this.

>>> list(reversed([1, 2, 3]))
[3, 2, 1]
>>> [1, 2, 3][::-1]
[3, 2, 1]

As an alternate way to this you could just calculate the range backwards off the bat.

>>> list(range(10, 0, -1))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

In short you could halve your code just by removing this.

If you wanted to keep it, then you would want to use the reversed range.
And do pretty much what you are now. To get:

def reverseIt(indexable):
    lst = []
    for index in range(len(indexable) - 1, -1, -1):
        lst.append(indexable[index])
    return lst

You could then use a list comprehension, if amount of lines dictates how good your code is.

def reverseIt(indexable):
    return [indexable[index] for index in range(len(indexable) - 1, -1, -1))]

allRolls

nums is pointless if you use a different algorithm. (Which is also more intuitive.)
index is never used.
retVal can be changed to a comprehension.
Manually counting cIndex is a frowned upon in Python.

In short, use a different algorithm.
The pseudo-code for this could be:

fn allRolls(sides):
    list = List()
    for dice1-face in dice-faces:
        for dice2-face in dice-faces:
            add dice1-face + dice2-face to list
    return sorted list

Or in Python:

fn allRoles(sides):
    ret = []
    for a in range(1, sides + 1):
        for b in range(1, sides + 1):
            ret.append(a + b)
    ret.sort()
    return ret

If you take it the next step then you would get @BenC's answer.

Misc

In short, you just used the wrong algorithm.

And in Python you should:

Use all_rolls instead of allRoles to follow function and variable naming conventions.
Have a space on both sides of operators, index >= 0 or newb = [] to increase readability.


"Largest power of two less than N" in Python

If what you really want is the "largest power of 2", you should make that more explicit:

def largest_power_of_two(n):

And does the largest power of two less than n mean in terms of bits? It's just dropping all of the bits except for the left-most one. Since we can get the bit length of a number directly, we can just do that:

def largest_power_of_two(n):
    return 1 << (n.bit_length() - 1)

If you want error check, you can add the value error if you want (note only positive ns are valid, you initially allowed for 0... but what is the largest power of 2 less than or equal to 0?):

def largest_power_of_two(n):
    if n > 0:
        return 1 << (n.bit_length() - 1)
    else:
        raise ValueError("only meaningful for positive values")

Don't write loops when you don't need to.


Option Strict

You should always set Option Strict = On.

Short circuit evaluation

You should use the AndAlso operator instead of the And operator. By using And both conditions will be evaluated. By using AndAlso the second condition will only be evaluated if the first returns true.

List(Of FileInfo)

Instead of returning a List(Of FileInfo) you should consider to return an IEnumerable(Of FileInfo).

Naming

You shouldn't prefix your variables like strWorkingPath or lstAllFiles.

GetFiles() vs EnumerateFiles()

From the docs

  The EnumerateFiles and GetFiles methods differ as follows: When you
  use EnumerateFiles, you can start enumerating the collection of names
  before the whole collection is returned; when you use GetFiles, you
  must wait for the whole array of names to be returned before you can
  access the array. Therefore, when you are working with many files and
  directories, EnumerateFiles can be more efficient.

Refactoring

First we will extract the loading of the file and reading the properties to separate methods and add a private class holding the TypeIndex and Version properties of the xml file.

Private Shared Function DoesFileMatch(file As FileInfo, index As String) As Boolean
    Dim version As XmlVersion = GetXmlVersion(file)
    Return (version.Version = "0" AndAlso version.TypeIndex = index)
End Function

Private Shared Function GetXmlVersion(file As FileInfo) As XmlVersion
    Return New XmlVersion(XElement.Load(file.FullName))
End Function

Private Class XmlVersion
    Public Property TypeIndex As String
    Public Property Version As String
    Public Sub New(element As XElement)
        TypeIndex = element.Element("TypeIndex").Value
        Version = element.Element("Version").Value
    End Sub
End Class

Next we add an overloaded GetListByType() method which takes a DirectoryInfo and a String as input parameter.

Shared Function GetListByType(directory As DirectoryInfo, ByVal typeIndex As String) As IEnumerable(Of FileInfo)

End Function

Which we call in our former method like

Shared Function GetListByType(ByVal typeIndex As Integer) As IEnumerable(Of FileInfo)
    Return GetListByType(typeIndex.ToString(), New DirectoryInfo(GetWorkspaceDir))
End Function

The overloaded method can then be simplified, using all above, to

Private Shared Function GetListByType(directory As DirectoryInfo, ByVal typeIndex As String) As IEnumerable(Of FileInfo)

    Dim filteredFiles As New List(Of FileInfo)

    For Each fic In directory.EnumerateFiles("*.xml", SearchOption.AllDirectories)
        If (DoesFileMatch(fic, typeIndex)) Then
            filteredFiles.Add(fic)
        End If
    Next

    Return filteredFiles.Distinct()

End Function

But wait, we can do this a lot more lambda like

Private Shared Function GetListByType(directory As DirectoryInfo, ByVal typeIndex As String) As IEnumerable(Of FileInfo)

    Return directory.EnumerateFiles("*.xml", SearchOption.AllDirectories) _
        .Where(Function(x) DoesFileMatch(x, typeIndex)) _
        .Distinct()

End Function


Capitalize all words in sentence string in Ruby

Your function name should be in snake_case, not PascalCase. (Thanks @rui.)
It seems like it would make more sense to use map than each here.
Ruby doesn't need explicit return.
You might even want to extend the base string class.

Here's my rendition:

class String
  def capitalize_words
    this.split.map { |x| x.capitalize }.join(" ")
    # or:     .map(&:capitalize)
  end
end

"this IS a Test".capitalize_words # => "This Is A Test"


Custom UI - Seeing which control has focus

Here's what I have so far

The code you wrote doesn't quite work properly; because, depending on the behaviour (which isn't clearly defined) of your HasFocus property:

Either it will return too early (it returns immediately, if this.HasFocus is true when a child has focus)
Or it will return null (it doesn't descend, if child.HasFocus is false when a grandchild has the focus).

I don't quite understand your question: Control is a System class, so how are you supplying source code for it? I'm guessing you're using it as an example and writing pseudo-code.

To avoid confusion, I'm going to:

Assume you're writing code for the standard System.Windows.Forms.Control class
Assume that Control has the standard ContainsFocus and Focused properties
Write a class which defines GetFocus has a new extension method

I suggest:

public static class ControlExtensions
{
    public static Control GetFocus(this Control control)
    {
        if (control.Focussed)
            return this;

        foreach (Control child in Children)
        {
            if (!child.ContainsFocus)
                continue;
            return GetFocus(child); // recurses
        }

        return null;
    }
}

Or, assuming that it is your own Control class as you wrote it in the OP, I would implement its recursive GetFocus as follows:

public class Control
{
    public bool CanFocus { get; set; }
    public bool HasFocus { get; set; }

    public Control GetFocus()
    {
        if (HasFocus)
            return this;

        foreach (Control child in Children)
        {
            Control found = child.GetFocus();
            if (found != null)
                return found;
        }

        return null;
    }

    public bool ContainsFocus
    {
        get { return GetFocus() != null; }
    }
}

In this second implementation, the GetFocus implementation doesn't call ContainsFocus:

Because ContainsFocus calls GetFocus
Because ContainsFocus descends the tree of children in order to decide whether to return true, so GetFocus might as well do the same (descend the tree of children) but return the actual Control instead of just returning bool.

Beware that your HasFocus implementation (as coded above) isn't good enough: because you must ensure that only one Control has the focus (so if you set the focus, then you need to remove focus from whichever control previously had the focus, if there is one).

  I considered a helper method with the signature bool FindFocus(out Control result), but it felt unwieldy.

It's enough to return null if there is no focus.

You might want to return bool if you want to return additional information; for example:

Customer customer;
bool success = FetchCustomer(customerId, out customer);
if (!success)
{
    // fetch failed because database or network is down
}
else
{
    if (customer == null)
    {
        // fetch successfully says that there is no such customer
    }
    else
    {
        // fetch successfully returned the requested customer
    }
}

In your example however the GetFocus algorithm/implementation cannot 'fail', so returning Control is enough (instead of returning bool as well as having an out parameter).

Having an out parameter is necessary if null is a valid value: for example the Dictionary.TryGetValue method (because a Dictionary can contains nulls, so it needs a bool to say whether it's in the dictionary at all).

Having a bool with an out parameter is also necessary if the type in question is a struct instead of a class: because a struct cannot be null. In this case though, Customer is a class not a struct.

  Also, I am concerned with invoking foreach within a recursive function.

Why? It's not a problem per se.


Serialize and deserialize binary tree with a lot of empty nodes

I would use a map mapping each key of a node \$u\$ in the tree to a 2-tuple containing the key of the parent \$p\$, and a boolean indicating whether \$u\$ is a left or right child of \$p\$:

class TreeNode:

    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

    def __eq__(self, other):
        return self.key == other.key

    def __hash__(self):
        return self.key

def serialize_tree(root_node):
    map_node_key_to_parent_data = {}

    def serialize_tree_impl(node, parent_node):
        if parent_node:
            parent_data = (parent_node.key, parent_node.left is node)
            map_node_key_to_parent_data[node.key] = parent_data
        else:
            map_node_key_to_parent_data[node.key] = None

        if node.left:
            serialize_tree_impl(node.left, node)

        if node.right:
            serialize_tree_impl(node.right, node)

    serialize_tree_impl(root_node, None)
    return map_node_key_to_parent_data

def deserialize_tree(map_node_key_to_parent_data):
    map_node_key_to_tree_node = {}

    for node_key in map_node_key_to_parent_data.keys():
        if node_key not in map_node_key_to_tree_node.keys():
            map_node_key_to_tree_node[node_key] = TreeNode(node_key)
        else:
            raise TypeError("Duplicate node in the tree.")

    root_node = None

    for node_key, parent_data in map_node_key_to_parent_data.items():
        node = map_node_key_to_tree_node[node_key]

        if not parent_data:
            root_node = node
        else:
            parent_node_key = parent_data[0]
            on_left = parent_data[1]
            parent_node = map_node_key_to_tree_node[parent_node_key]

            if on_left:
                parent_node.left = node
            else:
                parent_node.right = node

    return root_node

def binary_search_trees_are_identical(root_node1, root_node2):
    if not root_node1 and not root_node2:
        return True

    if not root_node1 or not root_node2:
        return False

    if root_node1.key != root_node2.key:
        return False

    return binary_search_trees_are_identical(root_node1.left, root_node2.left)\
        and binary_search_trees_are_identical(root_node2.right, root_node2.right)

def main():
    root_node = TreeNode(5);
    l = TreeNode(3)
    r = TreeNode(7)
    rr = TreeNode(10)
    lr = TreeNode(4)
    rrl = TreeNode(11)
    rr.left = rrl

    root_node.left = l
    root_node.right = r
    l.right = lr
    r.right = rr

    serialized_tree = serialize_tree(root_node)
    print serialized_tree

    deserialized_tree_root_node = deserialize_tree(serialized_tree)
    print "Trees are identical:", binary_search_trees_are_identical(root_node, deserialized_tree_root_node)
    pass

if __name__ == "__main__":
    main()

A bug?

On

root = TreeNode(1, TreeNode(2, TreeNode(3, TreeNode(4, TreeNode(5, None, None), None), None), None), None)

I get an IndexError.

Hope that helps.


Idiomatic iterator for a linear function

I suppose that if you don't really have a need to end member names with underscores, then you can avoid them.  Having similar names as constructor parameters won't even matter as long as you're using an initializer list.
Probably a bit nit-picky, but you may not need the precision of a double here.  If so, then you can just use floats.
With begin() and end(), you can also provide const versions (cbegin() and cend()).

Also, be careful with these names since they're also used in the STL.  You may also use slightly different names if you prefer.
If you really need operator!=, then you should also provide operator==.

In addition, it's usually preferred to define operator!= in terms of ==:

return !(xIter_ == other.xIter_);


Generating table rows for a form using js

You need to use loops. Really, that's about it - all of the element creation and appending can be done in a loop, while the prefix for each of the element's name and id be stored in an array.

function addNewRow(body, id) {
    var myRow = document.createElement("tr"),
        d = document.createElement("div"),
        inputPrefix = ['drwID_', 'pos_', 'stm_', 'note_'];

    myRow.id = id + '';

    for(var i = 0; i < inputPrefix.length; i++){
        var td = document.createElement('td'),
            input = document.createElement('input');

        input.type = 'text';
        input.id = inputPrefix[i] + id;
        input.name = inputPrefix[i] + id;
        input.disabled = !editing;

        td.appendChild(input);
        myRow.appendChild(td);
    }

    myRow.appendChild(d);
    body.appendChild(myRow);
}

You are generating invalid HTML here though - trs cannot contain div elements.


Roslyn analyzer, converted from C# to F#

I feel we can traverse the Roslyn AST but it's chatty and boring for write with a lot of non aspect code fragment :(

My suggestion for reference is my experimental project "F# Active pattern library for Roslyn Compiler Platform" can ease for use Roslyn AST directly F# pattern matching syntax.

https://github.com/kekyo/Microsoft.CodeAnalysis.ActivePatterns


Very basic isomorphic JavaScript application

You can render your webpage on the server complete with all props/state in place and at client-side React will pick up from initial state when he founds markup already existing.

So write your components the normal way, query database (or what have you) for props and render on server using ReactDOMServer. Here's a little example.

(As far as I can tell, you're doing something similar in your repo, so this is probably late to the party :)


Creating an IUserSession that is used throughout my code

It's great that you separated the ASP.NET specific implementation from the interface. Two things to watch:

Don't forget to call Session.Abandon();Session.Clear(); in the Logout method.
SetupProfile contains a lot of code. This seems like business logic to me. Try to extract this code to its own class. An IUserService for instance. Or perhaps explicitly define Query Objects.


Override equals() and hashCode() using reflection

It ignores values in superclasses. You might want to check that too.

Anyway, don't reinvent the weel, there is a library for that! I guess EqualsBuilder.reflectionEquals from Apache Commons Lang does exactly what you want.  It also has solutions to corner cases, like

transient fields (since they are likely derived fields, and not part of the value of the Object) in a configurable way
generated fields with $ (for inner classes).

You can also exclude field names from the comparison.

It's open-source, you can check the source for further details.

See also: Effective Java, 2nd edition, Item 47: Know and use the libraries (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)
The else keyword is unnecessary here:

if(currentObj==null || otherObj==null){
    return false;
}
else if(otherObj.getClass()!=null&&currentObj.getClass()!=null&&!currentObj.getClass().isInstance(otherObj)){
    return false;
}

The following is the same:

if (currentObj == null || otherObj == null){
    return false;
}
if (otherObj.getClass() != null && currentObj.getClass() != null &&
        !currentObj.getClass().isInstance(otherObj)) {
    return false;
}

It's called guard clause. I've also used a little bit more spacing to make it readable (easier separaton of values, comparisons, method calls).
Guard clauses would make this easier to follow too:

  if(value instanceof Boolean){
      result=areEqual((Boolean)value, (Boolean)attriButeNameValueMap.get(field.getName()));
  }
  else if(value instanceof Character){
      result=result&&areEqual((Character)value, (Character)attriButeNameValueMap.get(field.getName()));
  }
  else if(value instanceof Long){
      result=result&&areEqual((Long)value, (Long)attriButeNameValueMap.get(field.getName()));
  }
  ...
  if(!result){
      return result;
  }

I've used a few exaplanatory variable to remove some duplication:

Object value = field.get(currentObj);
String fieldName = field.getName();
if(attriButeNameValueMap.containsKey(fieldName)){
      Object otherFieldValue = attriButeNameValueMap.get(fieldName);
      if (value instanceof Boolean) {
          if (!areEqual((Boolean) value, (Boolean) otherFieldValue)) {
              return false;
          }
      }
      if (value instanceof Character) {
          if (!areEqual((Character) value, (Character) otherFieldValue)) {
              return false;
          }
      }

Note that it makes superfluous the result variable. The last line of the method could be simply the following, since its never modified anymore:

return true;

Formatting is not consistent. Indentation sometimes is two spaces, sometimes four.

  Map<String, Object> attriButeNameValueMap=null;
  /*This map to store *property name and its value of any of object in my calse the otherObj */
  try {
      attriButeNameValueMap=new HashMap<>();

B should be lowercase in the variable name (I guess it's just a typo) and you could declare it inside the try block:

I'd also rename it to otherObjectAttributeValues to make the comment unnecessary:

try {
    Map<String, Object> otherObjectAttributeValues = new HashMap<>();

(Effective Java, Second Edition, Item 45: Minimize the scope of local variables)
Consistent formatting would be great here too:

          } catch (IllegalArgumentException | IllegalAccessException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
  throw e;
          }

Furthermore, TODO comments does not suggest professional work. Fix that and remove the comment.

I'd throw out the IllegalAccessException or wrap it into a RuntimeException. The IllegalArgumentException already a RuntimeException, so you don't have to put it into the method signature.


Decorator that supplies arguments to functions

I don't think my_decorator is a very descriptive name, but maybe that's just part of the assignment.  Also, f isn't a very descriptive name for the function you are decorating.

I did my own test:

>>> @my_decorator(2)
... def here(*args):
...     print args
...
>>> here(4, 5)
>>>

Do you know why it doesn't print anything?  It's because you have if and elif in wrapped_f, but one argument to my_decorator and two arguments to here doesn't match either of your conditions, so wrapped_f doesn't know what to do.  To be safe, it does not call the function and just returns None.  That always happens when you don't tell a function what to return: it returns None.  My question is, why do you have those conditions?  I would change that function to:

def wrapped_f(*func_args):
    return f(*(deco_args+func_args))

Your code really has only four lines of reviewable code, so I will just suggest a new (not necessarily better) way:

from functools import partial

class MyDecorator:
    def __init__(self, *args):
        self.args = args
    def __call__(self, func):
        return partial(func, *self.args)

functools.partial takes a function and any other arguments and returns a callable object that, when called, calls the function with the original arguments and whatever other arguments are given.  Our decorator is called with 2 for my above example, so it sets self.args to (2,).  When our MyDecorator object is called (with here as an argument), the __call__ method is executed and we return a partial object with that function and the arguments we got earlier.  Therefore, when the result is called with more arguments, it calls the function with the arguments originally given to the decorator as well as the arguments being given currently.  You can see that partial is very similar to your decorator.  We just needed to make it decorator-compatible.

Edit: As mentioned by @JoeWallis in the comments, you could still use partial() in nested functions similar to yours:

def my_decorator(*deco_args):
    def wrap(f):
        return partial(f, *deco_args)
    return wrap


Looks pretty clean for me.

2 things:

I'm not an English expert, but check the name of the function and the action.
I understand "render" as to "display on the screen", or "write on the screen," but the function doesn't really write to the screen. It returns some template to be injected later.
Instead of using a concatenated string, you can use a template engine to avoid concatenating strings. It separates the logic from the template and makes both more maintainable. The most popular ones are Mustache, Handlebars, and the Backbone engine.


Vectorize pairwise edit distance computation

I do not think vectorisation to buy you anything "in the upper levels".
My guess is the statement little use due to data dependencies is true even more than for
parallel computing in general.
With SciPy/NumPy I'm out of my depth; drawing on Syncrossus levenshtein.py.
I'd need a better motivation for the distance function - I guess the minimum requirement being triangle inequality
Shot from the hip using set.symmetric_difference() as food for thought:

import numpy as np

def replacement_cost(s1, s2):
    return len(set(s1).symmetric_difference(s2))

def edit_distance(seq1, seq2):
    """ return edit distance between two list-like sequences of sequences
        Args:
            seq1, seq2: subscriptable objects compatible with len()
                containing objects comparable with the `==` operator.
    """
    m = len(seq1)
    n = len(seq2)
    dp = np.zeros(shape=(m, n))
    dp[0, :] = range(0, n)
    dp[:, 0] = range(0, m)

    for i in range(1, m):
        for j in range(1, n):
            cost = 0 if seq1[i] == seq2[j] \
                     else replacement_cost(seq1[i], seq2[j])
            dp[i][j] = min(dp[i][j - 1] + len(seq2[j - 1]),  # Insert
                           dp[i - 1][j] + len(seq1[i - 1]),  # Remove
                           dp[i - 1][j - 1] + cost)          # Replace
    return dp[m-1][n-1]


Just some generic note about the code:

If the parameter called input contains a name you should rename it to name to express its purpose.
Method names should be verbs. I would rename greetServer to serveGreeting or doGreeting. (Check Code Conventions for the Java Programming Language, Naming Conventions and Clean Code, page 25.)
Comments like this are rather just noise:

// If the input is not valid, throw an IllegalArgumentException back to
// the client.

It's pretty obvious from the code itself, so I'd remove the comment. (Clean Code by Robert C. Martin: Chapter 4: Comments, Noise Comments)
I'd move the complete validation logic to the FieldVerifier class (or another helper class or helper method) for better reusability and higher abstraction. It also would make the greetServer method more compact.
The isValidName could be a little bit shorter with the null-safe Apache Commons Lang StringUtils.length:

public static boolean isValidName(String name) {
    return StringUtils.length(name) > 3;
}

Usage of Google Guava would make checkName more compact:

public static void checkName(final String name) {
    checkArgument(isValidName(name),
        "Name must be at least 4 characters long");
}

(See also: Effective Java, 2nd edition, Item 47: Know and use the libraries The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)
public String greetServer(String name) throws IllegalArgumentException {
    ...
}

IllegalArgumentException is a RuntimeException, so declaring them in the method signature is not mandatory, you could omit it:

public String greetServer(String name) {
    ...
}