Need reviews for impacts of dirty bug fix

In Unix filesystems, an inode is a number that uniquely identifies a file within the filesystem.  (More strictly speaking, an inode is a data structure that holds metadata about a file within the filesystem; each inode is assigned an inode number, and the number is all you care about unless you're a kernel developer.)

However, the inode number only uniquely identifies a file within its filesystem.  If /tmp and /usr are separate filesystems, inode 3461 of the /tmp filesystem might be /tmp/.ICE-unix while inode 3461 on /usr might be /usr/share/dict/words.  Therefore, to uniquely identify a file on the whole computer, a tuple of (inode number, device major number, device minor number) is needed.

By ignoring the device number, you might end up acting on events on a file with a coincidentally equal inode number on a different filesystem — though the chance is miniscule.

If you decide to keep this workaround, then I think you should make a corresponding change on line 71 as well.


Partition a list of numbers into even and uneven numbers

Your naming for the array parameter 'a' is not good. Use something along the lines of input, input_array instead.

Also, rather than manually copying each element of the array in

for (int i = 0; i < a.length; i++){
    a[i] = tmp[i];
}

Use a = tmp.clone(); or a = Arrays.copyOf(tmp, tmp.length)

Arrays.copyOf has slightly bette performance than clone, but both are much better than manually iterating through the array as you are doing.

Also, rather than computing a.length each iteration you can use int size = a.length and then do for (int i = 0; i < size; i++) for even better performance.


Style

Your code looks nice. It is not splitted into small functions and it is not commented but it's easy to understand anyway.

A few easy things could be done to make it more beautiful :

define variables in the smallest possible scope. With the right version of C, this also include defining variables as part of the for syntax. This makes the code much clearer as it is easier to see where the variable is used.
define a variable to refer to coord[j].
use += instead of repeating variable = variable + something.

At this stage, the code looks like :

int main(){
    coordinate coord[100000];

    int N, C;
    scanf ("%d %d", &N, &C);

    for (int i = 0; i < N; i++){
        scanf ("%d %d %d %d", &coord[i].x1, &coord[i].y1, &coord[i].x2, &coord[i].y2);
    }

    for (int i = 0; i < C; i++){
        int xi, xf;
        scanf ("%d %d", &xi, &xf);
        int nbacterias = 0;

        for (int j = 0; j< N; j++){
            coordinate c = coord[j];
            if ((c.x1 >= xf && c.x2 >= xf) || (c.x2 <= xi && c.x1 <= xi))
                nbacterias++;
            else if ((xf < c.x2 && xf > c.x1 && xi <= c.x1 && xi < c.x2) || (xf < c.x1 && xf > c.x2 && xi <= c.x2 && xi < c.x1))
                nbacterias++;
            else if ((xi > c.x2 && xi < c.x1 && xf >= c.x1 && xf > c.x2) || (xi>c.x1 && xi < c.x2 && xf >= c.x2 && xf > c.x1))
                nbacterias++;
            else if ((c.x1 < xi && c.x2 > xf) || (c.x2 < xi && c.x1 > xf))
                nbacterias+=2;

        }
        printf ("%d\n", nbacterias);
    }

    return 0;
}

Tests

Before trying to make things faster, it is a good idea to write automatic tests. At the moment, your code relies on input, output so it is not really easy to tests. It could be nice to separate the concerns: the input/output on one hand, the logic on the other hand.

Let's write a function to perform the logic. Now, we can reuse data from the problem to write a few tests :

#include <stdio.h>
#include <assert.h>

typedef struct {
    int x1;
    int y1;
    int x2;
    int y2;
}coordinate;

int nb_bacteria_after_beam(coordinate coord[], int N, int xi, int xf)
{
    int nbacterias = 0;

    for (int j = 0; j< N; j++){
        coordinate c = coord[j];
        if ((c.x1 >= xf && c.x2 >= xf) || (c.x2 <= xi && c.x1 <= xi))
            nbacterias++;
        else if ((xf < c.x2 && xf > c.x1 && xi <= c.x1 && xi < c.x2) || (xf < c.x1 && xf > c.x2 && xi <= c.x2 && xi < c.x1))
            nbacterias++;
        else if ((xi > c.x2 && xi < c.x1 && xf >= c.x1 && xf > c.x2) || (xi>c.x1 && xi < c.x2 && xf >= c.x2 && xf > c.x1))
            nbacterias++;
        else if ((c.x1 < xi && c.x2 > xf) || (c.x2 < xi && c.x1 > xf))
            nbacterias+=2;
    }
    return nbacterias;
}

int automatic_tests()
{
    coordinate coord[] = {{1, 0, 4, 0}};
    assert(nb_bacteria_after_beam(coord, 1, 0, 2) == 1);
    assert(nb_bacteria_after_beam(coord, 1, 3, 5) == 1);
    assert(nb_bacteria_after_beam(coord, 1, 2, 3) == 2);
    assert(nb_bacteria_after_beam(coord, 1, 0, 5) == 0);
    coordinate coord2[] = {{2, 0, 4, 0}, {2, 0, 4, 0}};
    assert(nb_bacteria_after_beam(coord2, 2, 0, 1) == 2);
    assert(nb_bacteria_after_beam(coord2, 2, 1, 2) == 2);
    assert(nb_bacteria_after_beam(coord2, 2, 2, 3) == 2);
    assert(nb_bacteria_after_beam(coord2, 2, 3, 4) == 2);
    assert(nb_bacteria_after_beam(coord2, 2, 4, 5) == 2);
    assert(nb_bacteria_after_beam(coord2, 2, 5, 6) == 2);
    coordinate coord3[] = {{0, 0, 3, 5}, {3, 5, 0, 2}};
    assert(nb_bacteria_after_beam(coord3, 2, 0, 3) == 0);
    assert(nb_bacteria_after_beam(coord3, 2, 1, 2) == 4);
    assert(nb_bacteria_after_beam(coord3, 2, 2, 7) == 2);
    return 0;
}

int stdin_tests()
{
    coordinate coord[100000];

    int N, C;
    scanf ("%d %d", &N, &C);

    for (int i = 0; i < N; i++){
        scanf ("%d %d %d %d", &coord[i].x1, &coord[i].y1, &coord[i].x2, &coord[i].y2);
    }

    for (int i = 0; i < C; i++){
        int xi, xf;
        scanf ("%d %d", &xi, &xf);
        printf ("%d\n", nb_bacteria_after_beam(coord, N, xi, xf));
    }

    return 0;
}

int main(){
    return automatic_tests();
}

Please note that I had to reorder members of your struct so that I can simply reuse tests cases from the problem.

Now, I assume (which might not be nor true nor wise) that if anything goes wrong during my changes, I'll detect it almost instantly.

Better performances

At the moment, your code works by implementing the functionality with a straight-forward algorithm considering the different cases.

A simple observation can lead to better algorithm. For instance, if we order (x1,y1) and (x2,y2) in such a way that the left-most end is (x1,y2) and the right-most end is (x2,y2) then we have a much smaller number of situations. Assuming xi < xf, we have a bacteria on the left if and only if x1 < xi and a bacteria on the right if and only if x2 > xf (with the 4 combinations possible : right, left, right + left, none).

Before trying to perform any optimisation, we should try to be in a situation where performances can be properly measured : at the moment, the times are much too short to be analysed and the datasets might not correspond to situations leading to timeout.

Before I go further, the assumption here is that your code is not efficient enough when the number of queries performed on a sample gets huge. (This assumption is based on the fact that the values can be much bigger for the number of cases than the number of bactoeria). We can reproduce such a case by putting the lines doing assert(nb_bacteria_after_beam(....)) in for loops. This gives measurable times on my configuration :

int automatic_tests()
{
    int nb_tests = 10000000;
    coordinate coord[] = {{1, 0, 4, 0}};
    coordinate coord2[] = {{2, 0, 4, 0}, {2, 0, 4, 0}};
    coordinate coord3[] = {{0, 0, 3, 5}, {3, 5, 0, 2}};
    for (int i = 0; i < nb_tests; i++)
    {
        assert(nb_bacteria_after_beam(coord, 1, 0, 2) == 1);
        assert(nb_bacteria_after_beam(coord, 1, 3, 5) == 1);
        assert(nb_bacteria_after_beam(coord, 1, 2, 3) == 2);
        assert(nb_bacteria_after_beam(coord, 1, 0, 5) == 0);
        assert(nb_bacteria_after_beam(coord2, 2, 0, 1) == 2);
        assert(nb_bacteria_after_beam(coord2, 2, 1, 2) == 2);
        assert(nb_bacteria_after_beam(coord2, 2, 2, 3) == 2);
        assert(nb_bacteria_after_beam(coord2, 2, 3, 4) == 2);
        assert(nb_bacteria_after_beam(coord2, 2, 4, 5) == 2);
        assert(nb_bacteria_after_beam(coord2, 2, 5, 6) == 2);
        assert(nb_bacteria_after_beam(coord3, 2, 0, 3) == 0);
        assert(nb_bacteria_after_beam(coord3, 2, 1, 2) == 4);
        assert(nb_bacteria_after_beam(coord3, 2, 2, 7) == 2);
    }
    return 0;
}

On such a dataset, I can already see the benefits of the idea described above. Correspond code looks like :

int nb_bacteria_after_beam(coordinate coord[], int N, int xi, int xf)
{
    int nbacterias = 0;
    assert(xi < xf);

    for (int j = 0; j< N; j++){
        coordinate c = coord[j];
        int x1 = c.x1;
        int x2 = c.x2;
        if (x1 > x2)
        {
            // swap
            int tmp = x1;
            x1 = x2;
            x2 = tmp;
        }
        if (x1 < xi)
            nbacterias++;
        if (x2 > xf)
            nbacterias++;
    }
    return nbacterias;
}

When the number of cases gets huge indeed, it might be worth performing some preprocessing to ensure queries can be performed more efficiently.

We can easily write a procedure to prepare our datasets in such a way that we can apply the trick described above directly.

This leads to much better performances indeed :

void prepare_dataset(coordinate coord[], int N)
{
    for (int j = 0; j< N; j++){
        if (coord[j].x1 > coord[j].x2){
            // swap (to keep things nice, y coord has to be moved too even if it is not useful)
            int tmp = coord[j].x1;
            coord[j].x1 = coord[j].x2;
            coord[j].x2 = tmp;
            tmp = coord[j].y1;
            coord[j].y1 = coord[j].y2;
            coord[j].y2 = tmp;
        }
    }
}

int nb_bacteria_after_beam(coordinate coord[], int N, int xi, int xf)
{
    int nbacterias = 0;
    assert(xi < xf);

    for (int j = 0; j< N; j++){
        coordinate c = coord[j];
        assert(c.x1 <= c.x2);
        if (c.x1 < xi)
            nbacterias++;
        if (c.x2 > xf)
            nbacterias++;
    }
    return nbacterias;
}

int automatic_tests()
{
    int nb_tests = 10000000;
    coordinate coord[] = {{1, 0, 4, 0}};
    prepare_dataset(coord, 1);
    coordinate coord2[] = {{2, 0, 4, 0}, {2, 0, 4, 0}};
    prepare_dataset(coord2, 2);
    coordinate coord3[] = {{0, 0, 3, 5}, {3, 5, 0, 2}};
    prepare_dataset(coord3, 2);
    for (int i = 0; i < nb_tests; i++)
    {
        assert(nb_bacteria_after_beam(coord, 1, 0, 2) == 1);
        assert(nb_bacteria_after_beam(coord, 1, 3, 5) == 1);
        assert(nb_bacteria_after_beam(coord, 1, 2, 3) == 2);
        assert(nb_bacteria_after_beam(coord, 1, 0, 5) == 0);
        assert(nb_bacteria_after_beam(coord2, 2, 0, 1) == 2);
        assert(nb_bacteria_after_beam(coord2, 2, 1, 2) == 2);
        assert(nb_bacteria_after_beam(coord2, 2, 2, 3) == 2);
        assert(nb_bacteria_after_beam(coord2, 2, 3, 4) == 2);
        assert(nb_bacteria_after_beam(coord2, 2, 4, 5) == 2);
        assert(nb_bacteria_after_beam(coord2, 2, 5, 6) == 2);
        assert(nb_bacteria_after_beam(coord3, 2, 0, 3) == 0);
        assert(nb_bacteria_after_beam(coord3, 2, 1, 2) == 4);
        assert(nb_bacteria_after_beam(coord3, 2, 2, 7) == 2);
    }
    return 0;
}

More performance

This is pretty good but we haven't really changed the complexity of the algorithm. It used to be 0(N*C) and it still is. Only the constant factor has changed (basically, we still perform a huge number of operation considering all bacteria for all inputs, we just handle them in a more efficient way). What could be interesting (and is probably what is expected by the people who wrote the problems) would be to prepare the dataset in such a way that for a given input, you don't have to reconsider all bacteria again and again.

The point would be to be able to create some kind of summary of your dataset in such a way that you can easily determine the information you need. Basically, it boils down to determine how many items in a list are smaller or bigger than a value you'll be provided later. Indeed, the solution of the problem is the sum of the number of x1 such that x1 < xi and the number of x2 such that x2 > xf. An interesting idea could be to create a sorted array of the x1 values and a sorted array of the x2 values (don't forget that in order to have this trick to work, you first have to re-arrange x1,x2 in such a way that x1 < x2). Once this is done, the number of items smaller (or bigger) than a value can be determined with a binary search algorithm.

