How can I improve this PHP MySql Rank generation function?

Something you might try is keeping everything inside the database. Using the SELECT, create a temporary table:

CREATE TEMPORARY TABLE tmp_ranks (rank int auto_increment primary key, player_id int)
AS SELECT NULL AS rank, player_id AS player_id FROM player_stats
ORDER BY '.$rank_order.$limter

This should give you a table that looks like

| rank | player_id |
+------+-----------+
|    1 | 123456789 |
|    2 | 123456780 |

Now, using an UPDATE with a JOIN, update your player_ranks table:

UPDATE player_ranks, tmp_ranks SET player_ranks.$rank = tmp_ranks.rank
WHERE player_ranks.player_id = tmp_ranks.player_id;

This should run fairly quickly, but given your data size, could take a while. I'd suggest testing it on a non-production box first, in case it locks things up for a good while.

Note that I left your PHP variables inline, so you'll need to fix those.


Express.js handler to update user fields

Assignments can be contracted to something like below:

 req.user.firstName = req.body.firstName || req.user.firstName;
 req.user.lastName = req.body.lastName || req.user.lastName;
 req.user.email = req.body.email || req.user.email;
 req.user.phone = req.body.phone || req.user.phone;
 req.user.fax = req.body.fax || req.user.fax;
 req.user.notes = req.body.notes || req.user.notes;

I think it can further be reduced if properties are put in some array and iterated over (since source and destination property have the same name), but I would stick with this arguably more readable text.

I am not familiar with express.js, so the following might not be applicable (I usually work with Typescript in Angular).

Your request have both a body and some user property. It is recommended to clearly separate output from input in order to obtain pure functions as much as possible. Something like below:

 updateUserFromRequest(req, user) {

     // clone to avoid changing provided reference
     var ret = [... user];

     // assignment logic here using ret

     return ret;
 }


Retrieving user details from a custom form

First, I would apply self-encapsulation by changing:

$this->_salutation = $this->getRequest()->getPost('salutation');

to:

$this->set_salutation( $this->get_parameter( "salutation" ) );

Since PHP can call functions using a string, it can be simplified further:

function set( $p ) {
  $f = '$this->set_' . $p;
  $f( $this->get_parameter( $p ) );
}

function get_parameter( $p ) {
  return $this->get_request()->get_post( $p );
}

Then:

$this->set( "salutation" );
$this->set( "first_name" );
$this->set( "last_name" );
$this->set( "email" );
// ... etc.

You can take that one step further by iterating over all HTML FORM variables, which removes the repetition altogether:

foreach( $this->get_form_parameters() as $param_name => $param_value ) {
  $this->set( $param_name );
}

However, that could lead to attempts on making arbitrary function calls by the client, so you'd have to be careful.

What I like about removing the repetition is that it sparks of being consistent with the DRY principle. The HTML form has the list of variables that need to be set -- now the developer need only change the HTML form variable list to change what variables are set by the object. This leads to a single source for the variable list.


Reduce nested for loops and if statements using Iterator Blocks?

First, having this many nested loops indicates that your algorithm could have really bad time complexity. And with the way you're resetting the indexes, I'm not even sure your code is guaranteed to complete. There may be a more efficient algorithm to do what you want, but I'm not going to try to find that.

Second, the i, j, k naming convention for loop variables is okay if you have two or maybe three nested loops. But with six levels, it makes your code much less readable (and more error-prone). You should consider using locals with reasonable names instead of expressions like TimeLineInit[i].Stage[j].ToolList[m]. Or even better, foreach loops, which basically do the same with less code.

Third, I think the code you're using for resetting is wrong. For example, when i = 0 and you reset the loop variables, you end up running the innermost loop with i = 0 and k = 0, which should never happen (since the invariant is k < i).

Fourth, I think that a method that takes something as a parameter, modifies it and then returns it is a code smell. One exception would be a fluent interface, but that doesn't seem to be your case, since the method is not an extension method.

Fifth, you should use normal .Net naming conventions (e.g. camelCase for local variables, instead of PascalCase).

Sixth, you should do all your time calculations in TimeSpans, instead of doubles representing minutes, because it's simpler.

Seventh, I think you could make your code more readable using LINQ.

The whole code would look something like:

public void ToolArrangment(List<LCycle> timeLineInit)
{
    foreach (var lifeCycle1 in timeLineInit)
    {
        bool repeat;
        do
        {
            repeat = false;

            var stages = (from stage1 in lifeCycle1.Stage
                          from lifeCycle2 in timeLineInit.TakeWhile(lc2 => lc2 != lifeCycle1)
                          from stage2 in lifeCycle2.Stage
                          from tool1 in stage1.ToolList
                          from tool2 in stage2.ToolList
                          where tool1.ToolName == tool2.ToolName
                          where IsTimeOverLaps(stage1.StageSpan, stage2.StageSpan)
                          select new { stage1, stage2 })
                .FirstOrDefault();

            if (stages != null)
            {
                var replaceStage = stages.stage1.DeepCopy();
                var timeDifference = replaceStage.StageSpan.ToTime - replaceStage.StageSpan.FromTime;
                replaceStage.StageSpan.FromTime = stages.stage2.StageSpan.ToTime;
                replaceStage.StageSpan.ToTime = replaceStage.StageSpan.ToTime + timeDifference;
                LCycleTimeShift(lifeCycle1, replaceStage);
                repeat = true;
            }
        } while (repeat);
    }
}

I gave it some thought and I think a much more efficient algorithm to do the same is not that difficult. You would have a hash table indexed by ToolName and for each tool, you would keep a list of all known stages that use it. You would walk though all tools in all stages in all timelines and add them to the list of stages for that tool. If you couldn't do that because of an overlap, you would move the stage, just like you do right now (if I understand your code correctly).

I haven't though out all the details, but I think something like this should work and be much faster than your solution.


Is this an ugly/incorrect usage of subscriptions?

I don't think your approach is fundamentally wrong: Rx is all about exposing and responding to streams of data. I do wonder though if any of this is necessary; doesn't the Observable.Select method do essentially what you are trying to do?


Mapping/parsing database table data to output data

The only thing I would change is the mapping definition, e.g. separate the configuration from the actual logic so you don't have to write many mappers, but can use one with multiple configurations.

Quoting http://martinfowler.com/eaaCatalog/metadataMapping.html

  Much of the code that deals with object-relational mapping describes how fields in the database correspond to fields in in-memory objects. The resulting code tends to be tedious and repetitive to write. A Metadata Mapping allows developers to define the mappings in a simple tabular form, which can then be processed by generic code to carry out the details of reading, inserting, and updating the data.

The dollars method probably shouldn't be in your mapper though, because it is formatting the data. Move this to the presentation layer. If you want to map to money, introduce a Money object.

You can spice it up by also introducing a TypeConverter thing which then knows how to handle certain types from the ColumnDefinition, e.g. something like

class FooMapDefinition implements IteratorAggregate
{
    private $map = [
        'someProperty' => [
            'mapTo': 'propertyName',
            'mapAs': Money::class
        ],
        // … more definitions
    ];

    public function getIterator()
    {
        return this new ArrayIterator($this->map);
    }

}

Then inject a TypeConverterFactory into the mapper. When you map the properties, you let the factory create a converter from the class name in mapAs, push the value from the source data through it and then map it to your entity.


I see a number of things that may help you improve your code.

Eliminate unused variables

Unused variables are a sign of poor code quality, so eliminating them should be a priority.  In this code, amount_of_letters is set to 0 but never actually used.

Use better function names

The name main might be find if this were a C program, but there is no requirement or advantage to using the name main in a Python program.  Instead, I'd name it something like hangman.

Fix bug #1

At some point, if one is unsuccessful in guessing the word, the program will display the message:

You have  0  chances left.
Guess a letter:

If I have 0 chances left, why am I being asked to guess again?

Fix bug #2

If the word contains multiple copies of the same letter, such as "maxim", if the user guesses a, x and m in that order, they'll see this:

Guess a letter: m
max__
max__

Use a list comprehension

You might not have studied Python long enough to learn about them, but I'd use a list comprehension here.  Instead of the for letter in word loop, I'd write this:

hidden_word = [guess if word[i]==guess else ch for i, ch in enumerate(hidden_word)]

This looks complex, perhaps, but it's actually pretty easy to understand once you've mastered list comprehensions.

Set the case for all letters

At the moment, if the user guesses 'M' but the word is 'nadim', the program will count that as a bad guess.  In the traditional hangman game, no distinction is made between capital and lowercase letters.  You might consider handling that for your program, such as by forcing all letters to be lowercase for example.

Use variables consistently

The guesses variable looks like it's supposed to be the maximum number of guesses allowed, but then we also see a hard-coded 5 in the program at the top of the loop.  Choose one (I'd prefer a named constant such as max_guesses) and stick with it.


Airline/Hotel reservation system in Python

One obvious issue is that all of the data for hotels and airlines is stored in the base Reservation class. You should move it to the relevant sub-classes, and I would store it as class attributes (shared by all instances) rather than instance attributes (unique to each instance), otherwise you won't be tracking the correct numbers of free rooms:

class Hotel(Reservation):

    HOTEL_ROOM = {'Penthouse': 10,
                  'King Deluxe Bedroom': 20,
                  'Queen Deluxe Bedroom': 20,
                  'King Standard Bedroom': 30,
                  'Queen Standard Bedroom': 50}

Also, as it stands, your code effectively makes the booking before it checks the availability. If you try to book something when it's already booked up, you should be raising an error. The customer is too closely tied to e.g. the Hotel - think about it in real terms, do you have the names of all of the customers when you build a new hotel?

A better option would be to create a new class structure:

Reservation

HotelReservation
AirlineReservation

Bookable

Hotel
Airline

Customer

All Bookables (which you could extend to e.g. CarHire in the future) would implement check_availability and make_reservation. To make it clear that the sub-classes should implement these, you can put a stub in the parent:

class Bookable(object):

    def check_availability(self, *details):
        raise NotImplementedError

    def make_reservation(self, *details):
        raise NotImplementedError

The sub-classes would then have information specific to that type (e.g. a Hotel would have rooms, an Airline seats, etc.) and their implementations of those methods would reflect that.

The Reservation would then connect the Customer to a Bookable (you might even find you don't need the sub-classes there - what's the difference between an airline reservation and a hotel reservation?) This would go both ways - a Hotel needs to know when to expect whom, and a Customer needs to know what they have booked.

Your code might now look like:

a1 = Airline("Qantas")
h1 = Hotel("Mayfair")
c1 = Customer("Arun", "Raman")

if a1.check_availability("Business Class", "07-07-2014"):
    r1 = a1.make_reservation(c1, "Business Class", "07-07-2014")

