back: I'm not sure what this function is used for (and the name doesn't seem that great), but it is open to XSS. An attacker could create a page at http://evil.com/?<img src=onerror=alert(1)>, which would redirect the user to your back page, which would then echo the XSS payload.
you should always die after a header redirect (clients do not have to follow it, so any code after the redirect may be executed, which may have security implications).
your indentation is inconsistent, and 1 or 2 spaces aren't really enough. I would use 4 at a minimum to ensure readability.
your spacing is also off, and your positioning of curly brackets isn't consistent. You can easily solve all these formatting issues with any IDE.
try to always write out your variable names. Right now, fname may be clear to you (in context), but firstName is much easier to read.
a nested if-else in an if is often not so nice to read (especially with your formatting). It's difficult to see what happens when rowCount is not greater than 0. You could just combine the two ifs.
getColumn doesn't actually get anything, it echoes something. You could rename it to showColumn, but really, it should return an array of columns, which is then echoed in a view class.
the same goes for all the exceptions. Just catching them and echoing the message isn't a great way to handle it. If you can't recover in the function, just throw them upwards, and let the calling code decide what to do.


I'm going to limit my initial answer to not include modules, but I'll also cover a module that can help out some here too later.

my $initial_color = '#FF0000';
my $final_color   = '#00FF00';

While there's nothing wrong with using underscores, the tendency in Perl 6 has been to move towards hyphens, which would give us $initial-color and $final-color.

