Please make everyone (including yourself) a favor :

Declare your variable in the smallest possible scope. Also define them as your declare them if you can (and you usually can).
Indent your code properly.

Then you'd get something like :

unsigned char *slow_rescale(unsigned char *src, int src_x, int src_y, int dest_x, int dest_y)
{
    unsigned char* dst=(unsigned char *)calloc(dest_x*dest_y*3,sizeof(unsigned char));   // Allocate and clear destination image
    if (!dst) return(NULL); // Unable to allocate image

    double step_x=(double)(src_x-1)/(double)(dest_x-1);
    double step_y=(double)(src_y-1)/(double)(dest_y-1);

    for (int x=0;x<dest_x;x++) // Loop over destination image
    {
        for (int y=0;y<dest_y;y++)
        {
            double fx=x*step_x;
            double fy=y*step_y;
            double dx=fx-(int)fx;
            double dy=fy-(int)fy;

            unsigned char R1,R2,R3,R4; // Colours at the four neighbours
            unsigned char G1,G2,G3,G4;
            unsigned char B1,B2,B3,B4;

            getPixel(src,floor(fx),floor(fy),src_x,&R1,&G1,&B1); // get N1 colours
            getPixel(src,ceil(fx),floor(fy),src_x,&R2,&G2,&B2); // get N2 colours
            getPixel(src,floor(fx),ceil(fy),src_x,&R3,&G3,&B3); // get N3 colours
            getPixel(src,ceil(fx),ceil(fy),src_x,&R4,&G4,&B4);  // get N4 colours
            // Interpolate to get T1 and T2 colours
            double RT1=(dx*R2)+(1-dx)*R1;
            double GT1=(dx*G2)+(1-dx)*G1;
            double BT1=(dx*B2)+(1-dx)*B1;
            double RT2=(dx*R4)+(1-dx)*R3;
            double GT2=(dx*G4)+(1-dx)*G3;
            double BT2=(dx*B4)+(1-dx)*B3;
            // Obtain final colour by interpolating between T1 and T2
            unsigned char R=(unsigned char)((dy*RT2)+((1-dy)*RT1));
            unsigned char G=(unsigned char)((dy*GT2)+((1-dy)*GT1));
            unsigned char B=(unsigned char)((dy*BT2)+((1-dy)*BT1));
            // Store the final colour
            setPixel(dst,x,y,dest_x,R,G,B);
        }
    }
    return(dst);
}
void getPixel(unsigned char *image, int x, int y, int sx, unsigned char *R, unsigned char *G, unsigned char *B)
{
    // Get the colour at pixel x,y in the image and return it using the provided RGB pointers
    // Requires the image size along the x direction!
    *(R)=*(image+((x+(y*sx))*3)+0);
    *(G)=*(image+((x+(y*sx))*3)+1);
    *(B)=*(image+((x+(y*sx))*3)+2);
}

void setPixel(unsigned char *image, int x, int y, int sx, unsigned char R, unsigned char G, unsigned char B)
{
    // Set the colour of the pixel at x,y in the image to the specified R,G,B
    // Requires the image size along the x direction!
    *(image+((x+(y*sx))*3)+0)=R;
    *(image+((x+(y*sx))*3)+1)=G;
    *(image+((x+(y*sx))*3)+2)=B;
}

Then, try to compute things once and only once when possible and you'll get something like :

unsigned char *slow_rescale(unsigned char *src, int src_x, int src_y, int dest_x, int dest_y)
{
    unsigned char* dst=(unsigned char *)calloc(dest_x*dest_y*3,sizeof(unsigned char));   // Allocate and clear destination image
    if (!dst) return(NULL); // Unable to allocate image

    double step_x=(double)(src_x-1)/(double)(dest_x-1);
    double step_y=(double)(src_y-1)/(double)(dest_y-1);

    for (int x=0;x<dest_x;x++) // Loop over destination image
    {
        double fx=x*step_x;
        double dx=fx-(int)fx;
        int ffx = floor(fx);
        int cfx = ceil(fx);
        for (int y=0;y<dest_y;y++)
        {
            double fy=y*step_y;
            double dy=fy-(int)fy;
            int ffy = floor(fy);
            int cfy = ceil(fy);

            unsigned char R1,R2,R3,R4,G1,G2,G3,G4,B1,B2,B3,B4;

            getPixel(src, (ffx + ffy*src_x)*3, &R1,&G1,&B1); // get N1 colours
            getPixel(src, (cfx + ffy*src_x)*3, &R2,&G2,&B2); // get N2 colours
            getPixel(src, (ffx + cfy*src_x)*3, &R3,&G3,&B3); // get N3 colours
            getPixel(src, (cfx + cfy*src_x)*3, &R4,&G4,&B4); // get N4 colours
            // Interpolate to get T1 and T2 colours
            double RT1 = dx*R2 + (1-dx)*R1;
            double GT1 = dx*G2 + (1-dx)*G1;
            double BT1 = dx*B2 + (1-dx)*B1;
            double RT2 = dx*R4 + (1-dx)*R3;
            double GT2 = dx*G4 + (1-dx)*G3;
            double BT2 = dx*B4 + (1-dx)*B3;
            // Obtain final colour by interpolating between T1 and T2
            unsigned char R = dy*RT2 + (1-dy)*RT1;
            unsigned char G = dy*GT2 + (1-dy)*GT1;
            unsigned char B = dy*BT2 + (1-dy)*BT1;
            // Store the final colour
            setPixel(dst, (x + y*dest_x)*3,R,G,B);
        }
    }
    return(dst);
}

inline void getPixel(unsigned char *image, int offset, unsigned char *R, unsigned char *G, unsigned char *B)
{
    *R=image[offset+0];
    *G=image[offset+1];
    *B=image[offset+2];
}

inline void setPixel(unsigned char *image, int offset, unsigned char R, unsigned char G, unsigned char B)
{
    image[offset+0]=R;
    image[offset+1]=G;
    image[offset+2]=B;
}

I'd expect this to be much much faster than your original code and to do roughtly the same thing (I have have introduced errors though).


Searching for three positive integers as a solution to an equation

Here are some simple optimizations you can make that can push your limit a bit higher:

Don't use floating point arithmetic. Floating point arithmetic is slow compared to integer arithmetic (this is not always true with the advent of things like FPUs, but it is a good rule of thumb). Even worse, floating point arithmetic is prone to things like rounding errors, which means you might find solutions which don't work and miss solutions that do work.

One way to avoid using floating point arithmetic here is to expand out the equation into the form:

\$x(x+y)(x+z) + y(y+x)(y+z) + z(z+x)(z+y) = 4(y+z)(x+z)(x+y)\$

In this form you can check whether the equation is satisfied just using integer arithmetic (make sure you use a integer type large enough so that neither side overflows, however).
Make use of symmetry (thanks @Deduplicator). Another simple observation you can make is that this equation is symmetric in \$x\$, \$y\$, and \$z\$, i.e. if you have a solution \$(x, y, z)\$, then any permutation of this solution also works. One way to use this fact is to only loop over \$1 \leq y \leq x\$ and \$1 \leq z \leq y\$. This cuts down on your total number of iterations by a factor of \$3! = 6\$.
Reduce number of degrees of freedom. One interesting observation is that, once you fix \$x\$ and \$y\$, you don't have many choices left for \$z\$. So instead of looping over all \$z\$ in the range \$[1, L]\$, you can more efficiently compute the possible values of \$z\$. (This removes one of your for loops).

How do you find the possible values of \$z\$? Well, if we know what \$x\$ and \$y\$ are, the above equation reduces to a cubic in \$z\$; i.e., something for the form \$c_3z^3 + c_2z^2 + c_1z + c_0 = 0\$. There are a couple ways to solve this for \$z\$; the easiest way I can think of (but definitely not the fastest) is to try all the factors of \$c_0\$ (by the Rational Root Theorem, any integer \$z\$ that satisfies this must divide \$c_0\$). This does involve factoring \$c_0\$, however, which can take a while depending on how you implement it.

A faster method is to use binary search to find the roots, but you have to be a bit careful here, since the cubic might not be monotone increasing/decreasing over the entire interval. The correct way to do this is to first find the roots of the derivative of the cubic (the derivative of the cubic is a quadratic, so you can do this with just the quadratic formula); these are the critical points of the cubic, so the cubic is monotone increasing/decreasing on the intervals between these points, and you can binary search here.
Learn about elliptic curves. So it turns out that the smallest solutions to this Diophantine equation are immense, and it's pretty much impossible to find any via any method like this (I forget how large they are, but I believe each of x, y, and z is at least 10 digits long). The question then becomes, how did people find this answer in the first place?

