General Design

The pattern foreach...puts... means that each iteration performs IO. Because IO is slow and blocks writing the results of each multiplication to an output array and then batching the IO by writing the output array all at once is likely to improve performance.

Algorithm

From a pure algorithmic standpoint, using modular powers may significantly reduce computation. This website provides this example:

Let us compute 1143 (mod 13). As we saw before we start with squaring this number:

112 (mod 13) = 121 (mod 13) = 4 (mod 13)

114 (mod 13) = (112)2 (mod 13) = 42 (mod 13) = 16 (mod 13) = 3 (mod 13)

118 (mod 13) = (114)2 (mod 13) = 32 (mod 13) = 9 (mod 13)

1116 (mod 13) = (118)2 (mod 13) = 92 (mod 13) = 81 (mod 13) = 3 (mod 13)

1132 (mod 13) = (1116)2 (mod 13) = 32 (mod 13) =  9 (mod 13)

Putting this together (remember that 43 = 32 + 8 + 2 +1), we get

 1143 (mod 13) = 11 * 4 * 9 * 9 (mod 13)

Now we do our usual modular multiplication:
11 * 4 * 9 * 9 (mod 13) = 44 * 81 (mod 13) = 5 * 3 (mod 13) = 2 (mod 13).

When tackling a numeric problem and throughput matters, a good place to start is with assuming that the fundamental problem has already been solved and attempting to reduce the specific problem to an existing numeric algorithm. It is hard to embody performant mathematics into code without first knowing what is performant.


Always authenticate the user before you take any restricted action.

In login.php you have:

session_start();
if(!empty($_SESSION['username'])) {
header('location:plan.php');
}

This code has 2 vulnerabilities I can think of:

It assumes that the existence of username in the session is proof of authenticity. If your user doesn't log out, anyone who uses his browser much later to come to your site will be admitted; likewise anyone who logs HTTP requests and later looks at the log will find the session cookie and can impersonate the user. To fix, store a valid_until date in the session when the user logs in.  Then when you check for credentials, you only admit the user if the login validity has not expired.
Your site is vulnerable to Cross-Site Request Forgery (CSRF). Suppose your logged-in user visits my website where I have something like:

.

<--! Make user send request to your site without knowing -->
<img src="http://yoursite.com/plan.php?do=evil">

Because browsers send cookies automatically with every request, the user's session cookie will be sent to plan.php when the browser tries to load the image, and your script will treat the request as legitimate, therefore it will act on ?do=evil. To fix, set a token in your response headers when the user logs in, and expect the same token back from the request headers from legitimate requests.

The two points above lead to a modification of login.php. When the user logs in, you now do something like:

$_SESSION['username'] = $user;
$_SESSION['valid_until'] = time() + 60*60; //1hr from now
$_SESSION['csrf_token'] = 'long_random_string'; //research how to build this
header("X-CSRF: $_SESSION[csrf_token]");
header('location:plan.php');

When your user comes to my evil site and I try to connect to plan.php, the browser will still send the session cookie but it will not send the CSRF token, so before you grant access you would check for it:

session_start();
$logged_in = false;
if(isset($_SESSION['username'])){
    if(!$_SESSION['valid_until'] >= time()) $logged_in = false;
    $request_headers = apache_request_headers();
    $csrf = isset($request_headers["X-CSRF"])? $request_headers["X-CSRF"] : null;
    if($_SESSION['csrf_token']!==$csrf) $logged_in = false;
}
if($logged_in){/*give access*/}
else{/*block access*/}

By the way, this logic should be moved to a function that returns TRUE if the user is logged in, false otherwise. You can extend it with further checks. For instance you could record the IP address to which the session was granted, and if it doesn't match the IP of the request, deny access (to protect against an attacker stealing the session and CSRF token and trying to re-use it from another location).

In login.php you have:

$user = $_POST['username'];
$pass = $_POST['password'];
...
$query = $conn->prepare("SELECT username, password FROM users WHERE
username=? AND password=? ");
$query->execute(array($user,$pass));

It's great that you use prepared statements to prevent SQL Injection, but this code is evidence that you're storing the passwords in clear text, without hashing. This means that if your database gets stolen, the thief will know your users' credentials, and can use them to impersonate the users on other services. It also means that anyone with access to the database can do the same thing. Instead, when a user registers, hash the password before saving it.

$password = password_hash($_POST['password'],PASSWORD_DEFAULT);

Then when a user logs in, you verify the submitted password against the hashed password. Do something like:

$query = $conn->prepare("SELECT username, password FROM users WHERE username=?");
... // <-execute query and capture password in $db_pass

if($query->rowCount() > 0 && password_verify($_POST['password'],$db_pass)){
    //credentials are correct

}else{/*user unknown or password incorrect*/}


A vector is usually the best data structure to use unless you have a compelling reason to use something else.  Since you know how many buckets you need, one slight improvement you can make to your buckets is to use an array of vectors, rather than a vector of vectors:

std::array<std::vector<int>, 10> buckets;

This will create 10 empty vectors on the stack (without dynamically allocating those 10).

To find the largest element in an unsorted container requires looking at every element in the container.  The only way to improve on that is to change your algorithm so that it does not need to know what the maximum element is; more on that below.

There are several issues with your sort.  In its current form, it does not handle the trivial case of an empty arr as your scan for a maximum element will dereference the end iterator which is not allowed.  Nor does it does it handle negative numbers.  The % operator can return negative numbers if the numerator is negative.  This will result in an out-of-bounds array element access.  There will also be problems with really large numbers (greater than std::numeric_limits<int>::max() / 10).

One way to handle negative numbers is to make an initial pass where you split the array to sort into two groups, one with negative numbers and the other with non-negative numbers.  Then you can radix sort each group, taking care when doing the negative numbers to keep the intermediate results properly signed.

Failing that, how can you determine when to end your loop if you don't know what the maximum element is?  You can keep track as you put things into buckets.  When the num / radix calculation is 0, that element will always be placed in the first (0) bucket for the rest of the sort.  There may be a larger element earlier in the bucket (think of sorting {203, 3}) so it might still move.  But once all elements have that term 0 then you can stop sorting.

When moving the elements out of the buckets back into the array, you can use the standard algorithms rather than using your nested for loops.  The buckets[i].size() will potentially be calculated every iteration.  You can use std::copy to transfer the elements:

auto k = arr.begin();
for (auto &b: buckets)
    k = std::copy(b.begin(), b.end(), k);

You should pass the parameter to print_arr as a const &  (print_arr(const std::vector<int> &arr)).


Using a table here is the right choice, however I would put the total into a <tfoot> group where you can address its formatting needs specifically. In addition do use colspan="2" to collapse columns in the total, as well.


Problems

First of all, your current implementation is not truly in-place, since the slice operation creates a new list of that size, which breaches the required max constant extra space usage.

In addition you perform double work in the index_of_smallest_element when you first find the value you want, and then have to run through the entire list again to find the index (the index call has linear time cost)

Advise

When working in-place you usually have to work with indexes or pointers, and this is also such a case. Most of the work can be put into 3 categories, index work, swapping work, and control flow, if you are doing work outside of those you should think through an extra time on whether you are off in a problematic direction.

This means that you should manually keep track of relevant indexes, and when calling functions the way to work on a subset is to pass the indexes describing this to it.

Solution

there are 2 main changes to be done, both connected to index_of_smallest_element. We first change thats implementation to the following:

def index_of_smallest_element(some_list, start=0):
    smallest = some_list[start]
    for i in range(start+1, len(some_list)):
       value = some_list[I]
       if value < smallest:
           smallest = value
           start = i
    return start

With this it becomes easy to write the naive (and really bad) sorting in-place:

def naive_sort_inplace(some_list, out=None):
    def exchange(some_list,x,y):
        some_list[x],some_list[y]=some_list[y],some_list[x]

    for i in range(0,len(some_list)):
        j = index_of_smallest_element(remaining_list, i)
        if out is not None:
            out('i=',i,'j=',j,'list=',some_list)
        exchange(some_list,i,j)
    return some_list

I am not quite sure why you want to do all the printing, but I assume it is for testing or proving correctness. For reuse I have changed it so it by default does not print, but if you pass in print (or some other output function such as open(filename,'w').write) then it write those log updates to that output function.


There's a few general code hygiene things that I'll look at first, and then I'll comment on the algorithm design.

First, const should mean constant. I know that in Javascript you don't get in trouble for changing the contents of a const array but it's still confusing to use it with a variable whose job is to change. const arr I like but const resultArray I don't.

Second, although I appreciate that these practice challenges don't always give a huge amount of context to inform your purpose, it's important to think about variable names. In particular, arr is a very vague name at the best of times, and a moderately misinforming one in this context. I'd go for something like "instruction".

Third, three if statements checking the same expression for fixed values just screams "use a switch statement". Efficiency questions notwithstanding, switch will immediately clue anyone reading the code into there being one value to check against several options. (Whereas with long else if chains we have to focus on each condition because they could be different)

Fourth, avoid this little trick: if(frequencyArray[arr[1]]). Yes, Javascript will silently do all sorts of funky conversions, and this old implicit cast bool seems tame in comparison. But those conversions are hard to read and bug prone. If you want to check first whether it exists and then whether it is positive, check first whether it exists and then whether it is positive.

Fifth, tiny style thing, but consistency is often more important than what decision you come to. So with Javascript, you can leave off semicolons, or you can add them in. Either works. Some people insist one way or the other, and I won't do that. But if you do use them, use them. As is, 4 statements end with semicolons and 3 end without semicolons, with nothing to tell them apart.

As to the algorithm efficiency, you're making good use of the fact that Javascript "arrays" are dictionaries, so you can directly refer to frequencyArray[arr[1]] without having to worry about whether arr[1] being enormous. With that direct value lookup, your cases for 1 and 2 both consist of very quick operations. Case 3 is the one that will take time, even though it looks just as simple as the others. It's the includes function that's killing you. While the other cases just check one value in the array, includes has to check every single value. What you'll want to do is remember your frequency count as you go, taking a bit of extra time in your 1 and 2 cases to update an additional array/dictionary, so that in your 3 case you can just look up that already calculated value and output it.


You cannot really say that it's a good or bad implementation. It depends, but this doesn't look ok to me: class A : public Singleton<A>.
You don't need to inherit from it to use it: Singleton<A>::instance()

If you want to to use it as you wrote: A& s = A::getInstance(); then probably A's ctor/dtor shouldn't be public.


Why don't you read the code into a variable and check if it is in the array of codes? After that fill up an array with the results.

Nearly every time you have a variable with a counter in the name, you should use arrays.

Another optimization is using XMLReader::next() to go directly to the next sibling without reading the child nodes.

You don't need to append the imported node, you need to provide it as a context in the DOMXpath::evaluate() calls anyway.

$codes = ["BAS11", "BAS12", "BAS13", "BAS14"];
$hotels = [];

$dom = new DOMDocument();
$xpath = new DOMXPath($dom);

$reader = new XMLReader();
$reader->open($filename);

// look for the first Hotel element (include descendants)
while ($reader->read() && $reader->localName !== 'Hotel') {
  continue;
}

// while you have an Hotel element
while ($reader->localName === 'Hotel') {
  // no need to append the node to the document, just import it
  $node = $dom->importNode($reader->expand(), true);
  // read the HotelCode
  $code = $xpath->evaluate('normalize-space(./HotelCode)', $node);
  // if it is in the list
  if (in_array($code, $codes)) {
    // read the values
    $hotels[$code] = [
      'name' => $xpath->evaluate('string(./HotelName)', $node),
      'country' => $xpath->evaluate('string(./Country)', $node),
      //...
    ];
  }
  // move directly to the next Hotel sibling
  $reader->next('Hotel');
}

var_dump($hotels);


Compute histrogram bins for a large data.frame fast

Within the algorithm you post you can take advantage of a few features:

if(bins[j]<=convertedDates[i]&&convertedDates[i]<bins[j+1]) - as you check the bins in order there is no need to check that the previous bin.

As explanation say if j is 5 then you check bins[5]<=convertedDates[i]&&convertedDates[i]<bins[6]
But in the next step j is 6 and you check. bins[6]<=convertedDates[i]&&convertedDates[i]<bins[7]

So you twice compare with bins[6] - if you think about it you only reach j=6 if bins[6]<=convertedDates[i]. So no need to check that again.

if you would sort the convertedDates before the comparison you can use that you can start the search of bins by the last found bin - instead of the first.
actually there is no need to loop over all bins - instead if you calculate (convertedDates - absStart) %/% input$binning it should tell you exactly which bin the date belongs.
it may also help slightly if you preallocate the output lists as shown here.

It might also help to read the source code of the hist function and see what "tricks" they use there.


Backbone view that "starts" the application

You should shorten this up

if (pub_req) {
    Page.flip('splash');
} else if (!token) {
    Page.flip('splash');
} else {
    this.loadViews(token);
}

by merging the first two if statements, like this

if (pub_req || !token) {
    Page.flip('splash');
} else {
    this.loadViews(token);
}

This evaluates in exactly the same order as your code did, but it is shorter.

// View like objects - inject DOM elements needed
var BodyInstance = new Body(document.body);
var ErrorHandlerInstance = new ErrorHandler(document.body);
var TitleAjaxInstance = new TitleAjax($A.el("#timer"));

You have declared these variables but then you don't use any of them, anywhere in the code that you have posted, I can only assume that you don't need these and that you should remove the dead code laying around in your code.


Throw an exception to control the flow of code execution

I would say that this isn't controlling the flow of your application.  This is handling an exceptional circumstance (i.e., failure of your code to perform what as it's meant to), which is what Exceptions are meant to accommodate.