Unless I am mistaken, the complexity for such a strategy would be : 0( N*log(N)  +  C * log(N)) because sorting is 0(n*log(n)) and binary search is O(log(n)).

This should be much faster. I'll let you consider this :-)


Using d3.drag() to enable dragging on an SVG group

Yes, there is a simpler way to achieve this: just use d3.event.x and d3.event.y, holding their values in the bound data.

Thus, your drag function can be reduced to only this:

var dragcontainer = d3.drag()
    .on("drag", function(d, i) {
        d3.select(this).attr("transform", "translate(" + (d.x = d3.event.x) + ","
        + (d.y = d3.event.y) + ")");
    })

And, since you don't use them, just drop your "start" and "end" listeners.

Here is the demo (click and drag the group around):

var dragcontainer = d3.drag()
  .on("drag", function(d, i) {
    d3.select(this).attr("transform", "translate(" + (d.x = d3.event.x) + "," + (d.y = d3.event.y) + ")");
  });
var g = d3.select("g").datum({x: 0, y: 0}).call(dragcontainer)
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg style="border: 1px solid gray">
  <g>
    <circle cx="50" cy="50" r="20" fill="teal"></circle>
    <circle cx="100" cy="50" r="20" fill="tomato"></circle>
    <circle cx="150" cy="50" r="20" fill="tan"></circle>
  </g>
</svg>


Extracting the last component (basename) of a filesystem path

Firstly, you should use rsplit and next rather than split and last, as it starts at the more appropriate end:

fn basename<'a>(path: &'a str, sep: char) -> Cow<'a, str> {
    let pieces = path.rsplit(sep);
    match pieces.next() {
        Some(p) => p.into(),
        None => path.into(),
    }
}

Secondly, you shouldn’t be using strings for this; you should be using paths, because that’s semantically what you’re dealing with.

The easiest way to get a path tends to be to take a &Path or a generic parameter implementing AsRef<Path> and calling .as_ref() on it; str, String, Path, PathBuf and more implement it.

You can get the base name from a &Path with file_name; this admittedly produces a Option<&OsStr>, so if you want to display the path you’d need to convert it back towards a string with e.g. .and_then(|s| s.to_str()).

Anyway, the point of this latter part is just that for something that is semantically a path, you should be handling it specially, as a rule; a path need not be Unicode. Think on it more.


Your coding style could be improved, for instance you could respect the naming conventions detailed in the PEP8.

Using classes is not judicious (Python is not Java). You could use simple functions. I understand that this is an exercise but it looks weird.

A function can have parameters and return a value. For instance with divide, you can write:

def divide(number):
    return number // 2

You can do the same for multiply.
To use those functions:

number = ...
result = multiply(divide(number))

Catching TypeError, NameError and AttributeError is not a good practice because they are generally raised because the developer (you) had made an error. This is not the user fault, so the message you display to the user is not useful.

If you really want a class here, you can store the list of results in instead of the user input.

class Math(object):
    def __init__(self):
        self.results = []

    def divide(self, number):
        return number // 2

    def multiply(self, number):
        return number * 4

    def calc(self, number):
        result = self.multiply(self.divide(number))
        self.results.append(result)

You can use this class like this:

my_math = Math()
my_math.calc(5)
my_math.calc(8)
print(my_math.results)
# -> [8, 16]

I'm repeating myself: divide and multiply should be functions, not methods here.


Restucture code to wrap optional resources in a using block

The only think that I would do different is that I wouldn't dispose streams inside your FileProcessor classes. Disposing of resources should be done at the same level (or scope) where they were initialized. Unfortunately, even BCL classes like StreamWriter and BinaryWriter dispose underlying streams when disposed, so I cannot claim that this is unexpected behavior either.

IMO, there is nothing wrong with your code. Going out of your way simply to save two lines of code might make your code less readable, so your first version might easily be the simplest one.