The trick here is that the cubic above (in fact, pretty much any homogeneous cubic in three variables) is an instance of a mathematical object known as an elliptic curve, and that these objects have a ton of nice properties. One of these nice properties is that there is a method whereby you can take any two integer solutions to this equation and "add" them to get a third integer solution. So one approach which works is to start with an integer solution (but not a positive integer solution) such as (11, 9, -5), and repeatedly "add" it to itself until you end up with a positive integer solution (as far as I know, there's no guarantee you ever will end up with a positive integer solution, but in this case you do after a couple of steps).

EDIT:

I ran some tests to compare the above optimizations (see here). On my machine for limit=1000:

OP's code (removing the printf per iteration) takes ~14.5 seconds.
OP's code with optimization 1 takes ~4.2 seconds.
OP's code with optimizations 1 + 2 takes ~0.7 seconds.
OP's code with optimizations 1 + 2 + 3 takes ~0.25 seconds.

For larger limits, these differences are more pronounced. For limit=5000:

OP's code with optimizations 1 + 2 + 3 takes ~7.9 seconds.
OP's code with optimizations 1 + 2 takes ~86 seconds.
The other two cases each took at least 5 minutes.


Producing queries based on user interface selection

Company_contacts.Any(x => x.Company_contacts.Cust_order_header.Any(y => y.Order_time >= @0))

That should put the joins in for you. Right now it is not referencing the objects you use in the query through their relationships so it is writing the SQL out as though they were subqueries.


Your approach is technically correct, but very complex. Your call stack gets very big and you use very much memory by creating two objects for each point. But you don't need to.

What are you doing with your recursive calls? You go go from start to end and put every point on the call stack. But you have every point in the matrix. You don't need to create a copy.

You do a depth first search, but you should do a breadth first search. Think about how you can manipulate the grid on the way down, so the solution could be found in the grid.


Ignore exceptions when changing column formula in Excel table

Private Sub Worksheet_Change(ByVal Target As Range)

The Worksheet.Change event gets fired whenever anything changes anywhere in the worksheet. Code you write in a handler for that event must do its business as fast as possible, or it can significantly affect (negatively) the performance of the whole Excel instance.

Whenever possible, avoid using this event for anything that doesn't need to run whenever anything changes anywhere in the worksheet.

Application.Calculation = xlCalculationManual
If Target.Count = 1 Then
Application.EnableEvents = False

Your indentation is off, the assignment Application.EnableEvents = False should be one Tab further to the right.

I like that you're disabling automatic calculation and other worksheet event handlers, but I don't understand why only one of them is under the If block.

    Application.EnableEvents = True
    End If
    ActiveSheet.Calculate
End Sub

The result of this is that you're calculating the active sheet, but you've disabled automatic calculation of the workbook without reinstating it, and you end up systematically calling ActiveSheet.Calculate, which gives the illusion that automatic calculation is still enabled.

tb = Target.ListObject.Name

If the modified cell is outside of a ListObject, this is where your code blows up, and because you're not handling run-time errors, this is where your user sees a VBA debugger prompt and might accidentally end up in your source code with a puzzled facial expression.

Whenever you start writing a method/procedure/function in VBA, you should start with something like this:

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo ErrHandler

    'code goes here

CleanExit:
    Exit Sub
ErrHandler:
    Resume CleanExit
    Resume 'unreachable code, for debugging
End Sub

Now you can put a breakpoint on the Resume CleanExit instruction, and can inspect the Err object and then set the Resume dead code as the next statement to be executed, and be taken (F8) exactly on the line the error came from, whenever anything goes wrong with this code.

Dim tb As String
tb = Target.ListObject.Name

If tb is supposed to be the name of a table, then why is it not called tableName? Use descriptive identifiers when naming things!

Dim l As Long
Dim i As Long
Dim s As String
Dim cel As Range
Dim fmla As String
Dim nfmla As String
Dim mfmla() As String
Dim mad() As String

Oh, boy. Need I say more?

I'm not going to review your algorithm (not going to try to wrap my head around those cryptic identifiers), but one thing I can say is that, for the reasons explained at the top of this answer, I'd start the procedure like this:

If Target.ListObject Is Nothing Then Exit Sub

That way you don't bother with anything if the active cell isn't in a table, and the handler can't blow up either when you later try to get the table's name.

Also by only testing for Target.Count = 1 all you're really doing, is ensuring that the current selection only has a single cell. This means if a user selects an entire row (or column) and starts entering data, your code happily sets calculation mode to manual, skipts the entire handler and recalculates the sheet.

Hence, the next thing I'd do after ensuring the Target range has a ListObject, would be to toggle calculation mode and event firing. It's probably best to write a small procedure just for that:

Private Sub ToggleWaitMode(Optional ByVal wait As Boolean = True)
    Application.Calculation = IIf(wait, xlCalculationManual, xlCalculationAutomatic)
    Application.EnableEvents = Not wait
    Application.AutoCorrect.AutoFillFormulasInLists = Not wait
End Sub

That leaves your handler with pretty much only the code that's relevant for its task:

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo ErrHandler

    If Target.ListObject Is Nothing Then Exit Sub
    ToggleWaitMode

    '...

CleanExit:
    ToggleWaitMode False
    Exit Sub
ErrHandler:
    Resume CleanExit
    Resume 'unreachable code, for debugging
End Sub

I don't like the ReDim Preserve array handling. You know how many cells you're going to be iterating over (Range(tb & s).Count), therefore you know the size of the array you're going to need at the moment you're declaring it. You'll probably gain some performance by doing this, depending on how many cells the range has.


Keep solid picture of usage in your head

When creating a library, it is extremely important to always keep the intended usage in mind. If the usage syntax is disgusting, it is better to think of a new one before writing the library (of course within reasons). In this case, I believe it is not what you wanted.

Make interfaces easy to use correctly and hard to use incorrectly

Start() function could be built into constructor. If user didn't use Start(), they'll get wrong results. Constructor, on the other hand, will enforce initialization. Never write non-fully-initializable objects, unless it is not possible to do otheriwse (extremely rarely). Then, users will only need to create object at the right place.

Don't mix clocks

Doing this:

std::chrono::time_point<std::chrono::steady_clock> m_StartTime;

and then

m_StartTime = std::chrono::high_resolution_clock::now();

is extremely bad idea. Not all standard libraries alias std::chrono::high_resolution_clock to steady_clock. Though I guess this is a feature of the code rather than a bug. The above will trigger compilation error in libc++ at least.

Know the subject

I know this is extremely simple clock, but since std::chrono::high_resolution_clock is used, I'd expect at least some mechanism to prevent compiler/execution unit optimizations, like std::atomic_thread_fence around it to prevent compiler optimizations and in general, make the execution point in which the time is taken observable. If none of what I said makes any sense to you, then your usage cases don't care about this.

Make it more reusable

I'd expect something like this:

template <typename Clock = std::chrono::high_resolution_lock>
class stopwatch
{
    /*...*/
};

Both time_point and duration are inferrable from Clock. I'd also like to see this:

template <typename Units = std::chrono::nanoseconds, typename Rep = double>
Rep elapsed_time()
{
    //ns chrono omitted for brevity
    return static_cast<Rep>(duration_cast<Units>(/*...*/).count());
}

(The static_cast is just to remove warnings when narrowing is done, which is intentional in this case, as default doesn't perform narrowing).

The project might suggest to change ordering of the template parameters, as Rep might be used more compared to Units.

Minor

Naming

CamelCase is usually used for type names in C++, the rest is camelCase. I personally prefer snake_case for everything, except template parameter and concept names, for which I use CamelCase. It is a matter of preference and consistency though.

Make header only if feasible

In this case, adding .cpp file makes it harder to use. .cpp file doesn't seem to make any difference, as any linkage nuances are not mentioned in the post. Also, making it header-only will make it even more simpler, which is I guess, the intention.

Putting it all together

Final code roughly looks like this:

#include <chrono>
#include <atomic>

namespace shino
{
    template <typename Clock = std::chrono::high_resolution_clock>
    class stopwatch
    {
        const typename Clock::time_point start_point;
    public:
        stopwatch() :
            start_point(Clock::now())
        {}

        template <typename Rep = typename Clock::duration::rep, typename Units = typename Clock::duration>
        Rep elapsed_time() const
        {
            std::atomic_thread_fence(std::memory_order_relaxed);
            auto counted_time = std::chrono::duration_cast<Units>(Clock::now() - start_point).count();
            std::atomic_thread_fence(std::memory_order_relaxed);
            return static_cast<Rep>(counted_time);
        }
    };

    using precise_stopwatch = stopwatch<>;
    using system_stopwatch = stopwatch<std::chrono::system_clock>;
    using monotonic_stopwatch = stopwatch<std::chrono::steady_clock>;
}

As you probably noticed, I changed default template arguments in elapsed_time(), and also incorporated const correctness from @JDługosz answer. The defaults change is to support all possible clocks and still avoid lossy conversionsby default.

Lets use this:

Measuring scheduler overhead using stopwatch

The measurements are rather naive:

#include <iostream>
#include <thread>

int main()
{
    std::cout << "testing scheduler overhead\n";
    using namespace std::literals;
    for (auto wait_time = 100ms; wait_time <= 1s; wait_time += 100ms)
    {
        shino::precise_stopwatch stopwatch;
        std::this_thread::sleep_for(wait_time);
        auto actual_wait_time = stopwatch.elapsed_time<unsigned int, std::chrono::microseconds>();
        std::cout << "Scheduler overhead is roughly " << actual_wait_time - (wait_time + 0us).count() << " microseconds"
                  << " for " << wait_time.count() << " milliseconds of requested sleep time\n";
    }
}

(Weird +0us is to let compiler handle the conversion from ms to us)

On my system gives:

testing scheduler overhead
Scheduler overhead is roughly 114 microseconds for 100 milliseconds of requested sleep time
Scheduler overhead is roughly 110 microseconds for 200 milliseconds of requested sleep time
Scheduler overhead is roughly 75 microseconds for 300 milliseconds of requested sleep time
Scheduler overhead is roughly 111 microseconds for 400 milliseconds of requested sleep time
Scheduler overhead is roughly 111 microseconds for 500 milliseconds of requested sleep time
Scheduler overhead is roughly 107 microseconds for 600 milliseconds of requested sleep time
Scheduler overhead is roughly 110 microseconds for 700 milliseconds of requested sleep time
Scheduler overhead is roughly 110 microseconds for 800 milliseconds of requested sleep time
Scheduler overhead is roughly 112 microseconds for 900 milliseconds of requested sleep time
Scheduler overhead is roughly 93 microseconds for 1000 milliseconds of requested sleep time

Full code to copy and run

#include <chrono>
#include <atomic>

namespace shino
{
    template <typename Clock = std::chrono::high_resolution_clock>
    class stopwatch
    {
        const typename Clock::time_point start_point;
    public:
        stopwatch() :
            start_point(Clock::now())
        {}

        template <typename Rep = typename Clock::duration::rep, typename Units = typename Clock::duration>
        Rep elapsed_time() const
        {
            std::atomic_thread_fence(std::memory_order_relaxed);
            auto counted_time = std::chrono::duration_cast<Units>(Clock::now() - start_point).count();
            std::atomic_thread_fence(std::memory_order_relaxed);
            return static_cast<Rep>(counted_time);
        }
    };

    using precise_stopwatch = stopwatch<>;
    using system_stopwatch = stopwatch<std::chrono::system_clock>;
    using monotonic_stopwatch = stopwatch<std::chrono::steady_clock>;
}

#include <iostream>
#include <thread>

int main()
{
    std::cout << "testing scheduler overhead\n";
    using namespace std::literals;
    for (auto wait_time = 100ms; wait_time <= 1s; wait_time += 100ms)
    {
        shino::precise_stopwatch stopwatch;
        std::this_thread::sleep_for(wait_time);
        auto actual_wait_time = stopwatch.elapsed_time<unsigned int, std::chrono::microseconds>();
        std::cout << "Scheduler overhead is roughly " << actual_wait_time - (wait_time + 0us).count() << " microseconds"
                  << " for " << wait_time.count() << " milliseconds of requested sleep time\n";
    }
}

Wandbox demo.


If you aren't considering using a mapping solution such as AutoMapper, you could make this code a bit more succient by removing some of the local variables and creating a couple of local methods that are responsible for creating the select lists.

The end solution would look something along the lines of:

public ActionResult Create()
{
    var viewModel = new CreateAPIViewModel
    {
        Team = ToSelectList(team.getAllTeams(),0),
        Application = ToSelectList(application.getAllApplications(),0)
    };

    //Send view model back
    return View(viewModel);
}

private List<SelectListItem> ToSelectList(IEnumerable<Team> applications, int selectedApplicationId)
{
    return applications
            .ToList()
            .Select(p =>
                new SelectListItem
                {
                    Value = Convert.ToString(item.ID),
                    Text = item.Name,
                    Selected = item.ID == selectedApplicationId
                });
}

private List<SelectListItem> ToSelectList(IEnumerable<Team> teams)
{
    return teams
            .ToList()
            .Select(p =>
                new SelectListItem
                {
                    Value = Convert.ToString(item.ID),
                    Text = item.Name,
                    Selected = item.ID == selectedTeamId
                });
}

This has the added benefit in that you most likely have a Edit() action as well.  You could re-use these methods.

public ActionResult Edit()
{
    var viewModel = new CreateAPIViewModel
    {
        Team = ToSelectList(team.getAllTeams(),team.Id),
        Application = ToSelectList(application.getAllApplications(),application.Id)
    };

    //Send view model back
    return View(viewModel);
}


First, the thing that was most obvious in your code was that you never used a space after a comma.

Second, you have the Matrix class where you override __new__ and __init__, however it would be work just fine if you'd use class Matrix(Dim): pass.

That's where I started to wonder why you define a Dim class and than inherit from it for Matrix and Vec, instead of code Matrix and subclass Vec from it. Any reason?

I would move the tests from Dim.__new__, except for the numbers test, to __init__. The iter test is not needed, you'll get an error from the list constructor or the for loop anyway.

One issue I see is that Matrix('abc') will result in endless recursion, because strings are iterable. Those are the places where I regret the absence of chr type in python :)

In Vec.__new__, I would let others customize the way they inherit from, why do you check if the class is a Vec or a Dim?

Last tip, when inheriting types like list or str, you have to override all the operator overloading methods if you plan on doing things like Vec((0, 1, 2)) * Vec((2, 3, 4))

Also:

[Vec.__name__,Dim.__name__] use tuples here, memory management

test2DMat = [[1,2,3],[4,5,6],[7,8,9]] I would break lines here


How can I refactor for handling multiple proto generated service clients by eliminating double await and the DRY code?

Angular
If you use Angular you are able to use store. For example ngxs or ngrx modules for your application.
One more way in angular use resolvers.

Interface that classes can implement to be a data provider. A data
provider class can be used with the router to resolve data during
navigation. The interface defines a resolve() method that is invoked
when the navigation starts. The router waits for the data to be
resolved before the route is finally activated.

//player.resolver.ts
class PlayerResolver implements Resolve<number> {
   private req = false;
   private repSubject = new ReplaySubject(null);

   constructor(private service: PlayerServiceClient) { }

   public resolve(route: ActivatedRouteSnapshot): Observable {
        if (!this.req) {
            this.req = true;

            this.service.get().subscribe(res => this.repSubject.next(res));
        }
        return this.subject.pipe(first());
    }
}

//app-routing.module.ts
const routes: Routes = [
...
    {
     path: 'player'
     resolve: {data: PlayerResolver}
    },
    {
     path: 'friend'
     resolve: {data: FriendResolver}
    }
]

ReactiveX
If you use RxJs in your app, you would to do caching, create BaseSender:
//base.sender.ts
let hash = require('object-hash');

class BaseSender {

  ...
  protected httpSenderWithCache(service: Observable<any>,param): Observable<any> {
    const id = hash(param);

    if (!this.cache$[id]) {
      this.expireCache(id, time);
      this.cache$[id] = service.pipe(
        shareReplay(1), // last value
        catchError((err) => console.log(err))
      );
    }

    return this.cache$[id];
  }

}

shareReplay(1) gets last result.  const id = hash(param); generate unique hash for caching.
//player.service.ts
export class PlayerService extends BaseSender {
   ....
   public get(param = null): Observable<any> {
    param = param || {};

    const data = {
        url: 'https://example.com/player',
        options: {
          params: param,
        },
      };
    const request$ = this.http.get(data.url, data.options);

    return this.httpSenderWithCache(request$, data);
  }
}

General
If you don't use it all.

Install and configire inversify-binding-decorators with decorators for DI in app. In main.ts create container.

//main.ts
    import { injectable, Container } from "inversify";
    import { provide, buildProviderModule } from "inversify-binding-decorators";
    import "reflect-metadata";

    var container = new Container();
    // Reflects all decorators provided by this package and packages them into
    // a module to be loaded by the container
    container.load(buildProviderModule());

Create interface ClientServiceInterface

//client-service.interface.ts
interface ClientServiceInterface {
  public get(param = null);
}

Create services

    @provide(PlayerServiceClient)
    export class PlayerServiceClient implements ClientServiceInterface {

      private result;

      public function get() {
         if(!result) {
           return fetch('https://ex.com/player')
                   .then(res => {
                      this.result = res;
                      return Promise.resolve(res)
                    })
         }
         return Promise.resolve(result);
      }
    }

in your components you have to inject service

  class PlayerComponent {
       constructor(private playerService: PlayerServiceClient) {
         playerService.get().then(...)
       }
    }


split items of batch into multiple categories

Your Collector is reinventing the wheel.  There already exists a collector which partitions the collected items into groups: Collectors.groupingBy, which you could use something like:

.collect(
    Collectors.groupingBy(
        item -> (item.category == CAT_3 || item.category == CAT_4) && !isValid(item.id)
                     ? CAT_5 : item.category)
    )
)

