Understanding htaccess redirect to HTTPS and WWW

The code above works as expected. Why isn't the code in the next format, as it does the same thing? Is any difference ?
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

This code is different to your "working" code (at the top of your question). In this code, the www subdomain is always prefixed to the requested hostname. So, if you were to request http://www.example.com/foo (HTTP + www) then it will redirect to https://www.www.example.com/foo - which is presumably not the intention.
This can be "fixed" with an additional condition in order to capture the hostname less the "optional" www subdomain, however, this is still not "the same" as the "working" directives you posted. For example:
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+?)\.?$ [NC]
RewriteRule ^(.*)$ https://www.%1/$1 [R=301,L]

The only purpose of the 3rd condition is to capture the hostname, less the www. prefix (if any). This condition is always successful. The hostname (less the www. prefix) is stored in the %1 backreference.
Just to emphasise... this is not exactly the same as the "working" redirects you posted initially. This performs the HTTPS + www redirect in 1 go, instead of two (potentially) in your "working" directives. eg. When you request HTTP and non-www then your "working" redirects will trigger 2 redirects, first to HTTPS on the same host*1 and then to HTTPS + www.
*1 This is a necessary requirement if you have implemented HTTP Strict Transport Security (HSTS) - where you must redirect to HTTPS on the same host before canonicalising the hostname. So, one redirect is not always "better" than two.

The first line of code looks a little bit ambiguous. So I try to modify with:
RewriteCond %{HTTPS} != on # Put a space before on

It may look ambiguous to you, but I assure you it's not.
You cannot simply inject spaces here, since spaces are argument delimiters in Apache config files. So, by putting a space after the != you are now passing 3 arguments to the RewriteCond directive: %{HTTPS}, != and on. on is likely to trigger an "invalid flags" error, since this will be interpreted as the 3rd "flags" parameter (eg. normally something like [NC]).
The = and ! are prefix-operators and are in fact part of the argument (CondPattern). They change the way the CondPattern (2nd argument) is interpreted. != is not a single operator, it does not strictly mean not-equals, as you are perhaps expecting, although the net result is the same. (More on this below).
The only time you need to use double-quotes (not single-quotes) around an argument in Apache config files is if the argument contains spaces (since, as mentioned above, spaces are argument delimiters). Although you can always surround the argument in double-quotes if you wish. And you can sometimes backslash escape the space instead (if the argument is a regex).
But note, the double-quotes surround the entire argument (which includes the prefix operators). For example:
RewriteCond %{HTTPS} "!=on"

Aside: Apache does not support line-end comments, so the # Put a space before on at the end of the line is not valid. Due to the way Apache directives are processed, this may appear to be OK at times (ie. no error), but it is strictly invalid. (You may have only used this in the code sample in your question, however, it is a common source of error, so worth mentioning.)

I found some users which are using:

RewriteCond %{HTTPS} off

and not:
RewriteCond %{HTTPS} !=on

I understand that one line checks if the https is off and another one if https is not on. We can say they do the same thing. There are other differences here ?

I've actually answered the same question on the Webmasters stack previously, so I'll just link to that for more detail:

https://webmasters.stackexchange.com/questions/118391/in-htaccess-files-is-there-any-difference-at-all-between-on-and-off

But yes, the net result is indeed the same and it's primarily personal preference which method you choose. Although the two methods are technically different.

off is a regex comparison: Does off occur anywhere in the value of the HTTPS server variable?
!=on is not a regex comparison. The = prefix changes it to a lexicographical string comparison. ie. Is the value of the HTTPS server var exactly equal to "on"? The ! prefix then negates the expression. So the condition is successful when it does not match.

Can HTTPS not be neither on or off ?

The HTTPS server variable can only be "on" or "off" if your server is correctly configured.

If the answer is yes, that means the line RewriteCond %{HTTPS} !=on is better than RewriteCond %{HTTPS} off. Isn't it ?

Not necessarily. If HTTPS is not "on" or "off" then it's more likely to not be set at all (on all requests), so !=on would always be successful and result in a redirect loop. Whereas off will simply fail. Although this is hypothetical, your server would have to be "broken" for the HTTPS server variable not to be set at all and to not be "on" or "off".

When forcing www I have E=HTTPS:1 flag, which means I set the variable HTTPS with value 1.

First, a bit of clarification... there are 2 variables here:

The HTTPS server variable as set by Apache and referenced in %{HTTPS}. This is effectively readonly.
The HTTPS environment variable that you are setting here. This would be readable using the syntax %{ENV:HTTPS}.

Whilst it is relatively common to see this, it is arguably confusing to have two different variables of the same name. It would be better to change your environment variable to something like HSTS instead (see below), to avoid any confusion.

I don't understand the reason... When and who checks for this variable ?

Well, in the directives you posted it's not required. So, maybe this is not required here? But...
The reason for setting an env var on the HTTPS redirect like this is a common pattern when implementing HSTS*2. When implementing HSTS you need to set the Strict-Transport-Security HTTP response header on the HTTPS to HTTPS redirect itself. This is why I suggested using a variable called HSTS instead. If you are not setting this header with a conditional Header directive elsewhere in your config file (based on this env var) then you are not implementing HSTS (properly) and this env var is most probably superfluous.
*2 Although I wouldn't necessarily do it this way myself. I would set the env var in a separate rule, since you still need to set the STS header on other HTTPS responses, not just the redirect. See my answer to the following question on the Webmasters stack for more information on this, with example code:

https://webmasters.stackexchange.com/questions/115125/hsts-implementation-when-using-www-tld

Here, on question 4 I try to rename HTTPS to HTTPSaaa and then, with php, to get all server variable (from $_SERVER). I don't find HTTPSaaa. So this means that the flag is used only by htaccess ? So, I ask again. What's the reason for this flag/variable to exist ?

Yes, it's only used by Apache/.htaccess. It is set only on the redirect response back to the client. Your PHP script is not processed in this time, so cannot read it.
The reason would be to help with implementing HSTS, as described above.

If you are interested in HSTS then see this related CodeReview question (and my answer) regarding the implementation of HSTS in .htaccess:

HSTS Recommendations in .htaccess


Volatility updating with Heston-Nandi model

First, in R we use <- for assignment. It has its advantages.
It is prefered that you don't use T and F as variable names as these are
aliases to TRUE and FALSE.
Instead of this P <-  rep(P_0, T) you could have P <- vector(mode = "numeric", length = T).
This is just a suggestion: But there is no reason to not name your parameters:
para <- c(0.1, 0.2, 0.3, 0.4, 0.5, 0.7) # (beta_0,beta_1, beta_2, beta_3, r, gamma)
para <- c(beta_0 = 0.1,  beta_1 = 0.2, beta_2 = 0.3, beta_4 = 0.4, r = 0.5, gamma = 0.7) # (beta_0,beta_1, beta_2, beta_3, r, gamma)

Then, you may access them like para["gamma"], but not para$gamma.
Also, there is no need for para_vol<-para[1:6] in the loop, but I wager this is remnant
from other attempts.
In terms of performance, the pre-allocation I used did a 70 ms to 50 ms. Although,
I'm not confident in those numbers, as I did it fairly unscientifically.
Also, the referenced post shows a more direct way of calculating this.
Collapsed version of the code I ended up with:

library(fGarch)

T <-  3000
# For the example I simulate a GARCH
#process parameters
eta <-  0.2 #eta = 0 is equivalent to Geometric Brownian Motion
mu <-  100 #the mean of the process

#GARCH volatility model
specs <-  garchSpec(model = list(
  omega = 0.000001,
  alpha = 0.5,
  beta = 0.4
))
sigma <-  garchSim(spec = specs, n = T)

# library(ggfortify)
# autoplot(sigma)

P_0 <- mu #starting price, known
# P <-  rep(P_0, T)
P <- vector(mode = "numeric", length = T)
P[1] <- P_0

for (i in 2:T) {
  P[i] <-  P[i - 1] + eta * (mu - P[i - 1]) + sigma[i] * P[i - 1]
}
# DOESN'T WORK
# P[-T] <-  P[-T] + eta * (mu - P[-T]) + sigma[-1] * P[-T]

# Set the parameters :
para <-
  c(0.1, 0.2, 0.3, 0.4, 0.5, 0.7) # (beta_0,beta_1, beta_2, beta_3, r, gamma)
# Iteration to obtain the volatility associate to the model :

vol <- vector("numeric", length = length(P))
vol[1] <-  sd(P)
for (i in 2:length(P)) {
  # para_vol <- para[1:6]
  vol[i] <-
    para_vol[1] + (para_vol[2] * vol[i - 1]) + (para_vol[3] /
                                                  vol[i - 1]) * (P[i - 1] - para_vol[5] - (para_vol[4] + para_vol[6]) * vol[i - 1])
}
vol

# autoplot(vol)


Expand hostnames from a string of hostnames and/or regex

Your function expects a single argument that should contain hostnames or patterns separated by spaces:

sub expand_names {
    my $host = shift;
    my @raw_hosts = split(' ', $host);
    foreach my $raw_name (@raw_hosts) {

Why not use multiple arguments?

sub expand_names {
    foreach my $raw_name (@_) {

Since @hosts is empty when you reach this code:

# Gather all the hosts we found
foreach $raw_name  (keys %host_hash) {
    @hosts = (@hosts, (keys %{$host_hash{$raw_name}}));
}

You could simplify:

foreach $raw_name  (keys %host_hash) {
    push(@hosts, keys %{$host_hash{$raw_name}});
}

And actually, I don't see the reason for building a map of maps, when a simple flat map will do.
Consider this alternative implementation:

sub expand_names {
    my %hosts;
    foreach my $raw_name (@_) {
        #if the name might contain regex, let's see what it matched
        if ($raw_name !~ m/^[a-zA-Z0-9-]+$/) {
            my $found = 0;
            foreach my $target (@target_list) {
                if ($target =~ m/^$raw_name$/) {
                    $found = $hosts{$target} = 1;
                }
            }
            $hosts{$raw_name} = 1 if not $found;
        } else {
            # Regular host name or dotted-decimal
            $hosts{$raw_name} = 1;
        }
    }
    return sort keys %hosts;
}


In my opinion there are only few aspects:

Consistent use of assignment operator (either = or <-, mind that in special cases they aren't equivalent)
I like that you use package-references (::), you forgot about RANN:: though
You could use the purrr-package to replace sapply-type commands, which gives you more control over the output
When you refer to columns in a fixed position way such as colnames(data)[1] you should make sure that the data structure you give to the function is as expected


Given two vectors of ints, determine whether one vector is a prefix of the other

Embrace auto. Not only is it shorter, but avoids embarrassing bugs in choosing the wrong type.
decltype() is generally much more cumbersome.

Embrace abstraction. Solving the task itself deserves its own re-usable function. Good naming even reduces the need for comments, which can get out-of-sync.

Embrace the standard library. It is well-tested and well-known. Reinventing wheels for no reason is a poor use of time.

You refrained from using std::endl until your last line. No need to use it at all, ending the program flushed the output too.

std::boolalpha is the tool of choice for streaming a bool as "true" or "false".

Combine std::copy() and std::ostream_iterator for streaming an iterator-range.

#include <vector>
#include <iostream>
#include <algorithm>

template <class T, class U>
constexpr bool is_shorter_prefix(const T& a, const U& b) noexcept {
    const auto n = std::min(std::size(a), std::size(b));
    return std::equal(std::begin(a), std::begin(a) + n, std::begin(b));
}

template <class T>
void output_range(std::ostream& os, const T& t) {
    using U = decltype(*std::begin(t));
    std::copy(std::begin(t), std::end(t), std::ostream_iterator<U>(os, ", "));
}

int main() {
    const std::vector<int> a = { 0, 1, 1, 2 };
    const std::vector<int> b = { 0, 1, 1, 2, 3, 5, 8 };

    const auto is_prefix = is_shorter_prefix(a, b);

    std::cout << "small vector:\n";
    output_range(std::cout, a.size() <= b.size() ? a : b);
    std::cout << "\nIs prefix of big vector:\n";
    output_range(std::cout, a.size() > b.size() ? a : b);
    std::cout << "\n" << std::boolalpha << is_prefix << "\n";
}


Single-character variable names when used outside of 'traditional' loop constructs (e.g. i, j) or lambda bodies are bad not recommended, U(ppercase) case ones especially more so as they can get easily be confused with class names or generic type declaration (the usage most often seen). Therefore, please give better names to Matcher M and int T.

public static boolean doesTagEndInTheSameLine(String remainingHtml){
    Matcher endingOfTag = rgxForTagAtStart.matcher(remainingHtml);
    Boolean B = endingOfTag.find();
    return B;
}

I think a primitive boolean will do here. The whole method body can be simplified to just:

public static boolean doesTagEndInTheSameLine(String remainingHtml) {
    return rgxForTagAtStart.matcher(remainingHtml).find();
}

One more thing: You can do with more white spaces between operators...


Don't do the striping on the server. Don't do the striping with JavaScript. Since it's styling, do the striping with CSS.


Processing an image to extract green-screen mask

Use conditional indexing:

RED, GREEN, BLUE = (2, 1, 0) # Your numbers

empty_img = numpy.zeros((height, width, 3), numpy.uint8)

reds = img[:, :, RED]
greens = img[:, :, GREEN]
blues = img[:, :, BLUE]

empty_img[(greens < 35) | (reds <= greens >= blues)][BLUE] = 255

Edit:

empty_img[(greens < 35) | ((reds <= greens) & (blues <= greens))][BLUE] = 255

I was wondering if the compound relation would work. Sadly, not. This should. If it doesn't you can try composing it step by step - look at just the greens < 35 case, then the reds <=greens, etc.


I think you could change your code to this :

class Query < ActiveRecord::Base
  attr_accessible :customer_email, :customer_first_name, :customer_last_name,
                  :max_total_amount, :min_total_amount, :order_id, :order_is_deleted,
                  :order_max_date, :order_min_date, :results_limit, :postal_code,
                  :subscribes_to_daily_emails

 def orders
   @orders ||= find_orders
 end

  #TO DO:
  #1. Pagination:
  #2. Add limit if not present when there could be too many results. DONE! Set limit to 50.
  #3. Add export feature and remove limit for export.

  private
  def find_orders
    @results_limitVar = results_limit || 50

    @subscribes_to_daily_emailsVar = nil

    if subscribes_to_daily_emails
      @subscribes_to_daily_emailsVar = subscribes_to_daily_emails ? 1 : 0
    end

    @order_is_deletedVar = nil

    if order_is_deleted
      @order_is_deletedVar = order_is_deleted ? 1 : 0
    end

    #Added orders explicitly because otherwise first_name, etc is ambiguous
    #since it is in multiple models.

    orders = Order.order(:order_id)
    orders = orders.where("orders.first_name LIKE ?", "%#{customer_first_name}%")     if customer_first_name
    orders = orders.where("orders.last_name LIKE ?", "%#{customer_last_name}%") if customer_last_name
    orders = orders.where("orders.email_address LIKE ?", "%#{customer_email}%") if customer_email
    orders = orders.where("orders.order_id like ?", "%#{order_id}%") if order_id
    orders = orders.where("orders.is_deleted = ?", "#{@order_is_deletedVar}") if @order_is_deletedVar.present?
    orders = orders.where("total_amount >= ?", min_total_amount) if min_total_amount
    orders = orders.where("total_amount <= ?", max_total_amount) if max_total_amount
    orders = orders.where("order_date >= ?", order_min_date) if order_min_date
    orders = orders.where("order_date <= ?", order_max_date) if order_max_date
    orders = orders.joins("INNER JOIN customers ON customers.customer_id = orders.customer_id AND customers.postal_code LIKE ", "'%#{postal_code}%'") if postal_code
    orders = orders.joins("INNER JOIN email_preferences ON email_preferences.customer_id = orders.customer_id AND email_preferences.subscribes_to_daily_emails = ", "#{@subscribes_to_daily_emailsVar}") if @subscribes_to_daily_emailsVar.present?
    orders = orders.limit(@results_limitVar)
    orders
  end

end

I refactored your if conditions. Instead of :

if var.nil? == false
if !var.nil?

It's better to write like this:

if var.present?

In your case you can simply do :

if var

For your query, please watch look at the scopes.

You can do this :

class Query < ActiveRecord::Base
  scope :first_name_like, lambda { |first_name| where("orders.first_name LIKE ?", "%#{first_name}%") }
  ...
  def find_orders
    ...
    orders = orders.first_name_like(customer_last_name)
    ...
  end
end

It's interessent for your loooooong inner join.

I think if you column is a boolean you don't need to convert the value and you could do this :

orders.where("orders.is_deleted = ?", "#{order_is_deleted}")

The last thinks. Instead of this :

@results_limitVar

Write like this (by convention) :

@results_limit_var


as it say in the IPC::Open3 documentation, the filehandle for STDERR cannot be autovivified. You need to

use Symbol qw/ gensym /; my $stderr = gensym;

to create a file handle before opening your command.


How to take the some elements of a list of random numbers and sort them?

Instead of shuffling items yourselves it's easier to apply random sort. So your logic can be rewritten in a single statement:

var random = new Random();

var result = Enumerable.Range(1, total)
    .OrderBy(i => random.Next())
    .Take(take)
    .OrderBy(i => i);


Two times same code in methode except one little line

I think in this case I would simply make a private method to capture the duplicated code.  I probably wouldn't mind about the extra call to the SaveChanges() as it's only one line and removes any need for further complexity on the code.

public void Insert(Device device, IEnumerable<int> selectedFrameworks, IEnumerable<int> selectedOSs)
{
    UpdateDeviceProperties(device, selectedFrameworks, selectedOSs);

    _deviceRepo.Insert(device);
    _deviceRepo.SaveChanges();
}

public void Update(Device device, IEnumerable<int> selectedFrameworks, IEnumerable<int> selectedOSs)
{
    UpdateDeviceProperties(device, selectedFrameworks, selectedOSs);

    _deviceRepo.Update(device);
    _deviceRepo.SaveChanges();
}

private void UpdateDeviceProperties(Device device, IEnumerable<int> selectedFrameworks, IEnumerable<int> selectedOSs)
{
    device.Framework = GiveObjects<Framework>(selectedFrameworks, _frameworkRepo);
    device.OS = GiveObjects<OS>(selectedOSs, _osRepo);

    SetStateUnchanged<Framework>(device.Framework);
    SetStateUnchanged<OS>(device.OS);
}

I might also consider returning either a boolean (or some other error result) from the methods to raise awareness of whether the db action actually succeeded to help with raising failures back to the caller of the method.

In the case of Insert it could be as simple as (assuming device has an Id of course) return device.Id > 0;


Loading and parsing WinForms menus using LINQ

Try this:

public RegexOptions SelectedRegexOptions
{
    get
    {
       RegexOptions options = mnuRegexOptions.MenuItems
            .Cast<MenuItem>()
            .Where(
                x => x.Checked
            )
            .Select(s => (RegexOptions)s.Tag)
            .Aggregate(RegexOptions.None, (x, y) => x | y);

        return options;
    }
}

The Aggregate call will take care of the bitwise ORs.


Tweaks

for ($i = 0; $i < count($prods); $i++)
{
    for ($u = 0; $u < count($cats); $u++)
    {

I'd avoid calling count on each iteration of the loop.  Save the value at initialization time instead.

for ( $i = 0, $n = count($prods); $i < $n; $i++ ) {
    for ( $u = 0, $m = count($cats); $u < $m; $u++ ) {

I'd flip these around.

foreach ( $cats as &$category ) {
    foreach ( $prods as $product ) {

The switch to foreach means that you aren't having to muck with the count.  It will handle that in the background.

            array_push($cats[$u]['products'], $prods[$i]);

When adding a single value, []= is more efficient than array_push.

            $category['products'][] = $product;

When you use the reference version of foreach, you should explicitly break the reference using unset when done.

unset($category);

Note that if $cats were the inner loop, we'd need to do this for every iteration of the outer loop.

So in whole, that gives us

foreach ( $cats as &$category ) {
    foreach ( $prods as $product ) {
        if ( $product['category_code'] === $category['category_style_code'] ) {
            if ( ! isset($category['products']) ) {
                $category['products'] = array();
            }

            $category['products'][] = $product;
        }
    }
}

unset($category);

New Algorithm

But we can do even better.  Note that this runs count($cats) times count($prods) iterations.  But we don't actually have to check every category against every product.  We just need a way to look up the category for a given code.

    $category_of = array();
    foreach ( $cats as &$category ) {
        $category_of[$category['category_style_code']] = &$category;
    }
    unset($category);

Now our $prods loop can just look up the category.

    foreach ( $prods as $product ) {
        if ( isset($category_of[$product['category_code']]) ) {
            if ( ! isset($category_of[$product['category_code']]['products']) ) {
                $category_of[$product['category_code']]['products'] = array();
            }

            $category_of[$product['category_code']]['products'][] = $product;
        }
    }

If we don't mind having empty products arrays in a category, we can speed up the second loop by moving the check into the first loop.

    $category_of = array();
    foreach ( $cats as &$category ) {
        $category_of[$category['category_style_code']] = &$category;

        if ( ! isset($category['products']) ) {
            $category['products'] = array();
        }
    }
    unset($category);

Now each $category['products'] is guaranteed to be set, so we only do this check once per category not once per product.  Note that we may not need to do the check.  if we know that $category['products'] is not set until we do this, we can just do the assignment.

Currently we check that a given category exists before assigning.  If this will always be true, then we can remove the check and just assign:

    foreach ( $prods as $product ) {
        $category_of[$product['category_code']]['products'][] = $product;
    }

Now we iterate count($cats) plus count($prods) times.  This sum should be smaller than the product in most cases.  The exceptions would be single element cases (only one product or one category or both).  This will use more memory (for the $category_of array), but hopefully you aren't right up against the memory limit anyway.

Final Version

    $category_of = array();
    foreach ( $cats as &$category ) {
        $category_of[$category['category_style_code']] = &$category;

        $category['products'] = array();
    }
    unset($category);

    foreach ( $prods as $product ) {
        $category_of[$product['category_code']]['products'][] = $product;
    }

Another advantage of this version is that it is the first loop that does more work.  Since there are more products than categories (because there are multiple products per category but only one category per product in this model), this should speed things up.

Remember our assumptions though.  If they don't hold true, then the code should change:

$category['products'] is not set with data we need for any category prior to this code.
There is always a category for every $product['category_code'].

The original code did not make these assumptions.  It's unclear if that is because they don't hold as it needed the checks for other purposes.  Additional context might have made this clearer.

An advantage of this version is that it will throw an error if the second assumption does not hold.  The original code would just leave things in an inconsistent state.


I would not recommend putting your dal code in a try-catch block. At least you should be logging or doing something about it, currently you're just returning false (or no value). If an exception occur, let it happen, or put a try-catch on the function that calls it. Remember that exceptions vary (did the db server stop? was the sql malformed? these all are different cases.)

Using using is a better practice for all IDisposable objects, thus embrace it. If you run Visual Studio's code analysis tools (Ultimate Edition only I guess) it would also tell you to do so.

My version of your code is similar to Jeff's (which I wanted to vote up but didn't have enough rep yet) with an exception, SqlCommand is also disposable and can/should be used with using block.

public bool spInsertFeedback(string name, string subject, string message)
 {
     int rows = 0;
     using (var connection = new SqlConnection(cnnString))
     {
         connection.Open();
         using (var command = new SqlCommand("[dbo].[spInsertFeedback]", connection))
         {
             command.CommandType = CommandType.StoredProcedure;
             // params
             SqlParameter messageName = new SqlParameter("@name", SqlDbType.VarChar);
             messageName.Value = name;
             SqlParameter messageSubject = new SqlParameter("@subject", SqlDbType.VarChar);
             messageSubject.Value = subject;
             SqlParameter messageText = new SqlParameter("@message", SqlDbType.VarChar);
             messageText.Value = message;

             // add params
             command.Parameters.Add(messageName);
             command.Parameters.Add(messageSubject);
             command.Parameters.Add(messageText);
             rows = command.ExecuteNonQuery();
         }
     }
     return (rows != 0);
 }

Also I would suggest you to use connectionString instead of cnnString, which is not a proper naming.


Abstracting out two lines of code in Coffeescript

I'd say your abstracted function looks OK - it's up to the caller to supply the right height. That's the abstraction. The function doesn't have to know exactly what it's looking at, it just needs an element and (optionally) a height.

So you either call:

@computeStyle componentA.element, componentA.height * 50

or

@computeStyle someElement, componentB?.height

if I'm not mistaken. Something like that anyway.

I'd be more worried about the magic width/height values in the function, to be honest. And I'd encourage you to use is rather than == - both compile into === so there's zero difference, but I'd use the more coffeescript'y is.

Oh, and you have an error in your else if conditional: You're referencing element, but in your abstracted function, it's called componentElement

Incidentally, since returns are implicit at the exit point of a function, and object literals can be written quite tersely, you can reduce your function to this:

computeStyle = (componentElement, height) ->
  switch componentElement.type
    when 'table'
      height: height or 600
    when 'single_value'
      height: 200
      width: 800
    else
      {}

or even more tersely:

computeStyle = (componentElement, height) ->
  switch componentElement.type
    when 'table' then height: height or 600
    when 'single_value' then height: 200, width: 800
    else {}


Here's your code, and I've pointed out some potential problems:

for(needle in needles)
    if (haystack.indexOf(needles[needle]) >= 0)
        return true;

While this is possible, I suggest you use {} instead. This avoids ambiguity, and future danger, especially when you'll be adding more functionality beyond just a single line.

Additionally, for-in runs over prototype properties. If you happen to have a property that is similarly named as a native property in the prototype, you'll be in trouble. To avoid that, check using hasOwnProperty before proceeding with the code.

$(document).ready(function() {

Probably not better, but there's a shorthand for this: $(function(){...})

$("[data-from]").each(function(i, e) {

I'd probably avoid using attribute selectors. They're known to be slow, depending on the parser implementation. I suggest you stick to classes.

froms = $e.data("from").toString().split(/\s+/); // must do toString in case

A shorthand to convert stuff to string is to do '' + to it. Not so verbose, but it's somewhat elegant and short.


Vectorizing the product of an array of complex numbers

I was wondering if the compiler would more easily be able to vectorize it without the union-within-struct and the potential type punning of the e member (which doesn't seem to be used).

How about this?

typedef float v4sf __attribute__ ((vector_size (16)));
typedef struct {
  v4sf x;
  v4sf y;
} complex4;

static inline v4sf complex4_mul_r(v4sf a_r, v4sf a_i, v4sf b_r, v4sf b_i) {
  return a_r*b_r -a_i*b_i;
}
static inline v4sf complex4_mul_i(v4sf a_r, v4sf a_i, v4sf b_r, v4sf b_i) {
  return a_r*b_i + a_i*b_r;
}

complex4 f4(v4sf x_r[], v4sf x_i[], int n) {
  v4sf one = {1,1,1,1};
  v4sf p_r = one;
  v4sf p_i = one;
  v4sf p_r_temp;
  for (int i = 0; i < n; i++)
  {
     p_r_temp = complex4_mul_r(p_r, p_i, x_r[i], x_i[i]);
     p_i = complex4_mul_i(p_r, p_i, x_r[i], x_i[i]);
     p_r = p_r_temp;
  }
  return (complex4){p_r, p_i};
}

Looking at the assembly on https://godbolt.org/ it seems it gets fully vectorized. I can't get the godbolt sharing links to work.

I'm thinking about whether it might be possible to stick both the real and imaginary parts in the same vector, and use __builtin_shuffle() to permute them as necessary. Can't quite work it out.


The method should be static.
The method should throw NoSuchElementException when the list is empty.
I prefer to index by [left, right) instead of using subList
Choose a good pivot location, and you don't need the size() == 2.

In code:

    public static int findReset(List<Integer> rotatedArray) {
        if (rotatedArray.isEmpty()) {
            throw new NoSuchElementException("No reset for an empty list");
        }
        return findReset0(rotatedArray, 0, rotatedArray.size());
    }
    private static int findReset0(List<Integer> rotatedArray, int left, int right) {
        // when array is already sorted
        if(left + 1 == right || rotatedArray.get(left) < rotatedArray.get(right - 1))
            return left;
        int middle = (left + right) / 2;
        if (rotatedArray.get(left) <= rotatedArray.get(middle - 1)) {
            // when left side is monotonically increasing
            return findReset0(rotatedArray, middle, right);
        } else {
            // when right side is monotonically increasing
            return findReset0(rotatedArray, left, middle);
        }
    }

Here is a version with manual tail recursion optimization:

    public static int findReset(List<Integer> rotatedArray) {
        if (rotatedArray.isEmpty()) {
            throw new NoSuchElementException("No reset for an empty list");
        }
        int left = 0, right = rotatedArray.size();
        while(left + 1 < right && rotatedArray.get(left) >= rotatedArray.get(right - 1)) {
            int middle = (left + right) / 2;
            if (rotatedArray.get(left) <= rotatedArray.get(middle - 1)) {
                // when left side is monotonically increasing
                left = middle;
            } else {
                // when right side is monotonically increasing
                right = middle;
            }
        }
        return left;
    }


Show the results of linked list operations in sequence

Typo in method name?

insert_at_begning looks like it should be called insert_at_beginning?

insert_at_middle

The method name doesn't seem to match what it actually does.  It looks more like it's insert_after.

It also looks like it has a memory leak, what happens if you attempt to insert after a value that isn't currently in the list?

var

var is not a good name for a variable, it is totally nondescript. It is even worse when it is declared at a global/file scope where it's declaration isn't even visible.  You appear to be using a global variable var in your insert methods, however have a local var in your delete_from_middle method.  This is confusing.  Variable should be named after what they represent from a logical perspective.  You should also try to avoid using the same name for variables in nested scopes.

main

Your main looks mostly ok as a test harness, however it's rather inefficient.  Since your list doesn't maintain a tail pointer, inserting at the end is much slower than inserting at the beginning.  Similarly, inserting in the middle is relatively slow.  It would be more efficient to insert everything from the end to the front, rather than from the front to the end.

I'd also personally store the arrays to be inserted in the order that I wanted them to be in the list (not backwards), then iterate through them in reverse order.  I know this has the same effect, but when I look at the code I would then be able to see the list rather than having to mentally flip the arrays.


Improving PHP MVC code for personal website

If you want to learn best practices in MVC, I would suggest you to have Slim framework. If you don't want to use an existing framework and develop your own, still, I would recommend to install it on your local and understand how they are doing. Laravel is another best, but it would be overkill for a personal site.

Check their Routing example. You are almost close in your routing, but if you want to know the best practices, they have it: http://www.slimframework.com/docs/v4/objects/routing.html

In your example, I would include init.php and routes.php inside of index.php to keep it clean and declarative. Your init may eventually grow and it would become clumsy.


[ I'm assuming your example is meant to return x(dpy, drawable); rather than call itself recursively. ]

It's worth it if you have a use for it I guess.
Printing to std::cerr is not error handling, it's error logging. Pick a real error handling strategy and stick to it. Similarly is printing to std::cout necessary? I also believe that the fewer library calls there are in the constructor, the fewer risks of your wrapper calling itself recursively during static initialization of x, which will be disastrous.

Posix recommends the following way to cast when dealing with function types with dlsym:

*(void**)&f = dlsym(RTLD_NEXT, sym.c_str());

operator() can use perfect forwarding:

Ret
operator()(Args... args)
{
    f(std::forward<Args>(args));
}

The wrapping will cost two moves or one copy + one move per argument passed by value and one forward for reference types. It is transparent to the client; he or she won't need to use std::move unless the original function would already have him required to. Notice that the first copy or move of a by-value argument must be paid no matter what; the real opportunity cost of the wrapper is the (potential) move that comes after that, to pass the argument to the real function.

By comparison using Args const&... breaks if the wrapped function is void foo(T&&);, due to reference collapsing rules the signature will be void operator()(T&);

Perhaps the macro should take the name of the variable as an argument; but that may not be necessary depending on your planned usage.

Minor pet peeve: meaningful names. I would have called the constructor parameter symbol. The time it takes to type three more characters each time is simply negligible compared to the time it takes to write and maintain code. function_type instead of real_func possibly, too.


const float updatesRate = 1 / 60.0f;
const float framesRate = 1 / 308.0f;

The other time values are all doubles, it's a bit strange to use floats here.

    if ( newTime - timer >= 1 ) {
    ...
    if ( frameTime > 0.25 ) frameTime = 0.25;

These magic numbers should be named constants.

C++ now provides a variety of time-related utilities through the <chrono> header. We should use the clock types, type-safe duration types, and conversions that it provides.

double accumulator = 0.0;
double accumulator2 = 0.0;
uint32_t frames = 0, updates = 0;
double timer = hireTimeInSeconds( );

The naming of these variables leaves their purpose very unclear. Perhaps we could define an Accumulator class to group the variables for each accumulator and remove the duplication (see example code below).

hireTimeInSeconds This should probably be highResTimeInSeconds.

    while ( accumulator2 >= framesRate ) {
        //Rendering
        frames++;
        accumulator2 -= framesRate;
    }

I don't think this makes sense. We only want to render one frame, even if lots of time has passed. (We're not doing any updates between rendering frames in this loop, so we'd just be rendering the exact same thing over and over).

Applying the above suggestions, we might get something like the code below. It is quite a few more lines of code, but is also much more reusable (especially the accumulator and frame_timer classes), and is hopefully clearer in intent:
#include <chrono>
#include <iostream>

template<class c_t>
class accumulator
{
public:

    using clock_t = c_t;
    using duration_t = typename clock_t::duration;

    template<class d_t>
    explicit accumulator(d_t tick_length):
        m_tick_length(std::chrono::duration_cast<duration_t>(tick_length)) { }

    std::size_t accumulate(duration_t delta_time) // note: returns the number of ticks of m_tick_length triggered by this call
    {
        m_accumulated_time += delta_time;

        auto ticks = std::size_t{ 0 };

        while (m_accumulated_time >= m_tick_length)
        {
            ++ticks;
            m_accumulated_time -= m_tick_length;
        }

        return ticks;
    }

    duration_t get_tick_length() const
    {
        return m_tick_length;
    }

private:

    duration_t m_tick_length;
    duration_t m_accumulated_time;
};

template<class c_t>
class frame_timer
{
public:

    using clock_t = c_t;
    using duration_t = typename clock_t::duration;
    using time_point_t = typename clock_t::time_point;

    template<class d_t>
    explicit frame_timer(d_t initial_last_frame_time):
        m_last_frame_time(std::chrono::duration_cast<duration_t>(initial_last_frame_time)),
        m_last_tick(clock_t::now()) { }

    void tick()
    {
        auto now = clock_t::now();
        m_last_frame_time = now - m_last_tick;
        m_last_tick = now;
    }

    duration_t get_last_frame_time() const
    {
        return m_last_frame_time;
    }

private:

    duration_t m_last_frame_time;
    time_point_t m_last_tick;
};

int main()
{
    using clock_t = std::chrono::high_resolution_clock;
    using duration_t = clock_t::duration;
    using time_point_t = clock_t::time_point;
    using seconds_t = std::chrono::duration<float>;

    auto const update_time = seconds_t(1.f / 60.f);
    auto update_accumulator = accumulator<clock_t>(update_time);

    auto const render_time = seconds_t(1.f / 308.f);
    auto render_accumulator = accumulator<clock_t>(render_time);

    auto const print_time = seconds_t(1.f);
    auto print_accumulator = accumulator<clock_t>(print_time);

    auto const initial_frame_time = update_time;
    auto timer = frame_timer<clock_t>(initial_frame_time);

    auto const max_frame_time = std::chrono::duration_cast<duration_t>(seconds_t(0.25f));

    while (true)
    {
        auto const last_frame_time = (timer.get_last_frame_time() > max_frame_time) ? max_frame_time : timer.get_last_frame_time();

        if (print_accumulator.accumulate(last_frame_time) != 0) // note: will skip update periods if frames are super long (> print_time)
        {
            // ... print frames
            std::cout << "ping!" << std::endl;
        }

        auto const update_ticks = update_accumulator.accumulate(last_frame_time); // note: don't put this directly in the loop condition, we only want to call it once!

        for (auto i = std::size_t{ 0 }; i != update_ticks; ++i)
        {
            // ... do update
            std::cout << "update" << std::endl;
        }

        if (render_accumulator.accumulate(last_frame_time) != 0) // note: only ever render 1 frame, even if we should have rendered more
        {
            // ... render
            std::cout << "render" << std::endl;
        }

        timer.tick();
    }
}


Powershell script to create folders on remote servers

Congratulations, you managed to get a PS script to run, that's already something!

Jokes aside, you should look into parameterizing the script, so you could invoke it with command-line arguments instead of prompting for them, if that's possible. This would also reduce the maintenance burden on the script, because if the "server A" and "server B" aren't hard-coded in the script, there's nothing to change but how the script is invoked when either server needs to be changed.

Something like this at the start of the script:

param (
    $Company = "Contoso Inc."
    $ServerA = "PathA"
    $ServerB = "PathB"
)

There's no need for Write-Host, if you want to output a string, just output a string:

"Some output"

Will output the string... Some output. Yup. That easy.


Theme/skin swap... version 2! (CSS-driven)

Without having any other information available as to the restrictions of the project, I have to say that I do not like this implementation whatsoever.

The smartest way to go about swapping css "themes" is by ONLY changing class definitions.  There are several ways to do this, but in the case of a "themed" application the most practical approach would be having seperate .css files for each theme.

So for example, given the following HTML:

...and theme-default.css:

.header { background-color: black; height: 200px; width: 100%; }
.logo { background-image: url('/images/logo.jpg'); height: 200px; width: 200px; }

...and theme-red.css:

.header { background-color: red; height: 200px; width: 100%; }
.logo { background-image: url('/images/logo-red.jpg'); height: 200px; width: 200px; }

You would only need to swap out the css URL that is being called, something like this:

$(function(){
    $("#btnChange").click(function() {
        $('link[href="theme-default.css"]').attr('href','theme-red.css');
    });
});


Find the longest word in set D that is a subsequence of string S

First, the good news: your code looks pretty good. It's indented properly, spelled properly, spaced properly, capitalized properly, and uses the right Python style. Good work!

Here are a couple of nits:

This is a "program." (As opposed to just a module, or package, or library.) So use the standard python idiom for programs at the bottom:

if __name__ == '__main__':
    Main.get_longest_word("abppplee", {"ale", "bale", "able", "apple", "kangaroo"})

This mechanism is to allow your code to be loaded (via import myprogram) without having the main entry point automatically get invoked. That lets you load it up in the interpreter and browse around before you call it.
Use docstrings! Write down the problem you are trying to solve, and any notes about inputs or outputs for functions. Especially data formats.

For coding puzzle type problems, the docstring is a great place to copy the puzzle specification. This lets you refer back to it, lets you remember what you were doing when you wrote this code, and lets you paste it up at CodeReview with ease!

#!/usr/bin/env python3
""" Given a string S and a set of words D, find the longest word in D that is a subsequence of S.

    Word W is a subsequence of S if some number of characters, possibly zero, can be deleted from S to form W, without reordering the remaining characters.

    Note: D can appear in any format (list, hash table, prefix tree, etc.)

    For example, given the input of S = "abppplee" and D = {"able", "ale", "apple", "bale", "kangaroo"} the correct output would be "apple".

      - The words "able" and "ale" are both subsequences of S, but they are shorter than "apple".
      - The word "bale" is not a subsequence of S because even though S has all the right letters, they are not in the right order.
      - The word "kangaroo" is the longest word in D, but it isn't a subsequence of S.
"""

Now here are some possible improvements:

In create_dictionary

def create_dictionary(string):
    dictionary = {}
    index = 0

    for letter in string:
        if letter in dictionary:
            dictionary[letter].append(index)
        else:
            dictionary[letter] = [index]
        index += 1
    return(dictionary)

First, congratulations! You have written the hand-coded version of how to manage a dictionary whose values are lists. You got it right, your code works, and you should never do that again because it's boring. Instead, use collections.defaultdict(list). A defaultdict remembers a factory function that it will call whenever it is asked about a key but doesn't have a corresponding value.

The word list is not just the name of a Python data type, it's also the function to call when you want to construct one! (Just like you use the name of every class as it's constructor:  my_obj = MyClass(1, 2, "hello")) So when you want a dictionary that looks up lists, it's much easier to assume that there will always be a list in the dictionary, but it might be empty. That's what defaultdict(list) will get you:

import collections  # somewhere at top of file

def create_dictionary(s):
    dictionary = collections.defaultdict(list)
    index = 0

    for letter in string:
        dictionary[letter].append(index)    # defaultdict FTW!
        index += 1
    return(dictionary)

Next, give up your love affair with integers! Ned Batchelder gave a nice talk on the subject, so here's a link to that: https://www.youtube.com/watch?v=EnSu9hHGq5o

The idea is that many (most?) python loops don't need to use integers to index over things. And when you do need an integer index (and in this case you do!) there are better ways than maintaining your own integer index variable. Here's one such way: the enumerate() built-in function.

With enumerate, you can write a loop that iterates over the values from some iterable along with an automatically-associated integer:

    # No index=0 here
    for index, letter in enumerate(string):
        dictionary[letter].append(index)
        # No index+=1 here!

The index, string pair is called a tuple, and it is a built-in type just like list. The act of assigning or iterating using multiple target variables that take their values from a single tuple is called tuple unpacking. (Remember that phrase, you'll need it when you want to ask for help on the subject.)

In get_longest_word

The issue I have with this function is not one of Python, but rather of design. You are given some words, d. You want to find the longest word that is a subsequence of the string s. How do you do it?

In your case, the answer is "look at every single word in d, ignore the ones that are not subsequences of s, pick the longest one that remains."

There are a couple of better (read: faster, more efficient) ways of doing that job. Let me make one simple suggestion: sort the words!

In Python, there are Iterables and Sequences. An iterable is something you can iterate. A sequence is something you can access using s[i]. It's possible to have an infinite iterable, by writing an infinite generator function. It's not possible to have an infinite sequence, since you'll run out of memory trying to store it.

In this particular case it seems okay to assume that d is going to be a sequence: a finite list or tuple. So the fastest way to find the "longest word" is to start by looking at long words first. Because once you find a long word that is a subsequence, you can stop - there are no shorter ones!

The way to sort things in Python is the sorted built-in function. (Yes, it takes an iterable. No, it won't sort an infinite one. Yeesh!) By default, it sorts things by comparing the items using the "native" comparison. You can specify a key function, however, to sort using some different mechanism. Let's use the length of the words, which is the len function
(function len(x) -> int returns the length of the list/string/whatever). And let's reverse the order, so that the big ones come first:

d = sorted(d, key=len, reverse=True)

Now, instead of needing to check the length and update the longest-word-so-far variable, you can just return immediately once you find a subsequence.

In get_word_is_substring

Let's talk about default values. You say:

index_of_last_letter_found = None

But :! grep letter_found % in Vim tells me:

    index_of_last_letter_found = None
        if letter in dictionary and (index_of_last_letter_found is None or dictionary[letter][-1] > index_of_last_letter_found):
                if index_of_last_letter_found is None or index_of_last_letter_found < dictionary[letter][index]:
                    index_of_last_letter_found = dictionary[letter][index]

You're spending a lot of keystrokes checking for None. And all you do is compare using <, and assign new values. Why not just set the default value to some value that you know is going to be "too low"? Since string index values start at 0, maybe -1 would make sense:

index_of_last_letter_found = -1

While were at it, shorten that variable name. Names should be as long as they need to be, and no longer!

def get_word_is_substring(word, dictionary):
    last_index = -1  # Index of last letter found

    for letter in word:
        if letter in dictionary and dictionary[letter][-1] > last_index:
            index = 0
            while index < len(dictionary[letter]):
                if last_index < dictionary[letter][index]:
                    last_index = dictionary[letter][index]
                    break
                else:
                    index += 1
        else:
            return False
    return True

That's a lot more readable, since there are fewer tests and fewer characters.

Next, let's go back and work on your fetish for simple integer arithmetic. Now that you've watched Ned Batchelder's talk, you can see that index += 1 is not the way!

for index in dictionary[letter]:
    if last_index < index:
        last_index = index
        break

(There are some other ways to find the first element in an iterable that matches a condition. See here for many of them. But this is nice and clear, and works.)

Some words on "style"

The above code may be somewhat more difficult to understand because I changed the meaning of index. In your original code, index was an index into the list of indices that pointed to where letters occur in the master sequence. In my updated version index means the actual indices from the list. I have removed one level of indirection.

This is an example of why "too short" variable names are actually a good thing. You'll find a lot of people use very small names, like ch or i, to represent loop variables. This is because most of the time, loop variables are not a "concept" or a "noun". Instead, they are a subscript. We write a[i] because the original Teletype devices hand-carved out of wood by our pioneer forbears would not allow writing ᵢ.

But we don't really care about i, or about a[i]. We care about the thing stored there, and its properties. So, I encourage you to use short little 1-letter and 2-letter names when you are indexing a sequence, or when you're stuck in some other language that doesn't provide the nice looping options that Python does. Then you could say:

for i ...
    index = s_dict[letter][i]

And there would be no confusion between index and that-loop-variable.

Next, the structuring of your escape clauses: I see a lot of people being taught to code in a way that puts exit conditions last. You're doing that in your loop:

    for letter in word:
        if letter in dictionary and dictionary[letter][-1] > last_index:
            # much code here
        else:
            return False

But moving the exit condition to the top (by reversing the sense of the if statement) makes it clear what the alternatives are (if this is true, leave, otherwise ...) and reduces the indentation level of your code (by removing the else indent). Some people would have you use two-space tabs to address the indentation problem. Those people are all young with good eyesight. They're also quite wrong. :-)

    for letter in word:
        if letter not in dictionary or dictionary[letter][-1] <= last_index:
            return False

        # much code here

Lastly, there's the name. You called it get_word_is_substring, but we want subsequences not substring, and there's no reason to say get_ at the beginning. In fact, the word can be assumed, since you're passing it in, so:

def is_subsequence(word, s_dict):
    last_index = -1  # Index (in s) of last letter found

    for letter in word:
        if letter not in s_dict or s_dict[letter][-1] <= last_index:
            return False

        for index in s_dict[letter]:
            if last_index < index:
                last_index = index
                break

    return True

(Note: Because I suggested s_dict be a defaultdict, you could eliminate the if test entirely and rely on the for ... else construct, which is rather obscure. I don't recommend it, simply because it's non-intuitive, hard to understand, and because spelling out the failure conditions is better than leaving them to the language. ("explicit is better than implicit"))

The class

Finally, let's talk about the class:

class Main:

But first! Here's another video for you to watch, Jack Diederich's talk at Pycon 2012 entitled: "Stop Writing Classes!": https://www.youtube.com/watch?v=o9pEzgHorH0

As Jack says, "The signature of 'this shouldn't be a class' is that it has two methods, one of which is __init__."

In this case, you've created a class, but you don't store any data and you only call one method from the outside. It should be a function.


Thread Safe Circular Queue Implementation

First some style notes:

capactiy should be capacity. Spelling is important in all kinds of writing, because all writing is primarily communication, intended for humans just as much as for computers.
The entire RingBufferFree widget is unnecessary. std::unique_ptr<T[]> will do the right thing by default.
Temporary variables are often a code smell, if they're not serving an explanatory purpose. In the constructor, buffer_ptr is unnecessary.

explicit RingBuffer(std::size_t capacity) :
    _buffer_capacity(capacity),
    _ring_buffer_array(new T[capacity])
{}

Personally, I'd never write std::size_t, since size_t works just as well; but your mileage may vary.
~RingBuffer() {} is unnecessary; remove it.
It's unclear to me why you're using a std::unique_ptr<T[]> at all, when a std::vector<T> would work just as well.
It's odd that TryPush takes T& val, instead of const T& val or (better) T val or (perhaps best in this context) T&& val — where you move-assign either of the last two into place with _ring_buffer_array[current_write] = std::move(val);.
Likewise, in TryPop you probably ought to be moving-from the buffer element: *val = std::move(_ring_buffer_array[current_read]);

Okay, let's go find some concurrency bugs!

Obviously you'll have problems if two different threads try to call Push at the same time (because one will overwrite the other's pushed item); and you'll have problems if two different threads try to call Pop at the same time (because both could pop the same item).

So let's assume that this is just supposed to be a single-producer single-consumer queue, and look for bugs in that scenario.

Actually, assuming it's only supposed to be single-producer single-consumer, it's pretty clean! The only potential issue I see is that if the user calls Q.Pop() on an empty queue, or Q.Push(x) on a full one, then the thread in question will busy-loop forever — or at least until some other thread manages to break in and get some actual work done. It would be significantly friendlier if you put something in the while loop's body, e.g. std::this_thread::yield() — or even better, just return false or throw QueueEmptyException() or something like that, so that the calling code can decide what it wants to do, instead of getting blocked for an indefinite amount of time.

In other words, TryPush and TryPop smell like the real primitive operations here; Push and Pop are non-primitive operations of dubious utility.


Variable names. Imagine yourself a couple of months from now on, when you look back at the code. Will you remember without looking at the variable declaration what gnb is short for? I suggest you use longer variable names so that you even won't have to try to remember it. getNameBtn would be a better name, and it's still not too long. Using closeBtn instead of cb is also better. cb could just as well mean clearbright or something else totally irrelevant.
You seem to use setBounds to set the exact layout positions in pixels for your components. This is not recommended as this will not be flexible for resizing the windows. Instead use a proper LayoutManager such as BorderLayout and add some margins to make your buttons be placed approximately where they belong and still be flexible for if someone wants to resize the window. (Trust me, this can be more important than you think).
You seem to extend a lot of JButtons and other things. Technically, what's different between a CloseButton and a GetNameButton? The only differences are their positions, labels and I suppose there will be a difference in what happens when you click them. All these things are properties, it does not warrant extension of the original class. Instead you can use a public static method that creates a JButton with the initialized properties of a "close-button" or a "get-name-button". (The same goes for NameLabel, it does not need to extend JLabel)

Here's code for such a public static method:

public static JButton createGetNameButton() {
    JButton btn = new JButton();
    btn.setText("Show Name");
    btn.setBounds(20,100,120,20);
    return btn;
}

jliv902 has a good point in his comment of putting common features into a base class for your panels. However, think about whether or not you really should extend them or not. Personally I think that extending a JPanel or a JFrame is more OK than extending a button, but I want you to know that there are even reasons for why a JFrame shouldn't be extended. Instead of extending, consider this:

public class MyJPanelContainer implements ActionListener {
    private final JPanel panel;
    public MyJPanelContainer() {
        this.panel = new JPanel();
        // code to setup the panel the way you want it
        someComponent.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // ...
    }
    public JPanel getPanel() {
        // Technically, in another approach, you might not even need this getter, but that's a whole other story.
        return this.panel;
    }
}

If you would write a class like that, it will encapsulate the JPanel and thus hide several methods. The easiest effect to describe for using this approach is that it will drastically decrease the number of visible elements when you press Ctrl + Space, which will make it easier to see the method you are looking for.


Mean of combined sublists with different lengths

Assuming your nesting is only one level deep, the concatenation can be done very easily using np.hstack.  This will treat the inner lists as vectors, then concatenate them end-to-end as a 1D numpy array.  You can then take the mean of the resulting array.  So this will do what you want:

>>> np.hstack(a).mean()
10.79

Or equivalently (but more verbose in my opinion):

>>> np.mean(np.hstack(a))
10.79


Make a popup window that will stay open for 3 seconds

Alternative code:

ScheduledExecutorService executor =  Executors.newSingleThreadScheduledExecutor();
// assuming the stage-setup is perfomed already:
executor.submit(() -> Platform.runLater(stage::show));
executor.schedule(
    () -> Platform.runLater(((Stage)stage.getScene().getWindow()).close())
    , 3
    , TimeUnit.SECONDS);

This approach has multiple advantages:

The (costly) stage-setup is moved away from the UI Thread
Sleeping on the UI Thread doesn't happen, freeing it to do actual work
ScheduledExecutorService is more exact with it's scheduling than a sleep-call. It also doesn't involve having to handle InterruptedException or spurious wakeup

But it also has one glaring disadvantage:

You can't directly shutdown the ExecutorService, because that would cancel the scheduled Runnable.

This shouldn't be much of a problem though, since you should not be creating an ExecutorService in method scope in the first place.
Instead you should move multithreading facilities into the class scope (or even into static scope), so as to enable easy cleanup when the application is terminated or the instance reaches the end of it's lifetime.


Reading complete contact information in Android

Use AsyncQueryHandler, a helper class to help make handling asynchronous ContentResolver queries easier.

It basically wraps the ContentResolver object and handles background execution of its operations (CRUD) as well as passing messages (result) from the between threads (background and main/UI).

Just use to call the queryHandler.startQuery method and you will get callback in onQueryComplete method.

Example

class QueryHandler extends AsyncQueryHandler {

        public QueryHandler(ContentResolver cr) {
            super(cr);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {

                case CONTACT_QUERY:
//Do your stuff here
                    if (cursor.moveToFirst()) {
                        // Iterate through the cursor
                        do {

                            String id = cursor.getString(cursor.getColumnIndex(
                                    ContactsContract.Contacts._ID));
                            Log.e(TAG, " ID " + id);

                        } while (cursor.moveToNext());
                    }
                    break;
}
}

Use below method to fetch contact and add projection, selection according to your requirment.

public void fetchContact(){
        queryHandler.startQuery(CONTACT_QUERY, null, ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    }


Wow that's a big integer! What's its largest prime factor?

What a fascinating solution!  It seems that for every smart decision you made, you also threw in a poor decision or two.

Smart decision: In PrimeFactors(), you start testing divisors from small to large, rather than large to small.

Poor decision: You used if (IsFactor(number,divisor) … rather than while (IsFactor(number,divisor)).  Using if instead of while disastrously complicates the program.

Smart decision: In IsPrime(), the index loop skips even numbers.  (Why is the variable named index?)

Poor decision: The divisor loop in PrimeFactors() doesn't skip even numbers.

Smart decision: In IsPrime() the index loop goes up to Math.Sqrt(number).

Poor decision: In PrimeFactors(), the divisor loop goes all the way up to number / 2.

Smart decision: You defined an IsFactor() function for readability, and used it in PrimeFactors().

Poor decision: You didn't use IsFactor() in IsPrime().

Smart decision: In PrimeFactors(), whenever you find a successful divisor, you continue the calculation based on factor = number / divisor rather than number.

Poor decision: You continue to factor factor by recursion instead of looping.  Worse, the way you used recursion requires you to append the results to the results array.

Poor decision: In the innermost if-else of PrimeFactors()…

if (IsPrime(factor))
{
    …
} else {
    Int64[] recursiveResults = PrimeFactors(factor);
    …
}

the call to PrimeFactors() repeats a lot of throwaway work that was done by IsPrime().

Overall, though, the fundamental issue is the if-vs.-while distinction.  Had you chosen while, then you could…

enumerate the successful divisors in nondecreasing order.  Currently, you keep a list of all prime factors and find its maximum.  If you could obtain the divisors in order, then you wouldn't need to bother with keeping a list at all.
eliminate IsPrime() altogether.  Every successful divisor will necessarily be prime since you will have factored out all smaller divisors already.


Well, you don't need to use nested if statements here, but an if / else if ... chain seems unavoidable.

You can neaten up the code like this.  Note: 12 lines of code instead of 25.

private void loadTabsIfGPSAndInternetAvailable() {
    final Utils utils = new Utils(this);
    if (!utils.isConnected()) {
        utils.generateNoConnectivityAlert();
    } else if (!(new LocationClient(this).hasGPS())) {
        utils.generateNoGPSAlert();
    } else if (androidVersion >= Build.VERSION_CODES.M) {
        requestAllPermissions();
    } else {
        loadCameraAndForecastTabs();
    }
}

However, I suspect that there is something wrong with the logic of your original code ... which would make my refactoring incorrect as well.


Java solution to check if a Sudoku solution is valid

Your setting of count = 0 should be immediately before the appropriate for loop, not after it, and I would actually call that variable sum (renaming your sum to target) since it's not really a "count" at all, e.g:

private boolean rowCheck(){
    int target = size * (size + 1) / 2;
    for (int i = 0; i <size; i++) {
        int sum = 0;        // declaration moved, too
        for (int j = 0; j < size ; j++) {
            sum += board[i][j];
        }
        if (sum != target) return false;
    }
    return true;
}

The point being that you should be setting the variable in advance of the loop, not resetting it afterwards (that being a pointless operation on the final iteration).

I would probably also move target into a class member, calculated in the constructor.


Module for sending messages through PubNub

If you are receiving the data you expect, I think you are 99% there.

Alternatively, you could include the PubNub JS client into your Drupal app (vs. the PHP client), then you can publish asynchronously, or even completely after page load.

Link to the JS client and docs are available here, with a specific example of how to publish here


How could I make it look more like APL (and less like Python)?

Assuming you mean "in a more functional and less imperative way" by this line,

I don't think you can largely achieve that, for a good reason.

Basically, the array-based heap (and other common algorithms you see on algorithm textbooks) is designed for imperative languages. Translating it into a language whose main strength isn't imperative makes the code feel awkward and unfitting. It may also lead to code whose time complexity is actually worse than designed. See how it looks like when a similar algorithm is written in Haskell.

APL is not 100% functional, but definitely is more functional than imperative (especially when you mainly use dfns). If you want, search for "functional algorithms" and try implementing those. In the case of a heap, leftist tree isn't too complex, and supports one more \$O(\log n)\$ operation (heap merge) compared to an imperative binary heap. You can check out a nice illustration too.

But you can still improve some parts of the code.

Improvement in the algorithm

Use ⎕IO←1 instead.

Array-based heap uses 0-based indexing by default, so the parent-child relationship is slightly awkward:

$$
\begin{align}
\text{left child}&=1+2\times\text{parent} \\
\text{right child}&=2+2\times\text{parent} \\
\text{parent}&=\Bigl\lfloor \frac{\text{child} - 1}2 \Bigr\rfloor
\end{align}
$$

If you use 1-based indexing instead, it becomes slightly cleaner:

$$
\begin{align}
\text{left child}&=2\times\text{parent} \\
\text{right child}&=1+2\times\text{parent} \\
\text{parent}&=\Bigl\lfloor \frac{\text{child}}2 \Bigr\rfloor
\end{align}
$$

I don't have other better ideas to utilize the strengths of APL, due to the underlying algorithm being purely imperative.

General tips for writing APL code

Let the right argument of dyadic functions be the primary one (i.e. the heap).
If you see a negation of a comparison (e.g. ~heap[chp]<heap[rpos]), use a single equivalent function (e.g. heap[chp]≥heap[rpos]).
Prefer concatenation (e.g. 0,≢⍺) over stranding (e.g. 0(≢⍺)) when you concatenate two scalars.
Try not to modify existing variable's contents (e.g. avoid chp←((rpos<≢heap)∧~heap[chp]<heap[rpos])⊃chp rpos which refers to chp and then modifies it) when it isn't essential in implementing the algorithm. Try to choose a separate and meaningful name instead.
Parenthesize stranding assignments (e.g. (start pos)←⍵ instead of start pos←⍵).
Consider following a naming convention, and a little more descriptive names. (e.g. I can't easily see what chp stands for.)
Consider adding comments to each function which briefly describe the input(s) and the output.


Testing Terminal Text Game with Classes and Game Loop

You already have the answer to your "bug" given in the comments, but I will try to give you a more in-depth review. Nevertheless, I will repeat the aforementioned solution: to avoid the program auto-running on import, but your main call inside of a if __name__ == "__main__" (read more here if interested).

For your __init__ method, having your method initializers as (default) arguments tend to give more flexibility down the road as the project grows:

    def __init__(self, castle=1, villagers=1, warriors=0, food=0, stone=0):
        self.castle = castle
        self.villagers = villagers
        self.warriors = warriors
        self.food = food
        self.stone = stone

For your first real method, I would recommend staying with the Python standard of snake_case over camelCase. Furthermore, initialising the variable action to 0 doesn't really do you anything since you overwrite it in the following line. And since you rely on that input I think you should figure out what to do when you don't get an int, or if you get something like 11 (because 11 here would likely be a typo, given the options).

This, quite naturally, leads on to the purpose of testing (yay!). A nice thing about tests is that they allow you to think about what exactly you want to happen when you create an object or call on a function. For your takeTurns function, that would maybe be that you're only allowed to enter digits, and if you don't enter a single digit in the range 0–5 it throws an exception or it asks for another input. You would then basically implement your function (after the tests) to meet all the requirements you set forth in the beginning. You may then also find that maybe you were thinking about it the wrong way; in this case it could be that maybe take_turns (I renamed it for you...) shouldn't be asking for input() but rather be accepting an argument take_turns(user_choice).

To finalise, I'll add some smaller pieces of advice.

Instead of self.__class__.__name__ == "Player": you could (and should) use isinstance(self, Player).
Instead of action = random.randint(1, 4) coupled with 4 if-statements, there's a handy little function in random called choice (have a look here). You could also make your AI class much smaller by rethinking how the AI differs (or doesn't differ) from a Player.
f-strings are super nice. Instead of print("You:\nCastle: " + str(player.castle) + " Food: " + str(player.food) + " Stone: " + str(player.stone) + " Villagers: " + str(player.villagers) + " Warriors: " + str(player.warriors) + "\n"), you could have (and notice that I removed str() since you don't need it):

print(f"""You:
Castle: {player.castle}
Food: {player.food}
Stone: {player.stone}
Villagers: {player.villagers}
Warriors: {player.warriors}""")


Optimize this jQuery tab controller further

I've always been partial to writing JavaScript classes that take a root element:

function TabController() {
    // Maintain reference to "this" in event handlers
    this.toggleTab = this.toggleTab.bind(this);
}

TabController.prototype = {

    $element: null,

    constructor: TabController,

    init: function(element) {
        this.$element = $(element).on("click", ".js-tab", this.toggleTab);

        return this;
    },

    toggleTab: function(event) {
        var that = this,
            showTab = event.target.getAttribute("data-tab-content");
        event.preventDefault();

        this.$element.find(".js-tab").each(function() {
            var tabContent = this.getAttribute("data-tab-content");

            if (tabContent === showTab) {
                that.$element.find(".js-tab-" + showTab).removeClass("hide");
            } else {
                that.$element.find(".js-tab-" + tabContent).addClass("hide");
            }
        });
    }
};

Plus, I like to replace jQuery API calls that wrap cross browser native DOM methods  -- e.g. $(foo).data("bar") most times can be replaced with element.getAttribute("data-bar").

And to use:

// using document.documentElement means you don't need a jQuery dom-ready event handler
var tabs = new TabController().init(document.documentElement);

While you technically only need one tabber per page, making this an instantiable class allows you to unit test your JavaScript.

describe("TabController", function() {

    var element, tabs, event;

    function FauxEvent(type, target) {
        this.type = type;
        this.target = target;
    }

    FauxEvent.prototype.preventDefault = function() {};

    describe("toggleTab", function() {

        beforeEach(function() {
            element = document.createElement("div");
            tabs = new TabController().init(element);
        });

        it("shows a tab", function() {
            element.innerHTML = [
                'Tab 1',
                '

'
            ].join("");

            event = new FauxEvent("click", element.firstChild);

            tabs.toggleTab(event);

            expect($(element.lastChild).hasClass("hide")).toBe(false);
        });

    });

});

This makes your code truly modular. You could go a step further and make the CSS class names and data attributes customizable:

function TabController() {
    // Maintain reference to "this" in event handlers
    this.toggleTab = this.toggleTab.bind(this);

    this.options = {
        classPrefix: "js-tab",
        hiddenClass: "hide",
        dataAttribute: "data-tab-content"
    };
}

TabController.prototype = {

    $element: null,

    options: null,

    constructor: TabController,

    init: function(element, options) {
        this.$element = $(element).on("click", "." + this.options.classPrefix, this.toggleTab);
        jQuery.extend(this.options, options || {});

        return this;
    },

    toggleTab: function(event) {
        var that = this,
            showTab = event.currentTarget.getAttribute(this.options.dataAttribute);
        event.preventDefault();

        this.$element.find("." + this.options.classPrefix).each(function() {
            var tabContent = this.getAttribute(that.options.dataAttribute);

            if (tabContent === showTab) {
                that.$element.find("." + that.options.classPrefix + "-"
                    + showTab).removeClass(that.options.hiddenClass);
            } else {
                that.$element.find("." + that.options.classPrefix + "-"
                    + tabContent).addClass(that.options.hiddenClass);
            }
        });
    }
};

Some sample HTML

Tab 1

Tab 2

    Content A

    Content B

JSFiddle: http://jsfiddle.net/CL8Ns/


Intel® TinyCrypt: AES-128/CTR to encryption/decryption of 2D arrays

I find your code a bit dense and hard to read overall.

Your identifier names are compound words but all lower case.

plaintext

I prefer plainText others would prefer plain_text (and a lot of the code uses this second C like style). But either is preferable to your current style.

This seems redundant.

uint32_t result = TC_CRYPTO_SUCCESS;
result = tc_aes128_set_encrypt_key(&sched, params.key);

Just use one line:

uint32_t result = tc_aes128_set_encrypt_key(&sched, params.key);

Technically both functions exhibit undefined behavior (in C++ not sure about C). There is no return on successful completion.

    if (result != TC_CRYPTO_SUCCESS)
      return result;
  }
  // Add the following line
  return result;
}


JavaScript percentage calculation functions

Code level comments usually lose their context if not properly maintained. Using self descriptive variable names is a good choice. Appreciate your efforts in keeping the code highly readable.

First method, is trying to get the Percentage value, I would update the method definition to getPercentOfValue(from, percentage).
Second method, is trying to calculate percent rate, I would update the method definition to getPercentRate(newValue, originalValue) to follow the terminology in formula.


Lets start with your URI's.

GET /api/isAuthenticated - This is not restful I guess. isAuthenticated doesn't sound like it is a resource, instead it sounds like it is a method returning true or false. May be it would help if you read more on Restful architecture.

POST /api/login - Even this sounds like a process but not resource

Instead I would go with /api/authentication URI

On GET it returns authenticated user information
on POST you can send credentials to create a new authentication
on DELETE you delete the authentication resource which means logout.

Above is just for example about how to use Restful URI's. To be blunt, login process should not be done through RESTful URI's as it introduces stateful system where as RESTful API should be stateless. Instead you should use authentication headers of HTTP for authenticating and authorizing a user.

I hope this helps you in understanding RESTful API.


Reduce time
You can improve the function's time complexity at the expense of memory by tracking the duplicates in a separate Set. This will reduce the number of iterations by the number of unique items in the input array, and increase the memory need by the same number.
A further improvement can be gained if you delete duplicates from the unique set as you go. This will bring the memory use down.

function countDuplicates(original) {
  const uniqueItems = new Set();
  const duplicates = new Set();
  for (const value of original) {
    if (uniqueItems.has(value)) {
      duplicates.add(value);
      uniqueItems.delete(value);
    } else {
      uniqueItems.add(value);
    }
  }
  return duplicates.size;
}

/* Test code not related to solution */
function test(name, func, data, result) {
  const output =  `${name} [${data.join(", ")}] : `;
  console.log(output + (func(data) === result ? "passed" : "failed"));
}

test("1 duplicate ", countDuplicates, [9, 11, 12, 2, 7, 4, 2], 1);
test("1 duplicate ", countDuplicates, [6, 6, 6], 1);
test("2 duplicates ", countDuplicates, [0, 1, 4, 2, 7, 4, 2], 2);
test("3 duplicates ", countDuplicates, [0, 1, 4, 2, 7, 4, 2, 0], 3);
test("No duplicates ", countDuplicates, [0, 1, 4, 2, 7, 5, 8, 9], 0);

A look at memory.
Just out of interest I wanted to see the memory use. It turns out that the more unique items the lower the use (makes sense). The next snippet shows the memory use over 10000 calls to random arrays 1000 items long with a max range of item values to 10000.

function countDuplicatesMemory(original) {
  var maxSize = 0;
  const uniqueItems = new Set();
  const duplicates = new Set();
  for (const value of original) {
    if (uniqueItems.has(value)) {
      duplicates.add(value);
      maxSize = Math.max(maxSize, duplicates.size + uniqueItems.size);
      uniqueItems.delete(value);
    } else {
      uniqueItems.add(value);
      maxSize = Math.max(maxSize, duplicates.size + uniqueItems.size);
    }
  }
  return maxSize;
}

var memoryUse = 0;
var min = Infinity;
var max = 0;
const cycles = 10000;
const arraySize = 1000;
const maxRange = 10000;

for(let i = 0; i < cycles; i++){
  const arr = [];
  const range = Math.random() * maxRange | 0;
  for(let i = 0; i < arraySize; i++){
     arr.push(Math.random() * range | 0);
  }
  const mem = countDuplicatesMemory(arr);
  memoryUse += mem;
  min = Math.min(mem, min);
  max = Math.max(mem, max);
}
console.log("Mean memory use O(n * " + (memoryUse / cycles / arraySize).toFixed(3)+ ")");
console.log("Min memory use  O(n * " + (min / arraySize).toFixed(3)+ ")");
console.log("Max memory use  O(n * " + (max / arraySize).toFixed(3)+ ")");

The mean memory use is around O(n * 0.85)
These values are for a random set of values, there are cases where non random values may push the max memory just over O(n)


Using a custom type (with underlying type int) and using const to define the predefined colors is the perfect way to go.

If a user would want to use int, it is still possible by using a simple type conversion:

var myIntColor = 1 // Gray
var mycolor TagColor = TagColor(myIntColor)

Although by not using the predefined constants, you increase the possibility of errors (as the compiler will not be able to provide compile-time checks).

Note that your constant declaration can be a lot more compact and idiomatic by using the iota predeclared identifier which is auto-incremented, so you can use = iota to give value to all your colors. And also quoting from the spec: Constant declarations:

  Within a parenthesized const declaration list the expression list may be omitted from any but the first declaration. Such an empty list is equivalent to the textual substitution of the first preceding non-empty expression list and its type if any. Omitting the list of expressions is therefore equivalent to repeating the previous list.

This means you only have to write the initialization value for the first constant, and if you omit the rest, the same will be used for the rest (but iota will be auto-incremented of course). So your constant declaration can be this:

const (
    None TagColor = iota
    Gray
    Green
    Purple
    Blue
    Yellow
    Red
    Orange
)

Specifying a String() method for your type is also recommended, as many of the standard library functions check and use that if provided, for example the fmt package when printing values:

col := Orange
fmt.Println(col) // Will print "Orange"

The fmt package checks if the type of the value you passed has a String() method, and if it does, it will be called and its result will be printed.

Also note that you can "automatically" generate the String() method for your constants with go generate. There is a stringer tool which can be used with go generate and it generates a .go source file doing more or less what you did, but with a more efficient code. You can read more about go generate in the blog post Generating code.


Straightforward enumeration algorithms utilizing 2-layered loops will always take a lot of time on extremely large arrays where a possibility exists that the first match is achieved by elements near the start/end of the array (e.g. indices 515 and 9123456 of a 10 million elements array), which would lead to the same excessive number of iterations as the original code performed.

Here's an updated code that performs much faster on the average. The idea is to build a map of unique values and their minimal indices in the source array, and simultaneously check if there's an entry for the complementary number (addend) already.

var sum_pairs = function(ints, s) {
    var map = {},
        pair, pairMaxIndex = ints.length - 1;

    for (var i = 0; i <= pairMaxIndex; i++) {
        var a = ints[i];
        var b = s - a;
        var j = map[b];
        if (j !== undefined && i <= pairMaxIndex && j <= pairMaxIndex) {
            pairMaxIndex = i > j ? i : j;
            pair = i < j ? [a, b] : [b, a];
        }
        var tmp = map[a];
        if (tmp === undefined || i < tmp) {
            map[a] = i;
        }
    }
    return pair;
};

  10 million randoms in -100..100 range: 1ms - 1000ms
  10 million randoms in -1,000,000..1,000,000 range: 1ms - 5000ms
  10 million randoms in -10,000,000..10,000,000 range: 1ms - crash
  1 million randoms in -1,000,000,000..1,000,000,000 range: 1ms - 2000ms

The worst time in each case was caused by artificially crafting an array described above.
The crash in the 3rd test occured because the number of unique values neared 1G and the object exceeded 32-bit Javascript engine's memory limit of 2 GB. All tests were run on i7 CPU.

The code above incorporates the following optimizations as well:

Flambino's answer shows there's no need to continue enumeration if current index is bigger than the matching values' max index found already.
Jodrell's answer shows it's possible to do everything in just one loop, pointed out by Jonah.

And the tests:

console.clear();
var arr = [], max = 1000000;
for (var i = 0; i<10000000; i++) arr[i] = Math.random() * max * 2 - max |0;
console.log('array of', arr.length, 'elements is built');

console.time(1);
console.log(sum_pairs(arr, 1000));
console.timeEnd(1);


No need for a loop. The only difference between the functions is the target image (I assume it's an image, since DIVs don't have a srcattribute), so change the function to get the target from an data attribute of the input field:

function readURL(input) {
    if (input.files && input.files[0]) {
        var image = jQuery(input).data('image-target');

        var reader = new FileReader();

        reader.onload = function (e) {
            jQuery(image).attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

Add those data attributes to the HTML:

Image 1: <input type="file" data-image-target="#div1">
Image 2: <input type="file" data-image-target="#div2">

As you may notice the id of the input fields have gone. Instead of assigning them each their own separate event handler, assign one handler for all (or use a class):

jQuery("input[type=file]").change(function() {
   readURL(this);
});


TPL Dataflow BatchBlock with Batch Size & Timeout

class BatchedQueue

What's the reason for having this separate class? Is it so that there is only one instance of SlotClassLogger? If that's the case, that sounds like premature optimization to me.

class BatchedQueue<T> : BatchedQueue

You're not implementing (or exposing in other way) any of the dataflow interfaces. That means this class can't easily be used as a part of a dataflow network.

readonly int _interval;

When you have a value that is of some unit of measure, you should always very clearly specify what unit is uses. (You don't want your Mars probe to crash, right?) You can do that either in the name of variable or in a comment.

Though it seems you're not using any common unit. That should also be document very clearly and it should also have a very good reason. If the unit is something specific to your domain, then I don't think it belongs here, a class like this should be reusable.

If the condition for triggering it not actually some time elapsing, then consider using that condition directly, instead of approximating it using a timer.

transformer.LinkTo(_queue);
_source = new BufferBlock<T>();
_source.LinkTo(transformer);

I don't see any reason for the _source buffer block here. You could send items directly into transformer.

while (true)
{
    var buffer = _queue.Receive(_loopWait);
    if (buffer != null) { OnReceived(buffer); }
}

This code is blocking a thread unnecessarily when there is no work to do. The simplest solution would be to use ActionBlock to execute OnReceived.

There is no way to tell the queue to stop processing or for your to wait until its processing is done. Consider adding the Complete()/Completed pair used in dataflow blocks.

When dealing with time, Rx is often better than Dataflow. A behavior similar to yours could be achived by using Buffer():

_source = new Subject<T>();
_source.Buffer(_loopWait, size)
       .Subscribe(OnReceived);

Though this measures the timeout since the last batch, not since the last element. I think you could achieve that using something like (based on this SO answer):

_source.Buffer(() =>
    Observable.Merge(_source.Throttle(_loopWait).Take(1), _source.Skip(size - 1).Take(1)))
    .Subscribe(OnReceived);


Find the number of swaps that has taken place. New Year Chaos. Hackerrank

Time limit improvements

You don't need to implement a full bubble sort (as the maximum distance is 2 bribes!)
You can skip if a person is in the correct position if you know the processed part is correct.
You don't need to process the list twice, you only need to check if the person you are checking is within the maximum swap distance.

I commented my algorithm below; it is basically a bubble sort, only with a limit on how far the inner loop goes.

public class Solution {

    static final int MAX_SWAPS = 2;

    // Complete the minimumBribes function below.
    static void minimumBribes(int[] q) {
           int bribes = 0;

           int n=q.length;

           //we process from right to left
           for (int i=n-1; i>=0; i--)
           {
               int pos = i+1;
               int s;

               //if we are correct, we can proceed LEFT,
               //we know the right tail is correctly sorted
               //so after this step, the tail is 1 longer ans STILL correctly sorted
               if (q[i] == pos) continue;

               //try swap our position with previous positions, look MAX_SWAPS left.

               //for example:   1 5 2 4 3

               //if we are investigating position 5 (currently number 3)
               //we start swapping the items at position 3 and 4 if number 5 is at position 3.

               //if number 5 was not at position 3,
               //we try to find it at position 4
               //if number 5 was also not at position 4, we are too chaotic, as you
               //cannot bribe yourself more than MAX_SWAPS to the left.
               //so we are TOO CHAOTIC!

               //for example:   1 2 5 4 3

               //if number 5 is in position 5, we can skip it
               //(it is not)
               //if number 5 is at position 3
               //we swap the numbers 5 and 4 (at position 3 and 4) and have 1 bribe (bribes++)
               //situation becomes: 1 2 4 5 3
               //if now number 5 is at position 4, we have bribed again (bribes++)
               //situation becomes: 1 2 4 3 5

               //now we know 5 is in the correct position, and can scan from position 4
               //situation becomes: 1 2 4 3 [5]    // [] mark list that is DONE :)
               //if number 4 is in position 4, we add it
               //(it is not)
               //now if number 4 is in position 2, swap,
               //(it is not)
               //now if number 4 is in position 3, swap
               //it IS, swap them and bribes++
               //1 2 3 [4 5]

               //if number 3 is in position 3, we add it
               //1 2 [3 4 5]
               //etc.

               for (int m = MAX_SWAPS; m>0; m--)
               {
                   int left = i-m;
                   if (left>=0 && q[left]==pos)
                   {
                        s = q[left];
                        q[left]= q[left+1];
                        q[left+1]  = s;
                        bribes++;
                   }
                   else
                   {
                        if (m == 1) //if we didn't find the correct number at the last left position
                                    //after MAX swaps left, we are too chaotic
                        {
                           System.out.println("Too chaotic"); return;
                        }
                   }
               }
           }
           System.out.println(bribes);

    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int t = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int tItr = 0; tItr < t; tItr++) {
            int n = scanner.nextInt();
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

            int[] q = new int[n];

            String[] qItems = scanner.nextLine().split(" ");
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

            for (int i = 0; i < n; i++) {
                int qItem = Integer.parseInt(qItems[i]);
                q[i] = qItem;
            }

            minimumBribes(q);
        }

        scanner.close();
    }
}


I think the recursive approach, using a nested function, is a bit awkward. I tend to avoid reliance on closures ("explicit is better than implicit", after all!) and use explicit parameters instead.

To create a temp dictionary only on the top level call, I would use:

def recur_func(..., temp=None):
    if temp is None:
        temp = {}
    ...
    recur_func(..., temp)

(if you're wondering why not temp={} in the parameter list, see "“Least Astonishment” in Python: The Mutable Default Argument")

Rather than tup = d1.popitem() then indexing into the tuple, I would use key, val = d1.popitem(); this improves the readability of subsequent lines, as e.g. key is much more informative than tup[0]. You can also use dict.setdefault (or, as pointed out in Günther's answer, collections.defaultdict) to neaten up the logic:

key, val = d1.popitem()
temp.setdefault(val, []).append(key)

That just leaves factoring out the nested function, and making make_inverse_dict_recur directly recursive:

def make_inverse_dict_recur(d1, temp=None):
    if temp is None:
        temp = {}
    if not isEmpty(d1):  # why not just 'if d1:'?
        key, val = d1.popitem()
        temp.setdefault(val, []).append(key)
        make_inverse_dict_recur(d1, temp)
    return temp

Again, though, contrast that with the iterative version:

def make_inverse_dict_iter(d1):
    temp = {}
    for key, val in d1.items():
        temp.setdefault(val, []).append(key)
    return temp

This has the neat advantage of not mutating d1; generally, Python functions should either mutate their arguments or return a new object, not both. I suspect that this would be (at best) tricky to achieve with a recursive approach, though.


I'm not sure how this code works (I had to invent GetPrimaryKeyName) and I can't find a IQueryable<T> that has an OrderBy that takes a string parameter.  So faking it as much as possible, I came up with this:

    public IQueryable<TEntity> GetEntitySetMultipleTables(
        Expression<Func<TEntity, bool>> whereExpression = null,
        string orderBy = null,
        int? totalResults = null,
        int? skippedResults = null,
        string[] includes = null)
    {
        PropertyInfo orderbyProperty;
        int directionIndex;

        if (orderBy == null)
        {
            directionIndex = -1;
            orderbyProperty = null;
        }
        else
        {
            directionIndex = orderBy.IndexOf(' ');

            // Direction.
            if (directionIndex > -1)
            {
                orderBy = orderBy.Substring(0, directionIndex);
            }

            orderbyProperty = typeof(TEntity).GetProperty(orderBy);
        }

        if ((skippedResults != null) && ((int)skippedResults > 0) && (orderbyProperty == null))
        {
            orderbyProperty = typeof(TEntity).GetProperty(GetPrimaryKeyName());
        }

        // Base EntitySet.
        ObjectQuery<TEntity> objectSetResults = Context.CreateObjectSet<TEntity>();
        var results = includes == null
            ? objectSetResults.AsQueryable()
            : includes.Aggregate(objectSetResults, (current, include) => current.Include(include.Trim())).AsQueryable();

        // Filter by Where Expression.
        if (whereExpression != null)
        {
            results = results.Where(whereExpression);
        }

        // Order Results.
        if (orderbyProperty != null)
        {
            results = directionIndex > -1
                ? results.OrderByDescending(result => orderbyProperty.GetValue(result, null))
                : results.OrderBy(result => orderbyProperty.GetValue(result, null));
        }

        // Skip Records.
        if ((skippedResults != null) && ((int)skippedResults > 0))
        {
            results = results.Skip((int)skippedResults);
        }

        // Take Specific Amount of records.
        if ((totalResults != null) && (totalResults > 0))
        {
            results = results.Take((int)totalResults);
        }

        // Run the LINQ Query and return the results.
        return results;
    }