Having said that, if you really want to wrap it in a single using block, one idea (and I don't actually find it "better" than yours in any way) might be to wrap all your disposable resources into a single class:

public class InputFiles : IDisposable
{
    private readonly Dictionary<string, Stream> _files
        = new Dictionary<string, Stream>();

    public Stream GetStream(string type)
    {
        Stream input = null;
        _files.TryGetValue(type, out input);
        return input;
    }

    public InputFiles(string[] args)
    {
        // this is just an idea, you probably don't
        // use the extension to determine the type,
        // but it still seems a bit more general than
        // having strongly typed properties
        foreach (var path in args)
        {
            var ext = Path.GetExtension(path); // pdf or tif?
            _files[ext] = File.OpenRead(path);
        }
    }

    public void Dispose()
    {
        foreach (var stream in _files)
            stream.Value.Dispose();
    }
}

And then dispose the entire object when done:

static void Main(string[] args)
{
    using (var input = new InputFiles(args))
    {
        var pdf = input.GetStream("pdf");
        var tif = input.GetStream("tif");

        // use the appropriate strategy
        // (parsing strategy should not be concerned with
        // disposing of resources)
        Process(pdf, tif);
    }
}


I am going to challenge your premise

  ...then newArray is simply a pointer to oldArray rather than an
  independent copy.

The following code works fine ...

Sub myTest1()
Dim oldArray() As Double, newArray() As Double
Dim i As Long, j As Long

ReDim oldArray(0 To 1, 0 To 2)
For i = 0 To 1
    For j = 0 To 2
        oldArray(i, j) = (i * 10#) + (j * 1#)
    Next j
Next i

newArray = oldArray

For i = 0 To 1
    For j = 0 To 2
        Debug.Print i, j, newArray(i, j)
    Next j
Next i

End Sub

To verify that newArray is not just a pointer to oldArray, the following code ...

Public Declare PtrSafe Function VarPtrArray Lib "VBE7" Alias "VarPtr" (Var() As Any) As LongPtr

Sub myTest2()
Dim oldArray() As Double, newArray() As Double
Dim i As Long, j As Long

ReDim oldArray(0 To 1, 0 To 2)
For i = 0 To 1
    For j = 0 To 2
        oldArray(i, j) = (i * 10#) + (j * 1#)
    Next j
Next i

newArray = oldArray

Debug.Print "oldArray", VarPtrArray(oldArray), VarPtr(oldArray(0, 0))
Debug.Print "newArray", VarPtrArray(newArray), VarPtr(newArray(0, 0))

End Sub

... generates this result ...

oldArray       1633360       350127888
newArray       1633356       350126600

All of which means that, for arrays that do not contain objects, a simple assignment (e.g. newArray = oldArray) is fine to copy an array.


Rendering the periodic table in C++ using SFML

Looking at the code you've posted here, it's pretty straightforward and I'm able to understand what it does. That's great! I have a few suggestions on how to improve it.
Named Types
One common complaint about the standard template library and templates in general in C++ is the ridiculously long type names that result from using them. I see that in your code here. It's easily solved by creating new named types that represent the common types you use. For example:
std::vector<std::shared_ptr<sf::Drawable>>

uses 3 types with namespaces. If you did this:
typedef std::shared_ptr<sf::Drawable> sharedDrawable;

Then your new type becomes:
std::vector<sharedDrawable>

Or even better, use the new using directive in C++11:
using sharedDrawableVector = std::vector<std::shared_ptr<sf::Drawable>>;

Or something along those lines.
Use C++!
You're writing in C++, but you're using older methods of iterating through containers. In the destructor of Element you're going through the list manually when you could use a std::find() method instead.
Magic Numbers
In the constructor of Element you create a vector with coordinates <49, 49>. What does it mean? What is it? Why <49, 49>? You should create a constant with a name that describes what this represents:
const sf::Vector2f kRectOriginVector {49, 49}; // Or whatever it means

Then use that in the constructor.


Return the largest product of 2 numbers that is a multiple of 9 in O(n)

The solution will be of one of two forms :

  a * b where a is divisible by 9

or

  c * d where c is divisible by 3 and d is divisible by 3

To find the maximum of the first from we need to find the greatest number divisible by 9, and combine it with the greatest number, or the second greatest if the one divisible by 9 is the greatest.

To find the maximum of the second form we need to find the two greatest numbers divisible by 3.

So you can loop all numbers and determine for each number if it is a better candidate for a,b, c or d.

After that loop, calculate a*b and c*d, and the greatest of both wins, and is the result.

This algorithm results in \$O(n)\$ complexity.


Displaying a paginated list of forum topics using PHP PDO

This code is safe from the SQL injection standpoint but it is likely prone to XSS because of the untreated output, and also to possibly leak the sensitive information due to the error message unconditionally spat out.

Regarding other improvements I would suggest a more robust connection code and to avoid bindParam calls thanks to disabled emulation mode.

The rewritten code would be

include 'pdo.php';
$num_rows = $conn->query('SELECT COUNT(*) FROM a_topics')->fetchColumn();
$pages = new Paginator($num_rows,25,array(25,50,100,250,'All'));
$stmt = $conn->prepare('SELECT a_topics.pid, a_topics.title, a_topics.forum_id, b_forums.id, b_forums.name
    FROM a_topics INNER JOIN b_forums ON a_topics.forum_id = b_forums.id
    ORDER BY a_topics.pid DESC LIMIT :start,:end');
$stmt->execute(['start' => $pages->limit_start, 'end' => $pages->limit_end]);
$result = $stmt->fetchAll();

echo $pages->display_jump_menu().$pages->display_items_per_page();
echo $pages->display_pages();
foreach($result as $row) {
    echo htmlspecialchars($row[0]),
         " - ",
         htmlspecialchars($row[1]),
         " - ",
         htmlspecialchars($row[2])";
}


Interesting question:

Naming

JavaScript uses lowerCamelCase variable and function names. ( tblcontentstwo -> TblContentsTwo or TabelContents2
Some of your prefixes like sb are not adding anything. I would drop those prefixes.
Names like slideele2 are unfortunate, ideally the name should reflect what is being slided (slid?)

Comments

You have no comments whatsoever, fortunately the code reads well
Still, in some places, like sbContainer.swatchbook(, I have no clue what you are trying to accomplish

JSHint.com

Your code passes all checks, except for 1 semicolon, well done ;)

Readability

You don't use newlines consistently, more specifically you need more newlines in a few spots
Also your indentation is off in places, I would use a site like http://jsbeautifier.org/

Don't Repeat Yourself

This looks like copy pasted code:

var toggleStatemenu2 = true;
$(tblcontentstwo).on("click", function () {
if (toggleStatemenu2) {
    $(slideele2).animate({
    top: '+=171'
    }, 458, 'swing', function () {});
} else {
    $(slideele2).animate({
    top: '-=171'
    }, 458, 'swing', function () {});
}
toggleStatemenu2 = !toggleStatemenu2;
});
var toggleStatemenu = true;
$(tblcontents).on("click", function () {
if (toggleStatemenu) {
    $(slideele).animate({
    left: '+=240'
    }, 458, 'swing', function () {});
} else {
    $(slideele).animate({
    left: '-=240'
    }, 458, 'swing', function () {});
}
toggleStatemenu = !toggleStatemenu;
});

you could try to make a helper function there.

var toggleStates = {};

function createSlider( button, slider, animation1, animation2 ){
  toggleStates[button.id] = true;
  $(button).on("click", function () {
    if (toggleStates[button.id]) {
      $(slider).animate(animation, 458, 'swing', function () {});
    } else {
      $(slider).animate(animation2, 458, 'swing', function () {});
    }
    toggleStates[button.id] = !toggleStates[button.id];
  }
}
createSlider(tblcontentstwo, slideele2, {top: '+=171'}, {top: '-=171'} );
createSlider(tblcontents, slideele, {left: '+=240'}, {left: '-=240'} );


Your code looks good, seems to work and is somehow documented but it can still be improved in various ways (not only performances which will be only tackled at the end if at all).

Code organisation

Your call to main could be moved behind an if __name__ == "__main__": guard in case you ever want to reuse get_straight(). It may not be relevant in your case but it is a good habit to take.

Then, it may be a good idea to split your code into smaller functions, easier to understand and to maintain.

By doing so, you'd also separate the concerns my having the code computing the results you need not mixed up with the logic handling the input/output.

Finally, and maybe even more important, that will make your code testable. Indeed, before performing any changes in the algorithm, it is highly recommended to write unit-tests to prevent you from breaking everything (tests are usually not fail-proof but they help a lot).

from operator import itemgetter
from itertools import groupby

def get_straight(chunk: list, idx: int, straight: int, dice: set) -> int:
    """Get max straight starting at index idx."""
    if idx == len(chunk) - 1:
        return straight

    item = chunk[idx]

    return max((get_straight(chunk, idx+1, straight+1, dice-{x})
                for x in item[1] if x in dice), default=straight)

def longest_straight_length(dices):
    """Return the length of the longest possible straight using `dices`."""
    integers = []
    for j, dice in enumerate(dices):
        integers.extend((val, j) for val in dice)
    integers.sort(key=itemgetter(0))

    grouped = [(k, [x[1] for x in g])
               for k, g in groupby(integers, itemgetter(0))]
    chunks = []

    # find runs of consecutive numbers
    for k, g in groupby(enumerate(grouped), lambda x: x[0]-x[1][0]):
        g = list(g)
        if len(g) > 1:
            chunks.append(list(map(itemgetter(1), g)))

    chunks.sort(key=len, reverse=True)

    max_straight = 1

    for chunk in chunks:
        if len(chunk) <= max_straight:
            break

        for k in range(len(chunk)-1):
            if len(chunk) - k < max_straight:
                break
            dice = set(range(len(dices)))
            straight = get_straight(chunk, k, 0, dice)
            if straight > max_straight:
                max_straight = straight
    return max_straight

def interactive():
    for i in range(int(input())):
        ndice = int(input())
        dices = [[int(x) for x in input().split()] for _ in range(ndice)]
        print("Case #{}: {}".format(i+1, longest_straight_length(dices)))

def unit_tests():
    test_cases = [
        ([[4, 8, 15, 16, 23, 42],
          [8, 6, 7, 5, 30, 9],
          [1, 2, 3, 4, 55, 6],
          [2, 10, 18, 36, 54, 86]],
         4),
        ([[1, 2, 3, 4, 5, 6],
          [60, 50, 40, 30, 20, 10]],
         1),
        ([[1, 2, 3, 4, 5, 6],
          [1, 2, 3, 4, 5, 6],
          [1, 4, 2, 6, 5, 3]],
         3)
    ]
    for dices, expected_result in test_cases:
        actual_result = longest_straight_length(dices)
        if actual_result != expected_result:
            print(expected_result, actual_result, dices)

if __name__ == "__main__":
    if True:
        unit_tests()
    else:
        interactive()

Rewriting the logic

The beginning of the logic creating chunks could be rewritten using a dictionnary rather than performing smart groupby and tricky index accesses. (At the end, I re-build the data structure you are using to be able to keep the code you've written). We'd get something like:

def longest_straight_length(dices):
    """Return the length of the longest possible straight using `dices`."""
    # Mapping value to list of dice indices
    number_on_dices = dict()
    for i, dice in enumerate(dices):
        for val in dice:
            number_on_dices.setdefault(val, []).append(i)

    # Consecutive chunks
    chunks = []
    for k, g in groupby(enumerate(sorted(number_on_dices.keys())), lambda x: x[0] - x[1]):
        g = list(g)
        if len(g) > 1:
            chunk = [y for (_, y) in g]
            chunks.append(chunk)
    chunks.sort(key=len, reverse=True)

    # Re-add values to be reuse existing logic for the time being
    chunks = [[(val, number_on_dices[val]) for val in chunk] for chunk in chunks]

    max_straight = 1

    for chunk in chunks:
        if len(chunk) <= max_straight:
            break

        for k in range(len(chunk)-1):
            if len(chunk) - k < max_straight:
                break
            dice = set(range(len(dices)))
            straight = get_straight(chunk, k, 0, dice)
            if straight > max_straight:
                max_straight = straight
    return max_straight

Then, it appears clearer that the first element in pairs from chunks are never used.
We can simply have:

chunks = [[number_on_dices[val] for val in chunk] for chunk in chunks]

and in get_straight:

return max((get_straight(chunk, idx+1, straight+1, dice-{x})
            for x in item if x in dice), default=straight)

Ultimately, we can simplify the code building chunks:

# Consecutive chunks
chunks = []
for k, g in groupby(enumerate(sorted(number_on_dices.keys())), lambda x: x[0] - x[1]):
    g = list(g)
    if len(g) > 1:
        chunk = [number_on_dices[y] for (_, y) in g]
        chunks.append(chunk)
chunks.sort(key=len, reverse=True)

However, the expensive part is still here, in the recursive calls to get_straight. (I haven't found a trick for this yet but current version of the code is available here: http://termbin.com/yg5l ).

Bug ?

As I was trying to come up with bigger and bigger examples with more recursive calls, I've added the following test cases:

    ([[1, 2, 3, 4, 5, 6],
      [7, 2, 3, 4, 5, 6],
      [7, 8, 3, 4, 5, 6],
      [7, 8, 9, 4, 5, 6],
      [7, 8, 9,10, 5, 6],
      [7, 8, 9,10,11, 6],
      [7, 8, 9,10,11,12]],
     7),
    ([[1, 1, 1, 1, 1, 1],
      [2, 2, 2, 2, 2, 2],
      [3, 3, 3, 3, 3, 3],
      [4, 4, 4, 4, 4, 4],
      [5, 5, 5, 5, 5, 5],
      [6, 6, 6, 6, 6, 6],
      [7, 7, 7, 7, 7, 7]],
     7),

In both cases, we could generate the sequence [1, 2, 3, 4, 5, 6, 7] of length 7. However, the code returned 6. If you want to go further from that part, the code with additional tests and performance indicators is available here: http://termbin.com/c690 .


Product of all but one number in a sequence - Follow Up

You could eliminate the special case here:

//left most element special handling
new_arr[0]=1;

//swipe up
for(int i=1; i<arr_size; i++) {
    mult_prefix *= nums[i-1];
    new_arr[i] = mult_prefix;
}

by assigning before multiplying, and bringing index 0 into the loop:
//swipe up
for(int i=0; i<arr_size; i++) {
    new_arr[i] = mult_prefix;
    mult_prefix *= nums[i];
}

A similar transformation also applies to the downward sweep (so that each iteration only accesses nums[i], making it easier to reason about).
There is a cost associated with the simplification: an extra multiply, and risk of overflow (technically Undefined behaviour, even though we don't use the final value).


Given an array of Strings , check if they are anagrams are not

1

class anagrams: in Java, class names must begin with a capital letter.

2

You restrict yourself to ASCII. However, you could use a HashMap<Character, Integer>. Of course, it implies larger constant factor, yet it matches the linear time complexity of your implementation.

Summa summarum

I thought about this:

public static boolean areAnagrams(String word1, String word2) {
    if (word1.length() != word2.length()) {
        return false;
    }

    Map<Character, Integer> map = new HashMap<>();

    for (char c : word1.toCharArray()) {
        map.put(c, map.getOrDefault(c, 0) + 1);
    }

    for (char c : word2.toCharArray()) {
        int count = map.getOrDefault(c, 0) - 1;

        if (count < 0) {
            return false;
        }

        map.put(c, count);
    }

    return true;
}

Hope that helps.


Getting/setting default values from my App.config

While somewhat of a tangent from your question but you may find it helpful nonetheless.

I would recommend looking at a custom ConfigurationSection which allows you to define more complex configuration hierarchies that are strongly-typed.  I find it much easier to use a custom configuration section than having to remember a bunch of magic strings in the appSettings element and also allows you to specific which values are required, what the defaults values are, etc.

Using a custom configuration section you could create a configuration type like:

public class UboldiConfigurationSection : System.Configuration.ConfigurationSection {
    [ConfigurationProperty("schoolName")]
    public string SchoolName {
        get { return (string)this["schoolName"]; }
        set { this["schoolName"] = value; }
    }
}

Then to load that configuration type:

public static class UboldiApplication {
    public static UboldiConfigurationSection Config { get; internal set; }

    public static void Initialize() {
        Config = ConfigurationManager.GetSection("uboldi") as UboldiConfigurationSection;
    }
}

The app.config then would look something like this:

<configuration>
    <configSections>
        <section name="uboldi" type="Uboldi.UboldiConfigurationSection, Uboldi" />
    </configSections>
    <uboldi schoolName="Fillmore Central" />
</configuration>

Lastly, you use the configuration by:

public void Test() {
    //This only needs to be done once, presumably in your Program.Main method
    UboldiApplication.Initialize();

    var name = UboldiApplication.Config.SchoolName;
}

A couple of notes:

You'll need to reference the System.Configuration assembly as it's not usually referenced in VS by default.
The ConfigurationManager.GetSection("uboldi") is expecting the name of the section in the app.config file.  You'll note that this matches in the example above.
The section element in the app.config file uses the standard .Net type name convention to locate the specified configuration section.  In this example I am assuming that the UboldiConfigurationSection type is the Uboldi namespace and in an Uboldi assembly (dll or exe).
You can add hierarchy by creating ConfigurationElement sub classes and using them as properties in your configuration section and elements.
The link above is for a Web.config, but the same thing is possible in an app.config file.


Prime power mathematical problem in Python

Welcome, there are some aspects to comment about.

First is that, you should use specific names for your functions pp is ok and sounds quite interesting, but it would be better if you use is_prime_power (as mentioned by Konrad Rudolph in the comments).
Now, for the first function, I would change only two things:

def is_prime_power(q):
    fact = factorint(q)
    p = int(list(fact.keys())[0])
    n = int(list(fact.values())[0])
    return q == p**n # this line asks 'is prime power?'

# could also be:
def is_prime_power(q):
    return q == int(list(fact.keys())[0])**int(list(fact.values())[0])
# but is quite strange because p,n are not specified.

# this inverses the boolean answer, as you see
    if q != p**n:
        return False
    else:
        return True

For the procedure, you should avoid using comparisons with True and False. If the value is a boolean, Python deduces if it is true or false, in the case of compare with False use not:

a = [1,6][-1]

b = a*2
d = 1
while d != 0:
    c = b-a
    if not is_prime_power(b) and is_prime_power(c):
        for i in range(b-1, c-1, -1):
            if i == c:
                d = 0
            elif is_prime_power(i):
                b = i+a
                break
    elif not is_prime_power(b):
        for i in range(b-1, c-1, -1):
            if i == c:
                b = b+a+1
            elif is_prime_power(i):
                b = i + a
                break
    elif is_prime_power(b):
        b = b+a
b

Well, thanks for writing easy to read code, it is so good to see something like it.


Code that finds the largest palindrome from two three-digit factors

Code formatting

Your code seems to be poorly indented. I suggest you have a look at the documentation of your favorite text editor to see how to fix this.

Basic logic

It doesn't make much sense to check :

    if (fmod(p, i) != 0)
        continue;
    if (fmod(p, i) == 0)

Similarly,

        if (1000 <= c){
            return false;
        }
        else if (c <= 1000){

is quite redundant.

using namespace std;

Using using namespace std; is usually frowned upon, some will say that it is ok in a cpp file, some will say the opposite. I'll let you decide.

The right type

You are using double but long int are more than enough for what you are trying to do.

Right place to define variables

It is usually a good idea to define variables in the smallest possible scope. Among other things, it helps the reader not to have to keep too many things in mind. Also, it helps you see that intermediate is an unused variable. As a side-note, it is a good idea to activate all the warnings in your compiler to detect such a thing (and many other potential errors).

Define constants

Instead of having 5 in the middle of your code and need to comment it, you could store 6 in a constant named for instance NB_DIGITS and remove the need for any comment.

Use for loops when you can

Now, the loop to aquire digits can be rewritten :

for (int i = NB_DIGITS -1; 0 <= i; i--) { //acquire digits of number
    decimalDigit[i] = (number - fmod(number, pow(10, i))) / pow(10, i);
    cout << "Value of digit place " << i << " is " << decimalDigit[i] << endl;
    number = fmod(number, pow(10, i));
}

Compute things only once

You call pow(10, i) way too many times compared to what you actually need. You can simply write :

    double pow_ten = pow(10, i);
    decimalDigit[i] = (number - fmod(number, pow_ten)) / pow_ten;
    cout << "Value of digit place " << i << " is " << decimalDigit[i] << endl;
    number = fmod(number, pow_ten);

Smarter decomposition of a number

Instead of going through the hassle of getting digits starting with the one with the strongest weight, it is much easier to start by the end. Also, this makes you perform the iteration in the logicial order.

Better names

numberVectorAddition is a pretty bad name for a parameter. n conveys enough information as far as I can tell.

palindromeTests is also quite bad. hasDivisorsInRange is probably better.

Finally, DecimalDigit is a bit redundant are digits already include the notion of 10 but also, it probably should be plural to tell that it's a collection.

No need for new/delete here

You don't need to use new/delete here. If you just define it long int digits[NB_DIGITS];, it will be deleted when it does out of the scope.

Clearer responsability for functions

It could be interesting for your function to return values instead of printing them. This would lead to separation of concerns. One of the multiple advantages is to make your code easier to test.

At this point your code, looks like :

#include <iostream>
#include <math.h>

using namespace std;

const int NB_DIGITS = 6;

bool hasDivisorsInRange(long int n){//tests if the factors of the palindrome are both below 3 digits each.
    for (long int i = 999;; i--){
        if (n % i == 0)
        {
            long int c = n / i;
            if (1000 <= c){
                return false;
            }
            else if (c <= 1000){
                cout << "Factors of the number both below 1000 are " << i << " and " << c << endl;
                return true;
            }
        }
    }
}

long int LargestPalindrome(long int number){
    long int digits[NB_DIGITS];
    for (int i = 0; i < NB_DIGITS; i++) { //acquire digits of number
        digits[i] = number % 10;
        number /= 10;
        cout << "Value of digit place " << i << " is " << digits[i] << endl;
    }
    for (int q = 0; q < 100; q++){ //decreases size of palindrome, and also tests after the decrease.
        long int n = pow(10, 5)*digits[0] + pow(10, 4)*digits[1] + pow(10, 3)*digits[2] + pow(10, 2)*digits[3] + pow(10, 1)*digits[4] + digits[5];
        cout << digits[0] << digits[1] << digits[2] << digits[3] << digits[4] << digits[5] << '\t';
        cout << n << endl;
        if (hasDivisorsInRange(n))
            return n;
        digits[2]--;
        digits[3]--;
        if (digits[2] == 0){
            long int n2 = pow(10, 5)*digits[0] + pow(10, 4)*digits[1] + pow(10, 3)*digits[2] + pow(10, 2)*digits[3] + pow(10, 1)*digits[4] + digits[5];
            cout << digits[0] << digits[1] << digits[2] << digits[3] << digits[4] << digits[5] << '\t';
            cout << n2 << endl;
            if(hasDivisorsInRange(n2))
                return n;
            if ((digits[1] == 0) && (digits[2] == 0)){
                digits[1] = 9;
                digits[4] = 9;
                digits[2] = 9;
                digits[3] = 9;
                digits[0]--;
                digits[5]--;
                continue;
            }
            digits[2] = 9;
            digits[3] = 9;
            digits[1]--;
            digits[4]--;
        }
    }
    return 0;
}

int main(){
    long int n = 906608; //997799 is equal to 999*999 - 2; palindrome is smaller.
    int pal = LargestPalindrome(n); //finds the largest palindrome below "n" that has both factors of three digits.
    cout << "Solution is " << pal << endl;
}

Better algorithm

You are trying to iterate over palindromes in a quite complicated way (that I do not understand at all). To iterate over palindromes composed of 6 digits is nothing but iterating over values between 100 and 999 and adding the mirrored version of the number at the end.

This can be badly written :

long int LargestPalindrome(long int number){
    for (int beg = (number / 1000); beg > 100; beg--)
    {
        // Could be done in a clean way with array but I'm lazy
        int i = beg;
        int a = i % 10; i/=10;
        int b = i % 10; i/=10;
        int c = i % 10; i/=10;
        long int pal = beg * 1000 + 100 * a + 10 * b + c;
        if (pal < number && hasDivisorsInRange(pal))
            return pal;
    }
    return 0;
}

For n = 906608, this finds 888888 which happens to be a better solution that the one found by your code.

Also, you could perform a smarter research for divisors.

I have to go, I'll try to continue this answer at some point.


Project Euler #19: Counting Sundays in the 20th century using Pandas

It is good to use a library rather than re-inventing everything yourself. Just be sure to avoid explicit looping in Python:

sum(date.day == 1 and date.weekday() == 6 for date in rng)

The above sums the number of times that date.day == 1 and date.weekday() == 6 automatically, with no loops of counters, It should also be more efficient (sum is implemented in C)


How to write a simple script to read text from a file and compute the number of sentences, number of unique words and punctuation/symbols? (NodeJS)

Word count bug This line here:
const wordCount = (string) => string.split(" ").length;

will overcount the number of words if the input text happens to have multiple spaces in a row. For example:

const wordCount = (string) => string.split(" ").length;

console.log(wordCount(`
  foo        bar baz
`));

I'd use .match instead, and match contiguous non-space characters. (Can't use \w+, since that'd result in they're and similar being counted as 2 words, and since \w only works with English letters - matching non-spaces is easier than figuring out all the possibilities, and will work for any romance language)

const wordCount = (string) => (string.match(/\S+/g) || []).length;

console.log(wordCount(`
  foo        bar baz
`));

The .match(..) || [] is needed because .match will return null (and not the empty array) if no matches are found.
uniqueWords bug As noted above, \w+ won't be accurate given apostrophes and other punctuation marks that may be around or inside single words. (You also need to alternate the .match with [] as described above too)
paragraphCount issues
You have:
paragraphString = paragraphString.split("\n\n");

There are a few problems here:

The paragraphString is initially not the string of a paragraph, but a string containing the entire input text - better to call it something like inputText.
Then, the paragraphString becomes an array - but its name is paragraphString? Easy source of confusion.
You're unnecesarily reassigning the paragraphString variable - it may refer to one thing, or it may refer to another, depending on what point in the program you're examining it. Code is generally easiest to reason about when the contents of a given variable name doesn't change. Occasionally it's necessary (like with a counter), but often it isn't - better to put a new expression into a different variable rather than reassigning the old one, if possible.

Similarly:
let paragraphArray = paragraphString.length; // length of paragraph array

But the .length is a number, not an array. Giving variables understandable, precise variable names makes code easier to read and helps prevent bugs. I'd either call it paragraphIndex - or, even better, avoid manually iterating over the array entirely and use an array method instead, eg:
paragraphArray.forEach((paragraphString) => {
  // check paragraphString

Empty strings can have .replace called on them just fine, and it makes the code easier to read, so you can simplify the assignment of tmp to:
const paragraphString = paragraphStrings[paragraphIndex].replace(strip_whitespace,"");

Or you could simplify the whole function here by filtering the array of paragraphs by those with a trimmed length:
const paragraphCount = inputText => inputText
  .split('\n\n')
  .filter(paragraphText => paragraphText.trim())
  .length;

You could also use .reduce to count up, instead of constructing an intermediate array that gets used only for its length, but the intent of this .reduce is probably a bit harder to recognize at a glance for some:
const paragraphCount = inputText => inputText
  .split('\n\n')
  .reduce((a, paragraphText) => a + paragraphText.trim() ? 1 : 0, 0)

\n\n might not be good enough, though - can you count on the file encoding using \ns only for newlines? Some files/OSs use \r\n. I'd use /\n\r?\n/ instead.
Punctuation count idea Rather than:
const punctuations = [".", ",", "!", "?"];
// const symbols = ["~","`","!","@","#","$","%","^","&","*","(",")","_","+","-","=","{","}","|","[","]","\",":",";","'","<",">","?","/",]

With a lot of punctuation, the above can be both hard to read and easy to make typos on. If you have more than a few, consider using a string that gets parsed into an array later:
const symbols = `\`~!@#$%^`.split(''); // and so on

You could even make it multiline or put it in a separate file if you wanted, then parse it as needed.
To reduce the computational complexity of the algorithm, make a Set of the punctuations in advance; Set.has is O(1), but Array.includes is O(n). With large files, this could make a big difference, especially if you wree using the large symbols array instead of the smaller punctuations array.
Constructing a regular expression that alternates between all punctuation characters might be even faster.


Python class w/ Telnet interface to memcached

The pattern

self.client.write("some command\n")
response = self.client.read_until('END')

appears three times in your code. I think this is often enough to warrant refactoring it into its own method like this:

def command(self, cmd):
    self.client.write("%s\n" % cmd)
    return self.client.read_until('END')

In key_details you're using extend to build up a list. However it's more pythonic to use list comprehensions than building up a list imperatively. Thus I'd recommend using the following list comprehension:

regex = 'ITEM (.*) \[(.*); (.*)\]'
cmd = "stats cachedump %s 100"
keys = [key for id in slab_ids for key in re.findall(regex, command(cmd % id))]

Afterwards you do this:

if sort:
    return sorted(keys)
return keys

Now this might be a matter of opinion, but I'd rather write this using an else:

if sort:
    return sorted(keys)
else:
    return keys

I think this is optically more pleasing as both returns are indented at the same level. It also makes it immediately obviously that the second return is what happens if the if condition is false.


Avoiding race in a sub-millisecond TOD timer

Carefully examine all possible interactions between interrupts
There are many possible ways interrupts can happen, you should take some time and carefully try to map them out. I think you missed a few corner cases in case where usecs() is called from a higher priority context than timer_isr(). First, given your description, the function usecs() can be called either from a low or a high priority context:
Low priority call to usecs()
It's either not called from an interrupt context, or from an interrupt with a lower priority than the timer overflow interrupt. In this context, usecs() might be interrupted by timer_isr() at any point during its execution. So look at all the possible places where the timer_isr() could fire:
// 1
uint32_t counter1 = timer->COUNTER;
// 2
uint32_t ticks1 = ticks;
// 3
uint32_t counter2 = timer->COUNTER;
// 4
uint32_t ticks2 = ticks;
// 5

Before I am going to look at all 5 possibilities, I'm also going to make some assumptions:

Any higher interrupts together will never take more than 100 milliseconds. This should be reasonable, and avoids us having to worry about the timer overflowing twice while usecs() runs.
The COUNTER effectively gets reset to PRELOAD by the hardware during the interrupt to timer_isr(). You must verify this by reading the documentation of the MCU.

So now for the five possibilities of where the timer reset happens, and after the four statements have run the results will be:

ticks1 == ticks2 and counter1 > counter2 (trivial case)
ticks1 == ticks2 and counter1 < counter2 (only counter2 is valid)
ticks1 != ticks2 and counter1 < counter2 (either ticks1+counter1 or ticks2+counter2 are valid)
ticks1 != ticks2 and counter1 > counter2 (only ticks1 is valid)
ticks1 == ticks2 and counter1 > counter2 (trivial case)

It looks like your code handles all these cases correctly.
High priority calls to usecs()
Here we can never be that timer_isr() interrupts usecs(), but it could be that usecs() interrupted timer_isr(). Let's look at those cases separately.
usecs() did not interrupt timer_isr()
The question is now, what happens when the timer resets? Again, check the documentation of your MCU, but I am assuming that COUNTER will be reset to PRELOAD, just that timer_isr() doesn't fire because we are already in a higher level interrupt. So now ticks1 == ticks2 will always be true. We still have the five positions where the reset can happen:

counter1 > counter2 (ticks1 and ticks2 are behind)
counter1 < counter2 (ticks2 is behind)
counter1 < counter2 (ticks2 is behind)
counter1 > counter2 (everything is valid)
counter1 > counter2 (everything is valid)

Oops, you cannot distinguish case 1 from cases 4 and 5 just by looking at the counter values. The TIMER_STATUS_IF flag also doesn't help in distinguishing what happened, at least not if you check it after reading the counters. So you have to read the counter again:
if (timer->STATUS & TIMER_STATUS_IF) {
    // The counters wrapped somewhere prior to exactly this if-statement.
    // We assume it won't wrap again from here, because all interrupts will
    // be handled in less than 100 ms.
    counter2 = timer->COUNTER;
    ticks2 += 1;
} ...

usecs() did interrupt timer_isr()
In a way this looks simpler, because we know the counter reset just before usecs() was called, so we don't have to worry about the counters being able to reset during usecs(). However, now we have to worry about where exactly in timer_isr() we had the higher level interrupt. Again there are several possibilities:
// 1
ticks++;
// 2
timer->STATUS &= ~TIMER_STATUS_IF;
// 3

Oops, there is no way to distinguish case 1 from case 2 from usecs()! Reordering statements won't help here, there will always be a point right before and one right after the increment. The only way I see is to ensure both ticks++ and timer->STATUS &= ~TIMER_STATUS_IF are executed atomically. Perhaps this can be done by having timer_isr() disable higher level interrupts:
cli(); // disable all interrupts
ticks++;
timer->STATUS &= ~TIMER_STATUS_IF;
sei(); // reenable interrupts

This should make usecs() work correctly.


Function to find the minimum depth of a tree

This code will visit every node in the tree, but it's not always necessary to do all that work. Instead you can do a breadth-first traversal of the tree, and look for the first node that has no children.

Consider this tree:

    o
   / \
  o   o
       \
        o
         \
          o
          ...
            o
             \
              o

With a breadth-first traversal, you only need to look at two nodes to determine the minimum depth. With the current code, you will visit every node and use \$O(n)\$ stack space in the process.

In some cases you will have to traverse every node, but my point is that sometimes you can do better.

The only trick is that you also have to keep track of the depth of each node.

The idea is to:

Enqueue the root onto a queue
While the queue is not empty:

Dequeue from the queue
If the node has no children, return its depth; this is a node of minimum depth in the tree.
Otherwise, enqueue the children of the node onto the queue


Async task post method WebAPI controller

You need to take care of Single Responsibility Principle here.
Your Post method should handle only HTTP request and then it passes to another handler for further operation and after receiving the result, revert back to User.

You can follow SRP and DRY principle in your code.


Getting the order of values so none are hidden

As far as I can undestand the key point is that you need to have an order of the fields based on the fields value from the greater to the smaller.

I think you can solve it just sorting the fields like it is an array:

const firstElement = obj[0];
const sortedNamedValues = Object.keys(firstElement)
    .sort((a, b) => {
        return firstElement[b] - firstElement[a]
    });

So in sortedNamedValues are now the fields names sorted from the greater to the smaller.

Now I see the bar class is sticket to the field name: actual with bar, projected with bar2 and so on.

That could be done in a lookup table map:

const classesToValues = {
    actual: 'bar',
    projected: 'bar2',
    le: 'bar3'
};

So your assignment code will became:

const biggesteClass = classesToValues[sortedNamedValues[0]];
const biggestVal = firstElement[sortedNamedValues[0]];
const secondClass = classesToValues[sortedNamedValues[1]];
const secondVal = firstElement[sortedNamedValues[1]];
const thirdClass = classesToValues[sortedNamedValues[2]];
const thirdVal = firstElement[sortedNamedValues[2]];


There is a lot of things done right in your program. The code is structured into functions, there are docstrings, you validate user input and you even have a main guard. Still there is room for improvement.

code duplication

This is a minor issue in your code but I do not want to skip it. In

def print_header():
    print("-" * 40)
    print("Welcome to the number guessing game")
    print("-" * 40)

which could read

def print_header():
    dashed_line = "-" * 40
    print(dashed_line)
    print("Welcome to the number guessing game")
    print(dashed_line)

The reason for not duplicate code (even if it is less code) is maintenance. If you ever chose to increase the line length there is a single place to edit.
In your case the chance to miss the other number is low. But keep that in mind.

naming of functions and variables

user_input() is not the best name as there is many user interaction. A better name would be get_user_guess().
Also play_again() does not play but getting user input again. Might be get_user_play_again().

overdone design

Your function

def generate_number_to_guess(lower_number, higher_number):
    """Generates a random number between the given lowest and highest number

    Parameters
    ----------
    lower_number : int
        Lowest number for the generator

    higher_number : int
        highest number for the generator

    Returns
    -------
    int
        returns the generated random number that is in the given range.
    """
    return random.randint(lower_number, higher_number)

does nothing but calling a standard(!) function with the same parameter signature. Instead call the standard function directly.
Such detors are not good in terms of maintainability. Every reasonably experienced python programmer does know randint().
If reading that in a code he exactly knows what's happening. If he stumbles onto a call of your function he must immediately look upon your implementation to get to know what it does.
He must not trust your docstring (between?!) but read the code. He is even forced to write unittests if they are not existing and there are some lines of implementation.
In your case it is a pure delegation to a standard function, so the reviewer is happy to find a reliable implementation. But he lost time for no reason.
Do not do this.

Beside that issues your code is very maintainable! It is structured and readable. The complexity of your functions is reasonable. Be very careful with docstrigs.
Your docstring starts with

"""Generates a random number between the given lowest and highest number

while randint.__doc__ returns

'Return random integer in range [a, b], including both end points.\n        '

This is 'between' vs 'including both endpoints'.

global constants

Simply try to avoid them, especially if they are not naturally constant. You nearly did it right in the superfluous function generate_number_to_guess where you decided to pass tarameters instead of accessing the globals directly.
However you stopped early on the process of passing. If you also pass the variables to start_game()

def start_game(lower_number, higher_number):

and call the generator

    number_to_guess = generate_number_to_guess(lower_number,
                                               higher_number)

you are done with that path. Now you also pass these numbers to user_input()

def user_input(lower_number, higher_number):

and eliminate the globals in there.

You end up with shouting variable names (no global constants)

LOWER_NUMBER = 1
HIGHEST_NUMBER = 10

# [...]

if __name__ == "__main__":
    start_game()

which you change to

if __name__ == "__main__":
    start_game(1, 10)

If a value is not globally constant for a function - pass it as a parameter.
The function is then loosly coupled to the rest and is perfectly testable.


Quadrilaterals containing a square number of lattice points

1. Review

There are no docstrings. What do all these functions do? How do I call them? What do they return?
The code is not portable to Python 3 because it uses xrange and the print statement.
The function isSquare is not used and could be removed.
The function lattice does not actually make use of the memoization (it doesn't look at the dictionary memo until it has already computed the result).
There's no need to use math.fabs as the vertices are all at integer points. You could use abs instead.
The program is hard to test because it has code that runs at the top level. This means that you can't run it from the interactive interpreter, or using timeit. It would be better to organize the code into functions to make it easier to test.
It's inconsistent for the function PolygonArea to have a name using CamelCase but other functions (lattice, boundary, interior) to have names using lower case.
The nested loops can be replaced by a single loop using itertools.product.
In order to work on the performance, it would be handy if the parameter \$m=100\$ were not hard-coded. We'd like to be able to run the code with smaller values of \$m\$ and see how the runtime behaves.

2. Revised code

from fractions import gcd
from itertools import product

def polygon_area(corners):
    """Return the area of the polygon with the given vertices."""
    n = len(corners)
    area = 0.0
    for i in range(n):
        j = (i + 1) % n
        area += corners[i][0] * corners[j][1]
        area -= corners[j][0] * corners[i][1]
    area = abs(area) / 2.0
    return area

_memo = {}
def lattice(p1, p2):
    """Return the number of lattice points on the line from p1 to p2."""
    t = abs(p2[0] - p1[0]), abs(p2[1] - p1[1])
    if t not in _memo:
        g = gcd(t[0], t[1]) + 1
        _memo[t] = g
    return _memo[t]

def boundary(p1, p2, p3, p4):
    """Return the number of lattice points on the boundary of the
    quadrilateral with vertices p1, p2, p3, p4.

    """
    return lattice(p1, p2) + lattice(p2, p3) + lattice(p3, p4) + lattice(p4, p1) - 4

def interior(p1, p2, p3, p4):
    """Return the number of lattice points in the interior of the
    quadrilateral with vertices p1, p2, p3, p4.

    """
    corners = [p1, p2, p3, p4]
    A = polygon_area(corners)
    B = boundary(p1, p2, p3, p4)
    I = A - B/2 + 1
    return I

def problem504(m=100):
    """Return the number of quadrilaterals with vertices lying at lattice
    points on the coordinate axes, no more than m units from the
    origin, whose interior contains a square number of lattice points.

    """
    squares = set(i ** 2 for i in range(2 * m))
    count = 0
    for a, b, c, d in product(range(1, m + 1), repeat=4):
        I = interior((a, 0), (0, b), (-c, 0), (0, -d))
        if I in squares:
            count += 1
    return count

3. Measurement

We expect the runtime to be proportional to \$m^4\$, so let's see how this performs on smaller values of \$m\$ and then fit a curve to figure out the projected runtime for \$m = 100\$. Note that because lattice is memoized, we have to be careful to reset the memoization each time.

>>> from timeit import timeit
>>> _memo={}; timeit(lambda:problem504(10), number=1)
0.10902838699985296
>>> _memo={}; timeit(lambda:problem504(20), number=1)
1.7153344419784844
>>> _memo={}; timeit(lambda:problem504(30), number=1)
8.644499261979945
>>> _memo={}; timeit(lambda:problem504(40), number=1)
28.569149894057773

Let's fit these results to the equation \$t = am^4\$:

Gnuplot finds \$a = 1.11 × 10^{-5}\$, so we predict that when \$m=100\$, the runtime will be about 1110 seconds (about 19 minutes).

4. Performance improvement

The code here is general-purpose — for example polygon_area computes the area of any polygon. But in this problem we don't need the general case — we only have quadrilaterals whose vertices are at lattice points on the coordinate axes. So the obvious thing to do is to reduce the amount of work by only computing the bare minimum, and reusing as many results as we can.

The key observation is that we can compute the number of interior points in the quadrilateral from the number of interior points in the four right-angled triangles in the four quadrants, like this:

If I write \$T(a, b)\$ for the number of interior points in the triangle with vertices \$(0, 0)\$, \$(a, 0)\$ and \$(0, b)\$, then this diagram shows that the value we want is $$Q(a, b, c, d) = T(a, b) + T(b, c) + T(c, d) + T(d, a) + a + b + c + d - 3.$$ The value of \$T(a, b)\$ can be computed in various ways, for example using Pick's theorem. I like to use this diagram:

in which there are \$(a - 1)(b - 1)\$ dots altogether, of which \$\gcd(a, b) - 1\$ lie exactly on the hypotenuse (the grey dot), and the remainder divide into two equal halves (the blue and red dots), so $$T(a, b) = {(a - 1)(b - 1) - \gcd(a, b) + 1 \over 2}.$$ In this example, \$a=10\$ and \$b=12\$ so \$\gcd(a, b) = 2\$ and \$T(a, b) = 49\$.

There are now some micro-optimizations we can make:

Let \$U(a, b) = T(a, b) + a\$. Then $$Q(a, b, c, d) = U(a, b) + U(b, c) + U(c, d) + U(d, a) - 3$$ which avoids four additions.
Instead of creating a set of squares, create a set of squares plus 3. Then we can test \$U(a, b) + U(b, c) + U(c, d) + U(d, a)\$ to see if it is a square plus 3. This saves a subtraction.
Instead of maintaining a set of squares plus 3, create a list whose \$i\$th entry is True if \$i\$ is a square plus 3, and False otherwise. Fetching a list entry is faster than determining if an item is in a set.

That results in the following code:

def problem504a(m=100):
    """Return the number of quadrilaterals with vertices lying at lattice
    points on the coordinate axes, no more than m units from the
    origin, whose interior contains a square number of lattice points.

    """
    square_plus_three = [False] * (4 * m * m + 3)
    for i in range(2 * m):
        square_plus_three[i * i + 3] = True
    R = range(m + 1)
    U = [[((a - 1) * (b - 1) - gcd(a, b) + 1) // 2 + a for a in R] for b in R]
    count = 0
    for a, b, c, d in product(range(1, m + 1), repeat=4):
        if square_plus_three[U[a][b] + U[b][c] + U[c][d] + U[d][a]]:
            count += 1
    return count

After all those micro-optimizations, we had better check that we haven't made a mistake. So let's test the new code against the old code:

>>> all(problem504(i) == problem504a(i) for i in range(20))
True

And see what the performance is like:

>>> timeit(lambda:problem504a(10), number=1)
0.007875622948631644
>>> timeit(lambda:problem504a(20), number=1)
0.09821957419626415
>>> timeit(lambda:problem504a(30), number=1)
0.49982553208246827
>>> timeit(lambda:problem504a(40), number=1)
1.6008274049963802
>>> timeit(lambda:problem504a(50), number=1)
4.018431055126712

The runtime is still \$Θ(m^4)\$ so here's the best fit to \$t = am^4\$ as before:

Gnuplot finds \$a = 6.4 × 10^{-7}\$ and so we predict that when \$m=100\$, the runtime will be about 64 seconds. In practice it takes a little longer than that:

>>> timeit(lambda:problem504a(100), number=1)
69.0101949761156


See: https://stackoverflow.com/a/6225706/736079

For comments on enabling content compression for your HTML pages, that usually is enough to reduce the payload by more than 50%.

You can also make use of output buffering and combine it with the HTMLMinify function:

<?php
function sanitize_output($content) {
     $content = Minify_HTML::minify($content);
}

ob_start("sanitize_output");
?>

See: https://github.com/mrclay/minify/blob/master/min/lib/Minify/HTML.php

This still uses Regex at the core, which is still not ideal, but it has been tested by a larger audience and looks quite solid (test to make sure). If you are hosting on IIS, you might be able to use a .NET HttpModule or an ISAPI filter as well. This isn't limited to PHP only, sometimes the Web Server itself has plugins that can help you, like Apache's mod_pagespeed.


Calls many stored dataframes, change them and combine them

There are definitely ways to simplify this code to avoid code repetition. For each of your dataframes, I noticed that you are doing essentially the same thing with only two differences:

the path to the frame
the custom name of each frame

This suggests that these blocks can be simplified into a single function with the two dynamic elements passed in as parameters like this.

def modifyFrame(frameName,frameLocation):
    df = pd.read_pickle(frameLocation)
    lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'ALL']
    lvl1 = ['10x20', '10x10', '10x5', '10x2', ]
    df.index = pd.MultiIndex.from_product([lvl0, lvl1])
    df['Total Acc'] = df.mean(axis=1).round(4)*100
    df=df.reset_index().pivot('level_1', 'level_0', 'Total Acc').loc['10x10'].reset_index()
    df.rename(columns={'10x10':frameName},inplace=True)
    return df

Now there are a few ways to simplify your code. One of the simplest ways would be to just call the function four times. This might be an option if you only have a few frames to modify, and the parameters for the frames don't change.

df_NB_E = modifyFrame('NB_E', '/Dataframes/Total Accuracy NB_E')
df_LDA_E = modifyFrame('LDA_E', '/Dataframes/Total Accuracy LDA_E')
df_DT_E = modifyFrame('DT_E' , '/Dataframes/Total Accuracy DT_E')
df_RF_E = modifyFrame('RF_E' , '/Dataframes/Total Accuracy RF_E')

pd.concat([df_NB_E, df_LDA_E, df_DT_E, df_RF_E], axis=1)

If you have a lot of frames, or if you need to modify the list of frames to be modified often, then I would suggest that you group the parameters together in a list. This makes it easier to loop through the frames. Grouping the parameters into a list like this would also make it easier to store the parameters in a separate location so you could change the frame information without changing the code. This reduces the chance of introducing errors into working code.

frames = [('NB_E' , '/Dataframes/Total Accuracy NB_E'),
          ('LDA_E', '/Dataframes/Total Accuracy LDA_E'),
          ('DT_E' , '/Dataframes/Total Accuracy DT_E'),
          ('RF_E' , '/Dataframes/Total Accuracy RF_E')]

You can use a few different methods to loop through the frames. First you can use a for loop like you mentiond.

modifiedFrames = []

for frame in frames:
    modifiedFrames.append(modifyFrame(frame[0],frame[1]))

pd.concat(modifiedFrames, axis=1)

However, one of the most powerful features of the python language is list comprehension. I suggest that you read more about it here.

Below is my solution to your problem using a function, a list containing the frame information, and a list comprehension.

def modifyFrame(frameName,frameLocation):
    df = pd.read_pickle(frameLocation)
    lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'ALL']
    lvl1 = ['10x20', '10x10', '10x5', '10x2', ]
    df.index = pd.MultiIndex.from_product([lvl0, lvl1])
    df['Total Acc'] = df.mean(axis=1).round(4)*100
    df=df.reset_index().pivot('level_1', 'level_0', 'Total Acc').loc['10x10'].reset_index()
    df.rename(columns={'10x10':frameName},inplace=True)
    return df

frames = [('NB_E' , '/Dataframes/Total Accuracy NB_E'),
          ('LDA_E', '/Dataframes/Total Accuracy LDA_E'),
          ('DT_E' , '/Dataframes/Total Accuracy DT_E'),
          ('RF_E' , '/Dataframes/Total Accuracy RF_E')]

#Combining the 4 dataframes
pd.concat([modifyFrame(frame[0],frame[1]) for frame in frames], axis=1)


Testing a simple guard clause in isolation

Yeah, the code/test ratio is probably a little high - especially if you have to do this for many attributes.

May I direct your attention to the #try method? Seems to me you that you might be able to skip a lot of code (and tests) by doing things like @client.try(:occupation).try(:name).

#try simply returns nil if the receiver doesn't respond to the whatever message you're sending. And since #try is also implemented on the nil object, you can chain "tries" together.

In you views, writing something like <%= @client.try(:occupation).try(:name) %> will just print nothing if the try-chain ends up returning nil - same as your current setup. And if you want a different fallback, you can do this:

<%= @client.try(:occupation).try(:name) || "N/A" %>

In other words, having an entire decorator seems a bit much just to absorb nils. But granted, the view ends up having to dig a bit further into the models.

You can of course also keep the decorator (at least so you current code doesn't break elsewhere), but simply rewrite it using #try to something like

# app/decorators/client_decorator.rb
require "simple_decorator"

class ClientDecorator < SimpleDecorator
  def position
    occupation.try(:name) || ""
  end
end

which I honestly don't know if I'd bother to test very rigorously (lest it breaks horribly).


Counting the elements of one array that are less than or equal to some other numbers

For your current code, the more Ruby-esque and functional way to write it would be:

def counts(numbers, maxima)
  maxima.map do |max|
    numbers.count { |n| n <= max }
  end
end

Don't mess around with "manual" counting and array-appending when you don't have to.

As for general improvements:

Sort the numbers. If you sort them, you won't have to loop through the whole array, you just have to count up to the first case where the comparison returns false. Or you can use Array#bsearch_index to find the "split point" in \$O(\log n)\$ time. Better yet, invert the condition and the index you find is also the count you want:

def counts(numbers, maxima)
  sorted = numbers.sort
  maxima.map do |max|
    index = sorted.bsearch_index { |n| n > max } # note inverted condition
    index || sorted.size
  end
end

The above works because it's using #bsearch_index in its "find minimum" mode (i.e. find the first index for which the block returns true), but since the condition is flipped it'll find the first number that shouldn't be counted. And that number's index equals the count of the elements before it. E.g. using your example input, what happens is:

The numbers get sorted [2, 10, 5, 4, 8] => [1, 4, 5, 8, 10]
For a given maximum, we do a binary search for the index
If the maximum is, say, 7, we'll find index 3 (value 8), since that's the first place where n > max (i.e. 8 > 7).
And since indices are zero-based, 3 is also the total/count we want.

You can also sort the maxima array from high to low. Start with the highest maximum, and filter the numbers array to only include those that fit the n <= max condition. The length of the filtered array is the first count. To find the next count, we only need to find a subset of the filtered array because a lower maximum will always result in a smaller array and a lower count. And so on for the next, smaller, maximum. It's a bit trickier, since you still need to output the totals in the original (unsorted) order.

def counts(numbers, maxima)
  # create an array of [value, index] tuples, sorted (descending) by value
  pairs = maxima.each_with_index.sort_by(&:first).reverse

  result = pairs.each_with_object({numbers: numbers, counts: []}) do |(max, index), memo|
    memo[:numbers].select! { |n| n <= max } # note in-place modification
    memo[:counts] << [memo[:numbers].size, index]
  end

  # re-sort the counts so they match the original order
  result[:counts].sort_by(&:last).map(&:first)
end

which could also be written as:

def counts(numbers, maxima)
  pairs = maxima.each_with_index.sort_by(&:first).reverse

  # create a copy, since we'll be modifying it
  search_space = numbers.dup

  counts = pairs.map do |max, index|
    search_space.select! { |n| n <= max } # note in-place modification
    [search_space.size, index]
  end

  counts.sort_by(&:last).map(&:first)
end

Or you can do everything: Sort both numbers and maxima, and use bsearch_index to figure out where to split the numbers array instead of select!. However, all that sorting and extra busywork might end up being slow.

def counts(numbers, maxima)
  pairs = maxima.each_with_index.sort_by(&:first).reverse
  search_space = numbers.sort

  result = pairs.each_with_object({search_space: search_space, counts: []}) do |(max, index), memo|
    count = memo[:search_space].bsearch_index { |n| n > max }
    count ||= memo[:search_space].size
    memo[:search_space].slice!(0, count)
    memo[:counts] << [count, index]
  end

  result[:counts].sort_by(&:last).map(&:first)
end

And of course, you can memoize the total for a given maximum, so if you encounter the same maximum twice or more, you can just recall a known count without re-searching an array.


Reading two .dat files for calculating location distance

Stop doing this:

using namespace std;

Yes every text book does this. But once you start writing programs more than 10 lines long it causes issues. Prefix items in the standard namespace with std:: (it was designed to be short). See detailed explanation here: Why is using namespace std considered bad practice

OK. What is the difference between Foodbank and Residence looks like they should simply be a Location class. If in later code you you add differences you can derive from the Location (or better use a location member (prefer composition over inheritance)).

Be consistent (and neat with your spacing).

return os << r.x  << "\t"<< r.y<<"\t";
//                     ^^^      ^^^      Hard to read

return os << r.x  << "\t" << r.y << "\t";

When initializing your arrays. No need to use std::copy. Just use the iterators in the vectors constructor.

vector<Foodbank> foodbankData;
copy(std::istream_iterator<Foodbank>(foodbankFile),
     std::istream_iterator<Foodbank>(),
     std::back_inserter<std::vector<Foodbank>>(foodbankData));

// Can be replaced by a single line:
vector<Foodbank> foodbankData(std::istream_iterator<Foodbank>(foodbankFile),
                              std::istream_iterator<Foodbank>());

Not sure why you are pushing the distance into a long single array. That does not help you work stuff out.

for(auto r:residenceData)
{
    for(auto f:foodbankData)
    {
        //std::cout<<f.x <<", "<<f.y <<", "<<std::endl;
        distances.push_back(distanceCalculate(f.x,f.y,r.x,r.y));
    }
}

I would suspect that what you want is a 2D array. The FoodBanks on the Y axis and the Residences on the X axis (as an example). Then given any Residences  you just need to scan the array vertically to find the closest FoodBank.

std::vector<std::vector<double>>   distance;
for(auto r:residenceData)
{
    distance.push_back(std::vector<double>());

    for(auto f:foodbankData)
    {
        //std::cout<<f.x <<", "<<f.y <<", "<<std::endl;
        distances.back().push_back(distanceCalculate(f.x,f.y,r.x,r.y));
    }
}

Wow thats a lot of parameters

double distanceCalculate(double x1, double y1, double x2, double y2)

If your FoodBank and Residence just inherited from a base of Location (or had a location member) then you can pass location as the start and end point and calculate the distance between them.


Printing element combinations that make a neutral compound

I don't believe you can reduce the space complexity, and still maintain the \$O(n)\$ time complexity. There is a trade off here you have to compromise on. Of course, you can, if you want, run on \$O(1)\$ space complexity, but your time complexity will have to be compromised.

Now, your code has a bug.... it needs to add the element to the Dictionary even when it has a match for neutral.... Consider a data set like (fake elements and pH's):

H 0
He 1
C -1
Au 1
...

Then, I would expect there to be two matches, both C and He are 0, and Au and C are 0, but, when you matched C against He, you did not add C to the Dictionary, so it is not in the Dictionary when you process Au, and the match is missed.

Unfortunately, as you add the Au on the match, though, you will overwrite the existing He entry.... because you do not support multiple elements with the same pH.

You need your map to be a Dictionary<Int, IList<string>>, and you need to add the element to the list for the respective pH, Then, when you find a match, you need to map it against all the other Elements....

I believe this will require a full process once through the data, and then another to go through the keys of the Dictionary.

Edit: A third bug (thanks @Heslacher) is that the neutral pH is 7, so your check should be:

if (!map.ContainsKey( 7 - (phValue.Value - 7))


Easy things

auto-generated comments

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return data.size();
}

The method is not auto-generated any more, remove the comment. (this happens in a few places).
brace-placement

In Java, the opening brace { goes at the end of the line, not the start of a new line. Code like this:

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

should look like:

} catch(Exception e) {
    e.printStackTrace();
}

Hard Stuff

This code is likely your problem:

holder.mTitleView.setText(ITEM.get("name"));
Picasso.with(activity).load(ITEM.get("image"))
       .placeholder(R.drawable.icon).resize(150, 150)
       .error(R.drawable.icon).into(holder.imageView1);
System.gc();

There are two things here.

Firstly, System.gc() in any code that is not directly related to the system itself, is almost always a bug. There should never be a need for this. Let the system look after itself. It really does not need your help.

The second item is that it may be taking picasso a long time to load the Images. If you are scrolling to unseen areas of the system then the code may need to be calling the getView() method a lot. You need this method to be fast.

Convert the Picasso line to be an AsyncTask, and let it populate the imageView in the background. That will make populating the views a lot faster


Random Walk simulator seems slow, are there ways to optimize my code?

trials = [0] * 100
for i in range(100):
    trials[i] = randomWalk(200)

You don't need to create a list of zeroes in order to create a list of random walks.  Just use a list comprehension:

trials = [randomWalk(200) for _ in xrange(100)] # In Python3, you should use range().

sum = 0.
for trial in trials:
    sum += trial
avg = 0.
avg = sum / len(trials)

You shouldn't use sum as a variable name because it conflicts with the built-in function.  You know what?  You can use that built-in function:

avg = sum(trials, 0.) / len(trials)

print avg

I'm assuming that you are using Python2 just because of that line (and because of the decimal points in your numbers).  If you put parentheses around avg, your program would run in both versions.  Since I used xrange() above which is not around in Python3, you can't now; but you could also use range() up there to make it bothways-compatible.  range() takes up more memory than xrange(), in Python2, but with only a hundred numbers, it shouldn't really make much difference anyway.


Design a main function which determines which secondary function to be used

You could use match.arg and/or match.fun. They are both pretty standard approaches.

match.arg matches an input string to a pre-defined list. It allows for partial matches and handles the error in case it can't find a match.
match.fun is like a smart get for doing "the right thing" depending on the input.

Using match.arg:

square <- function(a, b) sprintf("square(%s, %s)", a, b)
cube   <- function(a, b) sprintf("cube(%s, %s)", a, b)
other  <- function(a, b) sprintf("other(%s, %s)", a, b)

main <- function(a, b, fun = c("square", "cube"), ...) {
   fun <- match.arg(fun)

   # Then, you could do
   # switch(method, square = square(a, b, ...),
   #                cube   = cube(a, b, ...))
   # or use match.fun:

   fun <- match.fun(fun)
   fun(a = a, b = b, ...)
}

main(a = 1, b = 2, fun = "square")
# [1] "square(1, 2)"
main(a = 1, b = 2, fun = square)
# Error in match.arg(fun) : 'arg' must be NULL or a character vector
main(a = 1, b = 2, fun = "cube")
# [1] "cube(1, 2)"
main(a = 1, b = 2, fun = "sq")  # partial matching
# [1] "square(1, 2)"
main(a = 1, b = 2)
# [1] "square(1, 2)"
main(a = 1, b = 2, fun = "other")
# Error in match.arg(fun) : 'arg' should be one of “square”, “cube”

Using match.fun:

main <- function(a, b, fun, ...) {
   print(fun)
   fun <- match.fun(fun)
   fun(a = a, b = b, ...)
}

main(a = 1, b = 2, fun = "square")
# [1] "square"
# [1] "square(1, 2)"
main(a = 1, b = 2, fun = `square`)
function(a, b) sprintf("square(%s, %s)", a, b)
# [1] "square(1, 2)"
main(a = 1, b = 2, fun = cube)
function(a, b) sprintf("cube(%s, %s)", a, b)
# [1] "cube(1, 2)"
main(a = 1, b = 2, fun = cub)   # no partial matching...
# Error in print(fun) : object 'cub' not found
main(a = 1, b = 2, fun = other)
# function(a, b) sprintf("other(%s, %s)", a, b)
# [1] "other(1, 2)"

As you can see, the two approaches behave a little differently as they may or may not:

allow functions as inputs (e.g. square instead of "square")
allow partial matching of function names
easily restrict the functions that can be used

So it will be up to you to decide based on your requirements.

Note: I have added ... to all your functions in case, in the future, your functions allow differing arguments. As you mentioned, your functions currently all only require a and b so you can get rid of , ... everywhere if you wish.


Counting number of unique elements in a sorted container

Worst case is \$O(n \log n)\$

If we pass an array of completely unique elements, we get a pretty bad runtime. Your solution is good if we expect a lot of duplicates, but bad if we don't.

As an optimization for the worst case, we could add some exponential bounding to find the next element. Basically, replace

it = std::upper_bound(it, last, *it);

with:

std::ptrdiff_t bound = 1;
while (std::distance(it, last) < bound && *std::next(it, bound) == *it) {
    bound *= 2;
}

it = std::upper_bound(
    std::next(it, bound/2),
    std::next(it, std::min(bound, std::distance(it, last))),
    *it);

Of course is now pretty bad for non-random access iterators since we have to keep doing lots of distance and advance related calls, so I would simply default to the trivial comparison algorithm in that case. That is:

template <class C>
size_t count_unique(C const& container) {
    using It = decltype(std::cbegin(container));
    return count_unique(container, std::iterator_traits<It>::iterator_category{});
}

template <class C>
size_t count_unique(C const& container, std::random_access_iterator_tag ) {
   // what I suggested
}

template <class C>
size_t count_unique(C const& container, std::forward_iterator_tag ) {
    auto first = std::cbegin(container), last = std::cend(container);
    if (first == last) return 0;

    size_t count = 1;
    for (auto next = std::next(first); next != last; ++first, ++next)
    {
        count += !(*next == *first);
    }
    return count;
}

Additional Requirements

The binary-search optimization requires that the type the container holds is ordered. You may want to fallback to the simple forward-iterator version if the type is only equality-comparable but not less-than-comparable.

Initialization

I would prefer:

size_t result = 0;

to

size_t result {};

No reason to hide the 0.


"A service per controller" sounds like a bad architecture. A good service should 'know' nothing about controllers and presentation details. Controllers should be thin, and any repeating code there should be abstracted into general purpose services not specific to controllers.

"UserViewService" should never be a name of Controller! And comments are not there to fix the confusion created by bad naming! In Angular, there are Services, Controllers, and Views - these are your Angular templates. You can have UserService and UserController, then your template can be called user-view.

Having new inside your Controller looks like a "code smell" to me. Controllers are only executed once upon initialization, and their purpose is to glue your data to your view (via Angular's $scope (which is in the ViewModel layer). The data should be either ready or you should get it from a service. Any other work like object creation is bloating your controller with too many responsibilities.

Further, it is Angular's job to create Services for you, so no need for new UserViewService whatsoever.

This function naming is misleading:

function watchUser() {
    return svc.user;
};

The name should tell roughly what function does, so I can skip this function's definition and still understand the rest of the code. This is a standard "getter"-function and should be name like that:

function getUser (svc) {
    return svc.user;
}

Note. Your code looks cleaner without ; after function declarations.

You watch svc.user and then update it upon change - this looks like a loop and may lead to your browser crash. Read best practices on using Angulars watch.


Style improvements:

The use of whitespace here is inconsistent:

int intnumbers[10]= { 10,11, 17,20,37,53,44,88,90,42 };

It's good to pay attention to detail by keeping it consistent:

int intnumbers[10] = { 10, 11, 17, 20, 37, 53, 44, 88, 90, 42 };

The spacing in between will make it a little more readable, even though it may increase the horizontal width.
This could also use some whitespace:

for(int i=0;i<10;i++)

It's good to keep one space between operators and operands so that they can be easily distinguished at first glance.

for (int i = 0; i < 10; i++)

Stick to one length of indentation.  For instance, I see two below the first {, just one after the first if, and four after the second if.  Four is most common in C++, so consider using that everywhere.
You can increase performance a little by outputting '\n' instead of std::endl.  The latter also flushes the buffer, whereas the former does not.
Want to stay ahead of the C++ game a bit (at least in a classroom setting)?  Use a container class such as an std::vector in place of the C array:

const std::vector<int> intnumbers { 10, 11, 17, 20, 37, 53, 44, 88, 90, 42 };

It may not matter that much in this small program without any functions, but it's a good habit for C++ programming.  You'll even benefit from various member functions and bounds-checking.


Please don't use using namespace std (read this).
The variable names are really not helping. Why not call a maze a maze instead of g? What are mj, z, l, k? It's hard to follow the logic with names like these.
Instead of working with strings like "K", "." and "P" it would be more efficient to use chars, and to give them meaningful names.
Instead of int visited[30][30], bool visited[30][30] would be more natural

Here's an alternative version of your code, with some variables renamed, constants used, using char instead of string, not using namespace std:

#include <iostream>
#include <vector>

using std::cin;
using std::cout;
using std::pair;
using std::make_pair;
using std::vector;

const char start = 'P';
const char target = 'K';
const char empty = '.';

int dfs(char maze[30][30], pair<int, int> p)
{
    vector <pair<pair<int, int>, int> > v;
    bool visited[30][30] = {0};
    int x, y, k = 0;
    pair <pair<int, int>, int> mj;
    pair <pair<int, int>, int> z;
    pair <int, int> l;
    z = make_pair(make_pair(p.first, p.second), 0);
    v.push_back(z);
    while(v.size() != 0)
    {
        mj = v.front();
        l = mj.first;
        x = l.first;
        y = l.second;
        k = mj.second;
        v.erase(v.begin());
        if (maze[x][y] == target) {
            return k;
        }
        if((maze[x+1][y] == empty or maze[x+1][y] == target) and not(visited[x+1][y]))
        {
            v.push_back(make_pair(make_pair(x+1, y), k+1));
            visited[x+1][y] = true;
        }
        if((maze[x][y+1] == empty or maze[x][y+1] == target) and not(visited[x][y+1]))
        {
            v.push_back(make_pair(make_pair(x, y+1), k+1));
            visited[x][y+1] = true;
        }
        if((maze[x-1][y] == empty or maze[x-1][y] == target) and not(visited[x-1][y]))
        {
            v.push_back(make_pair(make_pair(x-1, y), k+1));
            visited[x-1][y] = true;
        }
        if((maze[x][y-1] == empty or maze[x][y-1] == target) and not(visited[x][y-1]))
        {
            v.push_back(make_pair(make_pair(x, y-1), k+1));
            visited[x][y-1] = true;
        }
    }
}

int main()
{
    int n, m;
    pair <int, int> p;
    char s, maze[30][30];
    cin >> n;
    cin >> m;
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            cin >> s;
            maze[i][j] = s;
            if(maze[i][j] == start)
                p = make_pair(i, j);
        }
    }
    cout << dfs(maze, p) << std::endl;
    return 0;
}

Next, notice the duplication in this code:

if((maze[x+1][y] == empty or maze[x+1][y] == target) and not(visited[x+1][y]))
{
    v.push_back(make_pair(make_pair(x+1, y), k+1));
    visited[x+1][y] = true;
}
if((maze[x][y+1] == empty or maze[x][y+1] == target) and not(visited[x][y+1]))
{
    v.push_back(make_pair(make_pair(x, y+1), k+1));
    visited[x][y+1] = true;
}

The treatment for (x+1, y) is the same as for (x, y+1), and (x-1, y) and (x, y-1). Extract the duplicated parts to a helper method:

void check_maze_pos(char maze[30][30], int x, int y, int k, vector<pair<pair<int, int>, int> > &v, bool visited[30][30])
{
    if ((maze[x][y] == empty or maze[x][y] == target) and !visited[x][y])
    {
        v.push_back(make_pair(make_pair(x, y), k + 1));
        visited[x][y] = true;
    }
}

And then you can replace the 4 duplicated cases with these 4 simpler lines:

check_maze_pos(maze, x+1, y, k, v, visited);
check_maze_pos(maze, x, y+1, k, v, visited);
check_maze_pos(maze, x-1, y, k, v, visited);
check_maze_pos(maze, x, y-1, k, v, visited);

You can still improve further:

Eliminate the duplication of the magic number 30 in many places
Simplify the duplicated type definitions using typedef


Recursively searching the Windows Registry

This is probably a typo:

On Error GoTo ErrHandler:

It should read as:

On Error GoTo ErrHandler

The : denotes a label, or separates multiple instructions on a single line, allowing you to write something like  For i = 0 To 10 : DoSomething i : Next on a single line. Useful for the immediate pane, or for making your code harder to read by cramming multiple instructions on a single line.

I've seen this error-handling /exit pattern quite often, I find it's easier to follow/read the error-handling /exit pattern when the execution flow is more linear - the label could use a better name then:

Cleanup:

    'handle errors:
    If Err.Number <> 0 Then
        'errBox TypeName(Me), PROC_NAME
        Err.Clear
    End If

    'clean up regardless of error status:
    If Not (reg Is Nothing) Then
        Set reg = Nothing
    End If

    'clean exit
End Function

Doing this avoids resorting to jumps in the execution flow (Resume), and while it makes sense to say On Error GoTo Cleanup, it also makes sense to clean up in error cases as well, especially when dealing with external resources (a database connection, a registry key, a text file, etc.) - the only jump that needs to happen is a forward jump, only in case of an error: you want to skip everything else in the method's logic and jump straight to a clean exit.

If something goes wrong and I have a connected ADODB.Recordset object that blows up, I want to have code that closes the recordset and the connection (assuming the method opened them in the first place), and I don't want to copy that code into the happy path, ...and I don't want velociraptors to find me! To me the solution is simply to run that cleanup code whether or not an error is raised.

Dim reg As Registry

There's no reason not to New up this instance right away:

Dim reg As New Registry

That saves 1 line and a comment!

For i = 1 To iSectCount

Since the class doesn't specify Option Base 1 anywhere in the (declarations) section (just looked at the Google Drive link), it looks like there's a bug right here; you're systematically skipping index 0 - arrays are typically zero-based, and collections one-based:

MSDN (emphasis mine):

  Because the default base is 0, the Option Base statement is never required. If used, the statement must appear in a module before any procedures. Option Base can appear only once in a module and must precede array declarations that include dimensions.


It looks like you may come from a Java or scripting background. For .NET, the standard recommends PascalCasing for method names. This would turn your methods into:

Render()
GetBrush(...)
GetPoints(...)
GetTension(...)

Variable names should be camelCasing, where the first letter is lower case and the remaining words are capitalized. I'm not sure if NumOfShapes or ParameterNumber are class properties (Pascal Cased) or class-level fields (camel Cased), but you should follow the standard.

As far as your method names, you should avoid GetXXX which suggests that they should be properties. I would recommend the following changes:

GetBrush(...) -> CreateBrush(...)
GetPoints(...) -> GeneratePoints(...)
GetTension(...) -> CalculateTension(...)

For your variable names, curT doesn't help me understand what the parameter is for. :

for (int i = 0; i < NumOfShapes; i++)
{
    int curT = i * ParameterNumber;
    brushes[i] = getBrush(curT); // get value and clip it if need
    points[i] = getPoints(curT);
    tensions[i] = getTension(curT);
}

The definition and modification must be elsewhere. I'd have to go searching for it. It would be much simpler if you named it something meaningful, even if it is long, like currentImageIteration.

As far as coding goes, always, always dispose of GDI objects when you are done using them. You can get some pretty strange errors (OutOfMemoryException for example) when hitting the GDI object limit. Because GDI uses unmanaged objects, you should always dispose of them when you are done, see this question, and this question. The object will be disposed at some time in the future, but because the GC doesn't clean up managed objects, this will cause a memory leak.

Other than that, everything seems OK.


Binary Tree Longest Consecutive Sequence

Recursion is probably your main problem, as Graipher mentioned in the comments.

You could refactor it to be iterative:

def lcs(root):
    if root is None:
        return 0
    longest_sequence = 0
    nodes = dict()
    nodes[root] = 1
    while True:
        new_nodes = dict()
        for node, length in nodes.items():
            for subnode in (node.left, node.right):
                if subnode:
                    if subnode.val - node.val == 1:
                        new_nodes[subnode] = length + 1
                    else:
                        new_nodes[subnode] = 1
            longest_sequence = max(longest_sequence, length)
        nodes = new_nodes
        if not nodes:
            break
    return longest_sequence