Of course, this will return a Map<ItemCategory, List<Item>>.  You can transform this back to a list of lists, if needed.

And of course, you would need to add the CAT_5 to the ItemCategory enum.  Alternately, you could use null at the category 5 key, if you don't mind null as a key value, but be warned that it will make some people's skin crawl.

If the order of the items in the all of the groups (as opposed to just the Category 5 group) does not matter, then groupingByConcurrent will give better parallel stream performance.


Meta-class to allow inspection of all __slots__of a class

This is a clever use of metaclasses - in a good way. The only thing I would change is to use set().union over update (this is debatable).


Trigger custom implicit conversion on "copy"

No problem with that at all, since it's not the copy which is doing the conversion (which would be strange) but the constructor.  Since the vector templates you've mentioned are clearly of different types, the operation you describe would not at all be unexpected.  It's little different from using std::copy to read from a file into an STL container, which is a common idiom.


Calculating daily project drilling hours

I would consider first splitting the method into smaller methods as other people have mentioned.  The only suggestion for now is I might suggest changing your bool daily to a enumeration. This in theory means it might be easier to add a Hourly,Monthly etc reporting option.  Although this is only slightly better in my opinion and I'm sure there are better approaches  (maybe using interfaces?).

Something like this as an exercise in splitting things out into various methods keeping most of your code but just re-arranging it slightly.

public double CalculateDrillingHours(DrillingPeriod period = DrillingPeriod.Daily, bool timeFrame = false)
{
    Logger.Info("Calculating Drilling Hours");
    var tempList = GetDrillingTimes(period, timeFrame);

    var drillingHours = CalculateDrillingHours(tempList);
    SetDrillingTimes(period, drillingHours);

    return drillingHours;
}

private void SetDrillingTimes(DrillingPeriod period, double drillingHours)
{
    switch (period)
    {
        case DrillingPeriod.Daily:
            Logger.Info("Total Drilling Hours calculated");
            DailyDrillingHours = drillingHours;
            break;
        case DrillingPeriod.Total:
            Logger.Info("Daily Drilling Hours calculated");
            TotalProjectDrillingHours = drillingHours;
            break;
        default:
            throw new NotImplementedException("Drilling period not supported");
    }
}

private List<DateTime> GetDrillingTimes(DrillingPeriod period, bool timeFrame)
{
    var query = "SELECT timestamp FROM myDatabase WHERE measured_dist = bit_loc AND rop > 0";

    var daily = period == DrillingPeriod.Daily;
    query = BuildQuery(query, daily, timeFrame);

    var tempList = ExecuteQuery(query);

    if (tempList.Any())
    {
        return tempList;
    }

    // I would look at possibly using a custom exception here i.e. NoDataException
    throw new NoDataException("There was no data for the selected time frame.  Please select another. (Drilling Hours)");
}

private double CalculateDrillingHours(List<DateTime> projectHours)
{
    return Convert.ToDouble(Math.Round(TimeCalculations(ConvertStringListToDateTimeList(projectHours)).TotalHours, 2, MidpointRounding.AwayFromZero));
}


Collecting data from different positions in a given array