if h1.check_availability("Penthouse", "07-07-2014", "07-10-2014"):
    r2 = h1.make_reservation(c1, "Penthouse", "07-07-2014", "07-10-2014")

print(c1.bookings)

Looking at that, I'm thinking:

Could we cut the repetition of booking details? Perhaps introduce a Booking class? (e.g. b1 = Booking(c1, details) then for h in hotels: if h.check_availability(b1): h.make_reservation(b1))
Make the dates actual datetime objects, not strings.

But I will leave it there for now.


Am I correctly testing that methods from Kernel have been called?

I know MiniTest has an expectations framework, but I'm not familiar with it.  I use rspec-expectations to accomplish this, like so:

describe ClassName do
  let(:subject) { described_class.new }

  describe '#method' do
    it 'should sleep 3 times and output hello world' do
      expect(subject).to receive(:sleep).exactly(3).times
      expect(subject).to receive(:puts).with('Hello world!').exactly(3).times

      subject.method
    end
  end
end

I know this doesn't directly answer your question, but my hope is it leads you in the right direction.


Replace an element of a List with a concrete Id

I don't like your itemChanged and index variables.
If you iterate over a list and keep track of the index anyway, why don't you use an ordinary for-loop?
In addition to that, you also just copy the value of your index variable and break out of the loop; you could easily merge all that to one loop with one condition.
This:

    int itemChanged = -1;
    int index = -1;
    for (Suggestion suggestionItem : mSuggestions) {
        index++;
        if(suggestionItem.getId() == suggestion.getId()){
            itemChanged = index;
            break;
        }
    }
    if (itemChanged != -1) {
        mSuggestions.set(itemChanged, suggestion);
        notifyItemChanged(itemChanged);
    }

would become this:

for (int index = 0; index < mSuggestions.size(); index++) {
    if(mSuggestions.get(index).getId() == suggestion.getId()){
        mSuggestions.set(index, suggestion);
        notifyItemChanged(index);
        break;
    }
}

You don't even need to check if there is an item to replace, because if the condition is never met, it's never going to execute the code inside of it.


On PowerShell v6+, I would do the following:
$String = $Fragment1, $Fragment2 |
    Where-Object { -not [System.String]::IsNullOrWhiteSpace($_) } |
    Join-String -Separator $Separator

You could use [System.String]::IsNullOrEmpty() instead of [System.String]::IsNullOrWhiteSpace(), but I find [System.String]::IsNullOrWhiteSpace() to be the desired functionality in almost all cases.
On Windows PowerShell (versions prior to v6), the Join-String command doesn't exist. There I would use:
$String = ($Fragment1, $Fragment2 |
    Where-Object { -not [System.String]::IsNullOrWhiteSpace($_) }) -join $Separator

The @().Where({ ... }) method is fairly obscure, so I tend to avoid it.

it may not be clear to everybody what the semantics of $_ are.

I'm not sure it's valuable to consider this possibility. Simply put, if your reader doesn't understand the semantics of $_, then they cannot read PowerShell. It's a ubiquitous and pervasive variable both in practice and in design.


There's no need to roll your own: the library support is there.

public static int convertBits(int a, int b) {
    return Integer.bitCount(a ^ b);
}

For what it's worth, I don't think convertBits is a very descriptive name for the method. I'd suggest something like countBitDifferences.


Using state transitions to filter C comments

In all, this looks like pretty solid code.  I have just a few suggestions that may help you improve your code.

Use an enum for related constants

The states are all related and not just standalone constants.  For that reason, I'd recommend encapsulating them all in an enum:

enum { NORMAL, SINGLE_QUOTE, DOUBLE_QUOTE, SLASH, MULTI_COMMENT, INLINE_COMMENT, STAR } state_e;

Restructure or comment to make the code easier to read

The most significant feature in the code is a state machine.  In order to understand a state machine, I typically need to know what's being processed (an input C program), what the states are (which are enumerated) and how the code transitions from state to state.  The last bit is the part that is a little tough to decipher.  It's probably mostly right, but it's hard to decode.  For instance, see how long it takes you to answer the questions, "How does the code enter the SLASH state?", "How does it leave the SLASH state?"

Don't forget about line continuation

The \ character is a line continuation character in C.  One effect it can have that affects this program is to continue a single-line comment:

// BAD is never defined \
#define BAD 1

Don't forget about trigraphs

Many people either don't use or don't know about trigraphs but they exist and, for better or worse, are still part of the language. This affects this particular program because the ??/ is the trigraph for \ which is the line continuation character.  Related to the preceding comment, BAD is never defined in this code fragment:

// are you surprised??/
#define BAD 1


Insertion sort revised with output to console

One obvious optimization is to avoid many unnecessary swaps:

        int j;
        value_to_insert = inputArray[i];
        for (j = i; j > 0; j--)
        {
            if (inputArray[j - 1] > value_to_insert)
            {
                inputArray[j] = inputArray[j - 1];
            }
        }
        inputArray[j] = value_to_insert;

Just one assignment instead of 3.

Besides (sorry for repeating my mantra on a naked loops), now it becomes obvious that an inner loop implements some sort of a shift algorithm. Better to factor it out.

It is also very well possible that separating find and shift phases may also speed it up:

        value_to_insert = inputArray[i];
        int j = upper_bound(inputArray, inputArray + i, value_to_insert);
        shift(inputArray + j, input_array + i, 1);
        inputArray[j] = value_to_insert;

because both methods could be implemented as intrinsics.


Router should not accept request object in constructor. You will need a new router for each request.
I know PHP spawns a new process for each request so it gets created for each request anyway. But in tests it may be different...
And anyway it doesn't make much sense to hide the request inside the router from the logical point of view.
Hiding a constructor dependency means that the dependency is an implementation detail. And sure you agree that request is not just an implementation detail of a router. It is the input for routing.
Also the route should not be aware of how to determine controller class and surely it doesn't want to know or, and thats even worse, force no constructor arguments for all controllers. There should be a controller factory that knows the details.
And you don't want to pass controller factory to every route. So maybe instead, route should just define path mapping and controller factory should take a route as an input. Router would then pass the matched route to the controller factory.
Another thing is that the addRoute method doesn't really belong on a router, it belong on a router builder. You register routes on the builder and finalize by calling it's createRouter method.
What's entirely missing in your code is an "application" class - that's the one where run method belongs, not the router, router should really have a method that accepts request object and returns response object. Application might have a request factory, the router and some kind of response emitter which takes the response object returned by router and send it's representation to the client.


An ultimate speedup is achieved by preprocessing the dictionary one step further, into the binary format. Group the words of the same hashcode together, and prepare a TOC as an array of file offsets of each such group at the beginning of the file. This way the dictionary loads in a single fread() (you may also want to account for endianness with bit more sophisticated format).

I also found strange that you add nodes at the end of the list. Unless you have a very strong reason of doing so, crawling lists is a pure waste of time. Inserting node at the head unconditionally may - or may not - gain some performance, depending of the quality of the hash.

That said, I may only reiterate on the @Edward comment: profile the code.


tl;dr: If you are planning on adding more methods to each of these classes, then use them. If not, then don't.

One of the first things you should check when deciding whether to use a class or not, is if the class has two or less methods, __init__, and another function. Since your code doesn't like complete quite yet, I'm making the assumption that there will be more functions added to each of these classes.

Now, I do have a few things about your code that I want to point out. Here's a list of small things you could improve.

Class names should be in PascalCase. Not lowerCasePascalCase.
There should be two blank lines between each class/function/code block on the top level of your file.
You have a blank line before each of your class declarations. Preferably, you should either, put a docstring here, or, remove the blank line.

If you want to make sure that your code is PEP8 compliant, you can visit PEP8's page here, or use this online PEP8 checker here. If you want a checker on your local machine, you can just run pip install pep8, and to update, you can run pip install --upgrade pep8.


Changing element visibility based on multiple checkbox states

First iteration

You neglected to localize i.

I'd like to rewrite the statements to make it more obvious that the visible flag is something that can be falsified by each if condition.

function filterServices() {
    var download = document.getElementById('download').checked;
    var free = document.getElementById('free').checked;
    var pay = document.getElementById('pay').checked;
    var audio = document.getElementById('audio').checked;
    var video = document.getElementById('video').checked;
    var offline = document.getElementById('offline').checked;

    for (var i = 0; i < serwisy.length; i++) {
        var serwis = serwisy[i];
        var visible = true;

        if (download) { visible = visible && (serwis[2] == 1); }
        if (audio)    { visible = visible && (serwis[3] & (1 << 1)); }
        if (video)    { visible = visible && (serwis[3] & (1 << 2)); }
        if (offline)  { visible = visible && (serwis[3] & (1 << 3)); }
        if (free)     { visible = visible && (serwis[4] & (1 << 1)); }
        if (pay)      { visible = visible && (serwis[4] & (1 << 2)); }

        document.getElementById(serwis[0]).style.visibility = visible ? "visible" : "hidden";
    }
}

Second iteration

Let's make it even more obvious by combining everything into one giant conjunction.

function filterServices() {
    var download = document.getElementById('download').checked;
    var free = document.getElementById('free').checked;
    var pay = document.getElementById('pay').checked;
    var audio = document.getElementById('audio').checked;
    var video = document.getElementById('video').checked;
    var offline = document.getElementById('offline').checked;

    for (var i = 0; i < serwisy.length; i++) {
        var serwis = serwisy[i];
        var visible = (!download || (serwis[2] == 1)))
                   && (!audio    || (serwis[3] & (1 << 1)))
                   && (!video    || (serwis[3] & (1 << 2)))
                   && (!offline  || (serwis[3] & (1 << 3)))
                   && (!free     || (serwis[4] & (1 << 1)))
                   && (!pay      || (serwis[4] & (1 << 2)));

        document.getElementById(serwis[0]).style.visibility = visible ? "visible" : "hidden";
    }
}

Third iteration

But that looks like a mess, especially since the bit operations take a bit of thinking to understand.  Let's add some readability back in by introducing functions to explain the bit operations.

function filterServices() {
    var wantDownload = document.getElementById('download').checked;
    var wantFree     = document.getElementById('free').checked;
    var wantPay      = document.getElementById('pay').checked;
    var wantAudio    = document.getElementById('audio').checked;
    var wantVideo    = document.getElementById('video').checked;
    var wantOffline  = document.getElementById('offline').checked;

    function hasDownload(serwis) { return serwis[2] == 1; }
    function hasAudio(serwis)    { return serwis[3] & (1 << 1); }
    function hasVideo(serwis)    { return serwis[3] & (1 << 2); }
    function hasOffline(serwis)  { return serwis[3] & (1 << 3); }
    function hasFree(serwis)     { return serwis[4] & (1 << 1); }
    function hasPay(serwis)      { return serwis[4] & (1 << 2); }

    for (var i = 0; i < serwisy.length; i++) {
        var serwis = serwisy[i];
        var visible = (!wantDownload || hasDownload(serwis))
                   && (!wantAudio    || hasAudio(serwis))
                   && (!wantVideo    || hasVideo(serwis))
                   && (!wantOffline  || hasOffline(serwis))
                   && (!wantFree     || hasFree(serwis))
                   && (!wantPay      || hasPay(serwis));

        document.getElementById(serwis[0]).style.visibility = visible ? "visible" : "hidden";
    }
}