my @initial   = ($initial_color ~~ /\#(..)(..)(..)/).list.map: { .Str.parse-base(16) };

This is a bit of personal preference, I'd write this as

my @initial = .map: *.Str.parse-base(16) with $initial-color ~~ /\#(..)(..)(..)/;

Since it allows you to get rid of most of the parentheses/braces.  Note that in any case, you don't need the .list because your Match is already an Iterable.  But this is of course a pure matter of taste (some might prefer parentheses around the .map to emphasize it's separate from the with postfix.

You can also prestore the regex, particularly if you plan on using it more often:

my $hex-format = /\#(..)(..)(..)/;
my @initial = .map: *.Str.parse-base(16) with $initial-color ~~ $hex-format;

Your next two lines have two different techniques for applying math operators across lists:

my @range     = @final Z- @initial;
my @increment = @range.map: { $_ / $gradient };

You could use a zip operator for both ( @range Z/ ($gradient xx 3) ), or you could opt for a hyper meta operator:

my @range     = @final «-» @initial;
my @increment = @range «/» $gradient

Now for generating the colors themselves, you had

my @color;
@color.push: @initial;
for (1..$gradient) -> $i {
  @color.push: @(@color[$i-1]) Z+ @increment;
}

for (0..$gradient) -> $i {
  @color[$i] = '#' ~ ( @(@color[$i]).map: { .base(16,0).fmt('%02s') } ).join;
}

First the easy things.  If I see a variable @color, I assume it is a single entity with multiple constituent entities (one color, three values — R, G, B).  But in this case, it's a list of colors, so the variable name is best used in plural.  Also, you don't need parentheses around the list for the for loop.  Just for 0..$gradient -> $i works.

Your first for loop uses the previous item to determine the next one, so you have a push outside the loop.  There's a few ways to solve this.  If you have to do an initial step like that, I like to put it in the loop using FIRST (or once, both are functionally equivalent here).

my @color;
for 1..$gradient -> $i {
  FIRST @color.push(@initial);
  @color.push: @(@color[$i-1]) Z+ @increment;
}

But we can actually rewrite this to calculate the value without relying upon the previous entry:

my @color;
for 0..$gradient -> $step {
  @color.push: @initial «+» @increment «*» $step;
}

This could be even further reduced into a one liner, but I don't think that's necessary nor desirable here.  What's great here about the hyper operators is that they read like scalar arithmetic ($initial + $increment * $step) so readability is maintained.

Your second loop can also be simplified quite a bit by just looping on the values.  I think it makes most sense to just put them into a new array

my @html-colors;
for @colors -> @color {
  @html-colors.push: '#' ~ @color.map( *.base(16,0).fmt: '%02s' ).join;
}

Anytime, though, you have a .map that has another method chain in its code block, you have a candidate for a hyper method call ».

my @html-colors;
for @colors -> @color {
  @html-colors.push: '#' ~ @color».base(16,0)».fmt('%02s').join;
}

Basically, ».foo means take every element and .foo it, and it returns a list of the values, which can be ».bar on every element.  Note that .join doesn't have the hyperoperator, because we want to act on the resulting list.

But you could also loop in a rw manner (notice the <->) with

for @colors <-> @color {
  @colors = '#' ~ @color».base(16,0)».fmt('%02s').join;
}

Because now both loops though are 0 .. $gradient, it might make sense to merge them:

my @colors
for 0..$gradient -> $step {
  my @intermediate = @initial »+» @increment »*» $step;
  @colors.push: '#' ~ @intermediate».base(16,0)».fmt('%02s').join;
}

Lastly when you print, remember you can just loop on the color items:

for @colors -> $color {
  $fh.print: "&nbsp;";
}

Which also allows a one liner using the topic variable $_ (and in this case, absent doing anything else, makes more sense to me):

$fh.print: "&nbsp;" for @colors;

Since it's effectively the same loop, this is, of course, a candidate for putting back in the main loop, but there's something to be said for separating the calculations from the final output.

Rewritten, my version would be:

my $initial-color = '#FF0000';
my $final-color   = '#00FF00';
my $gradient      = 10;

my $hex-format = /\#(..)(..)(..)/;

my @initial = .map: *.Str.parse-base(16) with $initial-color ~~ $hex-format;
my @final   = .map: *.Str.parse-base(16) with   $final-color ~~ $hex-format;

my @increment = (@final »-» @initial) »/» $gradient;

my @colors;

for 0..$gradient -> $step {
  my @intermediate = @initial »+» @increment »*» $step;
  @colors.push: '#' ~ @intermediate».base(16,0)».fmt('%02s').join;
}

my $fh = open '/tmp/delete.html', :w;
$fh.print: "&nbsp;" for @colors;
$fh.print: '&nbsp';
$fh.close;


Tax calculator using functional programming

Hi and welcome to CodeReview.

You are right, your code does not modify state (has not side effects) and the output of the methods depends only from the input... Therefore I would guess that the functions are "pure functions".

However, I would prefere an IEnumerable of int instead of List of int as parameter type because with an IEnumerable the API shows that the method does not change the passed list.

If you value immutability, there are also some immutable collection in .net (e.g.: The ImmutableList).

If you like functional programming, F# is really worth a look! FSharpForFunAndProfit is a good point to start :D


Convert a number into a different base and return as string

Off by one

Your MAX_LLI_REP is 63, but since you are accepting long long inputs, you could have a 64 character representation if you pass in LONG_LONG_MIN which is 0x8000000000000000 and in binary would be 10000...000 which is one 1 and 63 0's.

When I ran your program passing in LONG_LONG_MIN (or -9223372036854775808), the first character in the output which should be a 1 was a random character instead, because it was the character that fell out of bounds and got overwritten by something else.  For example, I got:

-h000000000000000000000000000000000000000000000000000000000000000

When I set MAX_LLI_REP to 64, the problem went away.

Simplified expression

This expression:

result[j++] = c[(i--) - 1];

Could be simplified to:

result[j++] = c[--i];

Modified interface

Currently, you allocate a string and return it from your function.  This creates some potential awkwardness because someone has to free that string later on.

It might be nicer to pass in a buffer to your function and have the function fill it in instead.  The buffer size can be documented to be a minimum of 66 bytes, or you could pass in a buffer length argument as well and have the function fill up to the buffer length.

Alternatively, you could create a static buffer in your function and return a pointer to it.  This has the drawback that you must use the return value before you call the function again.  Some C library functions such as ctime() do this, so it isn't unprecedented.


I finally spotted the error in my submission : I was computing the maximum of left-most * right-most mod 1000000007 while I should have been computing the maximum  of left-most * right-most, then returning its value modulo 1000000007.

In other terms

int mp = 0;
std::stack<int> stack;
for(int i = 0; i < v.size(); ++i){
    int j = next_bigger(v, stack, i );

    int mp_i = mult_mod(j, r[i]);
    if (mp < mp_i){
        mp = mp_i;
    }
}
return mp;

Should be replaced by

long long int mp = 0;
std::stack<int> stack;
for (int i = 0; i < v.size(); ++i)
{
    long long int j = next_bigger(v, stack, i);
    long long int mp_i = j * r[i];
    if (mp < mp_i)
    {
        mp = mp_i;
    }
}
return mp % 1000000007;


Using a navigation menu to help keep material organized

First, it seems that isCtrl is not declared anywhere in your code. Put var isCtrl = false; as your first line inside the ready function. Otherwise, you will get a JavaScript error when the first key the user presses is not the Ctrl key. Also, == true is unnecessary within an if statement; it can be omitted.

Second, this line could be improved, as it fails if the element is a member of another class:

if($('#main').attr('class') != 'out') {

It can be rewritten using .hasClass() as:

if(!$('#main').hasClass('out')) {

In fact, you should refactor this entire block out to a separate function to avoid duplicating code:

function toggleMenu() {
    if(!$('#main').hasClass('out')) {
        // ...
    } else {
        // ...
    }
}

And put toggleMenu(); where the duplicate code was in each function. Also, if performance is a concern, you should cache the jQuery object $('#main') by declaring another variable at the beginning of the ready function. Not doing so is slow because jQuery would have to find the matched elements within the document again.

A more minor criticism is that of braceless control statements, such as:

if(e.which == 17) isCtrl=false;

Some say that it is best to always put the code within indented braces to avoid errors caused by incorrectly placed semicolons.

Finally, the indentation doesn't look right throughout the entire code. Fix that, and your code will become somewhat more readable.

To add: It also looks like you have an extra comma at the end of:

'margin-left': '+=210px',

This is syntactically valid, but it causes problems with Internet Explorer 7 and below.


You could move the logic that gets each panel / screen etc into it's own function, and remove some of the indenting, like so:

function getChildren(obj) {
    // No need to check hasOwnProperty, and keys only returns ownProperties
    return obj ? Object.keys(obj).map(function(key) {return obj[key]}) : [];
}

function removeImageFromSettings(imageName) {
    let panels = getChildren($scope.data);

    let screens = panels.reduce(function(result, panel) {
        return result.concat(getChildren(panel.screen));
    }, []);

    let variables = screens.reduce(function(result, screen) {
        return result.concat(getChildren(screen.variable));
    }, []);

    variables.forEach(function(variable) {
        if (variable.custom && variable.custom[0] === imageName) {
            variable.custom[0] = "";
        }
    });
}


LeetCode 552: Student Attendance Record II

Use C++ Container Classes
This code looks too much like C code and not enough like C++ Code.
In the modern day C++, the use of raw pointers such as uint32_t* accumulated = a; are frowned upon, and container classes such as std::array and iterators were developed to reduce the use of raw pointers.
The C style array b is never initialized, and the C style array a is initialized twice.
        std::memset(a, 0, sizeof(a));

        for (unsigned int node_x = 0; node_x < MATRIX_WIDTH_SQUARED; node_x += MATRIX_WIDTH + 1) {
            a[node_x] = 1;
        }

The first initialization can be accomplished by:
        uint32_t a[MATRIX_WIDTH_SQUARED] = {0};

and I would prefer to see an iterator used in the second initialization.
Use Proper Casting
Currently the code is implementing C style casting ((uint32_t) (first_col_sum % MODE)) which is not as type safe as either static_cast(VALUE_TO_BE_CAST) or dynamic_cast<NEW_TYPE>(EXPRESSION). In this case I recommend static_cast.
Static Functions
It is not clear why the checkRecord() function was changed to a static member function since the original prototype was int checkRecord(int n) in the question. There really is no need for it to be static.

By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator.

Variable Names
The symbolic constant names are clear as are the variable names adj_matrix (adjacency would be clearer), accumulated and adj_matrix_pointer, but the variable names a, b and temp are not clear and leave someone who has to read or maintain the code guessing.
Complexity
The function checkRecord() is too complex (does too much). After the if statement there should be a call to a function to execute the rest of the code, and that function might cal sub functions. Remember that it is much easier to write correct code when you limit what a function is responsible for.
There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:

that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.


bash grammar is notoriously hard to parse. Your script is easily misled by many valid bash constructs.

For example, it unconditionally consider # as a comment, whereas it could be escaped, or a part of a special parameter $#, or a part of ${parameter#word} expansion.

It will consider the assignment (stupid but valid)

    x=\;;

as an end of case. It will miss a loop in

    cat file | while read line

It will count the contents of a

    <<EOF
    while
    for
    until
    EOF

as loops.

It incorrectly handles nested case statements.
awk is a powerful programming language. If you feel you need to invoke it, consider using it for an entire script. It is particularly inefficient to invoke awk for a single line of input.
bash is also a very powerful programming language. The constructs like

    temp=`echo $line | cut -d ' ' -f1`

can be more clearly (and more efficiently) expressed in bash, e.g.

    read temp rest <<< $line

Testing for the presence of # to remove the comment is redundant. The expansion works correctly even if it is not there (in which case the line remains unchanged).


There are a number of things that you can do to improve your code.

Understand C arrays

In C, arrays are zero based, so the first element of array is array[0] not array[1].  A number of other things follow from that.

Use whitespace to improve readability

Lines like this:

for(line=1;line<=n;line++){

become much easier to read with a little bit of whitespace:

for (line = 1; line <= n; line++) {

Choose better variable names

Names like line and row are descriptive, but the name array is not so good.  Consider matrix or some other better name.

Use idiomatic C

The code currently includes this line:

for(line=1;line<=n;line++){

But since arrays are zero-based, as mentioned above, the C idiom would be this:

for (line = 0; line < n; line++) {

Similarly, instead of this:

sum_two=sum_two+array[line][row];

Write this:

sum_two += array[line][row];

Consider eliminating variables

The variable dif is only used at the very end of the program. Since it's really the calculation of this number that is the point of the program, it you don't really need to separately keep sum_one and sum_two.  For example the second calculating for loop could be written like this:

for (line = 0; line < n; line++) {
    dif -= array[line][row];
    row--;
}

Check return values for errors

The call to scanf can fail.  You must check the return values to make sure they haven't or your program may crash (or worse) when given malformed input.  Rigorous error handling is the difference between mostly working and bug-free software.  You should strive for the latter.

Decompose your program into functions

All of the logic here is in main in one rather long and dense chunk of code.  It would be better to decompose this into separate functions.

Avoid scanf if you can

There are so many well known problems with scanf that you're usually better off avoiding it.  A better way to handle this would probably be to input a char array (a string in C) and then parse that.  This would allow the code to handle the case that the number input by the user for the array size is not a number.  The current code loops infinitely when that happens.

Consider separating input and output

Right now, the main function reads in the the matrix, and then performs the calculation and then prints the result of the matrix calculation. A more modular (and likely more maintainable) approach would separate these into separate functions.

Consider more memory efficient calculation

In the current code, the entire matrix is stored in memory even though most elements are never used.  Consider instead that the calculation could be done as each line is read, and then the input line discarded.  For very large matrices this could make a significant difference in storage space required by this program.

Eliminate return 0 at the end of main

Since C99, the compiler automatically generates the code corresponding to return 0 at the end of main so there is no need to explicitly write it.


How to improve execution of web service using System.DirectoryServies.AccountManagement that runs very slow?

If you are writing this in Visual Studio 2010, it would be worth profiling your code to find out exactly what method calls take the longest.

Here is a link where you can watch a video from Channel9 about using the built in performance analyser tool in Visual Studio 2010 to perform CPU Sampling on your code: http://channel9.msdn.com/Blogs/wriju/CPU-Sampling-using-Visual-Studio-2010-Performance-Analyzer-Tool

Once you've identified the methods that take the longest to execute, you can start to work out if you're making any redundant or excessive calls and remove them, or research each call to find ways of optimising each.


EVAL, WHY!?

I really can't understand why you're using String concatenation and eval to calculate the result.

The most efficient way is to calculate \$2^{n+1}-2\$.

Additionally, your variable names are all one character long, and your code lacks spacing.

How can you tell what is t and what is q? Your variable names make no sense.

function solution (n) {
    var result = 2;
    for (var i = 1; i <= n; i++) {
        result *= 2;
    }
    return result - 2;
}

Another solution is to use bit shifting: (only works if \$n <= 29\$)

function solution(n) {
    return (2 << n) - 2;
}


1. Charset

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />

You declare a HTML5 doctype and two charsets. You can remove the first of the two rules and leave this:

  <meta charset="utf-8">

2. IE rendering engine

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

The browser should choose the fitting rendering engine on its own. Setting IE=edge should do nothing in most cases unless the default rendering engine was changed by the user.

That said, it doesn’t do harm.

3. Comments

<!-- META-TAGS -->

Don’t state the obvious. We can see every <meta> thing is a meta tag. Also there are other things under this comment as well. title and link are not meta tags.

I’d also leave out comments like the ones for twitter tags. Separating them by new lines creates enough distinctiveness.

4. HTML Shiv/Shim

<!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->

Don’t omit the type attribute for browsers that don’t understand HTML5, because it is not valid HTML 4/XHTML. You include the shiv to ensure IE8 support for HTML5 elements, so you should definitely have it there.

<!--[if lt IE 9]>
  <script type="text/javascript" src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
  <script type="text/javascript" src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->

4. SEO

Having a good structured document is the one thing which helps. You have description that search engines use, you have a page title, you probably will have fitting headings in your actual content.

However that’s just the foundation. With just that, search engines won’t give you a good ranking. The important part is the content. Make sure you have a good document outline.


A bash script to submit an AWS EMR job and poll until the cluster terminates

you can use emr wait instead of describe-cluster

aws emr wait cluster-running --cluster-id <value> --region <value>

http://docs.aws.amazon.com/cli/latest/reference/emr/wait/cluster-running.html


Java and C++ stack implementations with dramatically different performance

Performance

I'll get to a bit of a review, but first, since you're most interested in performance, I've done some benchmarking. In short, all evidence points towards maaartinus' theory being the cause.

Benchmark.java:

public class Benchmark {

    private static class Stored {
        private final int[] big = new int[250];

        public Stored() { }
    }

    public static void main(String[] args) {

        // Create the objects up front so we don't include allocation/construction time in the benchmark
        Stored stored[] = new Stored[1000000];
        for (int i = 0; i < stored.length; ++i) { stored[i] = new Stored(); }

        for (int n = 0; n < 100; ++n) {
            long start = System.nanoTime();

            ArrayStack<Stored> stack = new ArrayStack<Stored>(1000000);
            for (int i = 0; i < 1000000; ++i) { stack.push(stored[i]); }
            for (int i = 0; i < 1000000; ++i) { stack.pop(); }

            long end = System.nanoTime();

            if (!stack.isEmpty()) { System.out.println("This is just here to make sure nothing gets optimized out."); }

            System.out.printf("Time: %f seconds%n", (end - start) / 1e9);
        }
    }
}

Once the JVM has warmed up and some JITing has (presumably) happened, each test takes 0.0038 seconds (with a very small variance). If the size of big in Stored is changed, this doesn't change timings since the stack stuff is still just copying a reference. Even if more references are added to Stored, this increasing the size of stored, there is still no time increase. This all makes sense: all Java has to do is copy a pointer, and the size of this pointer is fixed.

benchmark.cpp

int main() {

    // To be consistent with the Java approach, we'll create the objects up front. Noteably, this doesn't actually
    // matter since the copying of the objects is just as expensive as creation.
    // (Note: typically it wouldn't make sense for this to be dynamically allocated, but 1000000 objects was too big for
    // the stack.)
    Stored* stored = new Stored[1000000]();

    // Do the simple approach
    for (int n = 0; n < 100; ++n) {
        auto start = std::chrono::high_resolution_clock::now();

        ArrayStack<Stored> stack(1000000);
        for (int i = 0; i < 1000000; ++i) { stack.push(stored[i]); }
        for (int i = 0; i < 1000000; ++i) { stack.pop(); }

        if (!stack.isEmpty()) { std::cout << "This is here so the code doesn't get optimized out.\n"; }

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff = end - start;
        std::cout << "Time: " << diff.count() << " seconds\n";
    }
}

This was run with a few different Storeds. The first was a relatively large class:

struct Stored {
    int x[250];
};

The second was a very light class:

struct Stored {
    int x[1];
};

As a third option, the large class was kept, but rather than storing a value, a pointer was stored in the stack:

for (int i = 0; i < 1000000; ++i) { stack.push(&stored[i]); }

The timings were 0.30 seconds, 0.001 seconds, and 0.001 seconds for options 1, 2, and 3, repsectively. This is consistent with the Java theory and findings: C++ is peforming expensive copies that Java is not doing.

Benchmark Conclusions

The question now obviously becomes how to optimize your C++, and unfortunatley there's no simple solution to that without knowing a lot more about what exactly it is that you're putting into your stack. Move semantics are one option, provided your copying is expensive and you'd be happy to sacrifice the object into the stack rather than copy it.

The other option is to move away from value semantics so that copies become cheaper. If you have simple hierarchical ownership semantics (e.g. the objects being stored in the stack will always outlive the stack), this is super easy: just store pointers in the stack instead of objects. If your ownership isn't quite so simple, you would need to consider using something like heap allocation and a smart pointer. Both of these approaches are trade offs though. Smart pointers are safe but relatively expensive to copy, and raw pointers can quickly become a confusing mess if you're not very particular and consistent with your semantics. In both cases you no longer have the pleasantness of value semantics.


Cross-cutting delete flag in a repository

You don't need to call AsEnumerable on the DbSet in fact, doing so isn't great at all... As far as I am aware, this will make your Where clause execute in C# rather than being translated to SQL meaning a massive perf hit (I would be happy to be corrected here).

You should return IQueryable<TEntity> directly:

return dbSet.Where(x => !x.IsDeleted);

Notice that I've removed the redundant this. and also changed the comparison to use ! (not operator) instead of comparing to false.

One additional warning I would give you is: are you sure you need a generic base class repository? I find that when I have used this pattern a lot of my repositories get methods they never use.

It can also be argued that it's a leaky abstraction, see e.g here and here

I prefer slim interfaces of only a few methods rather than using header interfaces.


Multithreaded lock-free queue implementation

This is not a lock-free queue, but a locking-agnostic queue. That means, it is not safe to use on multiple threads. The reason this works in your implementation is because the push calls alter the end of the queue and the pop calls alter the beginning (so conflicts are more or less, avoided).

If you tried adding elements from multiple threads at the same time (for example), you would leak elements.

Since bottomOfList is never changed in the destructor, if it is initialized, you will always get to throw the exception.

Consider splitting pop into a const T& top() const and a void pop(); This would allow for an exception-safe implementation of the operations.


Log Likelihood Calculations for Censored Data in R

Your function p_function is vectorized and that is nice. There's a little difficulty for the sum though.
Below is the improved code that takes advantage of the vectorization. I also replaced log(1+x) with log1p(x), which is better for a small |x|. And I replaced the stuff with the lgamma functions with some stuff with the lbeta function.
new_likelihood2 <- function(Y, R, k) {

  p_function <- function(y, n){
    exp(log(n) - log(y) - lbeta(k*y, y-n+1) - log(k*y+y-n) + (y-n)*log(R/k) - (k*y+y-n)*log1p(R/k))
  }

  p_function_sum <- function(y, n){
      vapply(
        seq_along(y), function(i) sum(p_function(1:(y[i]-1), n[i])), numeric(1)
      )
  }

  uncensored <- Y[, 3] == 0
  Yuncensored <- Y[uncensored, 1:2]
  Ycensored   <- Y[!uncensored, 1:2]
  liks_a <- log(p_function(Yuncensored[, 1], Yuncensored[, 2]))
  liks_b <- log1p(-p_function_sum(Ycensored[, 1], Ycensored[, 2]))

  sum(liks_a, liks_b)
}


Why are you giving up?

if (hi - lo == 1):
    return min(ary)

So we're almost done with our nice O(lg N) algorithm, when suddenly... we start over and do a whole new O(N) search from scratch throwing everything away? Why? Let's examine such a scenario:

ary = [3, 4, 5, 6, 0, 1, 2]

lo = 0, hi = 6, mid = 3
ary[mid] (6) > ary[hi] (2), so recurse mid to hi

lo = 3, hi = 6, mid = 4
ary[mid] (0) < ary[hi] (2), so recurse lo to mid

lo = 3, hi = 4
hi - lo == 1, so return min(ary) == 0

At this point, we have ary[lo] == 6 and ary[hi] == 0. We know one of those two is the minimum, and we know which one that is. So let's use that information:

def recurse(lo, hi):
    # Base cases
    if (ary[lo] < ary[hi]):
        return ary[lo]
    elif (hi - lo == 1):
        return ary[hi] ## just return a number, don't call min()
    else:
        mid = ...
        # rest as before


Model classes for an expense tracking app in Django

You would probably want to show total expenses in the category for each month, not just the last. So Category doesn't have a value. It has a value (which is a bad naming by the way) for each month. This can be modelled simply as a query like (pseudo sql) select sum(amount) from expenses where group = 'some group' group by date.month

And by the way you can use this declarative style here.

total = 0
for e in expenses:
    total += e.amount
category.value = total

category.value = sum(e.amount for e in expenses)


Draw an outline of an upward-pointing triangle

First of all, please avoid using namespace std;.  It is considered bad practice and will cause many problems.  See Why is using namespace std; considered bad practice? for more information.

Now let's try to simplify the logic.  The following loop:

for (int j = 1; j <= spaces_before; j++) {
  cout << ' ';
}

is a very verbose way to write

std::cout << std::string(spaces_before, ' ');

(this happened more than one time.)

And you don't need to keep the variables spaces_before, spaces_after, and star.  Just calculate them on demand.  Also, don't include the special cases in the loop:

#include <iostream>
#include <string>

int main()
{
    std::cout << "      *\n";
    for (int i = 0; i < 5; ++i)
        std::cout << std::string(5 - i, ' ') << '*'
                  << std::string(2 * i + 1, ' ') << "*\n";
    std::cout << std::string(13, '*') << '\n';
}

This should be enough since you are a beginner.  After this is done, it would be very nice if you extract the magic numbers into named constants.  And the whole process can be wrapped in a function for reuse:

#include <iostream>
#include <string>

void print(std::ostream& os, int rows)
{
    os << std::string(rows - 1, ' ') << "*\n";
    for (int i = 1; i < rows - 1; ++i)
        os << std::string(rows - i - 1, ' ') << '*'
                  << std::string(2 * i - 1, ' ') << "*\n";
    os << std::string(2 * rows - 1, '*') << '\n';
}

int main()
{
    print(std::cout, 7);
}


Removing duplication in horizontal and vertical checks

The most straightforward way to do this is to introduce a new boolean variable horz that is true in the case that you wish to check horizontals.  With that simple addition, both routines now can be expressed as one:

// if (horz) is true, check horizontals, else check verticals
aLimit = horz ? sGridHeight : sGridWidth;
bLimit = horz ? sGridWidth : sGridHeight;
for (int a = 0; a < aLimit; a++)
{
    Shape* groupShape = nullptr;
    int groupSize = 0;
    for (int b = 0; b < bLimit; b++)
    {
        GridItem* gridItem = (horz ? GetItem(b, a) : GetItem(a, b));
        Shape* shape = gridItem->GetShape();
        if (shape == groupShape)
        {
            groupSize++;
            if (groupSize == m_MatchSize)
            {
                g_Audio->PlaySound(m_GemDestroyedSound.c_str());
                m_Score += shape->GetScore();
                for (int tb = b - m_MatchSize + 1; tb <= b; tb++)
                {
                    RANDOMIZE(horz ? GetItem(tb, a) : GetItem(a, tb));
                }
                return;
            }
        }
        else
        {
            groupSize = 1;
            groupShape = shape;
        }
    }
}

However, there are a number of things that suggest opportunities for further improvement.  In particular, the use of pointers is probably not a good idea.  For example, these two lines:

    GridItem* gridItem = (horz ? GetItem(b, a) : GetItem(a, b));
    Shape* shape = gridItem->GetShape();

Are the only place that the gridItem pointer is used, and it's not checked for nullptr before it's dereferenced.  So either that's a bug if GetItem() could possibly return a nullptr or it should instead be written as a reference.  Even better, it could be combined into a single line and the variable eliminated completely.

Using this modified code is OK, but it's still a little unwieldy, so I would suggest that the GetItem() function should take a third argument which is the bool horz.  That would make those same two lines of code look like this:

    Shape* shape = GetItem(a, b, horz).GetShape();

Much nicer, but again, I'd turn this pointer into a reference (or better yet, a const reference if possible).


bool isPrime = true;
for (int j = 2; j < i / 2; j++)
{
    if (i%j != 0) continue;
    isPrime = false;
    break;
}
if (!isPrime) continue;

This is one of the most primitive and least efficient ways to calculate whether or not a value is prime.

First and foremost, we deserve a method which encapsulates this logic and can be called repeatedly:

bool isPrime(int value)
{
    // return true/false
}

This will allow us to write a set of unit tests around this method to make sure it's correct.  It also allows us to very easily measure exactly how much this part of our total algorithm is costing us in terms of time.  And in the end, it just makes our code more readable, which for me is usually enough of a reason to do anything.

Now, as for the logic here... I've got a few comments.

j < i / 2

Neverminding the fact that we need better variable names, we're calculating far too many numbers.  Consider the prime number 97.  Your algorithm will test every number up to 48, but we could stop at the closest thing to 97's square root, 10.  If no number 10 or smaller divides evenly into 97 whose square root is 9.8 something, then it's prime.

j++

We're checking every divisor.  We could eliminate the even numbers early and just see if our test value is divisible by odd numbers.

if (i%j != 0) continue;

First of all, omitting braces is a capital sin as far as I'm concerned.  You shouldn't consider them optional.  But perhaps more importantly, why the inverse logic?  Your loop body could simply be written as:

if (i % j == 0)
{
    isPrime = false;
    break;
}

But... there's a far more efficient pattern, so let's get back to that isPrime method I was talking about...

Let's start with this logic to deal with a few special cases:

if (value < 2) { return false; } // no number less than 2 is prime
if (value % 2 == 0) { return value == 2; } // no multiple of 2 is prime
if (value % 3 == 0) { return value == 3; } // no multiple of 3 is prime
if (value % 5 == 0) { return value == 5; } // no multiple of 5 is prime

We're also going to go ahead and filter out 7, which is a prime.

if (value == 7) { return true; }

We're taken out a lot of the primes now.  The first line takes out a little over half of all valid numbers (all negatives, 0, and 1).

The second line takes out another half of the remaining by eliminated all the even numbers.

The third line takes out a third of the remaining by eliminating all of the odd multiples of three (even multiples of three were eliminated in previous line).

The fourth line takes out about twenty percent of the remaining by eliminated the multiples of five which were not already knocked out by being even or a multiple of three (so for example, 10, 15, 20 already knocked out, but here we knocked out 25).

The final line deals with 7 so that all of our special cases are handled before we enter this pattern:

for (int divisor = 7; divisor * divisor <= value; divisor += 30)
{
    if (value % divisor == 0) { return false; }
    if (value % (divisor + 4) == 0) { return false; }
    if (value % (divisor + 6) == 0) { return false; }
    if (value % (divisor + 10) == 0) { return false; }
    if (value % (divisor + 12) == 0) { return false; }
    if (value % (divisor + 16) == 0) { return false; }
    if (value % (divisor + 22) == 0) { return false; }
    if (value % (divisor + 24) == 0) { return false; }
}

This loop starts at 7 and increments by 30 on each iteration.  Each line of this loop tests a different off set which makes sure we're not double checking our special cases.  With each line we're testing against a smaller portion of possible values, because the line above it eliminated more.

To be clear, our special cases eliminated...

roughly 50%
half of remaining
1/3rd of remaining
1/5th of remaining

Through the first iteration of this loop, we eliminated by line

1/7th of remaining
1/11th of remaining
1/13th of remaining
1/17th of remaining
1/19th of remaining
1/23rd of remaining
1/29th of remaining
1/31st of remaining

Notice those denominators?  They're primes.

The loop becomes less efficient per iteration (and as you get into requiring more and more iterations of the loop, a sieve starts to become faster at the expense of memory).

But by the end of the first iteration of the loop, we have tested the value against the eleven primes.  And that's the most efficient way to determine if a number is a prime, by testing if it is divisible by primes (which is what sieves allow you to do).

There's no point in checking if 97 is divisible by 4, because if it was going to be divisible by 4, it would have been divisible by 2, and we already checked 2.
There's no point in checking if 97 is divisible by 9, because if it was going to be divisible by 9, it'd be divisibly by 3, which we already checked.
There's no point in checking if 97 is divisible by 25, because if it was going to be divisible by 25, it'd be divisible by 5, which we already checked.

Also, we know that if 97 were divisible by 25, we would have already found the other number that divides in to it.  And to be more clear on that part, let's look at a similar number that isn't prime: 98.

So, 98 is divisible by 49, right?  49 will go into 98 twice.  So naïvely, we might consider in order to determine if 98 is prime, we need to check all the way up to 98 % 49, right?  Wrong.  Numbers factor into pairs.  For every pair, we only need to test the smallest pair against the value.

So for the factors of 98, we have these pairs:

(2, 49)
(7, 14)

For any number, if we break it into pairs like this and look at the smaller number in the pair, the largest smaller number will be less than or equal to the square root of the number we are factoring.

Consider a number that is a perfect square, like 100.  It's factor pairs look like this:

( 2,50)
( 4,25)
( 5,20)
(10,10)

Again, we only need to check the left column.  Here, the largest value out of the left column is 10.  This is the exact square root of 100, and we can stop our checking here.  No need to go all the way up to halfway.

Anyway, long story short, the final isPrime function looks about like this:

bool isPrime(int value)
{
    if (value < 2) { return false; }
    if (value % 2 == 0) { return value == 2; }
    if (value % 3 == 0) { return value == 3; }
    if (value % 5 == 0) { return value == 5; }
    if (value == 7) { return true; }

    for (int divisor = 7; divisor * divisor <= value; divisor += 30)
    {
        if (value % divisor == 0) { return false; }
        if (value % (divisor + 4) == 0) { return false; }
        if (value % (divisor + 6) == 0) { return false; }
        if (value % (divisor + 10) == 0) { return false; }
        if (value % (divisor + 12) == 0) { return false; }
        if (value % (divisor + 16) == 0) { return false; }
        if (value % (divisor + 22) == 0) { return false; }
        if (value % (divisor + 24) == 0) { return false; }
    }

    return true;
}


High Performance Calculation of Sums and Returns in Go

In Go, when you want to measure function performance, use the Go testing package to run a benchmark.

For example,

returns.go:

package finance

// Calculate returns
func Re(data []float64) []float64 {
    var re []float64
    if len(data) > 0 {
        re = make([]float64, len(data))
    }
    for i := 1; i < len(data); i++ {
        if data[i-1] != 0 {
            re[i] = (data[i] / data[i-1]) - 1
        }
    }
    return re
}

// Calculate sum
func Sum(data []float64) float64 {
    var sum float64
    for _, x := range data {
        sum += x
    }
    return sum
}

returns_test.go:

package finance

import "testing"

func BenchmarkRe(b *testing.B) {
    data := make([]float64, 5*12)
    for i := range data {
        data[i] = float64(i)
    }
    b.ResetTimer()
    for N := 0; N < b.N; N++ {
        Re(data)
    }
}

func BenchmarkSum(b *testing.B) {
    data := make([]float64, 5*12)
    for i := range data {
        data[i] = float64(i)
    }
    b.ResetTimer()
    for N := 0; N < b.N; N++ {
        Sum(data)
    }
}

Output:

$ go test returns.go returns_test.go -bench=. -benchmem
BenchmarkRe-4     7545566   156 ns/op     480 B/op    1 allocs/op
BenchmarkSum-4   28272992    41.5 ns/op     0 B/op    0 allocs/op
$

I looked at some other alternatives, but that's the fastest.

Note: I fixed your divide-by-zero bug.


I would base something like this on for rather than foreach

proc foreach_with_index {idxvar elemvar list body args} {
    array set opts {-start 0 -inc 1}
    if {[llength $args] > 0 && [llength $args]%2 == 0} {array set opts $args}
    upvar 1 $idxvar idx
    upvar 1 $elemvar elem
    for {set idx $opts(-start)} {$idx < [llength $list]} {incr idx $opts(-inc)} {
        set elem [lindex $list $idx]
        uplevel 1 $body
    }
}

So you get

% foreach_with_index i e {a b c d e} {puts "$i - $e"}
0 - a
1 - b
2 - c
3 - d
4 - e
% foreach_with_index i e {a b c d e} {puts "$i - $e"} -start 1 -inc 2
1 - b
3 - d

Some thoughts:

don't forget about upvar to link a variable up the call stack.
I chose to use Tk style -options for some reason. It looks a bit awkward, but it's not exactly pretty to have to jam arguments at the end. You might choose to arguments with default values for start and inc. Or you might decide to put optional arguments in the middle of the list somewhere (like the way puts has an optional filehandle as the 1st arg), but that's more work to parse the arguments.
in hindsight, using for vs foreach is a pretty arbitrary decision. Here, with for, you need to extract the element from the array. With foreach you need to increment the index.


You should consider testing only the creation of the object/array, i.e. [ x, y ] vs. { x: x, y: y }, and also how it reacts to more items:

http://jsperf.com/array-vs-object-tuple

I'd say that the conclusion would be that there is no dramatic performance difference, and they both react reasonably to an increased number of items. Either is cheap enough that the actual performance of the code is usually decided by the actual work of getting the values to put in the object/array.

So, you should normally use the one that makes for conventient use of the result, and maintainable code. Having the ability to name the items in the result can definitely be convenient if you have more than just a few.


Crawler for scraping and approving friend requests in Facebook

VBAs selenium bindings are not as rich in functionality as other language bindings, but I would improve the following:

use the "by id" locators whenever possible:

.FindElementById("email").SendKeys ("someEmail") --Fill in the email
.FindElementById("pass").SendKeys ("password") --Fill in the password
.FindElementById("loginbutton").Click

if tempting to use XPaths, give CSS selectors a chance:

Set posts = driver.FindElementsByCss(".friendBrowserNameTitle > a")

avoid "magic" numbers in the code, like that value 50 - the number of scroll actions - configure it as a constant
I also don't particularly like the .Wait calls - this is typically a red flag when it comes to browser automation with selenium, but I am not sure VB bindings provide an Explicit Wait with a pre-defined condition


Array alive/dead entity "refresh" algorithm

You could probably use std::remove_if instead of your algorithm. Take this example code:

std::vector<std::string> vec = { "0", "1", "5", "0", "3", "6", "0", "1" };
std::remove_if(std::begin(vec), std::end(vec), [](const std::string& val)
{
    return val == "0";
});

for (auto&& a: vec)
{
    std::cout << a << ' ';
}

I get the following output:

1 5 3 6 1 0 0 0

std::remove_if swaps the elements of a range so that the elements that are to be kept are at the beginning of the range and maintains their order. The elements that are still at the end have unspecified values, but if Entity is an RAII class, the deinitialization will happen at destruction. Since I don't know what Entity looks like, I can't be sure that this method will work, but there is probaby a way to ensure that it will do what you need it to do.

This method has two advantages: it allows to think in term of iterators instead of sizes and it uses an already existing algorithm. In your case, refresh could probably look like this:

void refresh()
{
    std::remove_if(std::begin(entities), std::end(entities),
                   [](const Entity& ent)
                   {
                       return ent.isDead();
                   });
}

Once again, I am assuming some implementation details that are not shown though. Anyway, try check whether std::remove_if coud be used to do what you want it to do. Standard algorithms can often do much more things than thought.


Use for in loops to avoid repetition

These 3 blocks of code are very similar:

1

    clist=node.getElementsByTagName('channel')
    for c in clist:
            print c.childNodes[0].nodeValue

2

    glist=node.getElementsByTagName('gpio')
    for g in glist:
            print g.childNodes[0].nodeValue

3

    colist=node.getElementsByTagName('cont')
    for co in colist:
            print co.childNodes[0].nodeValue

We can clean up by abstracting what is different (the name) into a loop variable:

for name in ('channel', 'gpio', 'cont'):
    for element in node.getElementsByTagName(name):
        print element.childNodes[0].nodeValue

Now also adding another name will lead to only adding it to the list instead of repeating similar code the fourth time.


CSV-simplified: A small open source project

Review

Hi and welcome to code review.

To help out I have numbered the lines of your code for reference.

I will ignore the console.log calls as they represent debugging code.

Line 3 Bad function name. You are not uploading a file, you are loading the file and displaying it. That is two separate tasks and should be handled by two separate functions.

It is important that functions do one thing (their role) as describe in the function name. Two functions loadCSV and displayCSV and the directing of what to load and where to display is upto the event listing for the CSV file.
Line 5. The variable 'data` is not used. You declare it again in the onload line 11.

You don't need to set a value to null if you have nothing to put in it yet. The default is undefined.
Lined 6 & 7 The variables file and reader should be constants as they dont change.
Line 10 the variable csvData should be a const but you only use it once on  line 11. Would have been better to add event.target.result on line 11
Line 11 'data' should be a const. You are storing the wrong thing in it. If you look at the rest of the code lines 12,13,16,18 you use data.data. If you assigned the second property data to data then you would not have to type data.data each time.

Thus the line becomes const data = Papa.parse(event.target.result, {header : false}).data;
Line 13  const for arrayLength but you don't need it. Tthe 'console.log' on line 12 will have the length and the for loop (line 15) is the only other place you use it. But next point means you don't need it at all.
Line 15 First the i should be a block scoped variable using let and data.length for the length eg for(let i = 0; i < data.length; i++) {

But rather than use a for(;;) loop you can use a for of loop. Thus line 15 becomes for(const item of data) { where item is each item data. It's a const as it is a new variable each iteration.
Lines 17,18 is a very poorly written. First line 18 should be indented one tab as it is a continuation of line 17.

The query $("#header") is very slow and you get the same element each time. Before the loop you should have found the element and stored it in a const saving heaps of time.

You append HTML to the page which means the browser must parse it, then do a reflow, for every item, so slow. It can be done much faster. See examples
Lines 21,22,23 (and line 9) There is a shorthand way of writing functions, called arrow functions. They help reduce code noise making the code smaller and easier to read.

They differ a little from standard functions but for now you can just change lines 21-23 to reader.onerror = ()=> alert('Unable to read ' + file.fileName);

 1    document.getElementById('txtFileUpload').addEventListener('change', upload, false);
 2
 3    function upload(evt) {
 4
 5        var data = null;
 6        var file = evt.target.files[0];
 7        var reader = new FileReader();
 8        reader.readAsText(file);
 9        reader.onload = function(event) {
10            var csvData = event.target.result;
11            var data = Papa.parse(csvData, {header : false});
12            console.log(data.data);
13            var arrayLength = data.data.length;
14            console.log(arrayLength);
15            for (var i = 0; i < arrayLength; i++) {
16                console.log(data.data[i]);
17                $("#header").append("<li>" +
18                JSON.stringify(data.data[i]) + "</li>");
19            }
20        };
21        reader.onerror = function() {
22            alert('Unable to read ' + file.fileName);
23        };
24    }

Rewrite

The first version is the simplest one (incase you have not used promises before) but not perfect. The role of loadCSV is not quite just loading as it passes it on to displayCSV. But would require callbacks to do properly so it will do as is.

Both example don't need jQuery

const uploadInputEl = document.getElementById('txtFileUpload')
uploadInputEl.addEventListener('change',event => { loadCSV(event.target.files[0]) });

// The following function would normally be part of some help utilities like jQuery
const createTag = type => document.createElement(type);

function loadCSV(file) {
    const reader = new FileReader();
    reader.readAsText(file);
    reader.onload = e => displayCSV(Papa.parse(e.target.result, {header : false}).data);
}

function displayCSV(data) {
    const list = createTag("ul");
    for (const item of data) {
        list.appendChild(
            object.assign(
                createTag("li"), {textContent : JSON.stringify(item)}
        ));
    }
    document.getElementById("CSVContainer").appendChild(list);
}

The next uses promises to help keep the function roles succinct. LoadCSV only loads the data, and displayCSV creates the displayable content, that goes back to the event that started it all to place where it is wanted.

const uploadInput = document.getElementById('txtFileUpload');
const CSVContainer = document.getElementById("CSVContainer");

uploadInput.addEventListener("change",fileListener);

function fileListener(event) {
    loadCSV(event.target.files[0])
        .then(data => displayCSV(data)
            .then(list => CSVContainer.appendChild(list))
        );
}

function loadCSV(file) {
    return new Promise(loaded => {
        const reader = new FileReader();
        reader.readAsText(file);
        reader.onload = e => loaded(Papa.parse(e.target.result, {header : false}).data);
    });
}

function displayCSV(data) {
    const list = tag("ul");
    for (const item of data) {
        list.appendChild(tagText("li", JSON.stringify(item)));
    }
    return Promise.resolve(list);
}

// The next two would be part of a utils lib  and beyond the scope of the answer
// They do not represent well written code.
const tag = type => document.createElement(type);
const tagText = (type, text) => (type = tag(type), type.textContent = text, type);


Selecting minimal sum of two distinct entries of two dicts with common keys

Simplified: Lines-of-Code

Sorting & Extracting

You are sorting lists of values, storing these in variables, and then extracting only the first entries from these lists.  You can use an array slice to keep only the first two entries from the sorted lists, and extract these:

    a1, a2 = sorted(a, key=a.get)[:2]
    b1, b2 = sorted(b, key=b.get)[:2]

If / Else

You test a1 != b1, and if that is True, you return a value.  If not, you again test these values with a1 == b1, and based that, you return different values, or raise an error.

What are the possibilities for a1 != b1 and a1 == b1?  Can the first and the second conditions ever both be False?  Either they are equal, or they are not equal.  Or something very strange is going on.  Since the values are keys to a dictionary, tests for equality must be possible and consistent, so this raising of an error looks like it can never be reached.

So you are left with an if and and else case.  In the else case, you again have two possibilities, so we can make the whole thing into one if/elif/else statement:

    if a1 != b1:
        return a1, b1
    elif a[a1] + b[b2] < a[a2] + b[b1]:
        return a1, b2
    else:
        return a2, b1

Simplified: Time Complexity

Python's sorting is an \$O(N \log N)\$ time-complexity operation.  This is done twice, once for the a dictionary and once for the b dictionary, but that doesn't change the complexity.

After sorting, the two smallest entries are retrieved.  You are taking a \$O(N \log N)\$ time complexity hit to extract the smallest and the second smallest entries.

Finding the minimum is a \$O(N)\$ operation:

    a1 = min(a, key=a.get)
    b1 = min(b, key=b.get)

Finding the second smallest can also be done in \$O(N)\$ time:

    a2 = min((k for k in a if k != a1), key=a.get)
    b2 = min((k for k in b if k != b1), key=b.get)

The above is doing two \$O(N)\$ passes over each list.  You can also find the lowest two values in a list using only a single pass by iterating over the list and maintaining the smallest and second smallest values (and their keys).  Implementation left to student.

Finally, you can use the Python heapq.nsmallest function.

  a1, a2 = heapq.nsmallest(2, a, key=a.get)
  b1, b2 = heapq.nsmallest(2, b, key=b.get)


Runge-Kutta 4th order using Python numexpr.evaluate()

I would make all objects numpy arrays and get the user to use index notation. They would have to write equations of the form R = np.array(['c[0]*y[0]*y[1]']) meaning that this will later evaluate just like your R = {'R1': 'c*y1*y2'}. Almost all functions can then take advantage of the fact that numpy does almost everything vectorized.

#!/usr/bin/env python3
# k_1 = dt*dcdt(C0, dt);
# k_2 = dt*dcdt(C0+0.5*k_1, dt);
# k_3 = dt*dcdt(C0+0.5*k_2, dt);
# k_4 = dt*dcdt(C0+k_3, dt);
# C_new = C0 + (k_1+2*k_2+2*k_3+k_4)/6;

import numpy as np

dt = 0.1

c = np.array([1])
y = np.array([[0, 0.1, 0.2, 0.3], [0, 0.1, 0.2, 0.3]])
R = np.array(['c[0]*y[0]*y[1]'])
dcdt = np.array(['-4 * R[0]', '-R[0]'])

def k_loop(y):
    rates_num = np.array([eval(k) for k in R])
    dcdt_num = np.array([eval(k, {'R': rates_num}) for k in dcdt])
    return dt * dcdt_num

def sum_k(A, B, b):
    return A + b * B * dt

def result(y_0, k_1, k_2, k_3, k_4):
    return y_0 + (k_1 + 2 * k_2 + 2 * k_3 + k_4) / 6

k1 = k_loop(y)
k2 = k_loop(sum_k(y, k1, 0.5))
k3 = k_loop(sum_k(y, k2, 0.5))
k4 = k_loop(sum_k(y, k3, 1))

y_new = result(y, k1, k2, k3, k4)
print(y_new)

Note that this is slightly slower for the small example given (0.09s vs 0.08s). Also the step rates_num = np.array([eval(k) for k in R]) looses some precision (up to 1E-4).

To see whether or not this performs better, a more realistic example would be needed.

The eval call can be back-substituted with ne.evaluate, I just didn't want to install it.

To calculate timings, I ran the result function 100000 times, like so:

for _ in range(100000):
    y = result(y, k1, k2, k3, k4)

When doing this with your original code, this takes 1.36s, while my code takes 0.99s.

However, when including updating the ks, this advantage goes away again:

for _ in range(10000):
    k1 = k_loop(y)
    k2 = k_loop(sum_k(y, k1, 0.5))
    k3 = k_loop(sum_k(y, k2, 0.5))
    k4 = k_loop(sum_k(y, k3, 1))
    y = result(y, k1, k2, k3, k4)

Note that this is ten times less often than before. Here your code takes 2.7s and my code takes 3.7s on my machine.


There is not too much to be said about the code as it is. A few (very minor) things I can point out as suggestions:

Make if 97 <= id <= 122: followed by if 65 <= id <= 90: an if-elif clause. That makes it clearer the code path can only follow one of these (or even neither).
Dedent the bottom letter = chr(shift) by one indentation and remove the other one; avoids duplication
There is inconsistent white space around operators (sometimes one space each side, sometimes no space). I think PEP 8 recommends a single space on each side.
Some people will argue that you shouldn't do new = ""; ... ; new = new + letter. But instead, something like letters = []; ...; letters.append(letter); ...; new = "".join(letters).
That would gain you some speed. But only if your string becomes (very) long. For small strings, I think the current way (appending to a string) is clearer.
Just so you know.

I can, however, suggest to use str.maketrans and str.translate.
 You'll need to set up the translation table in a smart way (the algorithm), but the actually encoding is then very clear and straightforward. Left as an exercise to the reader.

Which leads to the fun fact: rot13 is available as a standard encoding.
In Python 2:

>>> 'Caesar Cipher'.encode('rot13')
'Pnrfne Pvcure'

In Python 3 is slight more effort:

>>> import codecs
>>> codecs.encode('Caesar Cipher', 'rot13')
'Pnrfne Pvcure'


You have a lot of copy-and-paste code, where the only things that vary are the variable name, denomination, and textual description.  You can generalize the logic.

#include <iostream>

struct Denomination {
    const int cents;
    const char *description;
};

const Denomination DENOMINATIONS[] = {
    { 10000, "Hundred-Dollar Bills" },
    {  5000, "Fifty-Dollar Bills" },
    {  2000, "Twenty-Dollar Bills" },
    {  1000, "Ten-Dollar Bills" },
    {   500, "Five-Dollar Bills" },
    {   100, "One-Dollar Bills" },
    {    25, "Quarters" },
    {    10, "Dimes" },
    {     5, "Nickels" },
    {     1, "Pennies" }
};

int main() {
    double totalAmount;
    std::cout << "Please enter the amount to convert: $";
    std::cin >> totalAmount;
    std::cout << '\n';

    int cents = 100 * totalAmount;
    for (int i = 0; i < sizeof(DENOMINATIONS) / sizeof(DENOMINATIONS[0]); ++i) {
        std::cout << "Number of " << DENOMINATIONS[i].description
                  << ": " << (cents / DENOMINATIONS[i].cents) << '\n';
        cents %= DENOMINATIONS[i].cents;
    }
}

Also note:

A somewhat common convention is to use this NamingConvention for types, this namingConvention for variable names, and this NAMING_CONVENTION for constants.
Your DollarsConversion variable is misnamed, in my opinion, as it actually stores the number of cents.


Here's my take on this:

import kotlin.system.measureTimeMillis

fun sieve(xs: Sequence<Int>): Sequence<Int> = sequence {
    val head = xs.first()
    val tail = xs.drop(1).filter { it % head != 0 }
    yield(head)
    for (i in sieve(tail))
        yield(i)
}

val primes = sieve(generateSequence(2) { it + 1 })
fun isPrime(n: Int) = primes.contains(n)

val durationMs = measureTimeMillis {
    println("isPrime(4057) = ${isPrime(4057)}")
}
println("Duration = $durationMs ms")

Start with the first element in the sequence - number 2
Filter out all numbers divisible by 2
Yield 2
Yield the rest recursively:

Start with the first element in the sequence - number 3
Filter out all numbers divisible by 3
Yield 3
Yield the rest recursively...


If you are making many requests, it is worth it to have a look at requests.Session. This re-uses the connection to the server for subsequent requests (and also the headers and cookies).

I would also start separating your different responsibilities. One might be global constants (like your header and cookies), one a function that actually does the submission, one that creates the session and does each submission and then some code under a if __name__ == '__main__': guard that executes the code.

import requests
import json

COOKIES = {<redacted>}
HEADERS = {<redacted>}

def post(session, url, data):
    """Use session to post data to url.
    Returns json object with execute result"""
    response = session.post(url, data=data)
    json_file = response.content.split('<ExecuteResult>')[1]
    json_file = (json_file.split('</ExecuteResult>')[0]).replace("\\", "")
    return json.loads(json_file)

def post_submisssions(url, data, n):
    """Create a session and post `n` submissions to `url` using `data`."""
    session = requests.Session()
    session.headers.update(HEADERS)
    session.cookies = COOKIES

    for _ in xrange(n):
        json_response = post(session, url, data)
        print "Created Id:", json_response['_entity']['Id']

if __name__ == "__main__":
    url = "<redacted>"
    data = "<redacted>"
    post_submisssions(url, data, input("How many submissions to create:"))

I also added some rudimentary docstrings.

You could also change your parsing by using BeautifulSoup:

from bs4 import BeautifulSoup

def post(session, url, data):
    """Use session to post data to url.
    Returns json object with execute result"""
    response = session.post(url, data=data)
    soup = BeautifulSoup(response.content, 'lxml')
    return json.loads(soup.find('ExecuteResult'.lower()).replace("\\", ""))


Text tokenizer - extract words and positions from text

You shouldn't shorten class names. So WordPos should become WordPosition.

Right now you are creating WordPos items which you add to a List<WordPos> which is lost after returning from the method.

Instead of using substring() you could use a StringBuilder object, where you append if the current char is contained in DELIMITERS.

You would need to take care (which you don't do right now) about the case that the text ends without any of your delimiting chars.

public List<String> extractWords(String text) {
    List<String> words = new ArrayList<>();
    StringBuilder sb = new StringBuilder(text.length());

    for (int i = 0; i < text.length(); i++) {
        char current = text.charAt(i);

        if (DELIMITERS.contains(current)) {
            if (sb.length() > 0) {
                words.add(sb.toString());
                sb.setLength(0);
            }
        } else {
            sb.append(current);
        }
    }
    if (sb.length() > 0) {
        words.add(sb.toString());
    }
    return words;
}


Your _int_tuple function does not seem to serve any real purpose. U and V are always integers (you initialize them to 1 and do only arithmetic on them afterwards). And what exactly your program will do with a Q which is e.g. a string is hard to follow, but I think it will run into the else block (Q is neither 1 nor -1) and then try to do Qk = Q, followed by Qk *= Qk which fails for almost everything but number types.

I also can't see any parts of your code which would produce a float (though I might have overlooked one).

So I would get rid of that function and return just a tuple and see what it does.


Handling events in a multi threaded environment

The method StartListening takes one argument object dummy. It is not used in the method and from its name I conclude that it is not intended to be used. It is possible to declare the method with no arguments and call a variant of Task.Factory.StartNew that takes a parameter of type Action and TaskCreationOptions to start the new task.
The field private static EventWaitHandle _eventWaiter is only initialized in the constructor and never used. Its purpose is unclear from the code.


I'm just going to review the unit tests here.
Overall, it looks reasonably good.  I don't have many changes to suggest.
Drop test_test
I think you probably created this to experiment with the testing infrastructure.  It doesn't contribute to testing Stack, so it no longer needs to remain.
The tear-down is unnecessary
The Stack should not need its items removing after use, so just drop the tearDown method.  In fact, the setUp is debatable - it might be as easy to have a local s = Stack() in each test, rather than sharing a member.
Avoid deprecated methods
Replace failUnless with assertTrue, and failIf with assertFalse.
Simplest tests first
This might just be opinion, but I'd start with test_empty_function_on_empty_stack before test_empty_function_with_items_in_stack, and I'd write test_pop_function_on_empty_stack before test_pop_function_with_items_in_stack.  One reason is that when I do test-driven development, it's natural to test the empty stack functions before implementing push.
Don't use assertTrue for comparison
Here, we don't get much information if the test fails:
def test_push_function_for_one_item(self):
    self.s.push(10)
    self.assertTrue(self.s.size == 1)

Instead, we want
    self.assertEqual(1, self.s.size)

Avoid loops in tests
I'd be more explicit in the final test:
def test_lifo_functionality(self):
    self.s.push(1,2,3,4)

    self.assertEqual(4, self.s.pop())
    self.assertEqual(3, self.s.pop())
    self.assertEqual(2, self.s.pop())
    self.assertEqual(1, self.s.pop())
    self.assertTrue(self.s.is_empty())

Modified code
class TestStackMethods(unittest.TestCase):

    def setUp(self):
        self.s = Stack()

    def test_empty_function_on_empty_stack(self):
        self.assertTrue(self.s.is_empty())
        self.assertEqual(0, self.s.size)

    def test_empty_function_with_items_in_stack(self):
        self.s.push(1)
        self.assertFalse(self.s.is_empty())

    def test_pop_function_on_empty_stack(self):
        with self.assertRaises(IndexError) as c :
            self.s.pop()
        self.assertTrue('Stack Empty' in c.exception)

    def test_pop_function_with_items_in_stack(self):
        self.s.push(1)
        self.assertEqual(1, self.s.pop())

    def test_peek_function_on_empty_stack(self):
        self.assertIs(self.s.peek(), None)

    def test_peek_function_with_items_in_stack(self):
        self.s.push(1)
        self.s.push(2)
        self.assertEqual(2, self.s.peek())

    def test_push_function_for_one_item(self):
        self.s.push(10)
        self.assertEqual(1, self.s.size)

    def test_push_function_on_a_list_arg(self):
        args = [1,2,3,4]
        self.s.push(args)
        self.assertEqual(4, self.s.size)

    def test_push_function_on_multiple_args(self):
        self.s.push(1,2,3,4)
        self.assertEqual(4, self.s.size)

    def test_lifo_functionality(self):
        self.s.push(1,2,3,4)

        self.assertEqual(4, self.s.pop())
        self.assertEqual(3, self.s.pop())
        self.assertEqual(2, self.s.pop())
        self.assertEqual(1, self.s.pop())
        self.assertTrue(self.s.is_empty())


Associating a name with each bit in a bitmask

Suggestions

enumerate is built-in function useful here
dict comprehensions can be used to create dictionaries from arbitrary key and value expressions
imho '{:b}'.format(n) is easier to read than bin(n)[2:]
in additional you may use OrderedDict if you often iterate over agents 1, 2, 3, 4, ...

Final code (n = 10, size_bin =  6)

{'a{}'.format(k): int(v) for k, v in enumerate('{:b}'.format(10).ljust(6, '0'), start=1)}

and with full utilize format syntax

{'a{}'.format(k): int(v) for k, v in enumerate('{:<0{}b}'.format(10, 6), start=1)}


Getting position of coordinates and checking if they match

I find the original code overly complicated.

Here is a revised version of the original test code.

class Test {

    private $item = [ [ false, true ], [ true, true ] ];

    const VERTICAL_MIDDLE = 421;
    const HORIZONTAL_MIDDLE = 297;

    public function is_quadrant_valid($variable) {
        $down = $variable['y'] > self::VERTICAL_MIDDLE;
        $right = $variable['x'] > self::HORIZONTAL_MIDDLE;

        return $this->item[$down][$right];
    }

}

$t = new Test();
echo $t->is_quadrant_valid([ 'y' => 90, 'x' => 20 ]) ? 'Valid' : 'Invalid';

This includes a class, which seems to be consistent with the original code.

This version defines $item as a private property of the class.  Rather than making keys by concatenating strings, I use a two dimensional array system.  This also allows us to arrange $item such that the quadrant organization matches.

Rather than storing 0s and 1s that we have to convert into false and true values, this just stores true and false directly.

Instead of using regular variables to store the coordinates of the middle, this uses constants.

I changed the name of the function to be shorter, but I don't think that it is any less clear.

Since the original takes a function parameter, it seems that the test version should as well.  This way we could run multiple tests just calling with different values.

Since we index the arrays with 0 for false and 1 for true, we can simplify the variables.  I renamed them to better match what they hold.

I find this simpler and easier to read.  You should be able to easily transfer this back to your original code if desired.

As a general rule, if (is_true()) return true; else return false; can be replaced by return is_true(); which is much shorter.


This is more "streaming" in a sense:
from heapq import nlargest
from operator import itemgetter

def top_ten_scorers(stats):
    players = (dict(name=name, ppg=points/games, team=team)
               for team, players in stats.items()
               for name, games, points in players
               if games >= 15)
    return nlargest(10, players, key=itemgetter('ppg'))

Your with_teams and with_ppg are fully computed lists, and then sorted creates another one that it then sorts, and then you throw away all but ten elements of it.
My players is a generator iterator, computing more elements on the fly as requested. The players = ... assignment only sets up the iterator, but nothing gets processed yet.
Then nlargest consumes players one by one, keeping only the top 10 seen so far and returning them sorted (in descending order). Could also be more efficient than sorting everything, depending on the number of eligible players.
I actually found your first two steps more confusing than helpful, as your with_teams creates an intermediate result/format to understand. I think it's simpler and easier to read to just directly produce the player dicts from the stats. Then again, I might be biased towards this and away from yours because I'm used to Python, which, as you say, isn't much into chaining.
Btw, here's an old message from Guido about some forms of chaining. Not sure it relates to what we have here, but perhaps interesting anyway.
I used dict(...) just for brevity, but {...} is faster, so you might want to keep the latter:
Setup:
name, ppg, team = 'Betnijah Laney', 263/16, 'ATL'

Round 1:
  347.041 ns  dict(name=name, ppg=ppg, team=team)
  128.325 ns  {'name': name, 'ppg': ppg, 'team': team}

Round 2:
  350.576 ns  dict(name=name, ppg=ppg, team=team)
  129.106 ns  {'name': name, 'ppg': ppg, 'team': team}

Round 3:
  347.753 ns  dict(name=name, ppg=ppg, team=team)
  130.734 ns  {'name': name, 'ppg': ppg, 'team': team}


Is my handling of command line arguments correct or could it be done better?

It would be better to not reinvent the wheel and use argparse instead.

  Is the way I've broken my code down into individual functions reasonable or should certain functions be combined or broken apart?

It's quite fine the way you did it.
Every function seems to do just one thing, it's good like that.

  Are there any other glaring weaknesses?

Instead of this:

if len(sys.argv) == 1:
    return False
else:
    return True

Write like this:

return len(sys.argv) != 1

Instead of this:

with open(WORDS, 'r', 0) as in_file:

I'd recommend simply:

with open(WORDS) as in_file:

Instead of this:

for i in range(1, length + 1):
    key = generate_key()
    passphrase += word_dict[key] + ' '

This is simpler:

for _ in range(length):
    key = generate_key()
    passphrase += word_dict[key] + ' '

I replaced the loop variable i with _,
because it's a common convention when the loop variable is not used.

Lastly,
I recommend to switch to start using Python 3 instead of 2.7.


Typically, a character-for-character replacement is best done using str.translate():

strand.translate(str.maketrans('AaTtGgCc', 'TtAaCcGg'))

However, your situation is trickier, because you also want to map all invalid characters to 'x'.  To achieve that, you would need to read the str.maketrans() documentation carefully, and figure out that you can wrap the mapping in a collections.defaultdict.

from collections import defaultdict

DNA_COMPLEMENTS = defaultdict(lambda: 'x', str.maketrans('AaTtGgCc', 'TtAaCcGg'))

def complementary(strand):
    return strand.translate(DNA_COMPLEMENTS)

Note that lambda: 'x' is a way to make a function that, when called with no parameters, returns the letter 'x'.


This looks like something Optionals can handle, so:

public static Optional<Object> getById(int id) {
    for(Object thing : things) {
        if(thing.getId() == id) {
            return Optional.of(thing);
        }
    }

    return Optional.empty();
}

Now in your read code, you can simply do this:

public static void read(DataInputStream stream) throws IOException {
    Object thing = getById(stream.readInt())
                       .orElseThrow(() -> new IOException("Could not find Id"));

    // Do something with thing
}


I think this is the sort of thing for which HashSet is perfect. Your implementation would look something like I have shown below. The advantage is that you don't need a sort so your running time is strictly linear.

(Updated to fix syntax errors)

public static Integer[] outputSinglePair(Integer[] numbers){
    if(numbers == null)
        throw new IllegalArgumentException();

    HashSet<Integer> result = new HashSet<Integer>();
    for (int next: numbers) {
        if (result.contains(next)) {
            result.remove(next);
        }
        else {
            result.add(next);
        }
    }
    return result.toArray(new Integer[result.size()]);
}


My 2 cents are:

This code is understandable, but I would still rewrite it since it is cookie cutter, and you will surely move on to more complex stuff
Q uses a Promise object, Mongoose does not, so that would not work without some overhauling ( I personally like Q better though )
Async works with 'last parameter must be a callback' which is exactly how Mongoose works, so use that


Note: Each tip assumes you followed all of the ones before.

There are a bunch of trailing whitespace characters. Get rid of 'em. They're ugly.

Bst is a terrible class name. It means nothing out-of-context, and out-of-context is where it will be. I'd recommend renaming to BinarySearchTree.

In the if statements, there's sometimes an extra space before the close-paren but not after the open; I've only ever seen both or neither. Personally, I would just get rid of the parentheses entirely -- they're unnecessary.

Prefer if obj.nil? over unless obj. It makes it much clearer that it's checking the existence of an object, rather than, say, the result of a method called obj.

Prefer @data to self.data. It functions the same but it's far more standard to directly access instance variables, unless accessing it requires some guard clauses or the like. Ditto for self.right and self.left. The exception is when you're accessing the class from outside, in which case you obviously don't have direct access to instance variables.

Put a space after (but not before) commas -- so traverse_preorder(node.left,&blk) becomes traverse_preorder(node.left, &blk).

In that method, I'd recommend changing blk to block, because it makes no sense to shorten it.

With these changes, here's what your code looks like:

class BinarySearchTree
  attr_accessor :data, :left, :right

  def initialize(data)
    @data = data
  end

  def insert(data)
    if @data < data
      if @right.nil?
        @right = BinarySearchTree.new(data)
      else
        @right.insert(data)
      end
    else
      if @left.nil?
        @left = BinarySearchTree.new(data)
      else
        @left.insert(data)
      end
    end
  end

  def each(&block)
    BinarySearchTree.traverse_preorder(&block)
  end

  def self.traverse_preorder(node, &block)
    node.left.traverse_preorder(&block)
    blk.call(node.data)
    node.right.traverse_preorder(&block)
  end
end


If we are allowed to pass the tail node to the reversal method (Node reverseDLL(Node head, Node tail)), we can perform the reversal by reversing the data integer fields instead of restructuring the list. All in all, I had this in mind:

import java.util.ArrayList;
import java.util.List;

class Node {
    int data;
    Node next;
    Node prev;

    Node(int data) {
        this.data = data;
    }
}

public class ReverseDLL {

    static void reverseDLL2(Node head, Node tail) {
        Node left = head;
        Node right = tail;

        while (true) {
            if (left == right) {
                return;
            }

            int tmp = left.data;
            left.data = right.data;
            right.data = tmp;

            if (left.next == right) {
                return;
            }

            left = left.next;
            right = right.prev;
        }
    }

    static void printList(Node head) {
        for (Node current = head; current != null; current = current.next) {
            System.out.print(current.data);
            System.out.print(" ");
        }
    }

    public static void main(String[] args) {
        List<Node> nodes = new ArrayList<>();

        for (int i = 0; i < 10; ++i) {
            nodes.add(new Node(i));
        }

        for (int i = 0; i < 9; ++i) {
            nodes.get(i).next = nodes.get(i + 1);
        }

        for (int i = 1; i < 10; ++i) {
            nodes.get(i).prev = nodes.get(i - 1);
        }

        printList(nodes.get(0));
        reverseDLL2(nodes.get(0), nodes.get(9));
        System.out.println();
        printList(nodes.get(0));
        reverseDLL2(null, null);
    }
}

Hope that helps.


PowerShell script to read line by line large CSV files

It might be a little hard to make a suggestion about this as I cannot see how the data is being used beyond this. However I can point out the large performance flaw in your logic.
Building arrays with +=
You have multiple lines of code that go like this:
$20811 += New-Object PSObject -Property $details

What is actually happening there is PowerShell is destroying the array $20811 and creating a new one that is one element larger to house the data on the right hand side. For small operations this performance hit is negligible. However you will certainly feel it when you get into the thousands of elements. You are rebuilding new arrays with every operation.
Consider array lists
I would instead just create all of the custom objects in one pass into one large variable instead. Then you could use Where-Object to process the groups of rows as you see fit. Or you can still keep them as separate objects. Either way I would use an arraylist instead.
$11936 = New-Object System.Collections.ArrayList

# truncated ....
11936 # OS Identification
{
    [void]($11936.Add($details))
    break
}

The [void] cast suppresses the output created from the Add method
This should be significantly faster.
Read the CSV as a database
There are methods to read the CSV as a database as well. The one I tested was using the Microsoft.ACE.OLEDB.12.0 provider. This method allows you to use SQL statements against the CSV file. I don't really have the time to properly benchmark this but this should be faster than your current method as well. Consider a simple example using mock "employee" data:
@"
id,first_name,last_name,email,ip_address
1,Edward,Richards,erichards0@businessweek.com,201.133.112.30
2,Jimmy,Scott,jscott1@clickbank.net,103.231.149.144
3,Marilyn,Williams,mwilliams2@chicagotribune.com,52.180.157.43
4,Frank,Morales,fmorales3@google.ru,218.175.165.205
5,Chris,Watson,cwatson4@ed.gov,75.251.1.149
6,Albert,Ross,aross5@abc.net.au,89.56.133.54
7,Diane,Daniels,ddaniels6@washingtonpost.com,197.156.129.45
8,Nancy,Carter,ncarter7@surveymonkey.com,75.162.65.142
9,John,Kennedy,jkennedy8@tumblr.com,85.35.177.235
10,Bonnie,Bradley,bbradley9@dagondesign.com,255.67.106.193
"@ | Set-Content .\test.csv

$conn = New-Object System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\Cameron';Extended Properties='Text;HDR=Yes;FMT=Delimited';")
$cmd=$conn.CreateCommand()
$cmd.CommandText="Select * from test.csv where first_name like '%n%'"
$conn.open()
$data = $cmd.ExecuteReader()

$data | ForEach-Object{
    [pscustomobject]@{
        id=$_.GetValue(0)
        first_name=$_.GetValue(1)
        last_name=$_.GetValue(2)
        ip_address=$_.GetValue(4)
    }
}

$cmd.Dispose()
$conn.Dispose()

I have a SQL statement in there that will return all the records where the first name has a "n" in it. Using the field indecies we build a custom psobject that gets sent down the pipe.
Note that the source in the connection string is the folder that contains the csv file. And the table in the SQL statement is the CSV file name.


C++ object pool that returns a smart pointer on request

unique_ptr ownership / lifetime issues:
Normally, std::unique_ptr indicates single ownership of an object and thus gives the user certain expectations of how they can safely use it. But here the object_pool "owns" the object (or at least the underlying memory), so the use of unique_ptr is rather misleading. Consider the following code:
{
    auto ptr = std::unique_ptr<int, std::function<void(int*)>>();

    {
        object_pool<int> pool;
        ptr = pool.request(5);
    }

    // uh oh...
}

We would normally expect the above code to work without problems. However, the custom unique_ptr deleter will attempt to call _object_pool.push_back(object) on a pool that doesn't exist any more.
At the very least, I'd suggest "hiding" the use of unique_ptr behind a typedef, and documenting thoroughly that it must go out of scope before the object pool:
template<class T>
using object_pool_ptr = std::unique_ptr<T, std::function<void(T*)>>;

This also means the user doesn't have to worry about typing out the custom deleter signature.
It would be even better to make object_pool_ptr a wrapper class around the unique_ptr to hide it completely.

object_pool destructor:
As a debugging feature, the object_pool could keep track of the total number of objects allocated. We could then check that our "free list" (the _object_pool deque) is the correct size in the object_pool destructor, rather than waiting until a pointer goes out of scope.
I don't think it's necessary to call pop_front() on individual elements in the destructor. We could call clear() after the loop, or allow the _object_pool to clean up naturally in its own destructor.

[Note: below this point are just possible things that might be useful, depending on what other features your object pool needs, and what you're actually using it for].

tracking allocated memory inside the pool:
This "object pool is a free-list" strategy is really clever... but maybe there are advantages to keeping track of all the allocated memory inside the object pool too?
We could use a std::deque<std::aligned_storage_t<sizeof(T)>> member variable allowing us to call push_back to add more elements without invalidating references (and hence pointers) to the original elements.
This also means we avoid the need to call global operators new and delete for every element.

manual lifetime (but not memory) management:
If the object pool keeps track of all allocated memory as above, perhaps it's ok to give the user a simple raw pointer to an allocated object and expect them to call an object_pool.destroy(ptr); function when they're done with it?
This isn't dangerous in terms of object lifetimes, since the object pool can still call the object destructors when necessary (and maybe issue a warning or assert() if desired). Although it would open up the possibility of pointers to destroyed objects being accidentally reused.
It also allows us to make the object_pool moveable, and add a clear() function.


Don't do that it is so easy to have incorrect usage.

All your cases can be done using normal syntax in C++.

// int arr[128];
// ZeroArray(arr);

int arr[128] = {0}; // Zero whole array.
// Or better yet use a vector.
std:vector<int>  arr(128); // zero init the vector of 128 elements.
// Or alternatively an array
std::array<int,128> arr(0);

// S s;
// ZeroStruct(s);
S s = S();          // Calls the default constructor for zero initialization.

See:
C++ implicit copy constructor for a class that contains other objects
Proper way to initialize C++ structs
Does a c++ struct have a default constructor?


Parsing XML to get all elem.tag: elem.text pairs

XPath support fetching parent element https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax. Let's try to find name element and get parent of this element:

>>> [x for x in tree.findall('.//name/..')]
[<Element 'diag' at 0x7f9c8cece278>,
 <Element 'diag' at 0x7f9c85a84908>,
 <Element 'diag' at 0x7f9c85a93f98>,
 <Element 'diag' at 0x7f9c85a8f188>]

When we have parent element, we can get name and desc elements:

>>> [(x.find('name'), x.find('desc')) for x in tree.findall('.//name/..')]
[(<Element 'name' at 0x7f9c875ba7c8>, <Element 'desc' at 0x7f9c8cedfe58>),
 (<Element 'name' at 0x7f9c85a84958>, <Element 'desc' at 0x7f9c85a84f98>),
 (<Element 'name' at 0x7f9c85a8f048>, <Element 'desc' at 0x7f9c85a8f098>),
 (<Element 'name' at 0x7f9c85a8f1d8>, <Element 'desc' at 0x7f9c85a8f228>)]

And finally:

>>> [(x.find('name').text, x.find('desc').text) for x in tree.findall('.//name/..')]
[('A00', 'Cholera'),
 ('A00.0', 'Cholera due to Vibrio cholerae 01, biovar cholerae'),
 ('A00.1', 'Cholera due to Vibrio cholerae 01, biovar eltor'),
 ('A00.9', 'Cholera, unspecified')]


Project Euler problem # 3 is this the most efficient approach in Python or can I do better?

order
You wrote:
    if is_prime(divisor) and number % divisor == 0:

that is, if A and B:.
But B is typically false and is quickly computed.
Prefer if B and A:
stride
Rather than
    for divisor in range(int(number ** 0.5) + 1, 0, -1):

you might want to begin with an odd number and then use a stride of -2.
You needn't special case for when number is a power of two,
since the input clearly isn't.
sieve
Consider sieving for the solution.


You're missing a big simplification.  The hamming distance is the count of ones in x^y, so simply perform that xor and count the set bits.  There should be no need to convert to string.


Project Euler Problem 10 - Sum of primes < 2mil

I have several things to add onto @rolfl's great advice:

Since you have a container of bools, which doesn't store the actual primes, consider renaming primes to is_prime or something similar.  This sounds more conditional and makes more sense with the type of values being stored.
I might still assign the 2000000 to a constant to make this more understandable for users without the full documentation (someone might otherwise think that there should be 2M primes, looking at the vector's name).  It would also help in case you'll need this number elsewhere.

You could have something like this (feel free to use a better name):

const int maxNumbers = 2000000;

std::vector<bool> primes(maxNumbers, true);

You can leave out the true from your if statements:

This

if(primes[a]==true)

is the same as

if(primes[a])

If you were to do something with false, you would use !:

if(!primes[a])

You're hard-coding a*a+b*a in some places, and it's not quite clear what this computation corresponds to (especially with your single-character variable names).

You could assign it to a local variable and use it where it's needed.  To keep it within a close scope (it's only needed within a small space), initialize it within the loop.
Some of your comments seem noisy/useless:

// We will be storing the primes as bool in a vector.

The "we" sounds like you're demonstrating this code for a tutorial or such, and this doesn't appear to be the intent.  Just a simple "this does..." or "this is..." will do.

Other than that, the entire comment is not helpful.  It's clear that it's an std::vector of bools that stores primes.  There's no need to state the obvious; the code speaks for itself.

// This is the Sieve of Eratosthenes. It is not perfect, but It solve's the problem.

The second sentence is just noisy and adds nothing of value; just remove it.  The first sentence, however, is okay because it's not entirely obvious that this is the Sieve.


Unless you can make them share a common interface, it is not desirable to eliminate the code duplication -- best case (vb.net late binding on Object), trades your code size for the compilers.  Doing the work yourself, simply means more code for you.

That said, where the code duplication is, is something you might want to control.  Extract each assignment out into a similarly named method, and call the appropriate one.

Sub UpdateEntityFromPerson(ByVal entity as Entity, ByVal person as Person1)
    With person
        entity.Birthdate = .BirthDate

        entity.FirstName = .FirstGivenName
        entity.LastName = .FamilyName

        entity.Street = .StreetName
        entity.HousNr = .HouseNumberIdentifier
        entity.BoxNr = .BoxNumberIdentifier
        entity.PostalCode = .PostalCode
        entity.Municipality = .CityName
    End With
End Sub

Sub UpdateEntityFromPerson(ByVal entity as Entity, ByVal person as Person2)
    With Person
        entity.Birthdate = .BirthDate

        entity.FirstName = .FirstGivenName
        entity.LastName = .FamilyName

        entity.Street = .StreetName
        entity.HousNr = .HouseNumberIdentifier
        entity.BoxNr = .BoxNumberIdentifier
        entity.PostalCode = .PostalCode
        entity.Municipality = .CityName
    End With
End Sub

        If boolFlag Then
            UpdateEntityFromPerson(entity, offer.person1)
        Else
            UpdateEntityFromPerson(entity, offer.person2)
        End If

All of the code is still duplicated, but it type safe, clear, and easy to use and understand.  Of course, the best thing to do is probably to have an entity constructor that takes one or the other, or a builder that does so, but that depends upon other factors, outside your snippet...


Good work formatting and approaching styles in a fashionable method, it makes reading your code very easy! a couple things to note:

It's common to see private variables prefixed with an underscore to improve readability. It's up to you if you want to implement this, and if you use a framework, check their docs to see if it's standard.
Regarding your last method, dump(): the name dump could mean many things. Without seeing the source, what's it dumping? It'd be fine to leave it as is, but you may consider renaming to dumpRules() or something of that sort.
I'm not sure if you left it out, or you just haven't, but it's also a good practice to document your code. That means add comments. Googling PHPDoc will give you a good start, and if your familiar with JavaDocs, that's what I'm talking about.

Be careful making new array's with just = [].

  As of PHP 5.4 you can also use the short array syntax, which replaces
  array() with [].

That's from the docs. So if anyone using below 5.4 wants your code, they could experience some turbulence setting it up.

The one comment you do have, is started with #. I believe this style of comments are deprecated and the C style comments (/*...*/, //) are favorable. I'll try and find a reference to this claim.

I noticed you have

foreach ($this->rules[$rulename]['rules'] as $rule) {
    try {
        $rule->check($input);
    } catch (Exception $e) {
        $this->errors[$rulename][] = $e->getMessage();
    }
}

a couple times. You could put this in a function (with appropriate parameters) and simply call the function to reduce multiplicities.

Other than that, all looks well. Just in case you wanted to look at some other validation classes (if you haven't already), here's one to get you started.


You should avoid using global variables. If you import this code into a future project it might cause problems -- name conflicts etc.

If you must do this, put them in an anonymous namespace so that they're only in scope for this file:

namespace
{
    int my;
    int globals;
    int defined;
    int here;
}

The declaration of Check_date() is not necessary here:

void Check_date();
void Check_date()
{

This could perhaps written better:

for (int x=0, y=1; y<=3; y++, x++)
{
    while (input[x] !='/' && x !=input.length()) ss<<input[x++];
    ss>> date[y];
    ss.clear();
}

There is little point using x in the for loop as you don't have an exit condition for it. Also, I would prefer a more meaningful name.

Instead, perhaps:

int inputPos = 0;
for(int dateIndex = 1; dateIndex <= 3; ++dateIndex)
{
    while(input[inputPos] != '/' && inputPos != input.length())
    {
        ss >> date[dateIndex];
        ss.clear();
    }
    ++inputPos;
}

More generally you've written this in a very C-like style -- I would have defined a type (class) for Date, which would have month and day members. Then the logic for whether month lengths are valid can be encapsulated properly.

You could also encapsulate the read-from-stream code using an iostreams extractor.


Shifting the values before xor:ing them is somewhat better than the worst thinkable ways of combining the hash codes, but it's not very good. You will easily get combinations that cancel each other out, so you get hash codes with a distribution heavily skewed towards zero.

Multiplying values by a prime number on the other hand gives a pretty good distribution. Back in the day it was actually used to produce random numbers, partly because of how it spreads the values reasonably even over the number range.

A method that would give an even better distribution would be to use an advanced hashing algorithm like MD5 or CRC32, but the drawback would be that they are a lot slower. You would lose much of the advantage of using a hash code in the first place.

All in all, multiplying by a prime number gives a very good distribution in relation to the processing time needed. It's a compromise well suited for the GetHashCode method.


Your sorting logic is dependent upon the specific type.

"Separate your data representation from logic." you must take advantage of the generic to reuse the same component to sort any kind of object. In case of class you can specify comparer to sort the values.

Naming convention should be followed. i and j does not make sense and in c# standard method naming convetion should Pascal case , should not start with lowercase.

Rest logic looks good.

public static T[] PerformInsertionSort<T>(T[] inputarray, Comparer<T> comparer=null)
    {
        var equalityComparer = comparer ?? Comparer<T>.Default;
        for (var counter = 0; counter < inputarray.Length - 1; counter++)
        {
            var index = counter + 1;
            while (index > 0)
            {
                if(equalityComparer.Compare(inputarray[index - 1],inputarray[index])>0)
                {
                    var temp = inputarray[index - 1];
                    inputarray[index - 1] = inputarray[index];
                    inputarray[index] = temp;
                }
                index--;
            }
        }
        return inputarray;
    }


How to break this curse by a pure functional recursive function?

What about something like this (Please excuse my style/form - As with the other poster, I'm not very familiar with coding in Scala either):

def GetACycle(start: String, maps: Map[String, List[String]]): List[String] = {

//entry function
def explore(node: String): List[String] = {
    explore_r(node, List(), List())
}

//main recursive
def explore_r(node: String, visited: List[String], path: List[String]): List[String] = {
    println(node)
    if (!maps.contains(node)) return Nil
    if (visited.contains(node)) return path++List(node)
    val branches = maps(node)
    for (nextnode <- branches){
        val loop = explore_r(nextnode, visited++List(node), path++List(node))
        if (loop != Nil) return loop
    }
    Nil
}
explore(start)
}