Should work (at least it doesn't look like a riddle anymore:)

for ($i = 0; $i < 4; $i++) {
    $a = $i + 9;
    $b = 3 + $i * 4;

    $r[] = array(
        'na'   => $arr[$a][2],
        'pr'   => $arr[$a][3],
        'cu'   => $arr[$a][3],
        'val1' => $arr[6][$b],
        'val2' => $arr[5][$b],
        'val3' => $arr[4][$b]
    );
}

if $r[..]['cu'] is some function result assign to function call directly.


Checking an authentication decision in a JSON response

Guard Statements

My proposed changes takes advantage of Swift's guard statements. In this case I find them useful not only for breaking up the nested if statements, but also for clarifying the "requirements" or key conditions and increasing the readability for others and yourself.

For example:

guard let dictionary = json as? [String: Any] else {
   return
}

Can be interpreted as:

  "This dictionary must be valid or else we cannot continue"

The alternative to this is using a traditional if statement. However, this can lead to additional nesting and potentially also requires you to handle the alternative conditions, or in other words the else and else if conditions.

if let dictionary as? [String: Any] else {
    // I need another if statement to get something from the dictionary, but what if that key is not in the dictionary?
}

// Do I need an else condition? What if the dictionary is not valid?

Repetitive Code

The use of the guard statements also had the effect of eliminating some repetitive code used for setting up the UIAlertController. Repetitive code can lead to additional maintenance overhead and also bugs where you make a change in one place but forgot to replicate it in the duplicate code.

Unused Constant

I also made use of the json constant you declared. It seems that after it was declared, you did not use it in the block that follows.

Additional note

My proposed changes also incorporates oopexpert's advice. From a security standpoint, it would be better to not be specific as to why a login attempt has failed.

Proposed Refactoring

Alamofire.request(apiLink, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON {
    response in

    guard response.result.error == nil else {
        print("error calling POST in /###/###/###")
        print("Error: \(response.result.error)")
        return
    }

    if let json = response.result.value {
        print(response.result)
        print("JSON: \(json)")

        guard let dictionary = json as? [String: Any] else {
            return
        }

        guard let status = dictionary["status"] as? String, let message = dictionary["message"] as? String else {
            return
        }

        guard status == "ok" else {
            if message == "invalid_login" {
                let alertMessage = UIAlertController(title: "Unable to login", message: "Please try again", preferredStyle: .alert)
                alertMessage.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
                self.present(alertMessage, animated: true, completion: nil)
            }
            return
        }

        self.performSegue(withIdentifier: "Home", sender: nil)
    }
}


You could create your own TextReader that allows you to change the underlying Stream, or even directly reads from the ArraySegment<byte>.

But hundreds of times per second is not that often, are you sure worrying about allocations here is worth it? And if it is, I would first look at the 2 kB of buffer your StreamReader allocates every time it's created, rather than the few tens of bytes for the StreamReader and JsonTextReader objects.


Simple python COM server to expose scipy integration to VBA

Deferred Imports
Why is import win32com.server.register only imported during __main__? It should be inexpensive and clean to just leave it at the top with everything else. I'd also de-namespace from win32com.server.register import UseCommandLine but that's mostly a matter of taste.
Stubbing
You ask:

vbFunc is a PyIDispatch instance but not sure what that means for typing/mypy

If PyIDispatch is an importable type, then simply
def quad(self, vbFunc: PyIDispatch, a: float, b: float) -> float:

If it's not importable at all (this can happen for some libraries that are aggressively dynamic), then you basically have two options:

Declare an opaque, named NewType to make it clear to callers that this is not just "anything"
Do the work that the library should have done for you, and stub it yourself using a custom .pyi

Call protocols
# Callable[..., float]?

You're right to be confused, and mypy is still fairly terrible at annotating variadic callables. Here you should consider using Protocol:
class DispatchCall(typing.Protocol):
    def __call__(self, x: float, *parameters: COMCompatibleTypes) -> float:
        ... # literally an ellipsis

# Later:

func: DispatchCall = vb_dispatch.Evaluate

Unpacking
Re.
return integrate.quad(func, a, b)[0]  # only return val, not uncertainty

it's worth noting that uncertainty is not the only thing quad returns; there's actually y, abserr, infodict, message and explain.
It's minor, but I typically prefer to do at least a partial unpack to make it a little more clear what's happening:
y, *_ = integrate.quad(func, a, b)

Given the tuple length I don't think I'd do this, but you can if you think it adds clarity:
y, abserr, infodict, message, explain = integrate.quad(func, a, b)


In general the code is quite okay, here are a few remarks.

Maybe extract the body of the mouseClicked() method into a separate method, in case you have more code that would perform the same action, like when listening to keystrokes as well.
Consider using a JButton instead of a JLabel and use an ActionListener or even an Action instead of a MouseListener. Using a MouseListener for reacting on mouseClicked on the entire area of a JLabel seems like replicating something on a physical level for which Swing already provides something on a logical level.
I'd use WindowConstants.EXIT_ON_CLOSE instead of JFrame.EXIT_ON_CLOSE, as that's the original definition.
I'd use DISPOSE_ON_CLOSE instead of EXIT_ON_CLOSE and dispose all frames. Applications which use EXIT_ON_CLOSE become more difficult to test. When DISPOSE_ON_CLOSE doesn't work it usually means that you have a bad application design or bugs regarding threading.
Depending on what you want to achieve, you might be more interested in using JDialog or JOptionPane instead of JFrame for this use case. Maybe JOptionPane.showMessageDialog(). I can only recommend to look into those, not tell whether those are better for your use case, as your code and description don't give enough information for more.


Better late than never - Anon
first make it work, then make it right, and, finally, make it fast. -
Kernighan & Johnson
Rules of optimization:
(1) Don't.
(2) (for experts only) Don't yet.
(3) Profile before optimizing

First make it work, then make it right
There's a bug.  If $game_map#passable? always returns true, the
coordinates returned by this code are in this pattern:
XXXXXXXXX
X-X-X-X-X
XX-X-X-XX
X-X-X-X-X
XX-X-X-XX
X-X-X-X-X
XX-X-X-XX
X-X-X-X-X
XXXXXXXXX

Based on your description, you are (or were) looking for this pattern:
XXXXXXXXX
XXXXXXXXX
XXXXXXXXX
XXX---XXX
XXX---XXX
XXX---XXX
XXXXXXXXX
XXXXXXXXX
XXXXXXXXX

The trouble is here:
  radius.delete_if {|a|
    radius.include?([a[0] + 1, a[1]]) &&
      radius.include?([a[0] - 1, a[1]]) &&
      radius.include?([a[0], a[1] + 1]) &&
      radius.include?([a[0], a[1] - 1])
  }
  radius

One fix is to replace those lines with:
  radius.reject do |x, y|
    x.between?(@x - 1, @x + 1) && y.between?(@y - 1, @y + 1)
  end

and finally, make it fast
With the above fix, the code works, so let's benchmark it.  10,000
iterations of it take 0.600 seconds on my box.
We can do better.  Instead of adding coordinates just to remove them
later, how about not adding them in the first place?
    r = 4
    radius = []
    for x in @x-r..@x+r
      for y in @y-r..@y+r
        next if x.between?(@x - 1, @x + 1) && y.between?(@y - 1, @y + 1)
        radius.push([x, y]) if $game_map.passable?(x, y)
      end
    end
    radius

This is simpler, but is it faster?  Just a bit.  10,000 iterations now
take 0.500 seconds instead of 0.600.  More important, though, it's
simpler.
There doesn't seem to be much room for optimization here, which leads
to these questions:

Is the program fast enough?
If not, which part of the program is the bottleneck?

You can't answer those questions without profiling.  That's why the
first code you write should be clear and correct.  Then, only if it isn't
fast enough, profile to learn where it's too slow, and optimize that
part.  Repeat until it's fast enough, then stop.
The reason to optimize later rather than earlier is because
optimization has a cost.  It increases the complexity of the code,
often leading to code that's harder to read and maintain.  It's no
good to pay that cost unless you're getting actual benefit from it.
An OOP issue
This code should probably be in GameMap:
class GameMap
  ...

  def passable_coords_near(x, y)
    r = 4
    radius = []
    for x in (x - r)..(x + r)
      for y in (y - r)..(y + r)
        next if x.between?(x - 1, x + 1) && y.between?(y - 1, y + 1)
        radius.push([x, y]) if passable?(x, y)
      end
    end
    radius
  end

  ...
end


Use the function name given in the problem:
def getUnallottedUsers(bids, totalShares):

The problem doesn't provide any information about the likelihood of there being enough shares for all bidders, so IMO the first for-loop is an example of premature optimization.
Use constants instead of "magic numbers".  Use meaningful names.  Take a look at PEP8 about common formatting conventions.  These things go a long way in making code readable.
USERID = 0
SHARES = 1
PRICE = 2
TIME = 3

bids.sort(key=lambda bid:(-bid[PRICE], bid[TIME]))

for index, bid in enumerate(bids):
    totalShares -= bid[SHARES]

    if totalShares <= 0:
        break

Answer the question that was asked: "The function must return a list of integers, each an id for those bidders who receive no shares, sorted ascending"
return sorted(bid[USERID] for bid in bids[index + 1:])

All together:
USERID = 0
SHARES = 1
PRICE = 2
TIME = 3

def getUnallottedUsers(bids, totalShares):
    bids.sort(key=lambda bid:(-bid[PRICE], bid[TIME]))

    for index, bid in enumerate(bids):
        totalShares -= bid[SHARES]

        if totalShares <= 0:
            break

    return sorted(bid[USERID] for bid in bids[index + 1:])

Or use an iterator:
    bids = iter(bids)
    while totalShares > 0:
        price = next(bid)[PRICE]
        totalShares -= price

    return sorted(bid[USERID] for bid in bids)


Binary Search Tree implementation with topological validation

Coding style
Python has some conventions about coding style, for example snake_case for variables and functions etc. You can find these in pep-8
Node.__repr__
for troubleshooting, this can be handy:
def __repr__(self):
    return f"Node({self.value})"

with optionally the values of the children elements too
BST.update
adding a simple method to add multiple nodes can make initialization a lot simpler:
def update(self, values):
    for value in values:
        self.insert(value)

It also allows you to do this immediately in the __init__
def __init__(self, values=None):
    self.root = None
    if values is not None:
        self.update(values)

and use something like this in your tests:
bst = BST(range(5))

Node
All of the methods you prepend with an _ make more sense as methods on the Node
_xxorder
for example _inorder:
def inorder(self):
    if self.left is not None:
        yield from self.left.inorder()
    yield self
    if self.right is not None:
        yield from self.right.inorder()

and then BST.inorder:
def inorder(self):
    return self.root.inorder()

You can easily foresee a reverse iteration too (for example to find the maximum of the tree:
def inorder_reverse(self):
    if self.right is not None:
        yield from self.right.inorder_reverse()
    yield self
    if self.left is not None:
        yield from self.left.inorder_reverse()

same goes for the _doFind. Node.find:
def find(self, key):
    if self.value == key:
        return self
    next = self.right if self.value < key else self.left
    if next is None:
        return None  # or raise IndexError
    return next.find(key)

and BST.find:
def find(self, key):
    return self.root.find(key)

magic methods
isSameTree compares 2 trees. Why not name it __eq__.
Your implementation doesn't really use seld, so it might make more sense to transfer it to Node to compare subtrees
Node.__eq__:
def __eq__(self, other):
    if other is None:
        return False
    return (
        self.value == other.value
        and self.left == other.left
        and self.right == other.right
    )

BST.__eq__:
def __eq__(self, other):
    return self.root == other.root

You can easily implement the Iterator protocol on BST:
__iter__ = inorder

and reversed:
__reversed__ = inorder_reverse

Sum
You don't need the Sum class, you can just pass on a value. Also this method seems more appropriate under the Node class:
def sumRToL(self, partial_sum=0):
    if self.right is not None:
        partial_sum = self.right.sumRToL(partial_sum)
    self.value += partial_sum
    if self.left is not None:
        self.left.sumRTol(self.value)
    return self.value

Using this on mutable values might have strange effects.
on BST:
def sumelementsfromRtoLinplace(self):
    if self.root is not None:
        self.root.sumRToL()

validate
checking whether your tree is valid can become very easy via the iterator we just implemented. Using pairwise from the itertool recipes:
def validate(self):
    return all(a > b for a, b in pairwise(self)) # or self.inorder() for extra clarity

testing
These unit tests can be better done in another file, importing this file, and using one of the unit test frameworks. I'm quite happy with py.test.
import pytest

from binary_tree import BST

def test_order():
    bst = BST(range(10))
    assert [item.value for item in bst.inorder()] == list(range(10))
    assert [item.value for item in bst] == list(range(10))

def test_reverse():
    bst = BST(range(10))

    items = list(reversed(range(10)))
    assert [item.value for item in bst.inorder_reverse()] == items
    assert [item.value for item in reversed(bst)] == items

def test_equal():
    bst1 = BST(range(5))
    bst2 = BST(range(5))
    bst3 = BST(range(6))
    bst4 = BST(range(-3, 6))

    assert bst1 == bst2
    assert bst1 != bst3
    assert bst3 != bst1
    assert bst1 != bst4
...

total code
from general_tools.itertools_recipes import pairwise

class Node:
    def __init__(self, value):
        self.left: Node = None
        self.right: Node = None
        self.value = value

    def inorder(self):
        if self.left is not None:
            yield from self.left.inorder()
        yield self
        if self.right is not None:
            yield from self.right.inorder()

    def inorder_reverse(self):
        if self.right is not None:
            yield from self.right.inorder_reverse()
        yield self
        if self.left is not None:
            yield from self.left.inorder_reverse()

    def preorder(self):
        yield self
        if self.left is not None:
            yield from self.left.inorder()
        if self.right is not None:
            yield from self.right.inorder()

    def postorder(self):
        if self.left is not None:
            yield from self.left.inorder()
        if self.right is not None:
            yield from self.right.inorder()
        yield self

    def find(self, key):
        if self.value == key:
            return self
        next = self.right if self.value < key else self.left
        if next is None:
            return None  # or raise IndexError
        return next.find(key)

    def __eq__(self, other):
        if other is None:
            return False
        return (
            self.value == other.value
            and self.left == other.left
            and self.right == other.right
        )

    def sumRToL(self, partial_sum=0):
        if self.right is not None:
            partial_sum = self.right.sumRToL(partial_sum)
        self.value += partial_sum
        if self.left is not None:
            self.left.sumRTol(self.value)

    def __str__(self):
        return f"{self.value} "

    def __repr__(self):
        return f"Node({self.value})"

class BST:
    def __init__(self, values=None):
        self.root: Node = None
        if values is not None:
            self.update(values)

    def insert(self, key):
        if self.root is None:
            self.root = Node(key)
            return
        curr = self.root
        parent = None
        while curr and curr.value != key:
            parent, curr = curr, curr.right if curr.value < key else curr.left
        if parent is not None:
            if parent.value < key:
                parent.right = Node(key)
            else:
                parent.left = Node(key)

    def update(self, values):
        for value in values:
            self.insert(value)

    def delete(self, key):
        pass

    def find(self, key):
        return self.root.find(key)

    def inorder(self):
        return self.root.inorder()

    def inorder_reverse(self):
        return self.root.inorder_reverse()

    def preorder(self):
        return self.root.preorder()

    def postorder(self):
        return self.root.postorder()

    def sumelementsfromRtoLinplace(self):
        if self.root is not None:
            self.root.sumRToL()

    def validatebst(self):
        return all(a > b for a, b in pairwise(self))

    __iter__ = inorder
    __reversed__ = inorder_reverse

    def __eq__(self, other):
        return self.root == other.root


In terms of implementation, and making it more efficient, I don't think the linked list adds any particular value. I would rather see you implement the stack using a built-in list, which will improve both memory performance and speed.

So far, you have implemented push, pop, peek and iteration. Why iteration? I'm glad that it's destructive, but I don't understand why you felt you needed that.

I would suggest that you look at Python's Common Sequence Operations to see which you can implement. If you choose not to make the stack transparent, that's okay, but it might limit applicability. A transparent stack should be able to support in, count, maybe indexing, etc.

Likewise, have a look at the Mutable Sequence Types section and common operations. Also, check out the Abstract Base Classes for collections, and add whatever parent class(es) you implement.

Keep in mind that Python is a "consenting adult language." There is not a great regard for private data and access control. Instead, the expectation is that you will implement as much as you can, and not be surprised if someone wants to peek. So, I'd suggest trying to build as transparent and well-integrated a class as possible: allow accessing items on the stack via s[i] notation, support things like .find() and .count(), and inherit from whatever ABCs you support. If your stack is iterable, make sure you implement an Iterable abc. (Or Sequence, or Collection, or ...)


Couple of issues:

This appends the first letter of the word onto the end.

       word += word[0];

Since I don't know what "PigLatin" is I can't tell if this is correct. A comment about what is the expected translation is really required so we can understand if this is correct behavior.

This sets the first letter to 0.

       word[0] -= word[0];

Note: NOT the character 0 but the number zero which is an unprintable character (there are no glyphs that represent the number 0). Note the character 0 is represented by the number 48 (in ASCII or UTF-8).

Did you want to remove the first character from the string?

word = word.substr(1); // Gets the substring from 1 to the end.
                       // Assigns it to the variable word.

Adds the string "ay" to the end of word.

       word += "ay";

Sure. Sounds reasonable. But need to understand the expected behavior/

You have a string. Which you are converting into a sequence of words and storing in v.

    std::vector<std::string> v;

But the only thing you do with v is loop over it and get each word to call translate() with. Why not remove the middle man and not use the container at all.

Here You are creaging a loop as long as the string. But each iteration you are taking a word from the string.

    for(int i = 0; i < str.length(); i++){

So this will have a lot of blank words on the end. A better way is to read words from the stream until there are no more words in the stream.

    while (stringStream >> currentWord) {
        // Do stuff with currentWord
    }

Avoid the use of std::endl.

std::cout << std::endl;

Its probably not doing any harm here. But its a bad habit. The difference between \n and std::endl is that std::endl also flushes the buffer. Manually forcing a buffer flush is usually incorrect. The buffers will auto flush at the optimal time. Program inserted flushing is usually wrong and is a major cause of eniffciency in C++ code.

I would refactor the inner loop like this:

    while (stringStream >> currentWord) {
        std::cout << translate(std::move(currentWord)) + " ";
    }
    std::cout << "\n";

Notice the std::move() this moves an object to the function (saves a copy). So at the translate() needs to be changed slightly.

std::string translate(std::string&& word)
{                                ^^  bind a moved parameter.
   // stuff.
   return word;
}


Another view on @tokland solution:

def authenticate!
  return fail! unless account = Account.find_by(subdomain: subdomain)
  return fail! unless user = account.users.find_by(email: params["user"]["email"])
  return fail! unless user.authenticate(params["user"]["password"])
  success! user
end

This intention is to be as close to "original task explained in common English" as possible. And return keyword allows me to do that.


Here are a few callouts/suggestions:

You should throttle your code on the scroll event.  That way the event doesn't fire thousands of times.  You can read up this article for more information.  A basic example would be:

//which makes the `scroll` event fire every 250ms.
$(window).scroll( $.throttle( 250, loadVisibleImages) );

You probably don't need to get the viewport size every time through the loop.  This should be called once at the start and then only on the resize event.  Otherwise, it never changes so there is no need to re-calculate it.

//which makes the `resize` event fire every 250ms.
$(window).resize( $.throttle( 250, getViewportHeight) );

You can add a class to all the images that have already been processed and exclude them from your selector.  This way you are only dealing with new images.
For example:

function loadVisibleImages() {
  jQuery('img[data-src]').not('.processed').each(function() {
    if(jQuery(this).is(':visible')) {
        if(inView(jQuery(this), 100)) {
            this.src = jQuery(this).attr('data-src').addClass('processed');
        }
    }
  });
}

If you haven't already you should wrap your code in an IIFE so you can create a private scope.  Just take the code below and put it around your existing code.  This would also allow you to use $ for jQuery without worry.

(function( $ ) {
  //your code here
}) ( jQuery );

You could optimize the loop in your loadVisibleImages functions.  See your other question.

Hope that helps!


C++ minimal threadsafe array based on std::deque

Your code isn't thread-safe, as executing a read with .operator[]() and a write with .push_back() isn't synchronized in any way.
Even though no references to elements are invalidated by std::deque<T>::push_back(), it can change the data-structure to retrieve those references.

What you want to look into is called a readers-writer-lock, which is the primitive for allowing either multiple readers or only a single writer access at the same time.
C++17 provides it as std::shared_mutex, so you might have to use boost::shared_mutex unless your library is already there.


I believe this is as efficient as it gets, save for quickly detecting edge cases (a == 0 or a == b), which I think would be negligible anyway.

Recursion wouldn't be more efficient than iterative version. Functional languages can optimize recursion to the point where there's no difference, but I don't think Java excels at that and there's a performance penalty of adding new frames to the stack.

Recursion can make code clearer and more readable sometimes, but that's another story.

As a side note:

public EuclideanAlgorithm() {}; //Suppress default constructor

What's the purpose of this "suppression"?


Here is how you can use ExceptT:

  -- I hard-code the secret key, which I'm fine with for now
  let config = StripeConfig $ StripeKey "<redacted>"
  let stripe' :: (FromJSON (StripeReturn a))
              => StripeRequest a -> ExceptT StripeError Handler (StripeReturn a)
      stripe' = ExceptT . liftIO . stripe config

  -- Here's where things get hairy...
  r <- runExceptT $ do
    Customer {..} <- stripe' createCustomer
    Plan {..} <- stripe' $ getPlan (PlanId "PRO")
    stripe' $ createSubscription customerId planId
  case r of
    Left err -> do
      setMessage $ toHtml $ show err
      redirect (AppR :#: ("subscribe" :: Text))
    Right _ -> do
      setMessage "Subscription successful. Thanks!"
      redirect AppR

I used RecordWildcards so that the intermediate variables (e.g. cid and pid) aren't necessary.
You'll also need to enable FlexibleContexts because of the way stripe is defined in the library.


Find all instances of a given weekday in February for a given year

Java 8 Time APIs

Instead of the 'legacy' Calendar and DateFormat classes, you can rely on Java 8's new java.time.* APIs for more fluent chronology-related calculations.

For starters, your manually constructed Map can be replaced with a simple look-up on the DayOfWeek enum:

// scanner will be a wrapper over System.in
private static DayOfWeek getDayOfWeek(Scanner scanner) {
    String values = Arrays.toString(DayOfWeek.values());
    System.out.printf("Enter a day of week:%n%s%n", values);
    while (true) {
        try {
            return DayOfWeek.valueOf(scanner.nextLine().trim().toUpperCase());
        } catch (IllegalArgumentException e) {
            System.err.printf("Please try again with one of these:%n%s%n",
                    values);
        }
    }
}

The looping-validation ensures that only a valid DayOfWeek value is returned.

Next, you can use a couple of TemporalAdjusters to get the LocalDates you require:

firstInMonth(DayOfWeek): the first day-of-week of the month.
lastDayOfMonth(): the last day of the month.
next(DayOfWeek): the next day-of-week, i.e. 7 days from the LocalDate instance.

Then, with a helpful serving of DateTimeFormatter, the main processing logic can just be:

try (Scanner scanner = new Scanner(System.in)) {
    DayOfWeek dayOfWeek = getDayOfWeek(scanner);
    // getYear(Scanner) returns an int between the year range, MONTH = 2
    LocalDate first = LocalDate.of(getYear(scanner), MONTH, 1)
                                .with(TemporalAdjusters.firstInMonth(dayOfWeek));
    LocalDate last = first.with(TemporalAdjusters.lastDayOfMonth());
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
                                                    .withLocale(Locale.GERMANY);
    for (LocalDate date = first; !date.isAfter(last);
            date = date.with(TemporalAdjusters.next(dayOfWeek))) {
        System.out.println(formatter.format(date));
    }
}

Other observations

It's not recommended to throw a generic Exception as it's... too vague. You can consider using IllegalArgumentException for invalid year inputs outside \$[1500, 2005]\$, as the exception type is then more defined.
More importantly, you shouldn't be throwing your own Exceptions and then catching it purely as a form of flow control.
HashMap<String, Integer> daysOfWeek = new HashMap<>() can be better written as Map<String, Integer> daysOfWeek = new HashMap<>(), to program to an interface rather than the implementation.
As illustrated above, you should also consider using try-with-resources on the Scanner instance for safe and efficient handling of the underlying I/O resource.


People do this sort of thing all the time in the JavaScript (this.arguments) and Python world (*args); however, by removing type constraints from the parameter list, you have to be wary that you're always providing the types of parameters your function is expecting. If one of your parameters is supposed to be a string, and someone passes in an object, bad things may happen.

Conversely, some very respectable projects use multi-line parameter lists. It's fine to have a lot of parameters, as long as they're all necessary, but it's always good to be skeptical. Long parameter lists is a good code smell – if you see them, the code may need refactoring, but not always.

As far as the attributes of Box's, forget about programming for a second. Conceptually, what are the properties of a box? Can a box still be a box without a color, tileW, tileH, walkable, speedY, and speedX? Can a box still be a box if it doesn't know how to draw itself? If your answer is no to all of these, then your code is fine, and requiring parameters as a single collection/object vs. individual parameters is (arguably) a matter of preference.

That being said, I would move the three graphics.* lines to a separate method Box.draw(). It's best to only do construction in the constructor, and leave the rest – like rendering – to other methods.


Hackerrank "Breaking the Record" solution

You should be consistent with your naming: int[] score vs. int[] scores.

Avoid keeping state in static variables. Either pass the state explicitly as parameters in your function calls, or use instance variables. I recommend against mutating instance variables with recursion, since you would have to think about what the call stack looks like, while keeping track of what the mutable global state looks like. Those two styles of programming just don't mix well.

You have way overcomplicated the problem. The task is inherently O(n), because you must consider all n inputs. Furthermore, this task cannot be parallelized. You must consider the inputs in sequence, so divide-and-conquer is not an effective strategy. Basically, your recursion is just a pointlessly complicated way of iterating through the array from front to back.

The following straightforward loop would be much preferable:

public static int[] brokenRecords(int[] scores) {
    int highScore = scores[0],
        lowScore = scores[0],
        highRecords = 0,
        lowRecords = 0;
    for (int i = 1; i < scores.length; i++) {
        if (scores[i] > highScore) {
            highScore = scores[i];
            highRecords++;
        }
        if (scores[i] < lowScore) {
            lowScore = scores[i];
            lowRecords++;
        }
    }
    return new int[] { highRecords, lowRecords };
}


I don't think you need recursion. The items in your first loop always "eat" the other ahead of them. Loop all items, for each item check if it can merge into an item ahead of it, if yes, merge and remove the item that was ahead.

Now VB does store the "To" part of a for loop in memory, so you'll need to convert your For into Do loop instead.

If you want your main list to be untouched, you could clone it. But don't forget that it seems each instance will be affected in the two list if you do that.

Private Sub SimplifyModel2(ByVal listOri As List(Of Mesh3D))
    Dim indexOut, indexIn As Integer
    Dim currentMeshOutter, currentMeshInner As Mesh3D

    indexOut = 0

    Do While indexOut < istOri.Count
        currentMeshOutter = listOri(indexOut)
        indexIn = indexOut + 1

        Do While indexIn < istOri.Count
            currentMeshInner = listOri(indexIn)

            If Is3DOverlap(currentMeshInner, currentMeshOutter) Then
                currentMeshOutter.CombineMerge(currentMeshInner)
                istOri.Remove(currentMeshInner)
            Else
                indexIn += 1
            End If
        Loop

        indexOut += 1
    Loop

End Sub


Defining routes and controllers relationship for given pages

I asked myself today again the same question for my current project where I have to implement a bunch of entities that will need their own controllers implementing usual actions such as:

show()
list()
edit()
save()
delete()
etc...

I believe we can extract from each of these actions a logic/control flow pattern common to all entities.

Thus, an abstract EntityController implementing these actions seems to me the way to go... Of course we can inject in child controllers extending EntityController specific parameters and services.


Project Euler Problem #4 - Palindromic number

The other answers are all giving you different ways to reorganize your loops. They're all not bad in their own way, but the better solution in C# is to not write any loops in the first place.

Your program could be written like this:

static void Main()
{
    var query = from first in ThreeDigitNumbers()
                from second in ThreeDigitNumbers()
                let product = first * second
                where IsPalindromicNumber(product)
                select product;
    Console.WriteLine(query.Max());
}

Notice how every part of this program reads like the specification of the problem. The problem is "give the maximum of the palindromic numbers that are formed as the product of two three-digit numbers", and clearly that's what this program does.

Writing helper methods IsPalindromicNumber and ThreeDigitNumbers is left as an exercise.

Now, once that program is written and correct, then is the time to start asking questions about whether it is sufficiently fast, and so on. We could notice for instance that we check both 113 x 115 and 115 x 113, even though they obviously have the same result.  So we could then modify the query to

from second in ThreeDigitNumbersGreaterThan(first)

and then write that helper method. And so on.

(Exercise: Notice how introducing an optimization can introduce a bug if you're not careful. What bug did I just suggest that you write?)

But the takeaway here is write your program so that it looks like the specification. The specification does not say "write a bunch of loops". It says "find the maximum..." so there should be a call to Max in there somewhere. Write small methods that each do one thing well, and do exactly what they say on the tin.


Python script to scrape titles of public Youtube playlist

Well, how you handle the output of the titles can be improved. You don't need to fall back to using global variables here. They are very rarely really needed. Here it would be easier to make handle_starttag a generator, which is then consumed by str.join:

class MyHTMLParser(HTMLParser):

    def handle_starttag(self, tag, attrs):
        for attr in attrs:
            if attr[0] == "data-title":
                yield attr[1]

parser = MyHTMLParser()
titles = '\n'.join(parser.feed(html))
print(titles)

This assumes that HTMLParser.feed does not return any other values except from within the handle_starttag method (and that it actually returns the output of handle_starttag).

Note that I increased the number of spaces to 4 per indentation level, as recommended by Python's official style-guide, PEP8.

You also might want to add an early exit if the tag is not the correct tag.

If those assumptions above about feed are wrong, you might want to look for a different tool. Most parsing is done with BeautifulSoup, as far as I can tell. It offers strainers, with which you can reduce the amount of HTML to parse to only those tags you care about and CSS selectors which would let you directly select all of those tags with the right attribute.


just making sure this is efficient, for the null checks

Yes, it seems fine from an efficiency point of view. Here's a couple of simple alternatives you could consider.

Remove the need for the ! condition.  I quite like this option as I think it flows nicely and is easy to read.

private static string GetNeededValue(string param)
{
   // do we care about whitespace.  If so you could use IsNullOrWhiteSpace
   if(string.IsNullOrEmpty(param)) return param;

   var map = repo.Item(string.Format("CoverageName LIKE '{0}'",param));
   return map == null ? param : map.theNeededValue;
}

Or another alternative might be to be more explicit about when tValue is set.

private static string GetNeededValue(string param)
{
   var tValue = param;

   // do we care about whitespace.  If so you could use IsNullOrWhiteSpace
   if(!string.IsNullOrEmpty(tValue))

      var map = repo.Item(string.Format("CoverageName LIKE '{0}'",tValue));

      if(map != null)
         tValue = map.theNeededValue;
   }

   return tValue;
}


Program that provides diagrams for documentation

The Doxygen recommendation notwithstanding,

Consider adding PEP484 type hints, particularly to the signatures of functions such as draw_diagram. For that method, it's not really correct Python terminology to call the return value "void" - it's None.
Does the single-expression statement diagram.models actually have any effect? If so that deserves a comment.
Rather than glob.glob consider pathlib.Path.glob which has some usage niceties
path.basename(f)[:-3] is a very fragile way of acquiring a stem. Again, pathlib.Path can do a better job.

The line
dict([(name, cls) for name, cls in module.__dict__.items() if isinstance(cls, type)])

first of all should not use an inner list, since dict can directly accept a generator; and secondly would be better-represented as a dictionary comprehension:
{name: cls for name, cls in module.__dict__.items() if isinstance(cls, type)}

This loop:
    for name, cls in classes.items():
        print(f'Drawing {module_name}.{name} diagram')
        draw_diagram(module, cls_name=name, output_path=path.join(doc_path, module_name))

doesn't actually use cls, so should only iterate over the dictionary's keys, not its items.


I don't see an underscore variable name that is needed.  I don't understand why you did url_ = url in horoscope().  Why not just use url directly?  The only time you would want to do a straight var1 = var2 is for when one of them will be assigned to something else, and you want to remember the original value.  In this case, neither one changes, so they are still both the original by the end of the function.  I also don't see why you said horoscope_ = ... instead of just horoscope = ...  I think it may be because the function itself is named horoscope, but why should that make a difference?  Yes, conceivably you might have recursion later that would be surprised when horoscope means something else, but ... wait, why would you have recursion?  Since you won't, it doesn't change anything inside the function to have the same name, and since it isn't a global variable, it doesn't effect anything else.  As for sign_, I'll get to that later.

I am happy to see you using if __name__ == "__main__":.  That is an excellent piece of code that many people leave out.  I do wonder one thing, though: why is the print(...) outside of it?  Since url isn't defined unless the if __name__ == "__main__": block executes, you will have an error if you try to import this module.

The way you use str.lower(...) and str.strip(...) is definitely not conventional.  You very rarely need to access instance methods by using the class method with the instance as the first argument.  Just use it like an instance method:

sign = rinput.lower()
sign = sign.strip()

I would also suggest merging them:

sign = rinput.strip().lower()

rinput seems to be a strange name for user input. I would do something more like this:

sign = input("Enter your sign: ").strip().lower()

There really isn't a reason I can see to create more than one variable.

You first define url as blank.  I'm not sure why you do that, because a blank url causes a requests.exceptions.MissingSchema error in horoscope, whereas no url at all causes a NameError.  As far as I can tell, it doesn't make a difference to the user which error is shown.  I believe the error shouldn't be shown.  You should have error checking, and ask the user again for input.  (More later)

You don't need to use a for loop to get the index.  The list class already has a very handy method for it: .index().  I would suggest that you use it:

sign = signs.index(sign) + 1
url = "https://www.horoscope.com/us/horoscopes/general/horoscope-general-daily-today.aspx?sign={0}".format(sign)

This will throw an IndexError if the user types the wrong thing, so I would do something like this:

sign = ''
while True:
    sign = input("Enter your sign: ").lower.strip()
    if sign in signs:
        break
    print("That sign is not available.  The available signs are:")
    print("\n".join(signs)

That way, you make sure that the sign is valid before you try to get an index.

The requests.get function cat take a params argument for giving variables in the url.  I would suggest that you use that instead of putting the variables right into the url.  To do that, horoscope could be defined like this:

def horoscope(sign):
    url = "https://www.horoscope.com/us/horoscopes/general/horoscope-general-daily-today.aspx"
    page = requests.get(url, params={'sign': sign})

You can then call it with horoscope(sign) (where sign is the index + 1).


Optimizing this method (HashSet.RemoveWhere performance issue)

Instead of using the RemoveWhere() method together with the Any() method you should consider to just use ExceptWith() method.

public static HashSet<PathDetails> GetDeletedPaths(HashSet<PathDetails> old, HashSet<PathDetails> current)
{
    var deleted = new HashSet<PathDetails>(old);
    deleted.ExceptWith(current);
    return deleted;
}

Your approach calls for each item in deleted the Any() of current whereas ExceptWith() just calls for each item in current the Remove() method of deleted.


The above encrypt/decrypt functions can be summarized as follows:

void mad_encrypt(...)
{
  while(n)
  {
    SHA512(mad, 96, x);
    XOR(out, in, x);
    memcpy(mad->state, out, 64);
    ...
  }
}

void mad_decrypt(...)
{
  while(n)
  {
    SHA512(mad, 96, x);
    XOR(out, in, x);
    memcpy(mad->state, in, 64);
    ...
  }
}

This is basically the CFB mode. Note that the two functions are almost identical, except a small difference in memcpy.

AES in CFB mode is done in much the same way, except of course it uses AES block cipher instead of SHA512(...) function above. Also AES uses blocks of 16 bytes, so AES has to run 4 rounds to catch up with a single SHA512 round. Overall, AES is faster.

To compare the performance you can simply compare 4 rounds of AES to 1 round of SHA512. Watch out for compiler optimizations which may skew the result. Many tests have already been done for this, it shows AES is faster.

AES also uses key expansion which makes it more secure. Key expansion is relatively slow but it's done only once per file/data. This may skew the performance test depending on how the test is done.

typedef struct {
  unsigned char state[64];
  unsigned char key[32];
} MadCtx;

For improvement, don't let the key linger on in MadCtx::key. For example, you can use SHA512 to combine the key with IV (or state as you call it) so it becomes hidden during the operation, then you can drop key out of the structure.

Example:

unsigned char mad_IV[64];

void mad_init(const unsigned char *key, const unsigned char* iv)
{
    unsigned char buf[96];
    memcpy(buf, iv, 64);
    memcpy(buf + 64, key, 32);
    SHA512(buf, 96, mad_IV);
}

void mad_crypt(char const* in, int in_size, char* out, int encrypt)
{
    assert(0 == in_size % 64);

    int n = in_size >> 6; // in_size / 64
    while (n)
    {
        SHA512(mad_IV, 64, mad_IV);
        _xor64((uint64_t*)out, (uint64_t*)in, (uint64_t*)mad_IV);

        if (encrypt)
            memcpy(mad_IV, out, 64);
        else
            memcpy(mad_IV, in, 64);

        in += 64;
        out += 64;
        --n;
    }
}

int main()
{
    unsigned char iv[64] = { 0 };
    unsigned char key[32] = { 0 };
    memcpy(iv, "iv", 2);
    memcpy(key, "key", 3);

    int size = 640;
    char *plaintext = malloc(size);
    char *decrypted = malloc(size);
    char *encrypted = malloc(size);

    memset(plaintext, 0, size);
    memset(encrypted, 0, size);
    memset(decrypted, 0, size);

    strcpy_s(plaintext, size, "plainxxxxxx.");

    mad_init(key, iv);
    mad_crypt(plaintext, size, encrypted, 1);

    mad_init(key, iv);
    mad_crypt(encrypted, size, decrypted, 0);

    phex(encrypted, 64);
    printf("\n\n");

    printf("plaintext: %s\n", plaintext);
    printf("decrypted: %s\n", decrypted);

    putchar('\n');

    return 0;
}


Simplifying Cryptography Key Generation without Losing Security

Why are you using 3DES instead of AES?  Why is the algorithm hard-coded in EncryptBytes, but parameterized in GetKey() and GetIV()?

The last line looks suspicious — did you mean bits / 8?

protected byte[] DeriveBytes(int bits)
{
    Rfc2898DeriveBytes derivedBytes = new Rfc2898DeriveBytes(Password, Salt, 1000);
    return derivedBytes.GetBytes(bits / 8);
}

If so, then shouldn't it be…?

public byte[] GetKey(SymmetricAlgorithm algorithm)
{
    return DeriveBytes(algorithm.KeySize);
}


Sort by year and day descending, yet time ascending

Main problem that I see, is cast to int, as it will overflow in
   23 days!!!

Regarding 24:00 correctness, that depends is that ticks in local timezone or UTC and if you care, but I'd suggest to write Unit Test that validates this algorithm on some set of events, for whole year, and lot of events per day, to verify every case.

Additionally make millisecondsPerDay a constant inside Comparator, but upper then method

new Comparator<LogEntry>() {
        static final long MILLISECONDS_PER_DAY = 86400000;
        @Override
        public int compare(LogEntry lhs, LogEntry rhs) { ...}
}

EDIT

You don't need Math.floor, as this is integral numbers, so dividing gives number of days as integral number.

I'd suggest following code:

Collections.sort(listEntries, new Comparator<LogEntry>() {

        static final long MILLISECONDS_PER_DAY = 86400000;

        @Override
        public int compare(LogEntry lhs, LogEntry rhs) {
            long lhsCreatedAt = lhs.getCreatedAt();
            long rhsCreatedAt = rhs.getCreatedAt();

            long lhsDays = lhsCreatedAt/MILLISECONDS_PER_DAY;
            long rhsDays = rhsCreatedAt/MILLISECONDS_PER_DAY;
            if(lhsDays == rhsDays){
                 return (int)(lhsCreatedAt%MILLISECONDS_PER_DAY - rhsCreatedAt%MILLISECONDS_PER_DAY)
            }
            return (int)(rhsDays-lhsDays);
        }
    });

Well, if block can be following, as long as we are in the same day, no need to divide additional time:

            if(lhsDays == rhsDays){
                 return (int)(lhsCreatedAt - rhsCreatedAt)
            }


You can make your merge sort run 35% faster by allocating the auxiliary memory only once and reusing it throughout the algorithm:

def coderodde_merge(source,
                    target,
                    source_offset,
                    target_offset,
                    left_run_length,
                    right_run_length):
    left_run_index = source_offset
    right_run_index = source_offset + left_run_length

    left_run_index_bound = right_run_index
    right_run_index_bound = right_run_index + right_run_length

    while left_run_index != left_run_index_bound and right_run_index != right_run_index_bound:
        if source[right_run_index] < source[left_run_index]:
            target[target_offset] = source[right_run_index]
            right_run_index += 1
        else:
            target[target_offset] = source[left_run_index]
            left_run_index += 1
        target_offset += 1

    while left_run_index != left_run_index_bound:
        target[target_offset] = source[left_run_index]
        target_offset += 1
        left_run_index += 1

    while right_run_index != right_run_index_bound:
        target[target_offset] = source[right_run_index]
        target_offset += 1
        right_run_index += 1

def coderodde_mergesort_impl(source,
                             target,
                             source_offset,
                             target_offset,
                             range_length):
    if range_length < 2:
        return

    left_run_length = range_length // 2
    right_run_length = range_length - left_run_length

    coderodde_mergesort_impl(target,
                             source,
                             target_offset,
                             source_offset,
                             left_run_length)

    coderodde_mergesort_impl(target,
                             source,
                             target_offset + left_run_length,
                             source_offset + left_run_length,
                             right_run_length)

    coderodde_merge(source,
                    target,
                    source_offset,
                    target_offset,
                    left_run_length,
                    right_run_length)

def coderodde_mergesort(array, start, end):
    range_length = end - start

    if range_length < 2:
        return

    aux = [array[index] for index in range(start, end)]
    coderodde_mergesort_impl(aux, array, 0, start, range_length)

def coderodde_mergesort_all(array):
    coderodde_mergesort(array, 0, len(array))

When running this demonstration, I get the following results:

OP mergesort in 17628 milliseconds.
coderodde mergesort in 11411 milliseconds.
Algorithms agree: True

Also, as an additional nitpick, by PEP 8 you should separate binary operators by a space before and after, i.e., not i+=1, but i += 1.

Check you range

If I do something as crazy as

ar = [1, 2, 3]
merge_sort(ar, 0, -1)

you will get a stack overflow.


Converting decimal integer to binary string

What about taking the trailing zero out of the loop?

while (counter > 0) {

// ...

    if (counter == y) {
        bin[counter] = '\0';
    }

might look like this

bin[counter] = '\0';
--counter;

while (counter > 0) {

// ...

and you don't need int y anymore.

Also --counter might be tiny bit faster than counter-- in case your optimizer is not going to help you.

As the code is not dealing with negative values I guess

char* DectoBin(unsigned dec) {

would be more appropriate.


Yes, use namespace and resources:

namespace :oauth do
  resources :apps, controller: "applications", as: :applications
end

This is not 100% identical (the names of some of your routes have changed) but it is the way you should be building your routes, and you should change the rest of your app to reflect the change.

The primary difference is your names for the create and destroy routes have gone away; these routes shouldn't have names anyways. When you want to create/destroy a model, you should be using oath_applications_path, with  method: :post or method: :delete, not oath_apps_new_path/destroy_oauth_application_path.

My way also uses the correct verb (PUT) for updates.

Your rake routes:

       oauth_applications GET    /oauth/apps(.:format)             oauth/applications#index
    new_oauth_application GET    /oauth/apps/new(.:format)         oauth/applications#new
           oauth_apps_new POST   /oauth/apps/new(.:format)         oauth/applications#create
        oauth_application GET    /oauth/apps/:id(.:format)         oauth/applications#show
   edit_oauth_application GET    /oauth/apps/:id/edit(.:format)    oauth/applications#edit
                          POST   /oauth/apps/:id/edit(.:format)    oauth/applications#update
destroy_oauth_application DELETE /oauth/apps/:id/destroy(.:format) oauth/applications#destroy

My rake routes (reordered to match yours):

    oauth_applications GET    /oauth/apps(.:format)          oauth/applications#index
 new_oauth_application GET    /oauth/apps/new(.:format)      oauth/applications#new
                       POST   /oauth/apps(.:format)          oauth/applications#create
     oauth_application GET    /oauth/apps/:id(.:format)      oauth/applications#show
edit_oauth_application GET    /oauth/apps/:id/edit(.:format) oauth/applications#edit
                       PUT    /oauth/apps/:id(.:format)      oauth/applications#update
                       DELETE /oauth/apps/:id(.:format)      oauth/applications#destroy


Enhanced Hashmap - Add a number to all keys/values

I would suggest you create your own OffsetIntegerMap that can map between integers and handle an offset on the keys and values.
You don't necessarily have to implement the HashMap from scratch, define your own limited interface and implement it with an existing Map<Integer, Integer> through composition.
By handling the offsets separately from the keys and values the complexity of the offset operations end up O(1) instead of O(n) when doing recalculations and the Map<> put and get operations stay at their original O(1).
An example an "OffsetIntegerMap":
import java.util.HashMap;
import java.util.Map;

public class OffsetIntegerMap {
    private final Map<Integer, Integer> actualMap;
    private int keyOffset = 0;
    private int valueOffset = 0;

    public OffsetIntegerMap() {
        actualMap = new HashMap<>();
    }

    public int size() {
        return actualMap.size();
    }

    public boolean isEmpty() {
        return actualMap.isEmpty();
    }

    public boolean containsKey(int key) {
        var keyWithoutOffset = key - keyOffset;
        return actualMap.containsKey(keyWithoutOffset);
    }

    public boolean containsValue(int value) {
        var valueWithoutOffset = value - valueOffset;
        return actualMap.containsValue(valueWithoutOffset);
    }

    public Integer get(int key) {
        var keyWithoutOffset = key - keyOffset;
        var value = actualMap.get(keyWithoutOffset);
        if (value == null) return null;
        return value + valueOffset;
    }

    public Integer put(int key, int value) {
        var keyWithoutOffset = key - keyOffset;
        var valueWithoutOffset = value - valueOffset;
        var oldValue = actualMap.put(keyWithoutOffset, valueWithoutOffset);
        if (oldValue == null) return null;
        return oldValue + valueOffset;
    }

    public Integer remove(int key) {
        var keyWithoutOffset = key - keyOffset;
        var oldValue = actualMap.remove(keyWithoutOffset);
        if (oldValue == null) return null;
        return oldValue + valueOffset;
    }

    public void clear() {
        actualMap.clear();
        keyOffset = 0;
        valueOffset = 0;
    }

    public int getKeyOffset() {
        return keyOffset;
    }

    public void setKeyOffset(int keyOffset) {
        this.keyOffset = keyOffset;
    }

    public int getValueOffset() {
        return valueOffset;
    }

    public void setValueOffset(int valueOffset) {
        this.valueOffset = valueOffset;
    }

    public void addToValues(int toAdd) {
        this.valueOffset += toAdd;
    }

    public void addToKeys(int toAdd) {
        this.keyOffset += toAdd;
    }
}

By encapsulating the offset logic the processing loop also becomes much simpler without refactoring much of anything:
static long hashMap(String[] queryType, int[][] query) {
    long sum = 0;
    var map = new OffsetIntegerMap();
    for (int i = 0; i < queryType.length; i++) {
        String currQuery = queryType[i];
        switch (currQuery) {
            case "insert":
                map.put(query[i][0], query[i][1]);
                break;
            case "addToValue":
                map.addToValues(query[i][0]);
                break;
            case "addToKey":
                map.addToKeys(query[i][0]);
                break;
            case "get":
                sum += map.get(query[i][0]);
        }
    }
    return sum;
}


Refactoring code to throw a single exception per function

UnsupportedEncodingException can easily be avoided by wrapping the call that might throw it:

try {
  return java.net.URLDecoder.decode(body, "UTF-8");
} catch (UnsupportedEncodingException ex) {
  throw new IllegalStateException(ex);
}

Indeed, "UTF-8" is one of most common encodings and that would be really surprising that such exception is thrown here. Semantically, it is close to an illegal state of the application: one would hardly imagine that it cannot support this encoding nowadays.

Since the chained IllegalStateException is a RuntimeException, you will be able to remove it from the signatures of the methods.


I applaud any use sequential machine.  A primitive that simulates a state machine... fruit only the tree of J could produce... why resist?

So while in that way ;: is quintessential J, state machines are, on the other hand, procedural in mindset.  Idiomatic J, by contrast, tends to frame the problem as a whole -- to solve in a single leap, rather than step by step.

How can we do that in this case?

The big trick is to encode the directions as complex numbers.  An L just multiplies the current direction by i, or 0j1 in J.  And an R multiplies by 0j_1.  Then your direction at any point in time is just the scan product */\ of your starting position and the sequence of encoded L and R.  For this step, M is encoded as 1, since it doesn't alter the direction.

Making the above concrete, let's see how the first example looks.  The encoded commands (top) and their scan product (bottom):

┌───┬───┬──┬────┬────┬───┬─┬───┬───┬───┐
│0j1│0j1│1 │0j1 │1   │0j1│1│0j1│1  │1  │
├───┼───┼──┼────┼────┼───┼─┼───┼───┼───┤
│0j1│_1 │_1│0j_1│0j_1│1  │1│0j1│0j1│0j1│
└───┴───┴──┴────┴────┴───┴─┴───┴───┴───┘

We end facing N, as desired.

Similarly, thinking of adding complex numbers as vector addition, the final position is just the sum of the initial position and every direction vector corresponding to an M.  The latter sum is just the sum of the element-wise product of the bottom row above, and the boolean mask of Ms:

┌───┬──┬──┬────┬────┬─┬─┬───┬───┬───┐
│0j1│_1│_1│0j_1│0j_1│1│1│0j1│0j1│0j1│
├───┼──┼──┼────┼────┼─┼─┼───┼───┼───┤
│0  │0 │1 │0   │1   │0│1│0  │1  │1  │
└───┴──┴──┴────┴────┴─┴─┴───┴───┴───┘

Using your code for argument parsing, and putting this all together, we get:

NB. convert direction to complex number

j =: 0j1 ^ 'ENWS' i. ]

NB. full solution

final =. 3 : 0
  'a b dir cmds' =. y
  dirs=. */\ (j dir) , 0j1 ^ 'ML.R' i. cmds       NB. all directions
  pos =. (a j.&". b) + +/ dirs * 0 , 'M' = cmds   NB. all positions
  (+. pos) ; j inv {: dirs
)

and running it:

f=. 0 : 0
5 5
1 2 N
LMLMLMLMM
3 3 E
MMRMMRMRRM
)

input =.  _4]\ 2 }. '' cut (' ',LF) charsub f

echo input
echo final"1 input

produces:

┌─┬─┬─┬──────────┐
│1│2│N│LMLMLMLMM │
├─┼─┼─┼──────────┤
│3│3│E│MMRMMRMRRM│
└─┴─┴─┴──────────┘
┌───┬─┐
│1 3│N│
├───┼─┤
│5 1│E│
└───┴─┘

Try it online!


Church Numerals - implement one, two, and addition

Church defined numerals as the repeated application of a function.  The first few numerals are defined thus:

(define zero (lambda (f) (lambda (x) x)))
(define one (lambda (f) (lambda (x) (f x))))
(define two (lambda (f) (lambda (x) (f (f x)))))

... and so on.

To see how one is derived, begin by defining one as (add-1 zero) and then perform the applications in order as shown in the steps below (I have written each function to be applied and its single argument on separate lines for clarity):

;; Givens
(define add-1 (lambda (n) (lambda (f) (lambda (x) (f ((n f) x))))))
(define zero (lambda (f) (lambda (x) x)))

(define one
  (add-1    ;; substitute with definition of add-1
   zero))

(define one
  ((lambda (n)    ;; apply this function to argument zero
     (lambda (f) (lambda (x) (f ((n f) x)))))
   zero))

(define one
  (lambda (f) (lambda (x) (f ((zero    ;; substitute with definition of zero
                               f) x)))))

(define one
  (lambda (f) (lambda (x) (f (((lambda (f)    ;; apply this function to argument f
                                 (lambda (x) x))
                               f)
                              x)))))

(define one
  (lambda (f) (lambda (x) (f ((lambda (x)    ;; apply this function to argument x
                                x)
                              x)))))

(define one
  (lambda (f) (lambda (x) (f x))))    ;; we're done!

You may try your hand at two in a similar fashion. =)

By definition, Church numerals are the repeated application of a function.  If this function were the integer increment function and the initial argument were 0, then we could generate all natural numbers 0, 1, 2, 3, ....  This is an important insight.

Thus, a Church numeral is a function that takes one argument, the increment function, and returns a function that also takes one argument, the additive identity.  Thus, if we were to apply a Church numeral to the integer increment function (lambda (n) (+ 1 n)) (or simply add1 in Scheme), which we then apply to the integer additive identity 0, we would get an integer equivalent to the Church numeral as a result.  In code:

(define (church-numeral->int cn)
  ((cn add1) 0))

A few tests:

> (church-numeral->int zero)
0
> (church-numeral->int one)
1
> (church-numeral->int two)
2
> (church-numeral->int (add-1 two))
3
> (church-numeral->int (add-1 (add-1 two)))
4

A Church-numeral addition should take two Church numerals as input, and not integers, as in your code.

We use the insight above about increment functions and additive identities to notice that integer addition is simply repeated incrementing.  If we wish to add integers a and b, we begin with the number b and increment it a times to get a + b.

The same applies to Church numerals.  Instead of using integer increment function and integer additive identity, we use the Church increment function add-1 and we begin with a Church numeral as the additive identity.  Thus, we can implement Church-numeral addition as:

(define (plus cn-a cn-b)
  ((cn-a add-1) cn-b))

A few examples:

(define three (plus one two))
(define four (plus two two))
(define five (plus two three))
(define eight (plus three five))

... and associated tests:

> (church-numeral->int three)
3
> (church-numeral->int four)
4
> (church-numeral->int five)
5
> (church-numeral->int eight)
8


Python Binary Search Tree Implementation

docstrings

Docstrings matter. Delete the cryptic #BST comment and spell it out in a PEP8 class docstring:

class Node:
"""Implements a Binary Search Tree."""

Either search or __init__ needs a docstring that mentions the equality case (I'm looking at elif root.val < k:, as opposed to <= k).

correctness

I can't imagine successor is correct. You didn't offer any unit tests like this, but I'm thinking of passing in a node with no right subtree, a node having the same value as root. Then we return None ?? This comes back to the <= k detail I mentioned above. Anyway, predecessor is nicely parallel, simple is good. And insert is beautiful and concise.

public API design

For some methods, rather than passing in root, it would be more natural to be working with an instance of your BST class, with self.root implicitly available.

style

As a trivial style detail, in parent you might use parentheses a level deeper to remove the backslash.

I didn't run flake8 myself, but overall it looks good. I have a weak preference for if node.left: instead of if node.left is not None:.

tests

I'm looking at this:

class BSTTest(unittest.TestCase):
    def test_recursive_search(self):
        root  = build_bst()
        actual = search(root, 35).val
        expected = 35
        self.assertEqual(expected, actual)

I would much rather see the method expressed concisely:

    def test_recursive_search(self):
        root  = build_bst()
        self.assertEqual(35, search(root, 35).val)

It might even come out as:

    def test_recursive_search(self):
        self.assertEqual(35, search(self.root, 35).val)

where build_bst() is invoked by a setup method.

There are other tests, e.g. test_insert_on_empty_tree, where of course hanging on to an actual temp variable is the natural way to express it.

I am very glad to see these tests. They appear to give reasonable code coverage.

Another example tree that stores multiple copies of a given value (e.g. 30) would be of interest.

summary

Overall it looks good! Ship it.


The idea with objects is they maintain the data that they own. Try to avoid having the object hold onto other data just because it uses it. This makes later refactoring harder.
Below is a sketch of what the process chain might look like.

class Sensor(object):
    def process(self, conditions):
        if not self.is_respecting_conditions(conditions):
            raise Exception("Fill me in properly")

        self.apply(conditions)

class Module(object):
    def process(self):
        for s in self.sensors:
            try:
                s.process(self.conditions)
            except:  # Handle actual exception here
                pass  # whatever work is needed

class Environment(object):
    def process(self):
        for m in self.modules:
            m.process()

This assumes that the conditions are per module. If they are per Environment then you could would add the condition parameter to the process method of the Module object.


I think that caching should look the same on every function,

cached_f(args):
    if args not in cache:
        cache[args] = f(args)
    return cache[args]

So Fibonacci becomes:

cache = {}
def fib(n):
    if n not in cache.keys():
        cache[n] = _fib(n)
    return cache[n]

def _fib(n):
    if n < 2:
        return n
    else:
        return fib(n-1) + fib(n-2)

I'm not sure why the cache should not be global (other than namespace pollution), you could end with duplication of the results and also missing a cached result making you compute again what you wanted to avoid computing.

Also, you may initialize the cache with the base cases and skip them when writing the recursion, but that is not so clean.


If I understood correctly, you have to traverse a list of components where each element has a hierarchy-like structure?

Try the visitor pattern https://www.tutorialspoint.com/design_pattern/visitor_pattern.htm it is a very clean solution of what you're trying to do without any static methods.

And for traversing the children of each component, I think you're trying to do a pseudo-BFS, but it's a bit confusing. BFS is very tricky using recursion. The iterative version kf BFS should be something similar to this https://stackoverflow.com/questions/16380026/implementing-bfs-in-java