I have to say, though, that the serwisy data structure doesn't seem well designed.  Consider changing it from a two-dimensional array to an array of objects with reasonable names for the keys, so that you can write things like serwisy[i].elementId instead of serwisy[i][0].


Adding object to database, using linq or sql connection

As @ckuhn203 pointed out, the naming is pretty misleading, but it seems like your domain model calls that entity a Delegate. To dissipate ambiguity I'd call it something like DelegateEntity.

One convention in modeling, is to keep types singular, since an entity represents one single row in that tblDelegates table.

Now, in your insert code, the del instance is not needed. Leaves us with this (notice the name changes) - I'd recommend passing in your connection string to the context's constructor, instead of relying on the one in the designer:

    var context = new LinqToSqlDataContext(connectionString);
    var item = new tblDelegate
    {
        Pending = true,
        Manager_Alias = row.Cells[4].Text,
        Manager_Name = row.Cells[1].Text + " " + row.Cells[2].Text,
        Delegate_Alias = ADLookup.AD("alias"),
        Delegate_Name = ADLookup.AD("GivenName") + ADLookup.AD("sn"),
        Delegate_Email = ADLookup.AD("mail"),
        Created_User = ADLookup.ADCurrentUser(),
        Created_Dttm = DateTime.Now,
        Updated_User = ADLookup.ADCurrentUser(),
        Updated_Dttm = DateTime.Now // shouldn't this one be null?
    };

    context.tblDelegates.InsertOnSubmit(item);
    context.SubmitChanges();

A very important thing to keep in mind, is that a data context implements an interface called IDisposable, which means any instance of that type should be properly disposed, either by explicitly calling its .Dispose() method, or (the better way) by wrapping its usage inside a using block:

using (var context = new LinqToSqlDataContext())
{
    var item = new tblDelegate
    {
        Pending = true,
        Manager_Alias = row.Cells[4].Text,
        Manager_Name = row.Cells[1].Text + " " + row.Cells[2].Text,
        Delegate_Alias = ADLookup.AD("alias"),
        Delegate_Name = ADLookup.AD("GivenName") + ADLookup.AD("sn"),
        Delegate_Email = ADLookup.AD("mail"),
        Created_User = ADLookup.ADCurrentUser(),
        Created_Dttm = DateTime.Now,
        Updated_User = ADLookup.ADCurrentUser(),
        Updated_Dttm = DateTime.Now // shouldn't this one be null?
    };

    context.tblDelegates.InsertOnSubmit(item);
    context.SubmitChanges();
}

The context instance only exists within the using scope, and when the code exits that scope, context.Dispose() gets called, implicitly. Make it a habit to always put IDisposable instances in a using block.

Other than that, you're not following the naming convention for parameters: alllowercase is hard to read - should be camelCase:

public Delegates(bool pending, string managerAlias, string managerName, string delegateAlias, string delegateName, string delegateEmail)
{
    Pending = pending;
    ManagerAlias = managerAlias;
    ManagerName = managerName;
    DelegateAlias = delegateAlias;
    DelegateName = delegateName;
    DelegateEmail = delegateEmail;
}

But, instead of having a constructor with [potentially] dozens of parameters, you should simply remove all constructors (the parameterless one is there by default), and instantiate a Delegates like this instead:

var delegates = new Delegates {
                                  Pending = true,
                                  ManagerAlias = "foo",
                                  ManagerName = "bar",
                                  DelegateAlias = "_foo",
                                  DelegateName = "_bar",
                                  DelegateEmail = "foo@bar.com"
                              };

This syntax is the object initializer syntax - notice that you don't need to specify the () after new Delegates, because the syntax is calling the type's default constructor and the compiler knows this, so ()'s are redundant. Of course this syntax can't work if your type doesn't have a default, parameterless constructor.

If you have a linq-to-sql data context, you probably have a designer with a .dbml too; in there you can specify new, more C#-friendly names for tblDelegates and its columns, LINQ-to-SQL uses the read-only Source property to know which column it's referring to - this means you can have a table called SOME_UGLY_NAME in your SQL backend, and refer to it as SomeMuchBetterName in your C# code!

...this also means tblDelegates can be mapped to DelegateEntity ;)


You can use some ES6 functions and have something like:

var s = 'HEL-CAS|MAD-STO|XXX-YYY';
var s1 = [];
var s2 = []

for (var v of s.split('|').map(str => str.split('-'))) {
  s1.push(v[0])
  s2.push(v[1])
}

s1.join('|')
s2.join('|')


Chain-of-Responsibility in C++11 using smart pointers

First nit: boss and supervisor strike me as basically synonymous. So it's kind of confusing that you're using both of them as identifiers in your program. Are these identifiers supposed to be meaningful, or are they just placeholders like Alice or Bob?

Also a nit: If your destructor doesn't do anything, don't write it.

virtual  ~Boss() override {}

is just a waste of characters. (The definition of ~Handler() is important because you have to hang the virtual specifier on it; but the definition of ~Boss() is perfectly redundant.)

//receivers may be released at run time.
boss.reset();