The recommendation is more for circumstances like this:

public boolean itemExists(List<MyObject> list, MyObject object) {
    try {
        for(MyObject thisOne : list) {
            if(thisOne.getAttribute() == object.getAttribute()) {
                throw new Exception("found it");
            }
        }
    }
    catch(Exception e) {
        if(e.getMessage().equals("found it")) {
            return true;
        }
        throw e;
    }
    return false;
}

This controls the flow of the program based on normal execution.  It should be pretty easy to see why this isn't ideal, simply for code readability, not considering aspects like performance, style, and best practices.

What you have in the above code is fine.  Throwing Exceptions for errors is what they're for.  If you're throwing Exception simply to break out of loops or functions or are using them during the "intended" execution of your code, that's when you're going down the wrong path.


Animating the opacity of certain page elements

You have written a simple plugin as it is (see:http://learn.jquery.com/plugins/basic-plugin-creation/).

Firstly I don't think I'd put the document ready stuff inside the plugin. Secondly you should remember that jQuery objects are always based on an array (non matched selectors being a zero length array), so you can always use and return the .each function. As a caveat to that, if you are performing the same task on all elements in the jQuery object (and there isn't data bound to them or any calculations that you need to do on a per object basis) you do not need to use .each.

(function( $ ) {

    $.fn.animateFadin= function(amount) {

        return this.each(function() {
             //this is now an individual element you can manipulate
             this.delay(amount).animate({
                 opacity: 1
                 }, 700);
        });

    };

}( jQuery ));

Or in the simple case:

(function( $ ) {

    $.fn.animateFadin= function(amount) {

        return this.delay(amount).animate({
                 opacity: 1
                 }, 700);
    };

}( jQuery ));

You can now call $('#zone-menu-wrapper').animateFadin(500);

If you understand this then you should be able to use the `.each variant to achieve the delays in a marginally more tidy fashion.  What you might want to think about adding though is a callback to the animate function if what you hope to achieve is one element animating after the other.

To do that you would not use each but a simple recursion. Pseudo-code without error/bounds checking:

function chain(this, them) {
    If (!this) return;

    nextThis = them.pop();

    this.delay(whatever).animate({...}, 100, function() {
            chain(nextThis, them);
    });
}

Call this from within the body of animateFadin with the head and [rest] of the jQuery object's object array. What would be nice is to write a plugin to which you pass a function (the action, in your case delay then animate) so that this is reusable behavior. Maybe it already exists?

All code untested and written on my phone, which was harder than I thought! Good luck.


def class_cancelled(expected, arrival_times):
    ....
    return actual >= expected

print "NO" if class_cancelled(K, A) else "YES"

class_cancelled is a misnomer. It in fact computes a class_not_cancelled condition: class should be cancelled when actual < expected. Also the problem asks to print "Yes" when the class gets cancelled. Funny how two wrongs make it right.


I'm not completely sure what are you trying to accomplish, but I think this is bad and very confusing code.

You seem to be using the interface IEquatable<T> to mean “T, or a type that has some relation to T”. That's not what it's meant for at all!

Also, the point of interfaces is to be able to use different types in the same way. For example, if I have a IEnumerable<string>, I know I can iterate over it using a foreach and process the strings it gives me.

But that does not apply to your interface. I have to know whether I have have Simpleton<T> (I have to pass T to it) or ArrayExpectant<T> (I have to pass ArrayWrapper<T> to it).

Because of this, I would suggest you to drop the interface completely, I don't see any benefit of having it.


How can I have jQuery code further optimized?

I have few hints save jQuery in $ variable:
(function($) {
   // your code
})(jQuery);

$ is common for jQuery and it's easier to read because it shorter.
Second and obvious is using loop to run calls in:
    if (selectedValues.length > 0) {
       selectedValues.forEach(function(value, i) {
          var num = i + 1;
          $(`input[name=gift_${num}]`).val(value);
       });
    }

and further improvement is to move that into a function. So instead of comment:
// Set hidden input with the chosen gift.

you can have:
setHiddenInputs(selectedValues);

function setHiddenInputs(values) {
    values.forEach(function(value, i) {
        var num = i + 1;
        $(`input[name=gift_${num}]`).val(value);
    });
}

I would also merge those two lines:
var selectedValues = [];
selectedValues = $('#ff_124_multi_select_gifts').val();

you assign array for no reason and then replace it with output of val() call:
var selectedValues = $('#ff_124_multi_select_gifts').val();

also if selectedValues are gifts then you can use:
var selectedGifts = $('#ff_124_multi_select_gifts').val();
setHiddenInputs(selectedGifts);

which is exactly what your comment try to say


Split list of integers at certain value efficiently

I would use a generator:

def splitz(seq, smallest):
    group = []
    for num in seq:
        if num != smallest:
            group.append(num)
        elif group:
            yield group
            group = []

numbers = [1, 3, 3, 5, 1, 5, 5, 5, 1, 6, 5, 4, 1]
min_val = min(numbers)
print(list(splitz(numbers, min_val)))

It prints:

[[3, 3, 5], [5, 5, 5], [6, 5, 4]]

You could time it:

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("splitz(numbers, min_val)", setup="from __main__ import splitz, numbers, min_val", number=1000000))

On my machine, it is:

1.0186186955428558

Note the default number of times through the loop is one million.


The easiest way to improve this function is to use the C standard library. As it is, it's difficult to read; you can't understand what it does at a glance. And it's unnecessary difficult, because most of the building blocks are already available for free in <string.h>:

find a string in another string with strstr;
find a character in a string with strchr;
copy a string with strcpy or a substring with memcpy

Once you have simplified your code, you'll have more brain space to care for not so negligeable things such as testing memory allocations:

void httpString(char **dest, char *input, const char *find) {
    char* found = strstr(input, find);
    if (!found) {
        printf("find not found!");
        return;
    }
    char* assign = found + strlen(find);
    if (*assign != '=') {
        printf("ill-formed!");
        return;
    }
    char* value = assign + 1;
    char* end_value = strchr(value, '&');
    if (!end_value) end_value = strchr(value, 0);
    int length = end_value - value;

    *dest = (char*) malloc(length + 1);
    if (!*dest) {
        printf("Not enough memory");
        return;
    }
    memcpy(*dest, value, length);
    (*dest)[length] = 0;
}


There are no unintended consequences, but it is a little unusual and may surprise the reader.  However, it is a small surprise.

It usually communicates intent well to use subject to declare the subject, and before to setup preconditions unrelated to the subject.  For preconditions that involve the subject, those are often better in a before block as well, but it's not too surprising to find them in the subject block.

So, instead of this:

subject {
  @ability.can :manage, Station
  render
  rendered
}

this:

before(:each) do
  @ability.can :manage, Station
  render
end

subject {rendered}

I used do...end for the multi line block and {} for the single line block; this is a common (although not ubiquitous) practice.


If you make restriction only for ForwardIterators you can't call c.end()-1 from your question. It would be probably difficult to sort the whole container.


DFS should keep track of all the nodes visited. Not the node.

The node only properties is it self, and it's children.

Check this amazing implementation:

graph = {'A': set(['B', 'C']),
         'B': set(['A', 'D', 'E']),
         'C': set(['A', 'F']),
         'D': set(['B']),
         'E': set(['B', 'F']),
         'F': set(['C', 'E'])}

def dfs(graph, start):
    visited, stack = set(), [start]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited

dfs(graph, 'A') # {'E', 'D', 'F', 'A', 'C', 'B'}

As you can see DFS is called just once and it keeps track of visted nodes all the way, it will use pop(-1) so it will Depth-search, you could either change to pop(0), so it would Breadth-First Search. It's the same concept, the only difference is which node is visited in which order.

Your implementation will have some problems if the graph is too deep, because it could raise a Maximum recursion depth exceeded.


The great input from @hjpotter92 gets you 99% of the way there. The only additional comment I have is about this:
while num != random_num * random_num:

Exact comparison of floating-point numbers is problematic. You're going to want to pick some (very small) number, usually called epsilon, below which the error is insignificant and call that "close enough".
Read https://docs.python.org/3/library/math.html#math.isclose for more details.


Usage of static block vs. direct static variable initialization

In such scenario it only obstructs code readability. No benefits.
You should use static block only if static field initialization is not enough (e.g. you should call several methods, or this methods throw checked exceptions).

Just created 2 sample classes:

public class Static {
    public static String s = "qwe";
}

public class StaticBlock {
    public static String s;
    static {
        s = "qwe";
    }
}

And using javap -c we can see bytecodes of this classes:

Compiled from "Static.java"
public class Static {
  public static java.lang.String s;

  public Static();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  static {};
    Code:
       0: ldc           #2                  // String qwe
       2: putstatic     #3                  // Field s:Ljava/lang/String;
       5: return
}

Compiled from "StaticBlock.java"
public class StaticBlock {
  public static java.lang.String s;

  public StaticBlock();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  static {};
    Code:
       0: ldc           #2                  // String qwe
       2: putstatic     #3                  // Field s:Ljava/lang/String;
       5: return
}

As you can see, bytecodes are identical :)

UPD: Its getting more interesting! If we add final modifier to our static field, bytecodes will be different.

public class Static {
    public static final String s = "qwe";
}

public class StaticBlock {
    public static final String s;
    static {
        s = "qwe";
    }
}

We will have:

Compiled from "Static.java"
public class Static {
  public static final java.lang.String s;

  public Static();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return
}

Compiled from "StaticBlock.java"
public class StaticBlock {
  public static final java.lang.String s;

  public StaticBlock();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  static {};
    Code:
       0: ldc           #2                  // String qwe
       2: putstatic     #3                  // Field s:Ljava/lang/String;
       5: return
}

I found a little bit of explanation in this question.


Reducing cyclomatic complexity in a simple string concatenation

What about this:

var getAddressTooltip = function (address) {

    var tooltip = '';

    if (address.MasterAddress &&
        address.MasterAddress.Id) {
        tooltip += '[' + address.MasterAddress.Id + '] ';
    }
    if (address.PurchasingContact &&
        address.PurchasingContact.Name) {
        tooltip += $.trim(address.PurchasingContact.Name) + ',\n';
    }
    if (address.ShipTo) {
        tooltip += $.trim(address.ShipTo) + ',\n';
    }
    if (address.Line1) {
        tooltip += $.trim(address.Line1) + ',\n';
    }
    if (address.Line2) {
        tooltip += $.trim(address.Line2) + ',\n';
    }
    if (address.City) {
        tooltip += $.trim(address.City) + ',\n';
    }
    if (address.State &&
        address.State.Name) {
        tooltip += $.trim(address.State.Name) + ',\n';
    }
    if (address.ZIP) {
        tooltip += $.trim(address.ZIP) + ',\n';
    }

    //replace trailing comma / line break
    if (tooltip.substr(tooltip.length - 2, 2) === ',\n') {
        tooltip = tooltip.substr(0, tooltip.length - 2);
    }

return tooltip; };

Since JavaScript considers null, undefined, and the empty string to be falsy, the value of the variable itself can be used to substitute for all the tests. Further, as any object is automatically truthy, the tests like address.PurchasingContract will be true if the object is there.

References:

MDN: A Reintroduction to JavaScript (just the first thing I came across)


Implementation similar to boost::optional for modelling function failure

Let's go over it bit-by-bit:

You should sprinkle around quite a lot of constexpr and noexcept-markers.
If at least one instantiation of a template is potentially constexpr, marking the template thus is not an error. Not marking it means none is.
union{T value;}; better shows the intent and is simpler than alignas(T) char storage[sizeof(T)];.
Do not values with byte-for-byte unless they are trivial types. Doing so is simply wrong.
The move-ctor should move, not swap. That might be far less expensive anyway.
Your base variant should gain a specialization for trivially copyable types.
Your base-variant should have a variadic-template ctor for constructing the value directly.
Your references-variant does not need a separate valid-flag: *NULL is not valid, thus a null pointer serves adequately.
Only include the minimal headers you need in your include-file.
Do not use an unnamed namespace, or every translation-unit will have its own unique template (which is different from all the others).

As a side-note, boost::optional should serve for the case you describe.


Print all path from root to leaves - code review request

It looks good overall.

I see you have taken my previous suggestion to rearrange the TreeNode constructor arguments.  Now you have to readjust your calling convention accordingly.

Your create() method acts like a constructor, so you should just make it a constructor.  It desperately needs a JavaDoc comment explaining how the input array is to be interpreted.

In create(), I would not bother to check for arr == null.  You'll get a NullPointerException anyway when you fetch arr[0].  It's only worth the explicit check if such a check would make debugging substantially easier, i.e. when an improper null would get stored or propagated but not dereferenced until much later.  Even then, I'd throw an IllegalArgumentException rather than NullPointerException to emphasize that the caller is at fault.

In doPrint(), path.remove(path.size() - 1) should be just path.removeLast().


The largest odd number (follow-up code using nested functions)

Since your first attempt, you are indeed showing progress, and it's kind of fun to watch. When entering into the realm of using functions the ball game changes a little, and you need to start thinking of segregation of duties and possible whether you can reuse one or more of the functions.

Some more or less general cases, addressed toward your code:

Make functions general – Allow for the input function to enter an arbitrary number of integers, i.e. rename/repurpose the get_ten_ints() function
Be wary of global variables – Do not use global variables if they can be avoided. This also applies to using functions and variables defined within the function (i.e. the numbered_entries variable)
Try avoiding magic numbers – In your code the 10 stands out as kind of a magic number, which do affect the running of your code, but where does it come from? If you want to have such numbers, they are better declared as constants in top of the file (or function)
Don't use nested functions, unless there is a real good reason – To me, I don't see why the get_ten_ints() is a nested function. I would propagate it to the top level of your code
Start documenting your code – A common practice is to use docstrings to document your function, so that it is clearer when you return to your code what it was supposed to do
Separate presentation from business logic – Decide if a function is supposed to present stuff or return stuff. Your original code had find_largest_odd() both find this number, and present it. In such a small functions that could be OK, but it's better to make it a clean function returning the number, and then letting the caller decide what it wants to do with the number, i.e. print it or use it for other calculations
Introducing main() function – The larger the code base the more interesting is it to introduce a pattern which reveals a common entry point to your code. The __name__ == '__main__' test ensures that if you run python on your file you get the execution defined, but still allowing for the file to be imported as a module giving access to your functions
Normalize your print statements – I'm not sure according to which standard, but it's quite normal (both in python 2.x and 3.y) to use constructs like print("my text: {}".format(some_variable))

Applying all of these principles you could end up with something like:

def get_ints(number_of_ints):
    """Read from input exactly number_of_ints numbers, and verify that they
       actually are ints. Return the list of these numbers"""
    numbers_entered = []
    while len(numbers_entered) < number_of_ints:
        try:
            number = int(raw_input("Enter an integer: "))
            numbers_entered.append(number)
        except ValueError:
            print("That was not an integer!")

    return numbers_entered

def find_largest_odd(numbers):
    """From a given list, find the largest odd number. Return None if no odd
       number is found."""
    try:
        largest_odd_number = max(item for item in numbers if item % 2)
        return largest_odd_number
    except ValueError:
        return None

def main():
    """Read 10 integers into a list, and find the largest odd number"""
    my_numbers = get_ints(10)
    the_number = find_largest_odd(my_numbers)
    if the_number != None:
        print("Largest odd number in list: {}".format(the_number))
    else:
        print("No odd number in list")

if __name__ == '__main__':
    main()


Do I need to close my FileOutputStreams?

Yes, you do.

While the garbage collector does close your FileOutputStream (by calling finalize), it is not a good idea to rely on it because it runs unpredictably.

This means that if you do not close your streams explicitly, you may run into a limit on the number of simultaneously open files or into inability to open a file until you close the previous stream to it (on Windows) or into unpredictable file content if you open several streams to the same file (on Unix).


Replacing an application service class with multiple command handlers

What's wrong

First of all read the tutorial again, you missed his whole point.

You cannot use decorators with your current design. Why?

new AssignJobCommandHandler(
        new AssignJobCommand(jobId, userId)
).handle();

You use new therefore you cannot use a decorated version. You have a AssignJobCommandHandler and it is not a TransactionCommandHandlerDecorator.
You pass the command to the constructor. Constructors are not polymorphic. You cannot customize how a command is handle if you pass it to a constructor, (or equivalently a static method)
You don't pass the dependencies in the CommandHandlers, so you would have to use the Service Locator, Evil Singleton anti-patterns. I'm guessing it doesn't currently work at all.

Getters are not command handlers. A request is either a query (GET, etc) or a command (POST, etc), never both. Make sure your service methods follow CQS. Don't do this:

return new GetJobListCommandHandler(
                new GetJobListCommand()
        ).handle();

What to do

Depend on abstractions.

Create said the interface:

public interface CommandHandler<TCommand> {
    void handle(TCommand command);
}

and use it like this.

@Path("/app/jobs")
public class AssignJobController {

    @Autowired
    CommandHandler<AssignJobCommand> handler;

    @PUT
    @Path("{job_id}/assigned_to/{user_id}")
    public Response assignTo(
            @PathParam("job_id") @NotNull String jobId,
            @PathParam("user_id") @NotNull String userId
            ) throws JobException {

        handler.handle(new AssignJobCommand(jobId, userId));

        return Response.status(Response.Status.CREATED).build();
    }
}

You can use decorators like this, for example:

@Configuration
public class Config {
    @Autowired
    JobDAO jobDAO;

    @Bean
    public CommandHandler<AssignJobCommand> assignJobCommandHandler() {
        // pass in the dependencies as shown in the tutorial
        // I use a DAO instead of a UnitOfWork, as they are more common with Spring applications.
        CommandHandler<AssignJobCommand> handler = new AssignJobCommandHandler(jobDAO);

        // you can use multiple decorators
        // this kind of decorators do not need to use reflection, proxies, bytecode manipulation etc magic. They are plain-old java objects.
        handler = new TransactionCommandHandlerDecorator(handler);
        handler = new DeadlockRetryCommandHandlerDecorator(handler);
        ...
        ...
        return handler;
    }
}

Testing

Now that we pass the dependencies in the handlers, we can test them.

One way to do it is using a mocking framework, there are others.

Test may look like this, for example:

@RunWith(MockitoJUnitRunner.class)
public class AssignJobCommandHandlerTest {

    @Mock
    JobDAO jobDAO;

    AssignJobCommandHandler handler;

    @Before
    public void setUp() {
        handler = AssignJobCommandHandler(jobDAO);
    }

    @Test
    public void assignsAJobToAUser() {
        long jobId = 123L;
        long userId = 456L;

        Job job = new Job();

        when(jobDAO.getJob(jobId)).thenReturn(job);

        handler.handle(new AssignJobCommand(jobId, userId));

        assertThat(job.getAssignedUserId(), is(userId));
    }
}


Implementation of Sieve of Eratosthenes algorithm

What is the best way of storing a list of numbers?

Not doing them at all? It's both the fastest and the most memory-efficient solution.
And it applies perfectly to your use case as numberList[i] == i+2 always holds.

Is there a more efficent way of generating a list of numbers, rather than just using a for loop.

There are many ways to speed it up, but there's actually always such a loop. One trivial optimization is to ignore even numbers.

How efficent are arrays?

It's the fastest storage when you access data either sequentially or by index. So concerning isPrime, it's the best what you can do (unless you want to trade speed for memory, then look at BitSet).
Concerning numberList, it'd be much better to drop it. Computing i+2 is surely way faster than reading numberList[i].

Now I have a question: How can you code be used? The answer is that

not without user interaction
not without reading the console
not for task like this one

How can it be improved: Separation of concerns. Luckily it's very easy to do in your case: Just extract methods (the IDE can do it for you):

readInput
sieve
printResult

Review
    int maxPrime;

Note that it's (usually) no prime at all.
    int [] numberList = new int [(maxPrime - 1)];
    boolean [] isPrime = new boolean [(maxPrime - 1)];
    for(int i = 0; i < (maxPrime - 1); i++) {
        numberList[i] = (i + 2);
        isPrime[i] = true;
    }

Drop numberList, use Arrays.fill(isPrime, true).
    int tempAns;

You don't need it here.
        int temp = numberList[j];
        if(isPrime[j] == true) {
            temp = numberList[j];
        }

You mean, "in case of a prime, we really want that temp has the value already assigned and assign it once more, just in case".
        for(int k = j; k < (numberList.length - 1); k++) {

No need for parentheses here.
                for(int z = 0; z < numberList.length; z++) {
                    if(numberList[z] == tempAns) {
                        isPrime[z] = false;
                    }
                }

This makes your code very slow. You could do (possibly after some bounds checks)
 isPrime[tempAns-2] == false;

and save yourself a loop.
But actually you should simplify it so that you do just
 isPrime[tempAns] == false;

s saving two elements of a potentially huge array makes no sense. Btw., tempAns is a really bad name (even worse thantemp). Call it product.
        if (isPrime[n] == true) {

Don't do it. All the following expressions are equivalent:

isPrime[n]
isPrime[n] == true
(isPrime[n] == true) == true
((isPrime[n] == true) == true) == true
(((isPrime[n] == true) == true) == true) == true

Just use the simplest one.


Key-scanning macro in NASM Win16 against DOSBOX (Intel 8086)

It's fine to write this scan macro for educational purposes, but I think that considering its length a subroutine would have been more appropriate. The macro's bytes are inserted everywhere the macro is invoked. That adds up! Having that many duplicated bytes in a program is a waste of space.

Some observations

push    bp
mov     ah, 0Eh    ; print the valid character
int     10h
push    bp
stosb              ; write the character to the string

That second push bp was probably meant to be pop bp, wasn't it?
But why would you want to preserve the BP register when the BIOS.Teletype function doesn't even touch it.

User @ecm commented about the BIOS Teletype function: BUG: If the write causes the screen to scroll, BP is destroyed by BIOSes for which AH=06h destroys BP
If this is the bug that made you decide to preserve the BP register, then I would say that preserving BP is still not the right thing to do. Because your code only supports non wrapped backspacing, it is reasonable to assume that no scrolling will occur. If scrolling were to happen then the backspacing user could get confused! Furthermore it's easy to make sure that scrolling can't occur simply by setting the cursor at the left edge of the screen at the start.

For maximum safety, I would write the char from AL in the string before teletyping it. On some implementations of BIOS/DOS etc. , I've seen the AX register modified even when the official documentation told it was preserved.

stosb              ; write the character to the string
mov     bh, 0      ; DisplayPage
mov     ah, 0Eh    ; print the valid character
int     10h

I've added the required BIOS parameter for the DisplayPage. In all of your posts you keep ignoring this parameter. I'm wondering if you have any documentation about these BIOS video functions that possitively states that there are no selectable display pages.

%%bspace:
    cmp     cx, 0
    je      %%get      ; ignore starting bspace

The cmp cx, 0 instruction has a 3-byte encoding, but the test cx, cx instruction (that does the same) has but a 2-byte encoding. In any macro you will want to write the shortest code.

%%bspace:
    test    cx, cx
    jz      %%get      ; ignore starting bspace

There's also the jcxz instruction that you could use here. Again shorter but some people will say it is slow. It's up to you to decide if that is of real importance here. Don't forget that the user at the keyboard is much, much slower than any of the lesser instructions that you could choose!

%%bspace:
    jcxz    %%get      ; ignore starting bspace

cmp     cx, 80     ; ensure the buffer isn't exceeded
jae     near %%done
jmp     near %%get ; room for more

The code becomes a little more efficient if you write the jump that is more likely first. The buffer will nearly never fill up completely, and so the jump to %%done will almost never happen.

cmp     cx, 80     ; ensure the buffer isn't exceeded
jb      near %%get ; room for more
jmp     near %%done

A quick rewrite

; %1 = string to write into
%macro scan 1
    pushaw
    mov     di, %1     ; prep for stosb
    xor     cx, cx
    mov     bh, 0      ; DisplayPage
%%get:
    getc
    cmp     al, 13
    je      %%done     ; enter pressed
    cmp     al, 8
    je      %%bspace
    cmp     al, ' '
    jb      %%get      ; ignore most non-printing characters
    cmp     al, '~'
    ja      %%get

    stosb              ; write the character to the string
    mov     ah, 0Eh    ; print the valid character
    int     10h
    inc     cx
    cmp     cx, 80     ; ensure the buffer isn't exceeded
    jb      near %%get ; room for more
    jmp     near %%done
%%bspace:
    jcxz    %%get      ; ignore starting bspace
    mov     ax, 0E08h
    int     10h        ; bspace twice, to clear space
    mov     al, 32
    int     10h
    mov     al, 8
    int     10h
    dec     di         ; overwrite character position
    dec     cx         ; step back a character
    jmp     %%get

%%done:
    xor     ax, ax
    stosb              ; append null-terminating character (zero)
    newline
    popaw
%endmacro


You have kind of "logic" in your mapping (nickname, fullname and adress). And I assume that this will be the case also for the other data sets you mentioned. That makes generalizing hard. Especially when there is not much in common.

You COULD write a generator were you can configurate for each attribute the mapping strategy, but this would take more time then write the mapping of those 20-30 values directly.

I personally use in quite some cases classes instead of interfaces and then apply a public static "fromJSON(...)" or in your case "fromHuman(...)" method onto it. Its MORE code to write, but it makes everything explicit. And you are able to ensure that a object (a student) ALWAYS has a proper name. Such things make refactoring later easier. But as i said, the negative part is that you implement more code to gain this safety.

For example in the following code there is only ONE way to create a student. And if the primary identifier of this object (the firstname / lastname combination) is missing then it errors out.

export class Student implements Human {
  readonly first: string;
  readonly last: string;
  state: string;
  nickname?: string;
  fullname: string;
  address: string;

  private constructor(firstname: string, lastname: string{
    if(firstname && lastname){
      throw Error('Students must have a first and a lastname!');
    }
    this.first = firstname;
    this.last = lastname;
  }

  public static fromHuman(human: Human): Student {
    const student: Student = new Student(human.first, human.last);
    student.state= human.state;
    student.nickname = human.nickname | human.first
    // if you are using TSD 3.7 or above you should use the ?? operator
    // ...
  }
}

If some of the values may change, then i would think about NOT storing calculated values (like the adress) but use a GET method. The reason is, IF one of the values used for calculation (e.g. the state) changes, then a stored "adress" would have to get updated manually.

export class Student ...{
   // ...
   public get adress(): string{
      return `${this.first} ${this.last} live a ${this.state}`
    }
 }
}

PRO: Values get updated automaticly
CON: Values have to get recalculated each time. This may be a performance issue, depending on the usage.

At the end (as always) it depends what you want to achieve. If you need a quick way to generate data, then i would personally stick to your way.
If you are using the objects heavily in your application, then i would think about how they are used from the business perspective (which values may not change, which may change often ,...) and treat them as Business Objects. And then guard the objects against misuse. Even if only you are using that code, this may guard you against mistakes and help you understand your code when you have to fix a bug or add a feature a few months later.


Return n largest nonzero entries of an array

The algorithm you described has complexity O(n * m), where m is the size of the input array, since you run a full argmax at every one of the n iterations.
You can achieve the same thing by collecting the indices of the n largest values once, and then set only those indices to 1 in the result array.  For finding of the n largest values, you could use a heap, but Julia makes this easier with partialsortperm:
function nlargest(v, n; rev=true)
    result = falses(size(v))
    result[partialsortperm(v, 1:n; rev=rev)] .= true
    return result
end

This uses a BitArray for storage; if n << m, even a sparse array might pay off.  It should have complexity O(m + n log n), unless I'm misjudging partialsortperm.  Note that sorting algorithms in Julia work ascending by default, so you have to use rev=true to get the equivalent of your code.


Using large amounts of if-else statements for playing card numbers

Convert your constant values to an enum instead, for example:

enum Card {
    ACE_AS_ONE("A", 1),
    TWO("2", 2),
    THREE("3", 3),
    // and so on
    KING("K", 10);

    private final String name;
    private final int value;

    Card(String name, int value) {
        this.name = name;
        this.value = value;
    }

    public static Card decode(String name) {
        for (Card card : Card.values()) {
            if (card.name.equalsIgnoreCase(name)) {
                return card;
            }
        }
        return null;
    }
}

While at it, add some unit tests to verify, for example:

public class CardTest {
    @Test
    public void testDecodeNumeric() {
        assertEquals(Card.TWO, Card.decode("2"));
        assertEquals(Card.THREE, Card.decode("3"));
    }

    @Test
    public void testDecodeLabeled() {
        assertEquals(Card.KING, Card.decode("K"));
    }

    @Test
    public void testNonexistent() {
        assertNull(Card.decode("nonexistent"));
    }

    @Test
    public void testDecodeNull() {
        assertNull(Card.decode(null));
    }
}


How about this one? Representing numbers as object to be able to use the logic for both whole and fraction operations. Also using regexp to check input symbols and length:

function checkNumber() {
  var stringsFromInput = document.getElementById("inputNumber").value.split(/[,\n.]/),
      numbers = [
        {
          name: "whole",
          regexp: /^[0-9]{1,10}$/,
          errorMsg: " number expected to be 10 symbols maximum"
        }, {
          name: "fraction",
          regexp: /^[0-9]{0,5}$/,
          errorMsg: " number expected to be 5 symbols maximum"
        }
      ];
  for (var n in numbers) {
    var name = numbers[n].name,
        value = stringsFromInput[n],
        regexp = numbers[n].regexp,
        msg = numbers[n].errorMsg,
        div = document.getElementById(name + "Div");
        regexp.test(value) ? div.innerHTML = name + " number is OK" : div.innerHTML = name + msg;
  }
}
<form>

    Enter a number
    <input type="string" class="form-control" id="inputNumber" placeholder="123456789.54321">
    <button type="button" onclick="checkNumber()">Check</button>

Status will

appear here

</form>


Since you are only checking all of your fields against null, you could add the field names to an array and then loop through the array.

var isValid = true;
var fields  = ['title', 'description', 'objectives', 'outcome', 'hours'];

for ( var i = 0, n = fields.length; i < n; i++ ) {
    key = fields[i];
    if ( formData[key] == null ) {
        console.log("error on " + key);
        isValid = false;
    } else {
        console.log(key + " is valid");
    }
}


Unless you need some sort of high level interaction with those points, to create 400,000 shapes (which are FrameworkElement, all but lightweight) is a waste of time and resources.

Did you consider to use an image, drawing them inside a WriteableImage and to display the image instead? Check MSDN for DrawingVisual and DrawingContext subjects. I used this method for small multiples composed with really huge heatmaps and it worked like a charm. Simple hittesting (for example to show a tooltip with exact value) is trivial to implement using X-Y coordinates.

You will keep your visual tree almost empty, you won't create few thousands brushes each time (but you can create your color palette once and use it multiple times) and redrawing will be as fast as you want. In most applications you don't need an infinite number of color shades, consider to limit palette to 256 entries and to map values to those discrete values.

You will need to create an image with the proper size but this has a great advantage:

When redrawing is requested then immediately create a very low-res image with few hundred points.
Start a background thread to draw the full-resolution image (using current canvas size).
When image is ready then simply replace the old low-res one.

In this way you can even easily debounce multiple requests caused by resize operations (if you care at all).

Note: to pick one point every N is not a proper decimation method because it doesn't preserve local minimum and maximum; you may (will!) visualize wrong results. Consider using minmax or, only if your type of data allows it, at least an average.


Acquiring indices for anagrams of an input string

You're making an assumption that these strings contain just letters.  If there are spaces, digits, or letters with diacritics, then you'll end up with an ArrayIndexOutOfBoundsException.

isEqualCounts() is just a reimplementation of Arrays.equals(int[], int[]).  If you choose not to use Arrays.equals(), then I suggest starting with assert counts1.length == counts2.length;.

A more robust strategy, which doesn't rely on the assumption that the text is purely alphabetic, would be to check whether each sorted array of characters matches the sorted array of characters of the reference string.

You could optionally add a quick-but-crude check by calculating a "summary" or "fingerprint" of each string that consists of its length and, say, the sum of all its characters.  Any string whose fingerprint is different from the fingerprint of the reference could be immediately rejected.  The strings with matching fingerprints could then be checked more thoroughly.


AngularJS image size validation directive

if (attr.validateHeight != undefined) {
    ...
}

if (attr.validateWidth != undefined) {
    ...
}

The parts != undefined are unnecessary and just add noise to your code; JavaScript automatically checks to see if a conditional is true, or that it is not a false value. And undefined is a false value.

throw 'Invalid operator ' + operator + ' !';

Don't just throw a string as an error: create your own error object. I recommend calling it InvalidOperatorError as the reason why the error would be thrown is if an invalid operator was passed into your function.

Here is what the class would look like:

/*
* An error thrown if an invalid operator
* is passed into a function.
*
* @param(string) -- The error message
*/
function InvalidOperatorError(message) {
    this.name = "InvalidOperatorError";
    this.message = message;
}

Notice how I added documentation to this error? You should add this to your function validateImageSize so you can describe what each argument means and what the return means. Also, so you can describe the purpose of the function.

Now, you can use an instance of this class when you are throwing an error. Here is what that will look like:

throw new InvalidOperatorError('Invalid operator ' + operator + ' !');

See? Now you have a descriptive error.


Replacing specific words in text with words from another list python

Note that the condition if word in words in replacer performs a linear search on words if it's a list, as in the current code. Since this condition is executed for every word in the input, it would be good to optimize it a bit. You could for example pass a set of words instead of a list.

The names first_iter and second_iter are not very meaningful. It would be good to come up with some better names for these.


Just a few smaller issues:

Why expose buildHeap() when every other public method, including the constructors, already leaves you with a perfectly sorted heap?
Why does the add() method contain sorting logic? This would usually be placed in an increment() method.
An increment() method is missing.
Your add() method did not copy the element. Your heap is therefore vulnerable to side effects where any of the elements you have a reference on, did get modified in the outside world. Either warn, watch, encapsulate or make immutable.
Comments? At least your constructors and public methods should be documented, denoting which side effects are to be expected.
There is no interface to get the sorted list back.
The toString() method returns the internal order of the heap. Nice for debugging, but not what you would expect. You would expect it to return elements in lexicographical order.
Please don't use it in production. Your basic MaxHeap has significantly worse runtime characteristics than the default Fibonacci Heap.
There is a getParent() helper, but you have omitted such helpers for getLeft() and getRight(), even though you are using the corresponding expressions multiple times.


Loading in two CSV files and storing them in two separate arrays

I don't know about elegant, but you could load the files in parallel for better performance. To do something when all CSV files are ready you can use promises or just a simple counter.

The example also shows how you can use objects as return value in your arrow functions without the extra { return {...} }.

Example of loading in parallel using the counter method:

const express = require("express");
const parse = require("csv-parser");
const fs = require("fs");

const app = express();

const port = 3000;

var CSVOne = [];
var CSVTwo = [];
var toGo = 2;

fs.createReadStream("public/activity.csv")
  .pipe(parse())
  .on("data", data => CSVOne.push(data))
  .on("end", () => {
    sender = CSVOne.map(d => ({
      email: d.Sender
    }));
    maybeDone();
  });

fs.createReadStream("public/groups.csv")
  .pipe(parse())
  .on("data", dataTwo => CSVTwo.push(dataTwo))
  .on("end", () => {
    one = CSVTwo.map(d => ({
      clinic: d.one
    }));
    maybeDone();
  });

function maybeDone() {
  toGo -= 1;
  if (toGo === 0)
    done();
}

function done() {
  console.log("Both CSV files are ready");
  console.log(CSVOne, CSVTwo);
}

app.listen(port, function() {
  console.log("Server has started");
});


OpenMP parallel for critical section and use of flush

With just one function provided and some return information, it's hard to tell everything about it.  Since this is a member function with "get" in its name (meaning it's an accessor), and only local variables are being modified (no data members), then this should likely be a const function.

int Window_Shift :: get_window_shift() const {}

If you are actually modifying data members somewhere, then disregard this.
The whitespace in the for loop statement is a little inconsistent:

for(unsigned int node_id = 0;node_id< no_of_valid_nodes ;node_id++)

This is how it could look:

for (unsigned int node_id = 0; node_id < no_of_valid_nodes; node_id++)

In a conditional statement, you don't need to explicitly use true or false.  It's also safer to avoid this as it'll prevent a possible mismatch of = and ==.  This will cause bugs if the compiler doesn't warn you about it (although you should have compiler warnings turned up high).

This is the same as == true:

if (someConditional)

This is the same as == false:

if (!someConditional)

INFINITE isn't defined anywhere, so either this is your own definition, or this is supposed to be INFINITY from <cmath>.  You could instead use C++'s alternatives from <limits>.

If you must use int, which is finite, you can use std::numeric_limits::max() to get its maximum value, which is normally 231 -1:

int max = std::numeric_limits<int>::max();

If you can use a floating-point type (float or double), then you can get true infinity by using std::numeric_limits::infinity():

float infinity = std::numeric_limits<float>::infinity();

double infinity = std::numeric_limits<double>::infinity();

More information regarding infinity here.
You could consider defining private() and shared() for the variables, which goes inside of the parallel for directive. You'll also need default(none) so that the compiler will allow you to set this yourself.  This can give you more control over your code, as the compiler would otherwise have to determine what should be private and what should be shared.

  Should atomic be used instead of a critical section?

You may have to test this yourself, but atomic may be faster.  Critical sections, on the other hand, may lead to more serialization, especially if you have one in a loop.  Always try to avoid unnecessary serialization in parallel code. Atomics can also cause this, but usually not as greatly since it doesn't lock an entire code section for all of the threads, unlike a critical section.


Am I handling "spot the missing DLL" right?

As I mentioned in the comments, the code you've posted could very well be doing anything that could potentially throw any exception.

MainWindow window = new MainWindow();

By putting this constructor call outside the try block, any exception thrown in the MainWindow constructor will be unhandled and the program will terminate in a not-so-gracious way. I assume the constructor does nothing special, but your OnStartup override is also making that assumption; I'd move the call inside the try block.

var viewModel = new MainWindowViewModel();

Your usage of var is inconsistent - I'd declare the MainWindow with var as well, but you could also declare the MainWindowViewModel instance with an explicit type; all that matters is consistency.

The fact that the ViewModel's constructor isn't taking any parameters tells me that the MainWindowViewModel class is likely to be tightly coupled with whatever dependencies it might have; the ViewModel could instead be constructor-injected with some service whose sole purpose would be to perform the 3rd-party DLL late binding - if that service has its own dependencies, for example a Log4net logger, it can receive it in its own constructor:

var logger = LogManager.GetLogger(typeof(LateBindingService))
var service = new LateBindingService(logger);
var viewModel = new MainWindowViewModel(service);

That would make the intent of your code much clearer, and would keep the ViewModel class more focused on being a ViewModel.

Then if you want to use an IoC container to automatically resolve and inject dependencies, you'll have absolutely nothing to change!

I like that you are holding a reference to your handler so it can be unregistered, but I find it would be cleaner to just register a private method instead of a delegate:

var view = new MainWindow();

var logger = LogManager.GetLogger(typeof(LateBindingService))
var service = new LateBindingService(logger);
var viewModel = new MainWindowViewModel(service);

viewModel.RequestClose += ViewModel_RequestClose;
view.DataContext = viewModel;
view.Show();

And that would be the whole try block.

The LateBindingService would be responsible for knowing everything there is to know about the 3rd party DLL, and would expose a method to try loading it.

The catch block should catch a much more specific exception type than System.Exception, since you want to show that message box if the late binding fails, not if anything else goes wrong at one point or another in the View's lifetime.

I'd probably have the LateBindingService throw some LateBindingException which exposes properties for everything there is to know about the missing assembly; the Message property would be 100% under your control, and then the catch block could be like this:

catch(LateBindingException exception)
{
    MessageBox.Show(exception.Message);
    viewModel.OnRequestClose();
}

Notice that I'm not calling Close directly on the view, because I want the handler to unregister itself before exiting, so I'd just have the ViewModel expose a method that raises the RequestClose event - convention for such methods is On[EventName], so OnRequestClose.


Python program to calculate the area of two-dimensional shapes

Generally looks good so far (I especially like how you set length and width to an inline call to raw_input() -- less code's better).

One suggestion is to only take radius as a parameter to the circle function and instead use the math.pi constant and import math at the top of the program, making the top of your program the following:

import math
def circle(radius):
   area_circle = math.pi * (radius ** 2)
   print " the area of your circle equals %s" % (area_circle)

To add the thing where you keep prompting the user for yes or no until they enter on of them, although I suppose I can't give you code (think that's what StackOverflow is for), think about initializing the response string to something that isn't "yes" or "no" outside a while loop where you keep checking if it's a valid response and asking the user for input...


A PHP function that prints the url based on path

I am not sure that $_SERVER['SERVER_NAME'] would be a valuable fallback for $_SERVER['HOST_NAME'] as this can be really any arbitrary string.
Keep your 'protocol' portion of code together.  Also you can streamline conditional for https case.

Example:

$protocol = 'http';
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === "on") {
    $protocol = 'https';
};

You could also simplify here and just eliminate this https check if you simply build your URL string like //domain.com/uri with no protocol shown.  This would mimic current behavior of simply continuing current protocol.  You might consider adding parameter to force http vs. https if you ever need to move between the two protocols.

It does not make sense to me why the path of the currently executing script or the current request URI would have anything to do with formulating the URI portion of the URL when this URI value is being explicitly passed in as a parameter to this function.
I do not follow the logic on the null use case for URI.  Why would this case exist?  Is this just to link a page to itself?
You should add validation around parametric input.  In this case, I would guess you need to validate URI as null or non-zero-length string. You might need to validate that that $args is empty string or starts with ?.


A timer to track time spent practicing Python

Ways to improve and redesign:

I'll start with listing inner issues (duplication, redundant or over-complicated conditional/algorithms etc). Then I'll provide you with a new Object-Oriented approach as a more manageable, flexible and reliable.

options = [...]. "Practice options" is better designed as a constant with immutable items (tuple):

OPTIONS = ("Code Review",
        "Project",
        "Puzzles (Project Euler, Finxter, kaggle)",
        "Courses, Books, or Videos",
        "Read Docs")

practice_choice function:
Dragging num variable though the for loop is redundant and easily replaced with enumerate feature (with custom start= parameter):

print('\n'.join(f'{i}. {option}' for i, option in enumerate(self.OPTIONS, 1)))

timer function:
var variable here:

var = 1
total_so_far = 0
while var == 1:
    ...

is redundant and it's not reassigned anywhere. Simply go with:

while True:
    ...

total_so_far variable is better named as total_time
Datetime.now() is duplicated on constructing a dictionary of session info (notes, total minutes etc). Instead, use end_dt from the nearest statement end_dt = Datetime.now() as it's already contains the current datetime.
creating non-existent target file:
filling data dict with:

for each_item in options:
    data[each_item] = []

is easily substituted with dict comprehension:

data = {o: [] for o in self.OPTIONS}

saving data

with open(target_file, 'w') as json_file:
    json.dump(data, json_file, indent=4)

is extracted into a separate function/method with respective name

Now, the Object-Oriented PracticeTimer class with lot of benefits like:

class constants
encapsulated state/behavior
dealing with target file: initializing/saving
methods with specific responsibilities
easy to extend

Underlying Class diagram:

# timer.py - A timer to track time spent practicing python

from datetime import timedelta
from datetime import datetime as Datetime
import json
import os

class PracticeTimer:
    # practice options
    OPTIONS = ("Code Review",
               "Project",
               "Puzzles (Project Euler, Finxter, kaggle)",
               "Courses, Books, or Videos",
               "Read Docs")

    # practice_log file with all practice sessions are stored
    TARGET_FILE = "practice_log.json"

    def __init__(self):
        # creates json file if it doesn't exist
        if not os.path.exists(self.TARGET_FILE):
            # top level values of json are created corresponding to practice type
            data = {o: [] for o in self.OPTIONS}
            with open(self.TARGET_FILE, 'w') as json_file:
                json.dump(data, json_file, indent=4)

        # open json file and load session data
        with open(self.TARGET_FILE, 'r') as json_file:
            self._data = json.load(json_file)

        self._current_choice = None

    def practice_choice(self):
        """Prompts user to select practice item. User enters int."""
        print("Pick a form of practice:\n")

        # print options, then ask user to select
        print('\n'.join(f'{i}. {option}' for i, option in enumerate(self.OPTIONS, 1)))
        choice = input("\nPick a number: ")
        self._current_choice = self.OPTIONS[int(choice) - 1]
        return self._current_choice

    def _save_log(self):
        with open(self.TARGET_FILE, 'w') as json_file:
            json.dump(self._data, json_file, indent=4)

    def run(self):
        self.practice_choice()

        # store notes about practice session
        notes = input("Enter notes... ")

        # start timing session and get start time
        input("Hit Enter to begin practice...")
        start_dt = Datetime.now()

        # loop to allow for pausing. Infinite loop that breaks when user clicks enter to stop session.
        total_time = 0
        while True:
            pause_or_stop = input("Hit Enter to stop or space to pause...")

            # when user hits enters space char
            if pause_or_stop == ' ':

                # gets time session was paused. Calculates time practicing so far. Stores for later
                # Allows user to pause multiple times
                pause_dt = Datetime.now()
                total_time += int((start_dt - pause_dt) / timedelta(seconds=1))  # used sec for easier testing.

                # resume on enter key and overwrites old start time
                input("Hit Enter to resume")
                start_dt = Datetime.now()

            # breaks if enter key
            elif pause_or_stop == '':
                break
            # catch bad input
            else:
                print("Key not recognized")

        # get stop time and find total time in minutes
        end_dt = Datetime.now()
        total_mins = int((end_dt - start_dt) / timedelta(seconds=1)) + total_time  # used sec for easier testing.

        # add info to the current session (as a list of datetime info, notes, total_minutes)
        self._data[self._current_choice].append({'day': end_dt.strftime("%A"),  # %b %d %Y %H:%M),
                                                 'date': end_dt.strftime("%m-%d-%y"),
                                                 'time': end_dt.strftime("%H:%M"),
                                                 'notes': notes,
                                                 'minutes': total_mins})

        self._save_log()

if __name__ == '__main__':
    p_timer = PracticeTimer()
    p_timer.run()


public List<T>[] Classify<T>(IEnumerable<T> sequence, params Predicate<T>[] predicates)
{
    var result = new List<T>[predicates.Length + 1];
    // It's clearer to create elements of the array explicitly
    for (int i = 0; i < result.Length; i++)
        result[i] = new List<T>();

    foreach (var elem in sequence)
    {
        var index = predicates.TakeWhile(p => !p(elem))
                              .Count();

        result[index].Add(elem);
    }
}

There is a few LINQ methods to get an index, f.e. Select((i, e) => ...). If the list of unsatisfied elements was the first (0th), I would use Select. But since it is the last, TakeWhile gives the shorter code.


func backgroundExecutable(f: (() -> Void) -> Void) -> (() -> Void)

This is madness and it takes a number of mental gymnastics to figure out what is going on here.

This method takes, as its only (and poorly named) argument, a closure which returns void and takes, as its single argument, a closure which returns void from taking no arguments.  Then this method returns a closure which takes no arguments and returns void.

Even writing it out in plain-English, it's hard to understand what's actually going on.  And I'm left scratching my head trying to figure out why we even need a closure which takes a closure as its argument.

The major problem here is that we're using this closure's closure argument to pass the call to endBackgroundTask(), a method which must be called, or we risk the OS killing our app.

Your class is attempting to provide a convenient wrapper to handling the background means for executing code while your application is in the background.  But your class hasn't made things any more convenient then what they already are.  It only makes them more nested and complicated.

So let's look at execute for a second, shall we?

func execute() {
    let application = UIApplication.sharedApplication()
    identifier = application.beginBackgroundTaskWithExpirationHandler {
        application.endBackgroundTask(self.identifier)
    }
    f(endBackgroundTask)
}

The crux of this is that endBackgroundTask, another method of this class (which should perhaps be private) is passed in as the closure the the user's background executing closure.  If they don't call the closure that's passed in (and call it only as the last thing their closure does), there will be unintended problems going on here.

But why do that?  We can instead do this:

f()
endBackgroundTask()

That's a step in the right direction.  We're no longer relying on the caller to end the background task.

But there's another problem here.  What if we call execute multiple times and on multiple threads?  The identifier will be different each time we call execute, and each time it overwrites the previous identifier.  So all the previous background tasks can't be stopped, and so the OS will eventually kill our app for running indefinitely in the background.

Instead, we need our endBackgroundTask method to take a string argument... the identifier of the task we're stopping.  And we need to not rely on a string variable for our class.

So, it needs to look more like this:

f()
endBackgroundTask(identifier)

At this point, I'm not entirely certain the point of the class at all when a single method with just a handful of lines can manage it:

func backgroundExecute(worker: () -> Void) -> Void {
    let application = UIApplication.sharedApplication()
    identifier = application.beginBackgroundTaskWithExpirationHandler {
        // you can't call endBackgroundTask here, and you don't need to
        // here you should put code to handle the task running out of time before it is complete
    }
    worker()
    application.endBackgroundTask(identifier)
}


Since we're using the C++ wrappers around standard C functions (which is good - I like it!), we need namespace qualification of std::size_t and std::memcmp).  Although your implementation evidently takes advantage of the license to also include the unqualified names, it's not portable to rely on that.

Instead of repeating the type when casting a1 to s1 and a2 to s2, we can just use auto (and let's be clear about the cast - prefer reinterpret_cast to a catch-all C-style cast).

I managed to simplify memcmp_fixed_ by using a recursive template.  For me (with g++ -03), this gave roughly the same execution speed (I guess that loop unrolling makes the resultant binary very similar).  I got rid of the separate void* and unsigned char* overloads - that's just a compile-time overhead and makes no different to runtime speed, which gives 9 lines, compared to your 14 (counting physical lines that contain alphanumerics).

template<std::size_t SIZE>
int memcmp_fixed_(const void *a1, const void *a2)
{
    auto const s1 = reinterpret_cast<const unsigned char*>(a1);
    auto const s2 = reinterpret_cast<const unsigned char*>(a2);
    auto const diff = *s1 - *s2;
    return diff ? diff : memcmp_fixed_<SIZE-1>(s1+1, s2+1);
}

template<>
int memcmp_fixed_<0>(const void*, const void*)
{
    return 0;
}

I slightly simplified the test program to make it a single-character change to build the baseline test (and to send error messages where they belong), and massively reducing the repeated code:

#if 1
#define test_memcmp fast_memcmp
#else
#define test_memcmp std::memcmp
#endif

int main(int argc, char **argv)
{
    if (argc != 3) {
        std::fprintf(stderr, "Usage:\n\t%s [string1] [string2]\n", argv[0]);
        return 1;
    }

    const char *s1 = argv[1];
    const char *s2 = argv[2];
    auto const size  = std::min(strlen(s1), strlen(s2));

    volatile int x = 0;
    for (volatile std::size_t i = 0;  i < MAX;  ++i)
        x += test_memcmp(s1, s2, size);

    std::printf("%d %d\n", test_memcmp(s1, s2, size), x);
}


BitSet

A BitSet is deliberately designed to be a memory efficient way to hold Boolean values.

It also has initialize methods (clear and set) already, so no need for initArray.  In combination with nextSetBit and nextClearBit (or the previous variants), those methods can replace moveForward.  And copyBack isn't necessary without moveForward.

The single increment for loop in incrementArray would not be necessary with a BitSet.  Again, the nextSetBit and previousSetBit methods would allow you to jump through multiple steps at once.

I haven't compared performance, but generally built-in methods are more efficient than custom methods.  The counter-argument here might be that a BitSet is more space efficient than time efficient.  Or that using the built-in methods involves algorithmic tradeoffs.  You'd have to test to see.

Nitpick

Choosen is not a word.  Although the base word is choose, the past participle is chosen with a single o.  But the variable doesn't really hold what has been chosen.  It holds a count of how many choices should be set to true.  The BitSet definition suggests that the best name for this is cardinality.  At least that's the name of the BitSet method.

BitSet also uses size to represent the total number of choices.  And uses length for something else.  Consider switching the parameter name length to size to match.  Not because length is a bad name, just inconsistent with BitSet.


Adding and subtracting Matrices based on condition

You are only using single-letter variable names. While this is quite understandable for A, B and C, I don't recommend it for n and m.

The big problem about n and m (and i and j) is that it is hard to tell what is the row and what is the column. (The thing I hate the most about mathematics is the undescriptive variable names, it is not something I'd personally recommend carrying over to the programming side of things)

Speaking of names, your method is named E. That really doesn't say anything whatsoever.

I believe it's convention in Delphi to use an uppercase letter for the T prefix, so that would be TMatrix.

I'd use slightly more spacing in the code, and I'd also use a begin also for the outer for-loop.

This line:

if i<=j then C[i,j]:=A[i,j] + B[i,j] else C[i,j]:=A[i,j] - B[i,j];

is, except for the short and confusing variable names, not that bad really. I think it boils down to opinions how to write it 'the best'. An alternative to what you are doing is to use a addValue variable:

procedure ConditionallyAdd(rows, cols: Integer; A, B: TMatrix; var C: TMatrix);
var
  row, col: Integer;
  addValue: Real; // or Integer? or something. The type that your matrix uses
begin
  for row := 1 to rows do begin
    for col := 1 to cols do begin
      if row <= col then addValue = B[row, col];
      else addValue = -B[row, col];
      C[row, col] := addValue;
    end;
  end;
end;

There is essentially a lot of different ways to write this. Use the way you like the best.

I suspect that the integer values passed to the procedure always match the size of the matrices, in that case, use rows and cols as properties of the matrices if possible.


The latter query will be much more efficient-- it only requires hitting the table once.  You can do a quick test yourself to confirm this.

I'll create a simple two-column table with 1 million rows where the second column is one of 10 distinct values

SQL> create table t (
  2    col1 number,
  3    col2 number
  4  );

Table created.

SQL> insert into t
  2    select level, mod(level,10)
  3      from dual
  4   connect by level <= 1000000;

1000000 rows created.

Now, I'll run two different queries that retrieve 10% of the data.  I've set SQL*Plus to not bother displaying the data but to display the query plan and the basic execution statistics.  With the first query, note that the query plan shows that Oracle has to access the table twice and then do a sort and aggregate.  The query does ~10,000 consistent gets which is a measure of the amount of logical I/O being done (note that this is independent of whether data is cached so it is a much more stable measure-- if you run the same query many times, the consistent gets figure will fluctuate very little)

SQL> set autotrace traceonly;
SQL> select col1
  2        ,(select count(*) from t where col2=3)
  3    from t
  4   where col2 = 3;

100000 rows selected.

Execution Plan
----------------------------------------------------------
Plan hash value: 3335345748

---------------------------------------------------------------------------
| Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |      | 85706 |  2176K|   525   (3)| 00:00:07 |
|   1 |  SORT AGGREGATE    |      |     1 |    13 |            |          |
|*  2 |   TABLE ACCESS FULL| T    | 85706 |  1088K|   525   (3)| 00:00:07 |
|*  3 |  TABLE ACCESS FULL | T    | 85706 |  2176K|   525   (3)| 00:00:07 |
---------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - filter("COL2"=3)
   3 - filter("COL2"=3)

Note
-----
   - dynamic sampling used for this statement (level=2)

Statistics
----------------------------------------------------------
         32  recursive calls
          1  db block gets
      10465  consistent gets
          0  physical reads
        176  redo size
    2219528  bytes sent via SQL*Net to client
      73850  bytes received via SQL*Net from client
       6668  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
     100000  rows processed

On the other hand, with the analytic function approach, the query plan shows that we only have to hit the table once.  And we only have to do ~1,900 consistent gets-- less than 20% of the logical I/O that the first query had to do.

SQL> select col1,
  2         count(*) over ()
  3    from t
  4   where col2 = 3;

100000 rows selected.

Execution Plan
----------------------------------------------------------
Plan hash value: 2291049666

---------------------------------------------------------------------------
| Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |      | 85706 |  2176K|   525   (3)| 00:00:07 |
|   1 |  WINDOW BUFFER     |      | 85706 |  2176K|   525   (3)| 00:00:07 |
|*  2 |   TABLE ACCESS FULL| T    | 85706 |  2176K|   525   (3)| 00:00:07 |
---------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - filter("COL2"=3)

Note
-----
   - dynamic sampling used for this statement (level=2)

Statistics
----------------------------------------------------------
          4  recursive calls
          0  db block gets
       1892  consistent gets
          0  physical reads
          0  redo size
    2219510  bytes sent via SQL*Net to client
      73850  bytes received via SQL*Net from client
       6668  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
     100000  rows processed

Now, to be fair, you probably won't cut out 80% of your consistent gets moving to the analytic function approach using this particular query because it is likely that far fewer than 10% of the rows in your PEOPLE table have a birth date of today.  The fewer rows you return, the less the performance difference will be.

Since this is Code Review, the analytic function approach is much easier to maintain over time because you don't violate the DRY principle and you have to remember to make all the same changes to your inline query that you make in the main query.


First off, I would like to point you to the time module which has functions that are similar to what you want to accomplish.

Now as for DRYing your code up a bit. You were right to notice that you have blocks of:

if var in range1:
    func1(var)
elif var in range2:
    func2(var)
else:
    return 'blah_out_of_range'

I don't agree with your else block code. You are returning an error statement, which should actually be an exception such as a ValueError like so:

raise ValueError("blah out of range")

This is more readable, and more Pythonic.

Back to the code block, if we take each of the variant parts as arguments into a super function we get:

def process(var, cond1, func1, cond2, final):
    # ugly code here

This is trying to emulate the functional programming style of Lisp, Scheme, Racket and etc, which something that is generally avoided in Python code due to the final unreadability of the code.

Let's think of something else, such as checking all the conditions ahead of time, before doing any processing. This speeds up execution for failed inputs (as any failing input would fail as fast as possible), and simplifies the logic.

This would look something like this:

if year not in range(1001, 2035):
    raise ValueError("year not in range")
if month not in range(1, 13):
    raise ValueError("month not in range")

and so on. This can also be done via assert statements of the unittest module for even more compact code.

Then afterwards you will have blocks of the form:

if cond1:
    func1
else:
    func2

This is easily wrapped into a ternary operator:

func1 if cond1 else func2

Which will eliminate a lot of lines from your code.


Extract a range of rows from one file into another

public void blah(String fileName, String startRowCount, String totalRowCount)

A general purpose function should not have integer parameters passed as string, it's not its responsibility to parse them. Change them to int and move parsing outside. Side note: from given code it's not clear but parsing may fail if input is user provided (otherwise I see no reason you may have a string). In that case Integer.parseInt() will throw NumberFormatException.

br, sb but also newFile and counter aren't best variable names you can think of. Not to mention that you do not even use sb. Let's say you have these:

reader = new BufferedReader(new FileReader(inputFileName));
writer = new BufferedWriter(new FileWriter(outputFileName));

Note that I also changed parameter name and I introduced a constant for output file name. I'm generally against paths relative to current working directory but this may be a requirement in this case (I don't know.) If you're using Java 8 you also have an handy Files.lines(Paths.get(inputFileName)). You may also consider to use PrintWriter (which has a println() method) instead of BufferedWriter.

Your if condition inside while checks for two different things: skipping lines until first required one is read and ignore lines after last required one is read. If you do not require to consume all input lines then you're wasting time because you will read entire file even when you're done with your task. Few changes about names, you're counting line indices, not count.

String line = "";
int currentLineNumber = 0;

while ((line = br.readLine()) != null) {
    if (counter++ < startRowIndex)
        continue;

    if (counter > lastRowIndex)
        break;

    output.write(line);
    output.newLine();
}

Your pattern to catch IOException is little bit redundant, you do not need to log the inner error for close(), any relevant error might come from a previous call to flush():

try {
    // Do your stuff here...
    writer.flush();
} finally {
    if (writer != null) {
        try {
            writer.close();
        } catch (IOException e) {
            // We may ignore errors for close(), if anything went
            // wrong with our data then we already reported the issue
            // with the call to flush()
        }
    }
}

Note, however, that this pattern is prolix and it may be simplified (as you already marked in a comment) using try-with-resources:

try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath))) {
    // Do your stuff here...
} catch (IOException e) {
    // Log?
}


A tool to extract all links from a web-page in Python

Code style issues (from top to bottom)

imports - you should properly group imports as per PEP8 - in the first group you would have your system-level imports, then third-party libraries and then your local imports - all groups sorted alphabetically with a blank line between the groups:

import sys
from urllib.parse import urlparse

from bs4 import BeautifulSoup
import requests

docstrings should be enclosed into triple quotes, start with a capital letter and end with a dot. "Main" is though not a descriptive and useful documentation string - see if you can add details about what the function does
variable naming - use descriptive variable names - response instead of r
watch for spaces around the operators
when comparing to None, you should be using is and not ==, e.g. if anchor is not None - you though actually don't need these comparisons - see below
avoid using bare exception clauses

Other improvements

you should switch to argparse module instead of manually parsing and validating sys.argv
you don't actually need checks against None and filtering the links list - you can enforce the presence of attributes this way:

script_elements = [element['src'] for element in soup.select('script[src]')]
anchor_elements = [element['href'] for element in soup.select('a[href]')]
link_elements = [element['href'] for element in soup.select('link[href]')]
form_elements = [element['action'] for element in soup.select('form[action]')]

links = script_elements + anchor_elements + link_elements + form_elements

if performance is critical, see if you can use lxml instead of html.parser (requires lxml module to be installed):

soup = BeautifulSoup(response.content, "lxml")

see if you can join the current url with the relative link with urljoin() - might simplify the post-processing for the extracted links


Ring Timer Animation with Chasing Tail using CoreAnimation

There is one problem with your approach: Additional sublayers are added
in draw() and in animateTimerReset() and never removed. That can
cause memory problems and slower drawing eventually.

I would suggest to create and add only a single instance of the animation layer, this can for example be done in

override func awakeFromNib() {
    layer.addSublayer(animationLayer)
}

Then animate this single animation layer:

func animateTimer(over duration: TimeInterval) {
    animationLayer.removeAllAnimations()
    let head = CABasicAnimation(keyPath: "strokeEnd")
    head.toValue = 1
    head.duration = duration
    head.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    head.fillMode = kCAFillModeForwards
    head.isRemovedOnCompletion = false
    animationLayer.add(head, forKey: "strokeEnd")
}

func animateTimerReset() {
    let tail = CABasicAnimation(keyPath: "strokeStart")
    tail.toValue = 1
    tail.duration = 0.1
    tail.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    tail.fillMode = kCAFillModeForwards
    tail.isRemovedOnCompletion = false
    animationLayer.add(tail, forKey: "strokeStart")
}

Some further remarks: At several places the explicit type
annotation can be removed, e.g.

var trackColor: UIColor = UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1)
var trackShade: UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
var trackLight: UIColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.3)

is shorter written as

var trackColor = UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1)
var trackShade = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
var trackLight = UIColor(red: 1, green: 1, blue: 1, alpha: 0.3)

Also “implicit member expressions“ can be used if the type is inferred from the context, e.g.

layer.strokeEnd = CGFloat.leastNormalMagnitude

becomes

layer.strokeEnd = .leastNormalMagnitude


Performance and Readability Improvements for HTML Parser with BeautifulSoup

There are multiple things you can do to speed things up:

faster JSON parsing - try out ujson or simplejson; or even simplejson on PyPy
use lxml instead of html.parser (requires lxml to be installed)
do not parse the complete HTML, parse only what you need with SoupStrainer:

pattern = re.compile(r"^h[0-9]$")
parse_only = SoupStrainer(pattern)
soup = BeautifulSoup(data, "lxml", parse_only=parse_only)

You can then do simple soup.find_all() (or via a shortcut - soup()) since you'll only have header elements in your HTML soup.

Here is a demonstration of what SoupStrainer would do:

In [1]: import re

In [2]: from bs4 import BeautifulSoup, SoupStrainer

In [3]: data = """
   ...:
   ...:
Some Paragraph 1

   ...:

   ...:
Some Paragraph 2

   ...:

   ...:
   ...:
   ...:

   ...:
Some Paragraph 3

   ...:

   ...:
Some Paragraph 4

   ...:
   ...:
Some Paragraph 2

   ...:
   ...: """

In [4]: pattern = re.compile(r"^h[0-9]$")

In [5]: parse_only = SoupStrainer(pattern)

In [6]: soup = BeautifulSoup(data, "lxml", parse_only=parse_only)

In [7]: print(soup.prettify())

 Some Paragraph 1

 Some Paragraph 2

 Some Paragraph 3

 Some Paragraph 4

 Some Paragraph 2


Is there a better way to translate a string into methods?

The design flaw would have been the use of this switch case with 11 entries. That's already a lot. By the way I warn you, you have forgotten 9 break out of 11 cases.

However, in your case, each case relates to a single action. I mean, there is not a lot new to understand while reading: for each case you define a single behaviour action, inside a single word function call. (You don't put multi line, multi code, with multi conditions behaviour that is complex inside your switch case... : this is the thing to avoid and you have avoided it)

So honestly speaking it's totally acceptable.

Only for your culture I am mentionning some ways to get rid of switch case. I repeat myself, you shouldn't apply them in your case right now.

However, the first thing you may notice in such design, maybe there are common behaviours that are dupplicated between all your function call inside the switch case.

Imagine, if in roll() and turn() you would first have to

Turn head to the right to see if nothing tries to cross my path
Turn head to the left to see if nothing is moving straight right on me

and then only to roll() or to turn()

Then you could start thinking about using the Strategy pattern instead of simple function calls. This way, the strategy object which contain the action to do, can share common behaviour in a mother class.

If you started to have really many Strategies, that should be tune and tweaked precisely, then you would think about implementing the Interpreter Pattern so as to map between the precise language in your entry and the Strategies to apply.

And if you start to have a big Interpreter object and you think you need a grammar to express all the possibilities, then no doubt you should think about a Domain Specific Language. ( with you how parser etc... ).

In your case the switch case is entirely sufficient ;-)


Reversing the "words" of a container with a bidirectional iterator

Although not relevant to the algorithm itself, you could still consider these basic things:

It's best to use "\n" instead of std::endl for newlines.
You don't need a return 0 at the end of main(); it will do this for you automatically.
You should also add curly braces in my_reverse() for consistency and in case you'll need to add more to the loop.
The name IsSeparatorTester issep seems odd as an argument. Perhaps it should be renamed to something like Separator sep since it's not performing an action (like a function) and should therefore be a noun.

However, if you're mostly trying to reimplement std::reverse(), then you can leave it out this argument altogether.  There may not be many cases in which the user would choose something other than a space as a separator.


You could define intermediate views using common table expressions.  That would eliminate the redundancy of the calculations, but redundantly introduce a different kind of redundancy.

WITH ATable AS (
    SELECT amount, amount*.1 AS A FROM table
), BTable AS (
    SELECT amount, A, A+3 AS B FROM ATable
), CTable AS (
    SELECT amount, A, B, B/2 AS C FROM BTable
)
SELECT amount, A, B, C, C+37 AS D FROM CTable;