I think I don't get it. If this line had instead read supervisor.reset(), wouldn't boss have become unreachable, as far as handling requests was concerned? (Because requests go first to agent; then to agent->m_successor if it's non-null; but supervisor is gone, so handling just stops there.)

This seems like a bug in your design.

void handle(Event e) override {
    // ...
            ptr->handle(e);

This function call makes a copy of Event e, which might be expensive since Event contains an arbitrarily long std::string. You could fix this in either of two ways: either by changing the function signature to

void handle(const Event& e)

(throughout the whole hierarchy, of course), or else by changing the function call to

            ptr->handle(std::move(e));  // move, don't copy

I know you said "performance isn't a concern", but any time you're using exception handling for control flow you should really reconsider your design. Instead of throwing and catching bad_weak_ptr, I'd recommend

    if (std::get<0>(e) == 1) {
        std::cout << "Agent handled the request: " + std::get<1>(e) << std::endl;
    } else if (auto ptr = m_successor.lock()) {
        ptr->handle(e);
    } else {
        std::cout << "No successor handler" << std::endl;
    }

As for how your list of handlers should be defined: almost certainly you should just use a list of handlers (i.e. std::list<Handler> — or std::list<std::weak_ptr<Handler>> if you really want to keep your original design's ability to have handlers drop out of the list at random).

I don't think that a Handler ought to have any idea of its parent; unless... do you think that the parent of a given handler is part of its "identity"? For example, in my example above, do you think it does actually make sense that if an Agent's Supervisor dies, the Agent would have no way of contacting his late Supervisor's Boss, so certain requests would go unhandled? If that really is a feature-not-a-bug, then okay.

Lastly, even if everything else about this design were good, it's unsettling how easy it would be for someone to write a Handler class that just dropped messages on the floor.

class Stockboy : public Handler {
public:
    Stockboy(std::shared_ptr<Handler> successor = nullptr) :Handler(successor) {}
    void handle(Event e) override {
        if (std::get<0>(e) == 7) {
            std::cout << "Stockboy handled the request: " + std::get<1>(e) << std::endl;
        }
    }
};

IMO, it would be better to take the responsibility for forwarding unhandled messages and move that responsibility right out of the Handler class. Give it to a Dispatcher class whose job is to find the right Handler and call it. The Dispatcher might hold a mapping of ints to handlers so that it could find the right recipient quickly; or it might just query each handler in turn until some handler reports success.


Since all that is different about the two if/else bodies is the arguments to the fnFilter method, you can construct the difference in one if statement and then use that in one copy of the code rather than two.

/*
 * By default this is a global search box events. Global being searchable across all columns.
 * But if an int is provided as an input then it will apply the search only on that column.
 * */
_bindSearchEvents: function (onColumnIndex) {

    var self = this;
    var args = [];
    if (Math.ceil(onColumnIndex) === Math.floor(onColumnIndex)) {
        args.push(onColumnIndex);
    }
    self.settings.search.input.live('keyup', function () {
        var argsCopy = [].concat(args);           // make copy of args
        argsCopy.unshift($(this).val());      // push item onto front of args
        self.widget.fnFilter.apply(self.widget, argsCopy);
    });

    self.settings.search.reset.live('click', function () {
        self.settings.search.input.val("");
        var argsCopy = [].concat(args);
        argsCopy.unshift("");                 // push item onto front of args
        self.widget.fnFilter.apply(self.widget, argsCopy);
    });
},

If the fnFilter function is written to check to see if the second parameter is null (rather than checking the number of arguments passed), then this shorter version could work also, but we'd have to see what the fnFilter documentation says or how the fnFilter source code actually works to know if this shorter method would work:

/*
 * By default this is a global search box events. Global being searchable across all columns.
 * But if an int is provided as an input then it will apply the search only on that column.
 * */
_bindSearchEvents: function (onColumnIndex) {

    var self = this;
    var index = null;
    if (Math.ceil(onColumnIndex) === Math.floor(onColumnIndex)) {
        index = onColumnIndex;
    }
    self.settings.search.input.live('keyup', function () {
        self.widget.fnFilter($(this).val(), index);
    });

    self.settings.search.reset.live('click', function () {
        self.settings.search.input.val("");
        self.widget.fnFilter("", index);
    });
},


Move files to specific directory, according to file extension

I have no idea, how to make it simpler. I could only offer an alternative:

#!/usr/bin/env python

import os
import shutil

fullpath = os.path.join
python_directory = "./py"
start_directory = "./mixed"
text_files = "./txt"

def main():
    for dirname, dirnames, filenames in os.walk(start_directory):
        for filename in filenames:
            source = fullpath(dirname, filename)
            if filename.endswith("py"):
               shutil.move(source, fullpath(python_directory, filename))
            elif filename.endswith("txt"):
                shutil.move(source, fullpath(text_files, filename))

if __name__ == "__main__":
    main()

I think os.walk()is what you are looking for.


First, there would be much duplication between the parser classes. This kind of duplication should be avoided. If you find a bug in the way the csv is being parsed, you now have to fix it in multiple places. Consider using the template method pattern. In this scenario, you would extract the common logic into an abstract superclass with 1 or more abstract "template methods" that would be implemented by the subclasses. For instance, the abstract superclass could parse the fields into an array or strings, then pass the array to a method to construct an object using those fields.

public abstract class AbstractCSVParser<T> implements CSVParser<T> {

    public List<T> parseCSVFile(String fileName) {
        List<T> list = new ArrayList<T>();

        // for each line...
        String[] fields = // parse line into an array of strings
        T obj = buildObject(fields);
        list.add(obj);

        return list;
    }

    protected abstract T buildObject(String[] fields);

}

public class csvBParser extends AbstractCSVParser<ObjectB> {

    protected ObjectB buildObject(String[] fields) {
        ObjectB obj = new ObjectB();
        // populate object with fields
        return obj;
    }

}

In the parsing code, the InputStream and BufferedReader are never closed. Make sure you close resources when you are done with them, and make sure it is happening inside a finally block.

BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
    // do work with br
}
finally {
    br.close();
}

If you are using Java 7, you should check out the try-with-resources statement. The above example could be written like this:

try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
    // do work with br
} // close is called automatically at the end of the try block

In this example, the parser classes appear to be stateless. Given this, CSVParserFactory doesn't really need to return a new instance every time. One option to simplify CSVParserFactory is to initialize a static Map containing the parser instances.

public class CSVParserFactory {

    private static final Map<TableType, CSVParser> PARSERS = new HashMap<TableType, CSVParser>() {{
        put(A, new csvAParser());
        put(B, new csvBParser());
        put(C, new csvCParser());
        // etc
    }};

    public static CSVParser getParser(TableType type) {
        CSVParser parser = PARSERS.get(type);
        if (parser == null) {
            throw new IllegalArgumentException("No such table type");
        }
        return parser;
    }

}

If you don't want this, and still want to create the parser instances each time, you could use the same strategy with the class names instead of instances, then create the instance using reflection.

Finally, you may want to consider passing an InputStream to parseCSVFile instead of a file name. This would allow more flexibility of the source of the data. The current implementation is very specific as to the source.


My initial thought is that you don't :)

The whole idea behind the enum approach starts from your premise:

  Since everything is known from the start I tend to use enum

Which means you're dealing with a specific set with it's own rules and checks that you put into that enum.

If you were to start from the idea of reusing code to represent different kinds of sets you wouldn't go for enums (or static finals for that matter).
That requires a completetly different design.

In this case I'll point out Martin Fowler's rule of three.

More specifically, you should only consider refactoring this for reusability if you actually want to reuse it in the first place.

Also: copy-pasting some code isn't a deadly sin. It's only a bad smell, that you have to decide to remove or not.


Calculate someone's pay, including overtime

You should use better variable names, for a start.... consider:

public static double pay(double hourlyWage, int hours) {
    ...
}

Then, your code is not that bad (with some indentation fixes too):

public static double pay(double hourlyWage, int hours) {
    if (hours > 8) {
        return (hourlyWage * 8) + ((hours - 8)*(hourlyWage * 1.5));
    }
    else {
        return (hourlyWage * hours);
    }
}

There is no good way to handle the overtime rate other than with a conditional somewhere. Ternary conditions may help a bit.....

public static double pay(double hourlyWage, int hours) {
    int regular = hours > 8 ? 8 : hours;
    int overtime = hours - regular;
    return hourlyWage * (regular + (1.5 * overtime));
}


Keyboard handler for moving in four directions

Your code is rather short, but can still be greatly improved.

  Should I keep the default: break; or not?

Do not keep it. Since you aren't doing anything for the default case, there is no point in having it. You can remove that entire thing.

Map

In order to improve the readability of your code (and overall efficiency), I recommend creating a map that maps the key code values to the changes needed to be made to dx and dy. Here is what I mean:

var keyToChangeMap = {
    87: [0, -50], // [change in x, change in y]
    65: [-50, 0]
    ...
};

Now, you have an \$O(1)\$ method for finding out how to change the dx and dy values. This is also flexible: you can easily change the values that x and y change by, and you can easily add more keys to listen to.

Then, in your function, simply use the key code to get a value from the map:

function handleKeyDownEvent(event) {
    var keyCode = event.keyCode;
    if(keyToChangeMap.hasOwnProperty(keyCode)) {
        var change = keyToChangeMap[keyCode];
        player.dx += change[0];
        player.dy += change[1];
    }
}

Magic numbers

You have some magic numbers in your code. It's pretty difficult to understand these numbers, so you should create constants to represent these values.

For example,

var W_KEY = 87;
var A_KEY = 65;

You don't even have to be that specific. You can do something like this:

var UP_KEY = 87;
var LEFT_KEY = 65;

which is even more readable.


Implementing a method that escapes single quotes in a string

I'd suggest a Solution based on regular expressions like this:
import static org.junit.Assert.assertThat;

import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hamcrest.CoreMatchers;
import org.junit.Test;

public class EscapeQuotesTest {

    Pattern escapedQuotePattern = Pattern.compile("(\\\\)?(')(')");

    private String escapeString(String input) {
        Matcher escapedQuote = escapedQuotePattern.matcher(input);
        escapedQuote.find();
        Optional<String> escapeChar = Optional.ofNullable(escapedQuote.group(1));
        String result = String.format("%s%s\\'%s", escapeChar.orElse(""), escapedQuote.group(2), escapedQuote.group(3));
        return result;
    }

    @Test
    public void preseveLeadingBackslash() {
        String input = "\\''";
        String result = escapeString(input);
        assertThat(" The escape char survived", result, CoreMatchers.containsString("\\'\\''"));
    }

    @Test
    public void noLeadingBackslash() {
        String input = "''";
        String result = escapeString(input);
        assertThat("no escape char at beginning", result, CoreMatchers.containsString("'\\''"));
    }
}


Cases like this I would hide the "sloppy"

I would create a class that holds the mappings from the class to the table and create methods to build the mappings.  This way there is no need for reflection and we can save the funcs to be reused.

public class Mapper<TSource>
{
    private readonly DataTable _source = new DataTable();
    private readonly List<Func<TSource, object>> _mappings = new List<Func<TSource, object>>();

    public Mapper<TSource> Configure<TProperty, TData>(Func<TSource, TProperty> property, string colName,
        Func<TProperty, TData> mapper)
    {
        _source.Columns.Add(colName, typeof (TData));
        Func<TSource, object> map = s => mapper(property(s));
        _mappings.Add(map);
        return this;
    }

    public Mapper<TSource> Configure<TProperty>(Func<TSource, TProperty> property, string colName)
    {
        _source.Columns.Add(colName, typeof(TProperty));
        Func<TSource, object> map = s => property(s);
        _mappings.Add(map);
        return this;
    }

    public Mapper<TSource> Configure<TData>(string colName, Func<TData> mapper)
    {
        _source.Columns.Add(colName, typeof(TData));
        Func<TSource, object> map = _ => mapper();
        _mappings.Add(map);
        return this;
    }

}

With this class we now have a datatable in _source that holds the columns that we want and a list of mappings from our source to the datatable.   Now we just need to create a ToDataTable method to use these in the same class.

public DataTable ToDataTable(IEnumerable<TSource> items)
{
    // make a new datatable with the same columns as the source
    var dt = _source.Clone();

    foreach (var item in items)
    {
        dt.Rows.Add(_mappings.Select(f => f(item)).ToArray());
    }

    return dt;
}

We would use it like so.  Typically you would only do the configurations once and then just reuse it with different lists.

var inputClassMapper = new Mapper<InputClass>();
inputClassMapper.Configure(f => f.SomeField, "ColA", s => $"{s}ABCD")
                .Configure("ColB", () => DateTime.Now);

// have mapper convert input to datatables
var dt = inputClassMapper.ToDataTable(list);


My Sal's Shipping challenge on Codecademy

Ok, first of all you should've take care of variable names. Naming them like p, g, e, etc is really a bad habbit.

Once you change them, it's much easier to read.

def cost_calc(weight):
  ground_cost = calculate_ground_cost(weight)
  drone_cost = calculate_drone_cost(weight)
  premium_cost = 125
  ground_shipping_name = "Ground Shipping"
  premium_shipping_name = "Premium Ground Shipping"
  drone_shipping_name = "Drone Shipping"

Second python naming convention tells you to use underscores while naming variables or functions.

Third, your functionc that calculates costs can be minimized in many ways, when one of them is:

import bisect

def calculate_ground_cost(weight):
  limits = [2, 6, 10]
  multipliers = [1.5, 3, 4, 4.75]
  idx = bisect.bisect_left(limits, weight)
  return (weight * multipliers[idx]) + 20

def calculate_drone_cost(weight):
  limits = [2, 6, 10]
  multipliers = [4.5, 9, 12, 14.25]
  idx = bisect.bisect_left(limits, weight)
  return (weight * multipliers[idx])

Then you should take care of IFs statements that are really messy.

if drone_cost == ground_cost or drone_cost == premium_cost or ground_cost == premium_cost:

Is equvalent to

if drone_cost == ground_cost == premium_cost:

And the next rule good to follow is always return ASAP.

if drone_cost == ground_cost == premium_cost:
    return "All shipping method cost %s according to your items weight" % premium_cost

Then all of this mess:

if  d == g and d == p:
      print("All shipping methods cost $125 according to your items weight")
      return
    if d == g:
      same1 = dS
      same2 = gS
      cost = d
    if d == p:
      same1 = dS
      same2 = pS
      cost = d
    if g == p:
      same1 = gS
      same2 = pS
      cost = g
    print("Youre cheapest shipping method is "+same1+" and "+same2+" as they both cost $"+str(cost))
    return

Can be changed to

if ground_cost == drone_cost:
    return "Youre cheapest shipping method is %s and %s as they both cost$%s" %(ground_shipping_name, premium_shipping_name, ground_cost)

Because this is the last "IF" that is matching the statement.

And at the end, where u try to determine what is the lowest cost:

  elif (g < d) and g < p:
    cheapMeth = gS
    cost = g
  elif (p < d) and p < g:
    cheapMeth = pS
    cost = p
  elif (d < g) and d < p:
    cheapMeth = dS
    cost = d
  print("Youre cheapest shipping method is "+cheapMeth+" costing $"+str(cost))
  return

You can change it to

costs = sorted([
   (ground_cost, ground_shipping_name),
   (drone_cost, drone_shipping_name),
   (premium_cost, premium_shipping_name)])

min_cost, method = costs[0]
return "Your cheapest shipping method is %s costing $%s" % (method, min_cost)

So at the end, your code look like:

import bisect

def calculate_ground_cost(weight):
  limits = [2, 6, 10]
  multipliers = [1.5, 3, 4, 4.75]
  idx = bisect.bisect_left(limits, weight)
  return (weight * multipliers[idx]) + 20

def calculate_drone_cost(weight):
  limits = [2, 6, 10]
  multipliers = [4.5, 9, 12, 14.25]
  idx = bisect.bisect_left(limits, weight)
  return (weight * multipliers[idx])

def cost_calc(weight):
  ground_cost = calculate_ground_cost(weight)
  drone_cost = calculate_drone_cost(weight)
  premium_cost = 125
  ground_shipping_name = "Ground Shipping"
  premium_shipping_name = "Premium Ground Shipping"
  drone_shipping_name = "Drone Shipping"
  if drone_cost == ground_cost == premium_cost:
    return "All shipping methodrone_shipping_name cost $125 according to your items weight"

  if ground_cost == drone_cost:
    return "Youre cheapest shipping method is %s and %s as they both cost$%s" %(ground_shipping_name, premium_shipping_name, ground_cost)

  costs = sorted([
    (ground_cost, ground_shipping_name),
    (drone_cost, drone_shipping_name),
    (premium_cost, premium_shipping_name)])

  min_cost, method = costs[0]

  return "Your cheapest shipping method is %s costing $%s" % (method, min_cost)

weight = int(input("Enter weight: "))
print(cost_calc(weight))


To get rid of !! here, you can use it earlier and earlier until you never even generate an Int.

-- | Given 'key' & 'msg' generate a list of [Maybe Int] indices
-- to map 'msg' from 'key', skipping invalid characters
toIdx :: Key -> Msg -> [Maybe Char]
toIdx k m = toIdx_ (cycle $ map toUpper k) m
  where toIdx_ :: Key -> Msg -> [Maybe Char]
        toIdx_ _ "" = []
        toIdx_ key@(k:ey) (c:cs)
          | isValid c = Just k : toIdx_ ey cs
          | otherwise = Nothing : toIdx_ key cs

-- | Given 'key' & 'msg' generate a list of numbers representing
-- the amount to shift 'msg' characters based on 'key'
toShifts :: Key -> Msg -> [Int]
toShifts k m = map toKey (toIdx k m)
  where toKey :: Maybe Char -> Int
        toKey Nothing  = 0
        toKey (Just x) = ord x - ord 'A'

Of course, there is hardly a need to separate all these steps.

base :: Char -> Maybe Char
base c
  | 'a' <= c && c <= 'z' = Just 'a'
  | 'A' <= c && c <= 'Z' = Just 'A'
  | otherwise = Nothing

vigenere, unVigenere :: String -> String -> String
[vigenere, unVigenere] = (`map` [(+), (-)]) $ \direction k ->
  (.) snd $ (`mapAccumL` cycle k) $ \key@(k:ey) c -> case base c of
    Nothing -> (key, c)
    Just a -> (,) ey $ chr $ ord a +
      mod ((ord c - ord a) `direction` (ord (toUpper k) - ord 'A')) (ord 'Z' - ord 'A')


Join a JSON object of arrays and reduce down to one key

Review

I'm not a big fan of importing other libraries when a built-in alternative is available.

const R = require('ramda')

R.keys could be replaced by Object.keys:

const associatedNumber = Object.keys(heightsMap)
  .filter(key => heightsMap[key]
  .includes(height))[0]

Two improvements can be made. First, you're using filter which iterates all elements. This is a pity, since you're only interested in the first item [0]. Find is the method you were looking for. Second, You're traversing keys to perform another lookup heightsMap[key]. This could be done in a single iteration using Object.entries.

Proposed Rewrite

const associatedNumber = Object.entries(heightsMap)
  .find(([key, value]) => value.includes(height))[0];

console.log(associatedNumber);

Note that [0] in the refactored code gets the key of [key, value].


Checkbox binding to change the ListView's items source

You should probably bind ItemsSource to CollectionView, instead of binding to ObservableCollection. This way you don't have to recreate collection every time you want to apply your filter. May look like this:

//constructor
Parts = new ObservableCollection<EditPartViewModel>(allpvms);
PartsCollectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(Parts);

...............

public ListCollectionView PartsCollectionView { get; private set; }

public bool ErrorParts
{
    get
    {
        return _errorParts;
    }
    set
    {
        _errorParts = value;
        OnPropertyChanged("ErrorParts");
        PartsCollectionView.Filter = value ? (Predicate<Object>)(p => ((EditPartViewModel)p).Price == null) : null;
    }
}

Also if your viewmodles can contain errors, you should probably move your error-checking logic inside those viewmodels. So instead of writing p.Price == null you would write p.HasErrors or something.

You should also indicate, that ErrorParts is actually a bool property, unlike AllParts which is a collection. DisplayErrors or ShowErrors or FilterErrors etc. are better names for this property in my opinion.


One thing I'd change is to not use args everywhere. You use the name "n" in the problem description, so I'd use that in the program as well. Reading args only once, to store the value in n.
Your getones function is rather lengthy and inefficient, taking O(n2) time to build the string. Although the rest of the program can't handle large n anyway, so efficiency doesn't really matter here. (And maybe the conversion to int takes quadratic time, not sure.)
Here's a shorter solution:
e = sum(map(log10, range(int('1' * n), 0, -n)))
print('%.2fe%d' % (10**(e % 1), e // 1))

Demo:
>>> n = 9
>>> from math import log10
>>> e = sum(map(log10, range(int('1' * n), 0, -n)))
>>> print('%.2fe%d' % (10**(e % 1), e // 1))
9.22e93968682

Comparison with yours (at repl.it) for n=9, same result and mine's about three times as fast:
n = 9
yours:
9.22e93968682
0:00:11.911943
mine:
9.22e93968682
0:00:03.964518

We have a different result for example for n=2:
n = 2
yours:
1.03e4
0:00:00.011884
mine:
1.04e4
0:00:00.000085

The exact result is:
>>> math.prod(range(11, 0, -2))
10395

So I'd say yours isn't rounding correctly.


You can remove the toString() bit from here:
  let [int, dec] = inputNumber
    .toString()
    .split(".")
    .map((el) => parseInt(el));

toFixed returns a string. So, there is no need to call toString again.

The calculation part:
If the decimal part is 12, your output is 3/25. How do you get this? You get the greatest common divisor between 12 and 100 and divide both of them with it. GCD of 12 and 100 is 4. So, (12/4) / (100/4)
There's already a simple recursive implementation of euclidean algorithm for that:
function gcd(a, b)
    if b = 0
        return a
    else
        return gcd(b, a mod b)

You can get the precision required as an option parameter which defaults to a predefined MAX_PRECISION. Get the GCD between the dec and 10 precision (eg: 100 for precision = 2)

const MAX_PRECISION = 5

function toFraction(inputNumber, precision = MAX_PRECISION) {
  let [int, dec] = inputNumber
                      .toFixed(precision)
                      .split(".")
                      .map(n => +n)

  const powerOf10 = 10 ** precision,
        gcd = getGCD(dec, powerOf10),
        fraction = `${dec/gcd}/${powerOf10/gcd}`;

  return int ? `${int} ${fraction}` : fraction
};

function getGCD(a, b) {
  if (!b) return a;

  return getGCD(b, a % b);
};

console.log( toFraction(1.14)   );
console.log( toFraction(5.71)   );
console.log( toFraction(3.34)   );
console.log( toFraction(5.1044) );
console.log( toFraction(0.67)   );
console.log( toFraction(0.84)   );


Write the running time to file without capturing the program's output

Kudos

It's good to see appropriate quoting and correct use of "$@" in these shell scripts.  Although the samples are short, it's still good to see nice readable code.

Problems with the first approach

All the output of the command is sent to /dev/stderr; it's not possible to pipe the output into another command, or to separate the output and error streams.
The exit status of the command is lost, so you can't use this function as part of a conditional (if, while, &&, ||, ...).
Only a single command can be timed, rather than a full pipeline.

Problems with the second approach

The exit status of the command is lost.
Only a single command can be timed (but that's always the case with an external time command, and why it's a built-in in Bash).

An improvement

You can retain the exit status when using GNU time, by using a process substitution as the output file:

function run_time {
     command time --quiet \
                  --format '%e' \
                  --output >(tee -a run_time.txt >&2) \
                  "${@}"
}

Notes

I've also used the command keyword to find the external time without hard-coding its path.  You may or may not choose to follow this course.
I've sent the time result to standard error, for consistency with the command and built-in (note that the built-in outputs to the shell's standard error, not that of the pipeline it's timing).

Alternative using built-in

function run_time {
  local TIMEFORMAT='%R'
  { { time "$@" 2>&3; } 2> >(tee -a run_time.txt >&2); } 3>&2
}

That's a bit hard to follow, so let's unpick it from the inside:

{ time "$@" 2>&3; }

The command's standard output is unchanged (stream 1), but its stderr is redirected to stream 3; time's output will be on stream 2.
{...} 2> >(tee ... >&2)

The time output is redirected to the tee command; it writes to the file and to the enclosing stream 2 (the function's standard error stream).
{ ... } 3>2

The saved standard error stream of the timed command is diverted back to the function's standard error.

This allows independent redirection of the timed command's standard output and standard error (plus timing results).  The function's error status is that of the timed command.

One disadvantage is that it doesn't wait for the process substitution to exit before the function returns, so tee's output may occur unexpectedly late (e.g. after Bash has shown the next command prompt, in an interactive shell).


Reading a property on a main thread that is set on a background thread

If all you're trying to synchronize is TWReaderDocumentStatus, and if that's a simple data type (e.g. an integer or float, not an object), you can just define it as atomic, and it can be safely read and updated from multiple threads, with no custom getter required. This is one of the very few situations where atomic can be useful for synchronization (and it's remarkably efficient).

By the way, if your property has a public interface that is readonly, make sure the private class extension redefines it as readwrite so the setter is synthesized for you. And make sure that you only set it using the setter (not bypassing it and using the instance variable directly).


Image-processing algorithm on mobile device

Just loop over the index.
The first clamp is unnecessary. (X & 0xff) will always be between 0 and 255.
Look at it algebraically. There are some expressions that do not depend on R, B, or B that you can extract from the loop.
You can extract some common expressions and calculate them at the same time as grey.

.

void applyLevels(unsigned int *rgb, const unsigned int width, const unsigned int height, const float exposure, const float brightness, const float contrast, const float saturation)
{
    const float exposureFactor   = powf(2.0f, exposure);
    const float brightnessFactor = brightness / 10.0f;
    const float contrastFactor   = contrast > 0.0f ? contrast : 0.0f;
    const float saturationFactor = 1.0f - saturation;

    const float f01 = exposureFactor / 255.0f * contrastFactor;
    const float f02 = 0.5f * (1.0f - contrastFactor);

    const unsigned int nPixel = width * height;
    for(unsigned int pixelIndex = 0; pixelIndex < nPixel; ++pixelIndex)
    {
        const unsigned int pixelValue = rgb[pixelIndex];
        float R = static_cast<float>((pixelValue >> 16) & 0xff);
        float G = static_cast<float>((pixelValue >>  8) & 0xff);
        float B = static_cast<float>((pixelValue      ) & 0xff);

        R = R * f01 + f02;
        G = G * f01 + f02;
        B = B * f01 + f02;

        const float f03 = ((R * 0.3f) + (G * 0.59f) + (B * 0.11f)) * saturationFactor + brightnessFactor;

        R = (R * saturation + f03) * 255.0f;
        G = (G * saturation + f03) * 255.0f;
        B = (B * saturation + f03) * 255.0f;

        R = R > 255.0f ? 255.0f : R < 0.0f ? 0.0f : R;
        G = G > 255.0f ? 255.0f : G < 0.0f ? 0.0f : G;
        B = B > 255.0f ? 255.0f : B < 0.0f ? 0.0f : B;

        rgb[pixelIndex] =
            (static_cast<unsigned int>(R) << 16) |
            (static_cast<unsigned int>(G) <<  8) |
            (static_cast<unsigned int>(B)      );
    }
}

Other optimizations:

Do you need an entire 8MP image? Can you downscale the image or even grab a portion?
How often do you need to apply all four operations to an image? If it is common for some images to only require exposure and saturation then make separate functions.
Convert the for to a parallel for and use neon and other intrinsics.
Rather than doing the previous suggestion I would recommend using Renderscript. It will use your GPU if it can. If it uses the CPU it is automatically multithreaded.


Improving handling of data structure used in parallel

First of all, it's very good that you read about the evilness of lock(this). Avoid it at all costs :)

As for your solution, it's not thread safe, in terms of functionality:

Thread A tries to add an object to id = 123.
Since this object doesn't exist, the ContainsKey returns false, so the false part of the condition takes place.
Then Thread A acquires the lock and starts to add its object.

However, Thread A hasn't yet completed its processing, and the system now switches to Thread B.

Strangely enough, Thread B wants to add its own object with the same id = 123 (!).

And, what do you know, since Thread A hasn't finished its processing, Thread B asks if the dictionary ContainsKey(123) and gets false. That's the problem.

Even worse, when Thread B starts its processing of adding the object, an exception would be thrown, since there's already a key assigned with 123.

So, no, the suggested code is not thread safe. That's a classic race condition.

How to resolve this?

Option 1: Double check on read operations

Inside the lock, you can call again to the ContainsKey, which is a read operation. MS provided a cheering statement, that read operations on its data structures (dictionary, list, etc.) are all thread safe.

Update: from MSDN: A Dictionary can support multiple readers concurrently, as long as the collection is not modified (my emphasis). So please ignore this option.

Option 2: Use ReaderWriterLockSlim Class

This class is optimized to the scenario of multiple reads / seldom writes. So when you want to write, you upgrade your lock to have "write" scope, and you continue your code.

Option 3: Use a simple lock on the entire TryAdd method. This is very straight forward.

All options are fine, and my personal bias is towards option 2.

Update: see also a related post at Ayende: Why is this not thread safe?

Good luck!


Create 1% Sample Using Multiprocessing in Python

Disclaimer: I have never worked with multiprocessing, so I can't comment on that implementation.

Handling Files

I noticed at the top of the file you open a file, but never close it. (For the argument that an anonymous file is closed right after the statement is executed, see this post). Leaving files open is not a good idea. You should always close your files; leaving files open can slow down your program. I'd change that line to the code below:

with open('Subsets/unique_ids_final.txt') as file:
    uid = list(line.strip() for line in file.readlines())

While it is more typing, with automatically closes the file after the inner code is run.

List Comprehension

A couple of you for loops can be reduced to one line statements. You can create a list directly with a for loop. Take a look:

tlines = [line for line in lines if line.split('*')[30] in id_pct1]

Same with jobs:

jobs = [
    pool.apply_async(worker, (chunk_start, chunk_size, q))
    for chunk_start, chunk_size in chunkify('myfile.txt')
]

One line if statements

This

if m == 'kill': break

should be this

if m == 'kill':
    break

Even though it's one line, one word, you should still indent.

Docstrings

You should include docstrings when you write functions, methods, and classes. They are used to provide more description. Take a look:

def worker(chunk_start, chunk_size, q) -> List[str]:
    """
    Read original file and write 1% sample using multiprocessing

    :param <type> chunk_start: <description>
    :param <type> chunk_size: <description>
    :param <type> q: <description>

    :return: List[str]
    """

I had trouble following your code and understanding what variables were what types. Essentially, when labeling parameters in your docstrings, the format I used goes as follows:

:param <type of parameter> <name of parameter>: <description about parameter>

And returns are as follows:

:return: <type to return>

If you want docbuilders, consider using sphinx.

Type Hints

These help portray what types are accepted and returned by a function/method. Take a look:

def add(x: int, y: int) -> int:
    return x + y

While this is a very straightforward example, the idea is still there.

Variable/Parameter Names

These should be in snake_case, not mixedCase.

chunkStart -> chunk_start
chunkSize -> chunk_size


public T push(T data) {
    Node temp = new Node(data);
    if (top == null) {
        top = temp;
    } else {
        top.next = temp;
        temp.prev = top;
        top = temp;
    }
    return temp.data;
}

This can be simplified; since both cases have top = temp at the end, you can move it out of the if statement:

public T push(T data) {
    Node temp = new Node(data);
    if (top == null) {
    } else {
        top.next = temp;
        temp.prev = top;
    }
    top = temp;
    return temp.data;
}

And as a result of that, there's only 1 case you're interested in:

public T push(T data) {
    Node temp = new Node(data);
    if (top != null) {
        top.next = temp;
        temp.prev = top;
    }
    top = temp;
    return temp.data;
}

public T peek() {
    if (top == null) {
        throw new EmptyStackException();
    }
    return top.data;
}

public T pop() {
    if (top == null) {
        throw new EmptyStackException();
    }
    T value = top.data;
    top = top.prev;
    return value;
}

I'd extract the throwing to a separate function, like so:

public void throwIfEmpty(){
    if(empty()){
        throw new EmptyStackException();
    }
}

and use like this:

public T pop() {
    throwIfEmpty();

    T value = top.data;
    top = top.prev;
    return value;
}

Keep the blank line in there, it's for showing the difference between your guard clauses and the code that does the work.

        top.next = temp;

This is the only part in your code where you set the next attribute. Since it's not read, it can go; you have no need for a doubly-linked list and can just use a singly linked list. It makes sense, because all you need to access is the top node; the other nodes aren't important.

We can further improve things:

public T push(T data) {
    Node temp = new Node(data);
    if (top != null) {
        top.next = temp;
        temp.prev = top;
    }
    top = temp;
    return temp.data;
}

Now that we decided to remove the next setting,

public T push(T data) {
    Node temp = new Node(data);
    if (top != null) {
        temp.prev = top;
    }
    top = temp;
    return temp.data;
}

we really don't need that null check anymore. Either it is null, in which case you're going to skip setting temp.prev to the null it already is, or it is not null, in which case you want to set the value.

In both cases, simply setting the value gives the wanted outcome: the code does not crash and the top node's prev pointer points to the lower node if it exists, else to null.

So remove the if statement.

public T push(T data) {
    Node temp = new Node(data);
    temp.prev = top;
    top = temp;
    return temp.data;
}

Final result:

import java.util.EmptyStackException;

public class Stack<T> {

    private class Node {

        private T data;
        private Node prev;

        public Node() {
        }

        public Node(T data) {
            this.data = data;
        }
    }

    private Node top;

    public Stack() {
        top = null;
    }

    public void throwIfEmpty(){
        if(empty()){
            throw new EmptyStackException();
        }
    }

    public boolean empty() {
        return top == null;
    }

    public T peek() {
        throwIfEmpty();
        return top.data;
    }

    public T pop() {
        throwIfEmpty();

        T value = top.data;
        top = top.prev;
        return value;
    }

    public T push(T data) {
        Node temp = new Node(data);
        temp.prev = top;
        top = temp;
        return temp.data;
    }
}


Recursive uniform cost search that needs to be optimized

Unpack your tuple to improve readability. There's already a comment

# Each tuple is: (actualScore, minScore, previous, totalScore, y, x)

Put those names in code like this so you can use eg. actualScore instead of m[0]:

(actualScore, minScore, previous, totalScore, y, x) = m

You are using recursion to implement a simple loop. I get RuntimeError: maximum recursion depth exceeded even from problem 18. That's because you recurse from every node on every path until you find a solution. Just use a while loop instead.
Use the heapq module to implement a priority queue to avoid the linear search done by min.
Compare numbers using ==. Only use is for object identity.

To learn about the A* algorithm, see the highly readable tutorial at Amit’s A* Pages.
You'll notice that your approach is different. In particular, you don't compute a heuristic. On the other hand I'm not sure if a useful heuristic exists for this problem, but in any case your approach is more like Dijkstra'a algorithm.
You should keep track of already visited nodes to avoid exploring the same multiple times.
When you add nodes to the priority queue, you should already compute their scores. Now you add both children with the score of the parent. When you eventually pop these nodes from the queue, you get the left child even though you need the better one first. Try the small example at the top of the problem 18 page: program answers 19 instead of 23, because at the bottom row the 5 pops from the queue before the 9.


Update single common column in multiple has-many relationships rails

(Converted a comment into this answer)

If all the records should use @private_school.price_type as their own price_type, then make them fetch it from the school they belong to - don't duplicate the same value across a bunch of tables when you already have it in one place. Keep the database normalized.

Simplest way to do this is to add a price_type method to each of the non-school models. The method simply fetches and returns <belongs_to relation>.price_type. I.e. Document#price_type would call its owner's method, which would be LessonPlan#price_type, which would call it's owner, etc.. until it hits the school's price_type attribute.

It's not the most efficient as it may need to load some records in the chain, but it's a start.


Just a couple of remarks:

You should add a newline after the last line:

  $ ./nh
  First char match index: 18
  Char: t
  Exist count: 1
  Exist count: 2
  Exist count: 3
  Exist count: 4
  Position: 18 $

I don't know what compiler you use but with when compiled with gcc and -Wall -Wextra -pedantic you get:

gcc -O2 nh.c -lm -o nh -Wall -Wextra -pedantic
nh.c: In function ‘contains’:
nh.c:25:15: warning: unused variable ‘j’ [-Wunused-variable]
 size_t i, j;
           ^

Code formatting should be more consistent. For example, in this line you put a whitespace before needle but don't put a whitespace before haystack:

size_t contains(const char * needle, const char *haystack);

%lu is not a portable specifier for size_t type, you should use %zu introduced in C99.
You said:

  returns the position if it does or 0 if it doesn't, unless the
  position is 0 in which case, it won't be located.

This is really not good. For example, with this it returns 0:

char *needle = "This";
char *haystack = "This is a dinosaurtest.";

With this, it also returns zero:

char *needle = "non-existent";
char *haystack = "This is a dinosaurtest.";

You can't tell the difference between success and failure in this two
examples. Actually, atoi() has the same problem. I don't know what
operating system you use but maybe you could use ssize_t as the
return type if it's available and return -1 in case of failure.


From a short review;

Your own answer does read better
map is the right approach
I would go for filter instead of reduce (you only want 'true' values that are not keyword)
I probably would have named total -> keys
I prefer <verb><object> so combined -> addGroups
If you dont use a falsy comparison, then you dont need to check for 'keyword'

const data = [
    {keyword: 'banana', yellow: true, sweet: true},
    {keyword: 'pineapple', yellow: true, sweet: false},
    {keyword: 'apple', yellow: false, sweet: false},
];

function addGroup(o){
  return {
    ...o,
    group: Object.keys(o).filter(key => o[key] === true).join(' ')
  };
}

function addGroups(list){
  return list.map(o => addGroup(o));
}

console.log(addGroups(data))
.as-console-wrapper { max-height: 100% !important; top: 0; }


Not creating the VoteStats table makes a big difference. Gets it down to ~5.5 seconds.

set nocount on

select up, count(*)
from (
    select
        PostId,
        up = sum(case when VoteTypeId = 2 then 1 else 0 end)
    from Votes
    where VoteTypeId in (2,3)
    group by PostId
) a
group by up
order by up

http://data.stackexchange.com/stackoverflow/q/112108/

From the execution plan of the table variable version, it looks like the table scan and the sort on it is pretty expensive.


Reducing verbosity of RomanNumeral class

First thing you can do is put them in else if statements. It doesn't reduce the code but it do at least reduce the number of case the program has to check each time.

Because right now if the first match is good, it'll still check all the other statements.

To remove the ifs:

The other thing you could do is a Map. Doing that would not really reduced the amount of code but would make the code more readable. See this topic to learn more about the load factor in the map and how to initialize it.

private static final Map<String, Integer> ROMAN_MAP;
static
{
    // Note1 : Since you know the number of items in the map, you can initialize
    // the map directly with 7 safe "spots".
    // Note2 : We initialize it at 10 which is Roughly (N / load) + 1
    Map<Character, Integer>tempMap = new HashMap<Character, Integer>(10);
    tempMap.put('I', 1);
    tempMap.put('V', 5);
    tempMap.put('X', 10);
    tempMap.put('L', 50);
    tempMap.put('C', 100);
    tempMap.put('D', 500);
    tempMap.put('M', 1000);
    romanMap= Collections.unmodifiableMap(tempMap);
}

Then you can access it just like that :

ROMAN_MAP.get(romaNumera.charAt(i));

Changes with the use of a map :

Also, as mentioned, get rid of the floats AND of the Math.round() calls they are useless since your function returns an int anyway an that there is no possibility of displaying floating points anyway.

Your function can then be reduced to the following :

public int getDecimalValue() {
    int result = 0;
    int length = romaNumera.length();

    for(int i = 0; i < length; i++){
        int current = ROMAN_MAP.get(romaNumera.chartAt(i));
        int j = i+1;

        // Check if there is a next element and if it's bigger than current
        if(j < length && current < ROMAN_MAP.get(romaNumera.chartAt(j)){
            result -= current;
        } else {
            result += current;
        }
    }
    return result;
}

I've put { everywhere since they don't slow the process running in anyway and to me they make the code more readable and reduce the possibilities of error when refactoring.


function findOneDupe(input){

You name this function findOneDupe, but this code finds the first element that is not duplicated.

    function findFirstUnique(input) {

Now it does what it says, not the opposite of what it says.

  var b = input.split(/\s|\n/).map(Number);

Why call this b?  That gives me no idea what it holds.

  var tokens = input.split(/\s|\n/).map(Number);

The name tokens is far more understandable in terms of whitespace delineated text.

  b.shift();

Why?  Presumably you have some cruft to remove from the array.  Comment this and explain why it needs to be done.  Then you don't have to worry about someone optimizing it out later.

  for (var i=0;i<b.length;i++){
    var e = b.shift();
    if (b.indexOf(e) == -1) return e;
    b[b.length] = e;
  }

This seems more complicated than it needs to be.  You are both maintaining an index variable and removing from the array.  Why not pick one or the other?

  for (var i=0; i < tokens.length; i++) {
    if (tokens.indexOf(tokens[i], i+1) == -1 && tokens.indexOf(tokens[i]) == i) {
      return tokens[i];
    }
  }

Now we don't add or remove from the array at all.  Which is good, since Javascript arrays are not lists.  Removing and adding can cause the array to not fit its memory allocation anymore.  When that happens, the array will be copied into a new memory location.  Pure waste considering that you never use the array outside this function.

Note that the two indexOf checks will never check more elements than your single check.  The first one only checks things after i and the second one only checks up to i (because it always finds at i).

Note that this takes \$O(n^2)\$ time in the worst case, as you loop over every element and search the array for it.  You can get better asymptotic performance by sorting the array.

  tokens.sort();

  var i = 1;
  while (i < tokens.length) {
    if (tokens[i-1] != tokens[i]) {
      return tokens[i-1];
    }

    do {
      i++;
    } while (tokens[i-1] == tokens[i] && i < tokens.length);

    // we want to get all the way past anything equal
    // to the original tokens[i-1] value
    i++;
  }

This takes \$O(n \log n)\$ time for the sort and linear time to find any unique elements.


I didn't find much to say about your coding style.

Maybe in_sig is not a perfect name: signal_in would be easier to read in my opinion (putting the _in at the end is more consistent with you other variable names)

  it would require some re-writing if I wanted to extend it.

What kind of extension ?

Using iterators to get the samples

For your input functions, you could use a generator instead:

def sinusoid(initial_phi, frequency_offset):
    """Generates a sinusoidal signal"""
    phi = initial_phi
    while True:
        yield np.exp(1j*phi)
        phi += frequency_offset

When initially called, this function will return an iterator: iter_sin = sinusoid(3.0, -0.2)

And add set_signal_in and signal_out methods in your SimPLL class:

def set_signal_in(self, signal_in):
    """Set a iterator as input signal"""
    self.signal_in = signal_in

def signal_out(self):
    """Generate the output steps"""
    for sample_in in self.signal_in:
        self.step(sample_in)
        yield self.vco

(maybe signal_out could generate some tuples with the sample_in and phase_difference, or even yield self)

Usage

You can then do a pll.set_signal_in(iter_sin).

If you have a list of data, you can then do pll.set_signal_in(list_of_values).

Plotting

For plotting a limited amount of points, you may use itertools.islice


Good job with the type annotations! Here are a few things you could simplify/improve:

instead of listdir and an extra file extension check, you could use glob.iglob():

for filename in glob.iglob('./**/*.xlsx'):

to improve excel file read performance and memory consumption, you could use read_only=True mode
instead of iterating over sheetnames and getting a sheet by name, you could iterate over available worksheets directly:

for sheet in workbook.worksheets:

iter_rows() should improve the way you read the sheet cells

As a side note and as an idea for an alternative solution: what if you transition the data through a pandas.DataFrame, pandas has .read_excel() and .to_csv() methods.


feilds is spelled fields. IDEs like PyCharm will identify spelling mistakes in variables.

Why is there a ? after the space in your regex? Currently I believe it will pass input looking like

key,1key,2key,3

So you have to fix that edge case, probably by adding a final key-value pair with no space, and making the space in the first group mandatory.

This:

vals = dict([feild.split(",") for feild in feilds.split(" ")])
for k, v in vals.items():
    vals[k] = int(v)

should be

vals = {k: int(v)
        for field in fields.split(' ')
        for k, v in field.split(',')}

i.e. don't construct a list in memory only to throw it away.

This:

spacing = int(width / len(vals.keys()))

can be

spacing = width // len(vals)

This:

for x in reversed(range(len(max(horizontal, key=len)))):

doesn't actually need an index at all, since you don't use it. Also, lumping everything into one line is confusing. Instead:

longest_horz = max(len(h) for h in horz)
for v in val[longest_horz-1::-1]:

Then use v instead of val[x].


Speeding up evaluation of power series, Python

I think most savings are already achieved by the memoization. If you deconstruct the algorithms, your mgf and mgf_horner don't seem to do a lot different. The main difference is the direction of the summation, which affects the float rounding errors.

some small changes:

instead of reversed(range(1, MAX_DEGREE)) you can use range(MAX_DEGREE - 1, 0, -1)
you can use the built-in sum or math.fsum if you rewrite the formula's a bit

something like this:

@lru_cache(maxsize=MAX_DEGREE)
def p2(n):
    return sum((p_k(k, n) for k in range(1, n)), 1)

def mgf_fsum(x):
    if abs(x) >= 1:
        return 0
    return math.fsum(p2(i) * x ** i for i in range(1, MAX_DEGREE))

def mgf_horner_fsum(x):
    if abs(x) >= 1:
        return 0
    return math.fsum(p2(i) * x ** i for i in range(MAX_DEGREE, 0, -1))

def mgf_sum(x):
    if abs(x) >= 1:
        return 0
    return sum(p2(i) * x ** i for i in range(1, MAX_DEGREE))

def mgf_horner_sum(x):
    if abs(x) >= 1:
        return 0
    return sum(p2(i) * x ** i for i in range(MAX_DEGREE, 0, -1))

but this rounding has an effect on the results:

steps = 15
for x in range(1, steps, 1):
    print(x/steps, mgf(x/steps), mgf(x/steps)/mgf(x/steps), mgf_sum(x/steps)/mgf(x/steps), mgf_fsum(x/steps)/mgf(x/steps), mgf_horner(x/steps)/mgf(x/steps), mgf_horner_sum(x/steps)/mgf(x/steps), mgf_horner_fsum(x/steps)/mgf(x/steps))

x mgf_value mgf mgf_sum mgf_fsum mgf_horner mgf_horner_sum mgf_horner_fsum
0.06666666666666667 0.07655349092586666 1.0 1.0 1.0 1.0 1.0 1.0
0.13333333333333333 0.17795095671821595 1.0 1.0 1.0 1.0 1.0 1.0
0.2 0.3152135557353453 1.0 1.0 0.9999999999999998 0.9999999999999998 0.9999999999999998 0.9999999999999998
0.26666666666666666 0.5067809825345801 1.0 1.0 1.0000000000000007 1.0000000000000007 1.0000000000000007 1.0000000000000007
0.3333333333333333 0.7853123419985341 1.0 0.9999999999999997 1.0 0.9999999999999999 1.0000000000000002 1.0
0.4 1.2130721483139313 1.0 1.0 1.0 0.9999999999999998 1.0 1.0
0.4666666666666667 1.9206394911829312 1.0 1.0 1.0000000000000004 1.0000000000000004 1.0000000000000004 1.0000000000000004
0.5333333333333333 3.2187202179248864 1.0 1.0 1.0000000000000004 1.000000000000099 1.000000000000099 1.000000000000099
0.6 5.9870712939827015 1.0 1.0 0.9999999999999999 1.000000000201781 1.0000000002017808 1.000000000201781
0.6666666666666666 13.435823754250293 1.0 0.9999999999999999 1.0000000000000002 1.0000001435010422 1.0000001435010424 1.0000001435010424
0.7333333333333333 43.087235122138615 1.0 1.0000000000000002 1.0 1.0000353393606511 1.0000353393606507 1.000035339360651
0.8 288.2244586544328 1.0 1.0000000000000004 1.0 1.0023338650736258 1.002333865073626 1.002333865073626
0.8666666666666667 6672.576615237916 1.0 0.9999999999999998 0.9999999999999994 1.0273438993019854 1.0273438993019859 1.0273438993019859
0.9333333333333333 379389.61410647386 1.0 0.9999999999999997 0.9999999999999999 1.0860986641621089 1.086098664162109 1.086098664162109

for these tests I limited MAX_DEGREE to 70.

As you can see, the 3 methods with increasing iteration give a different result than the 3 methods with decreasing iterations, especially with values closer to 1

Once the p(x) are calculated and in memory, this goes pretty fast, and no noticeable difference between the algorithms


Let me start by saying I have very limited Android experience. That said, I did look into the SoundPool class a bit and have some questions/comments about your implementation:

If you aren't already aware of some of the reasons why people consider Singletons an anti-pattern, I suggest you do some research on the topic and make sure you're ok with the downsides.
Your class, for the most part, seems to be wrapping a SoundPool with a key value pair structure despite SoundPool already being a key value pair structure. I would imagine you could do away with most of this class and just use the SoundPool class directly.
If you don't want to use SoundPool directly for some reason, why not at least use the soundId as a key? It already appears to be unique, and it's what the calling code probably wants anyway. If not, you may want to do some checking to make sure that duplicate keys aren't entered, or take the key assignment out of the hands of the caller and simply return an id as the result of the addSound function.
Using both mSoundPoolMap and mAvailibleSounds means you have to manage keys in two locations which could lead to them getting out of sync or some confusion as to why there are two fields holding the same information. Using only mSoundPoolMap would be sufficient and avoid duplication. This highly voted question isn't quite the same, but it touches on a lot of good points why this kind of duplication can be bad.

Hope this helps!


Avoid mixing floating point and integer arithmetic
As mentioned by greybeard, there is a potential problem here:
const unsigned short n = log10(ULLONG_MAX);

ULLONG_MAX is larger than can be exactly represented by a double. This means the result might not be what you expect. The same goes for pow(10, n). While you can compensate for it, it is better to find a way to calculate the length of a number without using floating point math.
Keep it simple
Unless performance is a big concern, keep it simple. You don't have to know the number of digits up front if you push trailing digits to the front of the vector, like so:
vector<unsigned short> IntegerDigits(unsigned long long input)
{
    vector<unsigned short> output;

    while (input)
    {
        output.insert(output.begin(), input % 10);
        input /= 10;
    }

    // Handle input being equal to 0
    if (output.empty())
    {
        output.push_back(0);
    }

    return output;
}

Pushing to the front of a std::vector is less efficient, but on the other hand you don't need the double<->int conversions, and you don't need to handle the leading zeros inside the loop.
Avoid using std::endl
Prefer using "\n" over std::endl, the latter is equivalent to the former, but also forces a flush of the output, which can be bad for performance.
Avoid backspaces in the output
You used a neat trick to get rid of the last comma without having to have extra logic inside the for-loop in main(). However, consider that the output might not just be for human consumption, but is written to a file and/or is parsed by another program. In that case, the \b characters are probably unexpected and might cause problems.


Does Java need an Observable object with generics?

A few observations.

Your choice of Collection as type for registry and all other things point at it that you want this class to be extended. If it weren't so a few desing choices would have been different.

I still want to review the code as if it were a closed class. Because if it weren't I'd suggest you throw that all away and think about why able things very often are interfaces. Don't make the same design mistakes...

Your registry is overly Generic. Not in choice of generics, but in choice of Interface...

I'd have expected at least a Set instead of Collection. Also your code could greatly benefit from eagerly initializing it. For one it allows you to add a no-argument constructor easily, and secondly it's more conventional.

Let's look at getInstance for a moment.
You create an empty collection to be set as your registry. This is boilerplate code when extending your Observable.
Additionally it makes the behavior of your observable concerning references somewhat unconventional. I'd have expected:

 ... Observable (Collection <Observer <? super T>> registry) {
    this.registry.addAll(registry);
}

And here's already my next problem... why is your constructor private? I think it would be beneficial to allow me as programmer to instantiate Observables myself ;)

And last but not least toNotify in your update method is never written to again. I suggest you use a unmodifiableCollection instead of copying your registry into an ArrayList to clearly express what you actually want


That looks like it's close to what you're going to get with Python I think.

I'd suggest taking a profiler and optimising according to that; e.g. I can imagine that doing less work using split and instead just counting the number of spaces (instead of allocating all the results) should be a bit faster (in can_traffic_only).

can_data can be delayed till the condition for the if block is true, but again, depends on how often that's the case.

If there's nothing else you could inline can_traffic_only and see if that makes a difference.


If I understand correctly, you can unnest your code, and catch any possible error at the end. That's the idea of using promises:

websiteService.get('websites').then(function(data) {
  $scope.websites = data
  return websiteService.get('groups')
}).then(function(data) {
  $scope.groups = data
  return websiteService.get('websites_groups')
}).then(function(data) {
  $scope.websites_groups = data
}).catch(function(error) {
  $scope.errors.push(error)
})


You can use the function array_slice to take the subarray which contains the sizes from $size1 to size2. And then use implode to turn this subarray into a comma-separated string. This will simplify your algorithm.

You can also just use explode instead of substr and strstr to split the range string into its parts.

In addition I would recommend changing the variable names of $size1 and $size2. To me the name $size1 suggests that the variable contains the actual size while in fact it contains its index. Something like index_of_size1 or index_from might be more appropriate.

If I were to write this function, it'd look something like this:

function sizexpander($size_range) {
    $sizearray=Array("XS", "S", "M", "L", "XL", "XXL", "XXXL");
    list($size_from, $size_to) = explode("-", $size_range);
    $index_from = array_search($size_from, $sizearray);
    $index_to = array_search($size_to, $sizearray);
    $subsizes = array_slice($sizearray, $index_from, $index_to-$index_from+1);
    return implode(", ", $subsizes);
}


Determining the number of vowels in each word from a file

Don't do this:

using namespace std;

See: Why is “using namespace std;” considered bad practice?

Pass by value?

void printWords(string);

You are not planning on modifying so pass by const reference in preference. This will prevent an extra copy. This also tells the compiler you don't want to modify the word and thus the compiler can potentially do optimizations as it does not need to worry about mutations.

Main is special.
You do not need an explicit return. If non is defined then an implicit return 0; is panted for you. In the case where there is no chance of failure I prefer not to use an explicit return.

int main()
{
    readFile();

    return 0;
}//end main

May as well create and open file in a single statement.

    ifstream inFile;
    string words;

    inFile.open("words.txt");

    // I would have used:

    std::ifstream  inFile("words.txt");
    std::string    words;

This is always wrong:

    while(!inFile.eof())

see: Why is iostream::eof inside a loop condition considered wrong?

It should be re-written as:

 while(inFile >> word)
 {
     // STUFF
 }

But you can go further. You can use iterators and loops to achieve the same affect.

 for(std::istream_iterator<std::string> loop(inFile); loop != std::istream_iterator<std::string>(); ++loop)
 {
     // STUFF
 }

Now that you can see a loop using iterators you can look at using some of the standard algorithms.

 std::for_each(std::istream_iterator<std::string>(inFile),
               std::istream_iterator<std::string>(),
               [](std::string const& word){ /* STUFF */ }
              );

Don't manually close a file:

    inFile.close();

see:  My C++ code involving an fstream failed review

As noted above:

void printWords(std::string cosnt& str)
{

If variables do not change then mark them constant.

    char a = 'a', e = 'e', z = 'i', o ='o', u ='u';

I would have used an array here:

    int num_A = 0, num_E = 0, num_I = 0, num_O = 0, num_U = 0;

Prefer not to use std::endl  unless you want to force a flush (you usually don't as it is very costly). Prefer to use "\n" this has the same effect but with no flush.

    cout<< str <<endl;

If you know your access is in bounds then prefer to use operator[] it does no checking and is thus faster. Prefer .at() if you want to force the check.

        if(str.at(i) == a)

Saying all that I would have use a standard function to count vowels.

std::count_if(std::begin(word), std::end(word), [](char l){return isVowel(l);});

bool isVowel(unsigned char l)
{
    static char vowel[] =
                    {    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                         0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, // aeio
                         0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // u
                         0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, // AEIO
                         0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // U
                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    return vowel[l];
}

My solution would be:

#include <string>
#include <fstream>
#include <iostream>

WordInfo class

class WordInfo
{
    std::string     word;
    int             count;
    public:
        WordInfo(std::string const& word)
            : word(word)
            , count(0)
        {
            count   = std::count_if(std::begin(word), std::end(word),
                                    [](char l) {return isVowel(l);});
        }
        friend std::ostream& operator<<(std::ostream& str, WordInfo const& data)
        {
            return str << data.word << " " << data.count;
        }
};

main.cpp

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        std::cerr << "Error: Wrong usage\n";
        return -1;
    }
    std::ifstream   infile(argv[1]);

    std::copy(std::istream_iterator<std::string>(infile),
              std::istream_iterator<std::string>(),
              std::ostream_iterator<WordInfo>(std::cout, "\n")
             );
}

Note: The std::copy above acts like this:

    std::string     word;

    while(infile >> word)
    {
        std::cout << WordInfo(word) << "\n";
    }


Writing values from JSON on image and display image

header('Content-type: image/png');
imagepng($donationImage);

No real point in specifying the content type prior to actually outputting the image.

As mentioned in the other answer, json_decode(utf8_encode(file_get_contents("URI"))) can error out in multiple ways. If error reporting is active, this will result in a mismatch between content type and the response body. Even if it isn't, you end up sending a wrong content type for an empty body.

I hope you have placed a cache in front of that script. You are stalling the script with a REST query, and the memory footprint isn't negligible either.

If the web server isn't configured to cache, you want to fix that.

Caching the output with plain PHP is slightly more complex than that, with regard to acquiring a mutex on the cache during updates.

?>

Eventually you will end up with a newline following the closing code tag (be it the IDE or the VCS software being "smart"). This will add to the output, resulting in an invalid response.

Avoid using the closing code tag if there isn't any content following. This actually applies to all PHP files.