Angular 2 service to upload a batch job and poll for results

First of all, there are some stylish issues in the code:

let input = new FormData();
// `input` is never reassigned so you should use `const` instead of `let`:
const input = new FormData();

input.append("file", fileToUpload);
// you should use single-quotes for strings:
input.append('file', fileToUpload);

this.http.get("/emerald/storage/submit-status/" + trackingId)
// you can use string interpolation here:
this.http.get(`/emerald/storage/submit-status/${trackingId}`)

if (serverAnswer['status'] == 'PENDING') { }
// you should use triple-equals:
if (serverAnswer['status'] === 'PENDING') { }

and some semicolons are missing.

If you use @angular/cli with this project, I suggest ng lint to point and fix thoses little issues.

In the Upload class, we are expecting a message as a string but in case of failure we are passing an Error:

.catch((err: Error) => new Upload(Status.FAIL, err.message, new Date()));

Moreover about the Upload class, I think it can be misleading that timestamp member is typed as a Date, if it's a Date it should be named date or it should be typed as a number.

Then I think you can simplify the code with interfaces representing the server responses, here is a fixed and commented version of the code:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';

// it's possible to use string enum since typescript 2.4
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html
export enum Status { PENDING = 'PENDING', SUCCESS = 'SUCCESS', FAIL = 'FAIL'}

export interface ContentResponse {
  readonly success: boolean;
  readonly trackingId: number;
}

export interface StatusResponse {
  readonly status: Status;
  readonly timestamp: number;
}

export class Upload {
  constructor(public readonly status: Status,
              public readonly message: string,
              public readonly date: Date) { // renamed timestamp -> date
  }
}

@Injectable()
export class EmeraldBackendStorageService {

  constructor(private http: Http) {
  }

  upload(fileToUpload: any): Promise<Upload> {
    const input = new FormData();
    input.append('file', fileToUpload);
    return this.http.post('/emerald/storage/submit-content', input)
       // we don't need to manually json parse the response,
       // response has already a method for that exact purpose
      .map((response: Response) => response.json())
      // we assume that we get a ContentResponse from the server
      // so it's easier to use our serverAnswer
      .toPromise().then((serverAnswer: ContentResponse) => {
        if (!serverAnswer.success) {
          throw new Error('POST request failed');
        }
        return this.subscribeSubmitStatusTracker(serverAnswer.trackingId);
      }).catch((err: Error) => new Upload(Status.FAIL, err.message, new Date()));
  }

  private subscribeSubmitStatusTracker(trackingId: number): Promise<Upload> {
    return this.http.get(`/emerald/storage/submit-status/${trackingId}`)
      .map((response: Response) => response.json())
      .toPromise().then((serverAnswer: StatusResponse) => {
        if (serverAnswer.status === Status.PENDING) {
          return new Promise<Upload>((resolve) => {
            setTimeout(() => resolve(this.subscribeSubmitStatusTracker(trackingId)), 5000);
          });
        } else if (serverAnswer.status === Status.SUCCESS) {
          return new Upload(Status.SUCCESS, null, new Date(serverAnswer.timestamp));
        } else {
          throw new Error(`Server can't process uploaded file`);
        }
      }).catch((err: Error) => new Upload(Status.FAIL, err.message, new Date()));
  }
}

Finally, an api returning a Promise<Upload> and the use of the toPromise operator is clearly not the angular way. In angular almost everything is an observable so the users of your api will expect observables.

As suggested by NewtonCode, you should use rxjs to achieve the functionality and return an Observable<Upload>.

Here is a rewrite with observables in mind:

import { Injectable, InjectionToken, Inject } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/interval';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/take';

export enum Status { PENDING = 'PENDING', SUCCESS = 'SUCCESS', FAIL = 'FAIL'}

export interface ContentResponse {
  readonly success: boolean;
  readonly trackingId: number;
}

export interface StatusResponse {
  readonly status: Status;
  readonly timestamp: number;
}

// I need to configure the interval of time between request for testing purpose,
// because `fakeAsync`seems to have an issue with setInterval in Observable
// https://github.com/angular/angular/issues/10127
export interface EmeraldConfig {
  readonly intervalBetweenTrackingRequests: number;
}

export const EMERALD_CONFIG = new InjectionToken<EmeraldConfig>('EmeraldConfig');

export class Upload {
  constructor(public readonly status: Status,
              public readonly message: string,
              public readonly date: Date) {
  }
}

export const PostRequestFailedErrMsg = `POST request failed`;
export const UploadNotProcessedErrMsg = `Server can't process uploaded file`;

@Injectable()
export class EmeraldBackendStorageService {

  constructor(private http: Http, @Inject(EMERALD_CONFIG) private config: EmeraldConfig) {
  }

  upload(fileToUpload: any): Observable<Upload> {
    const input = new FormData();
    input.append('file', fileToUpload);

    return this.http.post('/emerald/storage/submit-content', input)
      .map((response: Response) => response.json())
      // we emit an error if the upload is a failure
      .map((serverAnswer: ContentResponse): ContentResponse => {
        if (!serverAnswer.success) {
          throw new Error(PostRequestFailedErrMsg);
        }
        return serverAnswer;
      })
      // then we return an observable emitting the succesful tracking response
      .mergeMap((serverAnswer: ContentResponse): Observable<StatusResponse> => this.track(serverAnswer.trackingId))
      .map((serverAnswer: StatusResponse): Upload => new Upload(Status.SUCCESS, null, new Date(serverAnswer.timestamp)))
      // finally we recover, but only if it's
      // a upload not processed error or a post request failed error
      .catch((err: Error) => (err.message === UploadNotProcessedErrMsg || err.message === PostRequestFailedErrMsg) ?
        Observable.of(new Upload(Status.FAIL, err.message, new Date())) : Observable.throw(err));
  }

  private track(trackingId: number): Observable<StatusResponse> {
    // we create an observable that emits every X ms
    return Observable.interval(this.config.intervalBetweenTrackingRequests)
      // then with mergeMap we are calling the tracking service every X ms and emitting the responses with an observable
      .mergeMap(() => this.http.get(`/emerald/storage/submit-status/${trackingId}`))
      .map((response: Response): StatusResponse => response.json())
      // we discard the pending responses
      .filter((serverAnswer: StatusResponse) => serverAnswer.status !== Status.PENDING)
      // and complete our observable if we get a success or fail response
      .take(1)
      // finally, we emit an error if the response is fail
      .map((serverAnswer: StatusResponse): StatusResponse => {
        if (serverAnswer.status !== Status.SUCCESS) {
          throw new Error(UploadNotProcessedErrMsg);
        }
        return serverAnswer;
      });
  }
}

As you can see, it's quite different from the promised code, but you will see with practice that observables are more powerful than promises.

You can easily limit the number of calls to the tracking service:

    return Observable.interval(this.config.intervalBetweenTrackingRequests)
      .take(3) // only 3 attempts
      .mergeMap(() => this.http.get(`/emerald/storage/submit-status/${trackingId}`))
      .map((response: Response): StatusResponse => response.json())
      .filter((serverAnswer: StatusResponse) => serverAnswer.status !== Status.PENDING)
      .take(1)

Or add a timeout to the entire process:

  upload(fileToUpload: any): Observable<Upload> {
    const input = new FormData();
    input.append('file', fileToUpload);

    return this.http.post('/emerald/storage/submit-content', input)
      .map((response: Response) => response.json())
      ... // all the operations
      .timeout(20000);
  }

Bonus

the spec of the observable version:

import { async, TestBed } from '@angular/core/testing';
import { BaseRequestOptions, Response, Http, ResponseOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import {
  EmeraldBackendStorageService, Status, StatusResponse,
  ContentResponse, Upload, EMERALD_CONFIG, UploadNotProcessedErrMsg, PostRequestFailedErrMsg
} from './emerald-backend-storage.service';

describe('EmeraldBackendStorageService', () => {
  let emerald: EmeraldBackendStorageService;

  const id3AndSuccessContentResponse: ContentResponse = {success: true, trackingId: 3};
  const id0AndFailContentResponse: ContentResponse = {success: false, trackingId: 0};

  const timestamp400AndSuccessTrackingResponse: StatusResponse = {status: Status.SUCCESS, timestamp: 400};
  const timestamp400AndPendingTrackingResponse: StatusResponse = {status: Status.PENDING, timestamp: 400};
  const timestamp5400AndSuccessTrackingResponse: StatusResponse = {status: Status.SUCCESS, timestamp: 5400};
  const timestamp5400AndFailTrackingResponse: StatusResponse = {status: Status.FAIL, timestamp: 5400};

  function respond(contentResponse: ContentResponse, ...statusResponses: Array<StatusResponse>): void {
    const mockBackend = TestBed.get(MockBackend);

    mockBackend.connections.subscribe(connection => {
      const response = connection.request.url === '/emerald/storage/submit-content' ?
        contentResponse : statusResponses.shift();

      connection.mockRespond(new Response(new ResponseOptions({body: response})));
    });
  }

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        EmeraldBackendStorageService,
        {
          provide: Http,
          useFactory: (backend, defaultOptions) => new Http(backend, defaultOptions),
          deps: [MockBackend, BaseRequestOptions]
        },
        {
          provide: EMERALD_CONFIG,
          useValue: {delay: 5}
        },
        MockBackend,
        BaseRequestOptions
      ]
    });
    emerald = TestBed.get(EmeraldBackendStorageService);
  });

  it(`should return an observable with an Upload{'SUCCESS', null, 400},
                 when successfully uploading a file
                 and the tracking response is {'SUCCESS', 400}`,
    async(() => {
      respond(id3AndSuccessContentResponse, timestamp400AndSuccessTrackingResponse);

      emerald.upload('myFile').subscribe((upload: Upload) => {
        expect(upload.status).toBe(Status.SUCCESS);
        expect(upload.date.getTime()).toBe(400);
        expect(upload.message).toBeNull();
      });
    }));

  it(`should return an observable with an Upload{'SUCCESS', null, 5400},
                 when successfully uploading a file
                 and the tracking responses are {'PENDING', 400} then {'SUCCESS', 5400}`,
    async(() => {
      respond(id3AndSuccessContentResponse,
        timestamp400AndPendingTrackingResponse, timestamp5400AndSuccessTrackingResponse);

      emerald.upload('myFile').subscribe((upload: Upload) => {
        expect(upload.status).toBe(Status.SUCCESS);
        expect(upload.date.getTime()).toBe(5400);
        expect(upload.message).toBeNull();
      });
    }));

  it(`should return an observable with an Upload{'FAIL', 'POST request failed', ...},
                 when upload response is {false, 0}`,
    async(() => {
      respond(id0AndFailContentResponse);

      emerald.upload('myFile').subscribe((upload: Upload) => {
        expect(upload.status).toBe(Status.FAIL);
        expect(upload.message).toBe(PostRequestFailedErrMsg);
      });
    }));

  it(`should return an observable with an Upload{'FAIL', 'Server can't process uploaded file', ...},
                 when successfully uploading a file
                 and the tracking responses are {'PENDING', 400} then {'FAIL', 5400}`,
    async(() => {
      respond(id3AndSuccessContentResponse,
        timestamp400AndPendingTrackingResponse, timestamp5400AndFailTrackingResponse);

      emerald.upload('myFile').subscribe((upload: Upload) => {
        expect(upload.status).toBe(Status.FAIL);
        expect(upload.message).toBe(UploadNotProcessedErrMsg);
      });
    }));
});


Random missile generator and air defense system

Consider var

Using the var keyword when the right-hand-side of an assignment makes the type obvious can shorten your code and make changing types much easier.

The missile type is unused.

You use Type, but not type. Remove that.

Use constructors

For your two missile types, the properties don't change after they've been set, so make them getter-only properties and set them in the missile constructors.

public interface IMissile
{
     int SerialNumber { get; }
     string Type { get; }
}

public class FacetBomb : IMissile
{
    public int SerialNumber { get; private set; }
    public string Type { get; private set; }

    public FacetBomb(string type, int serialNumber)
    {
        Type = type;
        SerialNumber = serialNumber;
    }
}

Avoid using strings for type information

This is what types are for, so remove the Type property entirely. When you need to check a type, you can use type checks.

public void InterceptMissile(IMissile missile)
    {
        IGun igun = null;

        if(missile is ThermoNuclearBomb)
        {
           igun = new AntiThermoGun();
        }
        else if(missile is FacetBomb)
        {
           igun = new AntiFacetGun();
        }

        igun.Neutrilize(missile);
    }

It's "Neutralize" or "Neutralise"

Naming

Your interface is IMissile but your concrete types all end in Bomb. You have a variable called igun which belies its type. If you change the type you'd then have to go around changing the name of the variable too. Consider instead a variable name that specifies its purpose, not its type.

What is the serial number for?

It is never used, as far as I can tell.

Use a getter to return a specific value, not a setter

This doesn't make much semantic sense.

    private string name;
    public string Name
    {
        get {return name;}
        set { name = "AntiThermoGun"; }
    }

If I call .Name = "foo" .Name will next return "AntiThermoGun". Instead, stop me from setting .Name at all:

    public string Name
    {
        get {return "AntiThermoGun";}
    }


Typically the primary key on the Models is the id in the database table. You have these set as group_id and country_id. This is possible, but confusing. You usually only reference these when making relationships and Laravel will do this automatically if your keys follow a convention. Here is an example:

Group Model

class Group extends Eloquent {
    protected $table = 'group'; // this is assumed by the model name
    protected $guarded = array('id'); // this is usually id
    protected $primaryKey = 'id'; // this usually isn't necessary

    public function country()
    {
        return $this->belongsTo('country'); // this is referencing `country_id` on the groups table and associating it with the Country model.
    }

    // this pertains to part of the answer about the controller
    public function scopeStatus($query, $status)
    {
        return $query->where('group_status', 'LIKE', $status);
    }

    public function scopeName($query, $name)
    {
        return $query->where('group_name', 'LIKE', $name);
    }
}

Country Model

class Country extends Eloquent
{
    protected $table = 'country';
    protected $primaryKey = 'country_id'; // not necessary, should be `id`

    public function groups() {
        return $this->hasMany('group'); // you should have a `group_id` column on the `country` table to associate with, this is automatically inferred by Laravel
    }
}

Group Controller

There are many pieces of your Controller which should be part of your Model. These custom queries can be reused and make your application more flexible. You can use query scopes to add to your models.

I will do my best to show you an example. I will be updating your model as well so you can see what I am moving into the model.

public function index()
{
    // search variables here
    $s_name   = Input::get("s_name");
    $s_status = Input::get("s_status");

    // order variables here
    $sortBy  = Input::get("sort_by");
    $orderBy = Input::get("order_by");

    // if you are going to filter all groups anyways
    // there is not a reason to get all of them, just
    // query the ones you need! :)
    if (!empty($s_name)) {
        $groups = Group::name($s_name); // this is a query scope defined in your model
    }

    if (!empty($s_status)) {
        $groups = Group::status($s_status); // this is a query scope defined in your model
    }

    //.. other logic here
}

I tried to understand your other sorting logic as well but couldn't comprehend all of it without seeing the data. This sorting could be added as a filter in your model or even to your query scopes. Then all of this logic would be removed from your Controller and could be re-used throughout your application.

Hopefully this helps!

Here are some other resources on query scopes. I find many people miss the power of these:

http://www.develophp.org/2013/05/laravel-4-model-query-scopes/
http://ifonlyiknewthat.com/laravel/laravel-4-orm-query-scope/


Why are you using ArgumentNullException? PortalUser isn't an argument, personalData isn't an argument, etc.

PortalUser should be camelcase.
getPersonalData should be PascalCase. Ditto getUsarioPortalByIdPersonalData. Ditto setuserConsultado (and "User" should be capitalized).
iID_PersonalData should be PascalCase; moreover it seems to be using Hungarian notation which is against the C# standards, and it contains an underscore which is also against the C# standards.

I can't say much about the code, since there's so little of it. It doesn't look that good, to be honest, and I'd certainly move it to a specific method since both blocks seems to be part of a much longer method.


Working with user input and dictionaries inside of lists

You should put all code that isn't in a function in a if __name__ == '__main__' guard. So that it doesn't run when it shouldn't.
You can simplify quitting by using exceptions. If you make a function that raises say KeyboardInterupt if the input is 'q' then you can reduce the amount of code needed.
I like to not use variables when they're not needed, or increase readability, and so you may want to move riven straight into the creation of differents.
You can use f-strings or str.format to build your prints for you:

>>> i = {'title': 'title', 'album': 'album'}
>>> i['title'] + ' by ' + i['album']
'title by album'
>>> "{i[title]} by {i[album]}".format(i=i)
'title by album'
# Python 3.6+
>>> f"{i['title']} by {i['album']}"
'title by album'

You can simplify make_album by using dictionary sugar:

def make_album(artist, album, tracks =''):
    return {
        'artist_name': artist,
        'album_title': album,
        'tracks': tracks
    }

You can alturnatly use collections.namedtuple:

# Python 3.7
Album = collections.namedtuple('Album', 'artist album tracks', defaults=('',))

# Otherwise
Album = collections.namedtuple('Album', 'artist album tracks')

def make_album(artist, album, tracks=''):
    return Album(artist, album, tracks)

I'd create a couple more functions. But honestly your code is pretty great. Half my suggestions I wouldn't expect a beginner to use.

import collections

Album = collections.namedtuple('Album', 'artist album tracks', defaults=('',))

def ask_user(message):
    user_input = None
    while not user_input:
        user_input = input(message)
    return user_input

def check_quit(user_input):
    if user_input == 'q':
        raise KeyboardInterupt()
    return user_input

def get_additional_albums():
    albums = []
    try:
        print("type q to quit")
        while True:
            albums.append(Album(
                cheack_quit(ask_user("Enter artist: ")).title(),
                cheack_quit(ask_user("Enter album: ")).title(),
                cheack_quit(input("Enter number of tracks: "))
            ))
    except KeyboardInterupt:
        pass
    return albums

if __name__ == '__main__':
    differents = [
        Album('Zeppelin', 'Houses of the Holy', 8),
        Album('Tool', 'Lateralus', 13),
        Album('Pink Floyd', 'Dark Side of the Moon')
    ]
    differents += get_additional_albums()

    for i in differents:
        output = f'{i.title} by {i.album}'
        if i.tracks:
            output = f'{output} it has {i.tracks} tracks'
        print(f'\n{output}.')


Searching a 2D matrix for a consecutive sequence

The efficiency of this check must surely be suffering because of the final check.... create a String for each four-some, and compare it against a reference String. In general this will be slow, but, in particular, there can only be 9 reference strings, so why do you have to calculate it each time? An array with these 9 values would be simple to create, and then you can just say:

if reference[number] in ''.join(map(str,group)): return True

I am not suggesting that this is a good solution, just a better/faster solution. The best/fastest solution would not create two string values for comparison, but would leave the values in their native integer format.

Secondly, why do you have 4 diagonals? You should be able to get by with just 2 (since there are only two of them). I have not been able to get my head around this problem quickly enough to understand whether there is a particular use-case requiring the 4, but at face value, this means that you are double-checking your diagonals.

While I understand that you are trying to get a handle on generators and comprehensions, a more simplistic approach to this problem would be more efficient, and probably more readable.

The standard HPC (high-performance-computing) method for this type of problem is to create a logical box that spans the problems space. In this case, the box would be 4 by 4. You then create a cursor that traverses the problem space, where the bottom-right member of the box is on the cursor.

You then test that box for a vertical line above, the cursor (if there is space), a horizontal-line to the left, and the two diagonals in the box.

This type of approach is easy to multi-thread or distribute. There are ways to make the memory access more efficient as well by splitting the problem on clever boundaries when parallelizing.

But, what you want to avoid is generating values for each movement of the box....


I'd suggest:

If you have the height of a node in the Node constructor, you don't need to create a separate function getBinTreeHt. It is error prone (what if you change the way the tree is constructed, or add another one?) and costly - each call to it is O(n). Instead, use smart constructors as shown in this answer. Then you'll get the heights computed automatically, with minimal overhead, and it will work correctly regardless of what kind of tree or how you'll be constructing it.
The implementation is now correct, but it is somewhat inefficient. Since you call splitInHalf for every Node you're constructing, the total time complexity will be O(n^2), as each this call computes length xs and splitAt mid xs, which are both O(n). There is no simple way how to fix that though, you'd need to re-thing the algorithm. (Hints: compute the length only at the beginning and then use it to compute the sizes of subtrees; try to consume the list from the beginning, without splitting, and pass around the unconsumed part, as you're building the tree; if you want, I can provide a code sample.)
Usually the main reason why you want to have a balanced tree is that you can search in it fast. In order to do that, you need the tree to have the property that all elements in the left (right) subtree of a node are less (greater) than the node's element. I don't know if this is your aim, but if it is, you probably want to modify the algorithm so that if it's given a sorted list, it'll create a balanced, properly ordered tree.


There are a number of things that could be improved with this code.  I hope you find these suggestions helpful.

Specify which assembler

Unlike C or Python, there are a great many variations in assembler syntax, even for the same architecture, such as the x86 of this code.  Generally, it's useful to note which assembler, which target processor and which OS (if any) in the comments at the top of the file.  In this case, it looked most like 16-bit TASM, so that's the compiler I used to test this code.

Use an ASSUME directive

The code would not assemble for me until I added an ASSUME directive. The ASSUME directive doesn't actually generate any code.  It simply specifies which assumptions the assembler should make when generating the output.  It also helps human readers of your code understand the intended context.  In this particular case, I added this line just after the CODE SEGMENT declaration:

ASSUME CS:CODE, DS:DATA, ES:DATA

The CS and DS assumptions are obvious, but the ES assumption is less so. However, the code uses the CMPSB instruction and based on the context, this means an implicit assumption that ES also points to the DATA segment.  In my case, (emulated 16-bit DOS), I had to add a few statements to the start of the code to actually load the DS and ES segment registers appropriately.

Avoid instructions outside any segment

The EXIT code currently looks like this:

EXIT:
        CODE ENDS
        END
        RET

The problem is that the CODE ENDS closes the CODE segment and the END directive tells the assembler that there is no more code and thus the RET instruction may or may not be assembled, and may or may not actually be placed in the CODE segment.  You probably meant instead to do this:

EXIT:
        RET
        CODE ENDS
        END

Eliminate convoluted branching

Avoid needless branching.  They make your code harder to read and slower to execute.  For example, the code currently has this:

        JA EXIT
        JE SAMELENGTH
        JB FIND

SAMELENGTH:
        CLD
        REPE CMPSB
        JNE RED
        JMP GREEN
        ; ... code elided
GREEN:
        MOV BX, 0001H;  substring found
        JMP EXIT

RED:
        MOV BX, 0000H;  substring not found
        JMP EXIT
EXIT:

This could be very much simplified:

        JA EXIT
        JB FIND
        ;  fall through to same length
SAMELENGTH:
        XOR BX,BX      ; assume string not found
        CLD
        REPE CMPSB
        JNE EXIT
        INC BX         ; indicate that string was found
EXIT:

There are a number of such simplifications possible with little effort.

Know your instruction set

The code currently has this set of instructions

        DEC DX
        CMP DX, 0000H
        JE RED

However, the DEC instruction already sets the Z flag, so the CMP instruction is not needed.

Use REPNE SCASB as appropriate

The code at the location FIND is largely the same as would have been done by using REPNE SCASB.  The only difference is in which registers are used.  The code you have isn't necessarily wrong, but it could probably be shorter.

Avoid using SP as a general register

Just after CHECK, the code saves a copy of the pointer (not an index as the comment falsely claims) to the SP register.  However, SP is a stack pointer, so this code can only be used in an environment in which the stack is not used.  That could be the case, but it makes the code much less portable to code it that way, especially because the AX or BX registers could just as easily have been used here.

Consider using standard length lines

The comments in the code are very long and the semicolon is right after the instruction. Neither of these things are necessarily wrong, but they are different from the usual convention which is to align the semicolon character in some column and making sure that lines are no more than 72 characters long (some use 78).


Just a couple of notes. The biggest of which is that I think you've misunderstood what VB_PredeclaredId does. It creates a default instance of the class. Which allows you to do things like this

UniqueList.Add someItem

Without declaring and setting a new instance of the class. It's a cool feature, but it's not what allows the list to be iterable and you don't need it here. The [_NewEnum] is what allows the For Each syntax.

The Clear method doesn't need to Set list = Nothing. Drop that line and just set it to a new instance of Collection.

Lastly, I find it really odd that you have a list with no way to get an element back out of the list. We can add and remove items, but not retrieve them. I would rethink implementing an Item method.


Accept a boolean or a list of acceptable values

Of the two I'd go with the second, it doesn't make too much sense to use Booleans and Lists, but Lists and None makes more sense type wise.

The un-Pythonic part of this code, is you assign to check_values twice, which confused me a bit as I thought you were changing check.

I'd also recommend that you try to move away from global variables, c. But otherwise your code is good, :)

If you want to shorten your code a little bit, in the second version you can use or rather than a turnery, this is something that I've noticed to be somewhat popular in JavaScript, but I'm not too sure on how Python folk think of it.

def _raw(self, ssh_command, statuses=None):
    if c.call_result.status not in (statuses or []):
        raise RuntimeError("Exit status of command {} was {}.".format(ssh_command, c.call_result.status))
    return c.call_result


Creating a masonry effect with varying height rectangles

Consider splitting the code that increments the column into a separate method that can be called manually. Now you do not have to pass in column or row, and index can be incremented by the AddCard method. This greatly simplifies usage and allows you to make use of a for loop.

private float startX = 0.0f;
private float startY = 0.0f;
private float posX = 0.0f;
private float posY = 0.0f;
private float prevWidth = 0;
private float prevHeight = 0;
private int index = 0;
private int currentCol = 0;

private void IncreaseColumn()
{
    currentCol++;
    posX += width;
    posY = 0;
    prevHeight = 0;
}

private void AddCard(float width, float height)
{
    GameObject goCard = (GameObject)GameObject.Instantiate(pfCard00);
    PackedSprite psCard = goCard.GetComponentInChildren<PackedSprite>();

    goCard.name = "QuestItemCard" + index.ToString();
    goCard.transform.parent = goCardContainer.transform;
    psCard.height = height;

    // placement
    posY += (prevHeight / 2) + (height / 2);
    goCard.transform.localPosition = new Vector3(startX + posX, startY - posY, goCard.transform.position.z);

    prevWidth = width;
    prevHeight = height;

    index++;
}

Usage:

var columns = 2;
var rows = 4;

for(int x= 0; x< columns; x++)
{
    for(int y = 0; y<rows-1; y++)
    {
        AddCard(100, 100);
    }
    AddCard(100, 200);
    IncreaseColumn();
}


I took a look at it and will elaborate on my few findings below.
First of all, your default export is wrong, but most likely you knew about it and you have already fixed it in your local version (might be also some pasting issue) - it's a no brainer. SimpleLocalStorageCache vs. CacheSimpleLocalStorageCache. Also I don't think it's necessary to export the interface CacheItem as it's most likely an internal interface to be used. Do not leak it, to prevent misuse :-)
Next, looking at the constructor constructor(private key: string, private durationInSeconds: number) {} it's quite nice that you've used constructor assignment, thumbs up for that. What I think is a bit weird though, is the fact, that you've decided that the consumer of the API has to pass in seconds. That's a bit odd if we look at for example the parameters of setTimeout.
Another thing that bugs me with the seconds/calculation is, that I would except it to be converted to milliseconds inside the constructor. That's a one time calculation and isn't required to be done each time a consumer of this API is calling the update function.
I noticed that I can pass in functions which get's lost:
import Storage from "yourStorageImplementation";

const TWO_SECONDS = 2;
const instance = new Storage("someKey", TWO_SECONDS);
instance.update(() => console.log("this will be lost!"));

Fetching the exact same, results in this unexpected behavior:
instance.get() // -> { data: undefined, expiration: /*some value */ }

If you don't support persisting functions, which is fine, prevent the consumer of the API to pass in such data. This could be achieved by e.g. adjusting the generic to only allow strings, booleans, and objects with key, value pairs maybe extend/reduce this to your needs:
class SimpleLocalStorageCache<T extends string | number | boolean | { [key: string]: string | number | boolean }> { ... }

Alternatively you could do filter out just any function like:
type IsNotFuction<X> = X extends (...args: any[]) => any ? never : X;

class SimpleLocalStorageCache<T> {
  ...
  update(data: IsNotFuction<T>): void {
    const durationInMilliseconds = this.durationInSeconds * 1000;

    localStorage.setItem(
      this.key,
      JSON.stringify({
        data,
        expiration: Date.now() + durationInMilliseconds,
      })
    );
  }
}

// Usage, isn't quite handy:
const storage1 = new SimpleLocalStorageCache<() => void>("someKey", 2); // It's required to provide the generic here, meeeh!
console.log(storage1.update(() => alert("bla"))) // Errors here!
console.log(storage1.get());

I do like the solution and most of my write up is opinionated. Below are some suggestions I came up with while fiddling around with your solution:
Suggestion: Do you intend to extend it for sessionStorage and let the user decide the caching strategy? Is there a plan to properly support functions?
Suggestion: What do you think about a fluent API for this extension. Wouldn't it be nice to support something like: new Storage("key", 2).update(/* some data */).get(); to immediately fetch the result again?


Using a 2D array to store the matrix, we can simplify the function greatly. This uses Python 2 syntax.

def print_matrix(n):
    mat = [[0]*n for _ in xrange(n)]

    k = 0 # value to write
    for level in reversed(xrange(n, 0, -2)):
        start = n/2 - level/2
        pr = pc = start # current row, column indices
        if level == 1: # special case: no perimeter crawl
            mat[pr][pc] = k
            k += 1
            continue
        # walk along each edge of the perimeter
        for dr, dc in [(0,1), (1,0), (0,-1), (-1,0)]:
            for i in xrange(level - 1):
                mat[pr][pc] = k
                k, pr, pc = k+1, pr+dr, pc+dc

    width = len(str(n*n-1))
    for i in mat:
        for j in i:
            print '{:<{width}}'.format(j, width=width),
        print

Samples:

>>> print_matrix(4)
4  5  6  7
15 0  1  8
14 3  2  9
13 12 11 10
>>> print_matrix(3)
1 2 3
8 0 4
7 6 5
>>> print_matrix(2)
0 1
3 2
>>> print_matrix(1)
0
>>> print_matrix(9)
49 50 51 52 53 54 55 56 57
80 25 26 27 28 29 30 31 58
79 48 9  10 11 12 13 32 59
78 47 24 1  2  3  14 33 60
77 46 23 8  0  4  15 34 61
76 45 22 7  6  5  16 35 62
75 44 21 20 19 18 17 36 63
74 43 42 41 40 39 38 37 64
73 72 71 70 69 68 67 66 65


Minimum number of swaps required to sort the array in ascending order

Analyzing the problem, finding clues

  I used selection sort approach as selection sort makes minimum swap operation.

Really? (I don't know.) More importantly, are you sure sorting is needed here?

  My time complexity is \$O(n^2)\$. Can I reduce it?

When the time limit is exceeded,
and the program appears to work correctly for non-large inputs,
the typical cause of slowness is the algorithm.
It can be hard to find an efficient algorithm.
To figure out the trick, look for clues.
For example, look details in the question that are not used in the current algorithm.

  You are given an unordered array consisting of consecutive integers ∈ [1, 2, 3, ..., n] without any duplicates.

Take a closer look. What's in there that your solution is not using?

There's nothing in your implementation that benefits from integers being consecutive, without any duplicates.
That is, it's not benefitting from this constraint on the input:

$$
1 \leq arr[i] \leq n
$$

In other words, the input consists of the numbers \$1, 2, 3, ..., n\$, shuffled.
Given such input,
you can produce a correct ordering in \$O(n)\$.
And as such, maybe sorting is not needed here after all.

This is still just a hint, without directly answering how to compute the minimum number of swaps.
But this observation must surely be part of the implementation.

(I suggest to stop reading here and try to come up with an algorithm that uses the above observation and implement a passing solution. Continue reading only if you need hints.)

Alternative algorithm

Consider this algorithm:

Build an array of indexes of the values in the input: indexes[arr[i] - 1] = i;.
Iterate over the input array, and when arr[i] != i + 1, then swap arr[i] with  arr[indexes[i]], and update the index of the original value of arr[i].

For example, for [7, 1, 3, 2, 4, 5, 6], the content of indexes would be [1, 3, 2, 4, 5, 6, 0] (indexes[7 - 1] = 0; indexes[1 - 1] = 1; indexes[3 - 1] = 2; ....

Then, the content of arr and indexes will go through these changes:

i       = 0; 7 != 1 so swap it with 1 (the element that belongs here)
arr     = [7, 1, 3, 2, 4, 5, 6]
indexes = [1, 3, 2, 4, 5, 6, 0]

i       = 1; 7 != 2 so swap it with 2 (the element that belongs here)
arr     = [1, 7, 3, 2, 4, 5, 6]
indexes = [1, 3, 2, 4, 5, 6, 1]

i       = 2; 3 == 3 so no swap
arr     = [1, 2, 3, 7, 4, 5, 6]
indexes = [1, 3, 2, 4, 5, 6, 3]

i       = 3; 7 != 4 so swap it with 4 (the element that belongs here)
arr     = [1, 2, 3, 4, 7, 5, 6]
indexes = [1, 3, 2, 4, 5, 6, 4]

And so on, two more swaps (total 5) and 7 reaches the end.

Bugs in questions

I don't recall ever finding a bug in an online puzzle (and that should always be the very last thought on your mind),
but this puzzle has one.
The 3rd sample input [1, 3, 5, 2, 4, 6, 8] (Testcase 14) violates the constraint \$1 \leq arr[i] \leq n\$. The 8 should be replaced with 7.
I worked around that by doing this when building indexes:

if (arr[i] > N) arr[i] = N;


Re-implementation of `std::tuple` for MCUs

Good stuff!
improvements:
Your constructors should move the value.
constexpr pack(type arg) : value(arg) {}

vs
constexpr pack(type arg) : value(std::move(arg)) {}

Inconsistent constructor parameter:
Your pack<...> template's constructor's first argument is by reference, whereas your root template takes it by value. Be consistent, pick one. (the one by value with a move is the correct choice here)
This is not actually forwarding:
constexpr pack(const type& arg, types&&... args)
          : value(arg), next(std::forward<types>(args)...) {}

Forwarding is needed when the template deduction can deduce the type of a parameter to be a reference. I.E. the arguments themselves need to be templated. That's not the case here.
You can simply use:
constexpr pack(type arg, types... args)
          : value(std::move(arg)), next(std::move(args)...) {}

Note that your make_tuple() function DOES perform forwarding, so that one is fine.
Get by reference, please.
Your get function returns by value, when a reference would make more sense:
auto get(const tuple<types...>& tuple) {}

vs
const auto& get(const tuple<types...>& tuple) {}
auto& get(tuple<types...>& tuple) {}

make_tuple() should decay the type of its arguments.
Specifically, you should apply std::decay on a per-arg basis so that make_tuple(int&, const float&) returns a tuple<int, float>.
No EBO
Since you seem to care about packing, you should really be performing empty base class optimisation to get the maximum oomph out of your tuple class. This does make the code a lot more complicated though, so if you know for a fact that you'll never pack 0-sized types in a tuple, then I wouldn't bother.
A note on PACKED_TUPLES:
Making this a compile-time switch like this is pretty dicey, as you can eventually run into some nasty binary incompatibilities in the future. I would rather make a complete separate class called packed_tuple<>, and use the compile-time switch in higher-level code so that symbols related to tuple<> and packed_tuple<> remain consistent between binaries. It also allows you to mix packed and unpacked tuples in the same binary which is potentially convenient, since __attribute__((__packed__)) can have a substantial hit on performance.


Thanks for posting your code.  You've done a good job with:

formatting
variable and method names
relatively small, focused methods

You may be new to Ruby, but I don't think you're new to programming.

There's not much to be improved here.  A few Ruby idioms you missed, and a few matters of style that aren't all that important.

Matters of Style

Line width

Some of the lines are a bit long.  While there is no longer universal agreement that lines of code should be kept to less than 80 characters, there are many benefits to doing so.  One of them is that, when you paste code into StackOverflow, the reader won't have to bother with horizontal scroll bars.  Consider breaking long lines up.  Usually, you can just hit enter where you want it, indent, and the code will still work fine.  Sometimes, you'll need to add a \ (continuation) to the end of a line to let Ruby know that the rest of the statement is on the following line.

For example, this:

series_data << {name: "Cluster #{ index + 1 }", data: question_means_for_cluster}

could be formatted like this:

series_data << {
  name: "Cluster #{ index + 1 }",
  data: question_means_for_cluster
}

Vertical white space

There's more vertical white space than I'd use.  I'd get rid of most, if not all of it.  For example, instead of this:

  clusters_for_axis = cluster(axis.id, i)

  clusters_for_axis.each_with_index do |cluster_axis_summary, index|

    cluster_name = cluster_axis_summary[:name]

this:

  clusters_for_axis = cluster(axis.id, i)
  clusters_for_axis.each_with_index do |cluster_axis_summary, index|
    cluster_name = cluster_axis_summary[:name]

In general, I don't consider vertical white space within a method bad, in itself, but when it is used to separate lines into groups that have some similar purpose, I wonder if those lines could be moved into separate methods.

Code comments

Similarly, comments that say what the code is doing, while not bad, are better if they can be replaced with code that says what the comment used to say.  Often the lines after a comment can be moved into a method with the method name serving the purpose the comment used to serve.

Ruby idioms

Let's let Ruby do some of the busywork for us.

Replacing a loop with reduce

In this code:

  sum = 0
  count = 0

  # data_items is an array containing each respondent's survey scores (as an array)
  cluster.data_items.each do |item|
    sum += item[i]
    count += 1
  end

We are calculating a sum and a count.  The count doesn't need to be calculated: just use cluster.data_items.size.  To calculate the sum, this code using reduce is idiomatic Ruby:

  sum = cluster.data_items.reduce(:+)

Map

Ruby has a wonderful idiom for transforming one sequence to another, map.  Whenever you see code like this:

  series_data = []
  clusterer.clusters.each_with_index do |cluster, index|
    ...
    series_data << {
      name: "Cluster #{ index + 1 }",
      data: question_means_for_cluster
    }
  end

You can do this instead:

  series_data = clusterer.clusters.map.with_index do |cluster, index|
    series_data << {
      name: "Cluster #{ index + 1 }",
      data: question_means_for_cluster
    }
  end

Ruby frees you from the bother of creating the array and adding elements to it.  map can also be used in #diana_clusterer.

self

There are a few uses of self that you don't need.  For example, this:

self.members.each do |member|

could be:

members.each do |member|

See this SO question for more.


Building a task listing for a task manager

This is really a SQL question, I'd encourage you to keep learning true SQL because it's a skill that's invaluable and it's increasingly not learnt thanks to the popularisation of noSQL solutions and abstraction heavy ORMs

To answer your question swap the direction of the query from tasks to projects instead of from projects to tasks, this will ensure you only get projects that have tasks, alternatively you could have added an extra condition in your where clause to exclude NULL tasks on the left join

or you can simply swap the left join to a normal join

$this->db->select("tasks.*, projects.project_name");
$this->db->from('tasks');
$this->db->where('projects.id', $project_id);
$this->db->join('projects', 'tasks.project_id = projects.id', "LEFT");
$this->db->order_by('tasks.created_date', 'DESC');
return $this->db->get()->result_array();


Dictionary for locking on unique identifiers without leaking memory

ItemLock._ItemLock is not used anywhere. Also, as a side note, I'm not a fan of using _NamesLikeThis for public items
Using a single lock may not be the best idea performance-wise (though heavily scenario-dependent). Consider using CuncurrentDictionary (which of course brings all sorts of new propblems, but this is how concurrency works). Also, you may consider using a ReadWriteLockSlim, it might be more performant in some scenarios
ReleaseLock is not safe if not matched by a Lock call. Which might happen for example in case of a ThreadAbort. An ugly, but widespread way of dealing with it is placing the critical code to a finally block. This article from the SQL Server people might also be of interest: https://docs.microsoft.com/en-us/dotnet/framework/performance/reliability-best-practices


Find and extract delimited packet in buffer

Not a full review, but:

If String.IsNullOrEmpty(Data) Then is completely unnecessary. Because Data will be null if you didn't set it within the If portion. Just add an else to the previous if and have it return.

If (newline_index >= 0 AndAlso newline_index < inoff) Then   ' packet found
    ...
else
    Return
End If

Also your variable names could use some work. I actually don't know what inoff is supposed to stand for here.


My suggestions are mostly focused on making the code as concise and clear as possible.

Simplify the return statement.

if (correctTested > 0) {
    var percentageCorrect = correctTested / num_split * 100;
    return percentageCorrect >= 50;
} else {
    return false;
}

can be reduced to

return correctTested >= num_split * 0.5;

This eliminates both the condition as well as concern about div by 0.
Since you do not need a post-increment, choose pre-increment.
++correctTested or correctTested += 1 rather than correctTested++.
Choose clear names.

searchSplit might be clearer as searchTokens, correctTested as matchedTokens, num_split as tokenCount.
Consistent names.
searchCase is camel case while num_split is snake case.
You have not articulated the functional spec, but consider whether the search should be case-insensitive.  Also consider whether partial word matches are in fact acceptable or whether you require full token matches.

For ease of testing and for the ability to add different decision criteria you could consider decomposing match counting and the decision criteria into two separate functions.


Using EF 6.1 for updating objects and their children

You don't have to use a using statement. You can use an IoC container such as Autofac and let it dispose the PollContext for you.
I think you probably should update the children collection in memory first and call context.SaveChange() only once at the end, so the whole update operations are wrapped with in a unit of a work.
I don't think try/catch is needed here as you only re-throw the exception, which could be handled on a higher level.
There's lots of repeating of:

context.Entry(poll).State = poll.PollId == Guid.Empty ? EntityState.Added : EntityState.Modified;
context.Polls.AddOrUpdate(poll);

You should probably create a generic function for it.


Find the current max
There are some very simple improvements you can make to reduce the run time and the complexity.
Your code looks for sequences, puts them all in an array and then sorts and filters that array to find the longest. However if you check the length of each sequence as you find it and compare it against the longest you have found to that point you no longer need to keep an array of sequences, only the current longest.
This also helps reduce the amount of processing. When you know the length of the current longest sequence, you are able to know before calling findFirstSequence(s1,s2) if it will find a longer one. The function can not find a sequence longer than the shortest string you pass it so if either is shorter than the current max then skip the call.
Also in the function findFirstSequence(s1,s2) as you build the sequence you can workout how long it can possibly get well before you get the sequence. You can thus exit early from that function as well just by knowing the current longest sequence.
There are also two more places that you can exit early. When you first enter the function 'findLongestSubsequence` you can check if the string are the same. If they are ether one is thus the answer.
The same after the calls to removeDistinctChars(s1, s2) if s1NoDistinct === s2NoDistinct then you have the answer and can return the result then.
Some style points

Use semiColons, Javascript requires them, and if you dont add them it inserts them automatically. Unfortunately it does not always put them where you may think it will. If you can not list all the times ASI (Automatic Semicolon Insertion) can ignore the line end than you are best to put them in manually.

Watch your indentation. It's not bad, just one line is 2 space in too far. But good code does not have style errors.

Don't leave for loop segments empty. You have for (; s1Idx < s1.length; ++s1Idx) { which is poor style. for (s1Idx = 0; s1Idx < s1.length; ++s1Idx) { lets you know at a glance what the loop is starting at, rather than having to find where you set the value. In this case I would also say use i rather than s1Idx but that is more a personal preference.

A rewrite
So using your approach and just finding some early exits and avoiding repeated processing the following rewrite keeps track of the current longest sequence. Returning the first longest sequence found.
const findLongest = (s1, s2) => {
    const removeDistinct = (s1, s2) => s1.split("").filter(c => s2.includes(c)).join("");
    const findFirstSeq = (s1, s2) => {
        var seq = "", i, j = 0;
        for (i = 0; i < s1.length; i++) {
            const c = s1[i];
            while (j++ < s2.length) {
                if (seq.length + (s2.length - j - 2) < max) { return "" }
                if (c === s2[j - 1]) {
                    seq += c;
                    break;
                }
            }
        }
        return seq
    }
    const findSubseq = (s1, s2) => {
        if (s2.length <= max || s1.length <= max) { return maxSeq }
        while (s1.length && s1.length > max) {
            const seq = findFirstSeq(s1, s2);
            if (seq.length > max) {
                max = seq.length;
                s1 = s1.slice(max);
                maxSeq = seq;
            } else { s1 = s1.slice(1) }
        }
        return maxSeq;
    }
    var max = 0, maxSeq;
    if (s1 === s2) { return s1 }
    const s1D = removeDistinct(s1, s2);
    const s2D = removeDistinct(s2, s1);
    if (s1D === s2D) { return s1D }
    findSubseq(s1D, s2D);
    return findSubseq(s2D, s1D);
}


Using lock with value type (multithread context)

Thread safety

I've not tested this, but it looks solid enough, since the only non-trivial logic is held in lock statements. Encapsulation is accordingly good.

Depending on the load, and if performance is critical, some reader/writer locking might help to ease contention (e.g. if the lock object already exists, you don't need to write-lock the dictionary to retrieve it, and if the count is non-zero when you release the lock, you don't need to write-lock to remove it), but it will dramatically increase the complexity.

Naming API

Lock isn't a great name: it doesn't lock anything, it just gives you a handle to a LockObject, which you happen to have to release. Unlock similarly. Personally I avoid split prepositions

Locked isn't a great method name either: Locked suggests a state, not an operation. I'd rather call these RunLocked, or RunExclusive or something.

I don't like this:

return action == null ? default( TResult ) : action();

It means that if action == null, then the system goes to all that effort just to return a meaningful-but-made-up value. What use case could this have? This may end up obscuring a bug later on, when something which shouldn't be null ends up being null, and this code covers up the fact by returning default(TResult). In the very least this behaviour should be clearly documented, but I'd much rather it just throw an ArgumentException with a helpful error message.

The same goes for action?.Invoke(); in the other overload.

As always, I'll suggest inline-documentation (///) on the type and public members: it is little (well spent) effort; makes it so much easier to exploit the API without having to leave the IDE; and improves maintainability, as anyone working on the code can see inline what it is meant to be doing and avoid breaking that contract.

Why is this static? I'd much sooner make this non-static, and provide a static instance if that is a meaningful concept. That way, if you need to lock on the same type for different purposes then you can. Making this static needlessly restricts the applicable use-cases.

Dodgy try...finally

The try...finally constructs in the Locked methods are a bit dodgy... Unlock will throw if lockObject is null, which means you should be entering the try knowing that it is not null. The quick-and-easy solution is to move the call to Lock out of the try. If Lock can crash (it's not immediately clear how under normal circumstances it would, thought), then you need to consider that specifically.

Other misc

allready is misspelt in one of the comments.
The lockTable can (and arguably should) be readonly.
I'd consider replacing the Counter++ and Counter-- with dedicated Increment()/Decrement() methods in LockObject (making counter private), since any other usage would (presently) make no sense.
Many people object to the if without {} construct: you only have one usage, so I'd consider putting the braces in.
Personally I like to make the accessibility of everything explicit (i.e. mark private members and classes private); it just saves the reader having to remember anything, and avoids any confusion when coming from languages with different defaults.


It looks good and is readable.

A few notes :

current_state = "#{@display_content}" could be written current_state = @display_content.clone
words[rand(words.length)].strip could be words.sample.strip
select { |word| word.length.between?(5, 12) } will select words with a length between 4 and 11 due to the newline.
It would be nice to have some more feedback:

when the game has been successfully saved
when the game has been loaded, what the drawing looks like
when the last letter has been guessed, what the complete word was. Here's an example output:

_u_ar_
4 turns left
Enter a letter or attempt the full word: s
  ______
 |      |
(oo)    |
/||\    |
        |

su_ars
4 turns left
Enter a letter or attempt the full word: g
  ______
 |      |
(oo)    |
/||\    |
        |

You found the correct word!

You could replace the whole case;when statement with an array of strings.

Keep up the good work!


Finding (and counting) duplicate JS/Java files

Aside from running essentially the same find command three times, the main issue is that you run a separate basename instance for every single found file.

If you are using GNU find (verify with find --version), you can get find to print the basenames directly:

find . -name '*.js' -type f -printf '%f\n'

On my system this is about 900  times faster than calling basename when run on a directory with about 200,000 files in it.

If your system does not come with GNU find (e.g. MacOS, OpenBSD, FreeBSD) and you do not want to install it (the package is usually called findutils), you can use sed to do the same as basename but for all found files at once:

find . -name '*.js' -type f | sed 's@.*/@@'

On my system this is only slightly slower than using -printf.

If you want to reduce the amount of times you run find, you can just save the output in a variable:

filelist="$(find . -name '*.js' -type f -printf '%f\n' | sort)"
echo "$filelist" | uniq -c | grep -v "^[ \t]*1 ";
echo "$(echo "$filelist" | wc -l) JS files in search directory";
echo "$(echo "$filelist" | uniq -c | grep -v "^[ \t]*1 " | wc -l) duplicates found"

Note that on bash you need to put double-quotes around $filelist so that the newlines are not squashed.


Method to find posts in children categories

Some notes:

You should limit the lines to 80/100 chars.
When a call chain seems to include too much logic, move it to methods/class-methods of models.

As a first refactor, I'd implement Category#with_children and then write:

@categories_posts = current_user.
  get_voted(Category).
  flat_map(&:with_children).
  flat_map(&:posts).
  reject { |post| post.status == "draft" }

On a second refactor, it's nice to have relations instead of arrays as output. This way you can use scopes, paginators and such, even if you cannot directly use has_many here (because of the recursive category requirement):

categories = current_user.get_voted(Category).flat_map(&:with_children)
@categories_posts = Post.where(category: categories).published

That's to show the implementation, on the controller you should still have less logic, something like this: @categories_posts = current_user.posts_of_voted_categories.published.


Flattening a 2D array to a 1D array based on indexes

Don't use raw types:

List result = new ArrayList();

Should be:

List<Integer> result = new ArrayList<>();

If you are using Java8, you could simplify the code of the map creation using the function computeIfAbsent:

for (int i = 0; i < input.length; i++){
    for (int j = 0; j < input[i].length; j++){
        elements.computeIfAbsent(j, k -> new ArrayList<>()).add(input[i][j]);
    }
}

In the next loop, you are using the break condition incorrectly.

for(int i=0;i<input.length;i++){ // input.length is not what you need
    if(elements.get(i)!=null)
        result.addAll(elements.get(i));
}

input.length is the number of arrays in your 2d array. If the length of any array is greater than the number of arrays, the code is skipping values.

This is a failed test:

Input: {{1,2,24},{12,1241,122}}
Output: 1 12 2 1241
Expected: 1 12 2 1241 24 122

You don't need to use input in the loop, you have a map with all the elements for each index, so you can make the conversion using only the map:

// Use a TreeMap instead of a HashMap to have the elements ordered by index
Map<Integer, List<Integer>> elements = new TreeMap<Integer,List<Integer>>();
...
for (List<Integer> e : elements.values()) {
    result.addAll(e);
}


Here's a recommendation to bind parameters correctly. This sort of thing is used to prevent against SQL injection attacks.

$query = "SELECT * FROM table WHERE name = :keyword";
$statement = $this->pdo->prepare($query);
$statement->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$result $statement->execute();

Read more about PDOStatement#bindParam here


Reading a line ending with a newline character from a file descriptor

Static buffer

In my_getchar(), you use a static buffer buff along with some other static variables.  The problem with this is that you can no longer call get_line() on two different files at the same time.  For example, if you did this:

get_line(fd1, &line1);
get_line(fd2, &line2);

Then the second get_line() would actually read characters from the first file descriptor, because you have buffered its contents in the static buffer.

Reallocation strategy

Your current reallocation strategy is to increase the size of the buffer by BUFF_SIZE when you run out of space.  This causes your function to have a \$O(n^2)\$ time complexity.  It would be better if you doubled the size of your buffer instead of adding a constant to it.


Construct an 2D array of contiguous elements comparing master and incident arrays

The code could be reduced to a single line by utilizing Array.prototype.reduce()

const mainArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const compArray = [1, 2, 3, 6, 7, 11, 12, 13, 15];

const finalArray = mainArray.reduce((a, b) => {
  // `c` is boolean result of checking if `compArray` includes `b`
  // `x` is first, and if matching elements found, last array in `finalResult`
  const [c, x] = [compArray.includes(b), a[a.length - 1]];
  // if `c` push `b` to last array of `a`
  if (c) x.push(b)
  // else if `x.length` push a new array to `a`
  else if (x.length) a.push([]);
  // return `a`
  return a;
}, [[]]); // pass initial array containing single array `a` to `reduce`

console.log(finalArray);


Algorithm for comparing two lists of objects, to insert added items, and delete removed items

1) In your for-loop, when the if is true, you should not only set coupleFind = true, but also add a break since you keep looping for nothing otherwise.

2) I'm not sure why the customerId is not already part of the invoice.

3) Instead of looping over the lists, you could just create a HashSet and check if the invoice is already present. There is some extra complexity if you take this approach, but if you call that method often, it will definitely be cheaper computationally.  You should define some class InvoiceIncludingCustomerId if you don't want to put the customerId within the invoice.  And you should override (carefully) the hashCode() and equals() of that class so that the hash is unique, but quick to compute: invoiceId and customerId should be sufficient.

You then just need a HashSet<InvoiceIncludingCustomerId> knownInvoices and you just check if an invoice exists with knownInvoices.contains(invoice).  If it is missing, you add it to the DB and knownInvoices.add(invoice).


One optimization you should do in any case is not to have all rules inside html { ... } and body { ... }, because the resulting CSS rules all require the renderer to unnecessarily check every single element if it is actually a decedent of html and body - which they undoubtedly are.


I had to adjust your code style a bit before I could easily read the code. In particular:

Use InitialCaps for template parameters
Add a space before {
A newline after template<...> generally improves readability

Thus:

template<class T, size_t Dimensions>
struct vec {
    using coord_type = T;
    static constexpr size_t dimension_count = Dimensions;

    std::array<T, Dimensions> coords;

    template<class U>
    operator vec<U, Dimensions>() const {
        std::array<U, Dimensions> casted_coords;
        std::transform(
            coords.begin(),
            coords.end(),
            casted_coords.begin(),
            [](T coord) {
                return static_cast<U>(coord);
            }
        );
        return {casted_coords};
    }
};

Notice that I personally prefer to use the original template parameters T, Dimensions, etc. in places where your code used the member typedefs coord_type, dimension_count etc.; I find that this improves readability but I believe reasonable people may differ on the subject.

(In particular, the C++ Standard always uses member typedefs in declarations such as reference operator*() const as opposed to T& operator*() const; but I think that's because the name reference is part of the API of the class, whereas the name T is given for exposition only. That's a Standard-ism that we don't necessarily need to emulate when writing our own code.)

Nit: Dimensions is technically the wrong name for a single dimension. Also, by capitalizing the template parameter, we've freed up the shorter name dimensions (or dimension) for the constexpr member variable. You never have to use a tediously long name like dimension_count if you manage your naming real estate effectively!

        return {casted_coords};

The extra braces here are a pessimization; they inhibit move-elision (a.k.a. Named Return Value Optimization). Remove them... oh wait, I see, casted_coords is a std::array, not a vec! Why are you constructing a separate array and then copying it into the vec? That seems pointless!

At the very least, this should be

return { std::move(casted_coords) };

but ideally you'd define casted_coords to be of type vec<U, Dimensions> and then transform the data straight into casted_coords.coords.begin().

            [](T coord) {
                return static_cast<U>(coord);
            }

This lambda takes its parameter by-copy, which is going to be expensive if T is, say, std::string. Prefer to take generic parameters by const& or (in C++14) by perfect-forward:

            [](const T& coord) {
                return static_cast<U>(coord);
            }

            [](auto&& coord) {
                return static_cast<U>(std::forward<decltype(coord)>(coord));
            }

In this case the former is better because it's less typing (and thus fewer chances to screw something up).

Your operator vec<U, Dimensions>() should be explicit, unless you have a darn good reason for it not to be. Most possible reasons I can think of do not qualify as "darn good."

In fact, I'd prefer to go further, and say that you shouldn't be using C++'s native "conversion" mechanisms for this kind of conversion at all. IMO you should write a user-defined function, along the lines of static_pointer_cast or any_cast, that does precisely and explicitly what you want.

template<class To, class From, size_t Dim>
auto static_vec_cast(const vec<From, Dim>& from) -> vec<To, Dim> {
    vec<To, Dim> to;
    std::transform(
        from.coords.begin(),
        from.coords.end(),
        to.coords.begin(),
        [](const From& x) {
            return static_cast<To>(x);
        }
    );
    return to;
}

int main() {
    vec<int, 3> a = {{1,2,3}};
    vec<float, 3> b = static_vec_cast<float>(a);
}

Season with SFINAE to taste.

However, this still has a major flaw: You're accidentally requiring that To be default-constructible! That's no good (especially if it does happen to be default-constructible but the default constructor is expensive). You can fix this issue, but it requires metaprogramming.

template<class To, class From, size_t Dim, size_t... Is>
auto static_vec_cast(const vec<From, Dim>& from, std::index_sequence<Is...>) -> vec<To, Dim> {
    vec<To, Dim> to = {{
        static_cast<To>(from.coords[Is])...
    }};
    return to;
}

template<class To, class From, size_t Dim>
auto static_vec_cast(const vec<From, Dim>& from) -> vec<To, Dim> {
    return static_vec_cast<To>(from, std::make_index_sequence<Dim>{});
}

The advantage of this approach is that it's hardly any more lines of code, but it's more correct, and it doesn't rely on running std::transform at runtime — it just generates the correct code directly inline.

Writing an efficient static_vec_cast<U>(vec<T, Dim>&&) is left as an exercise for the reader.


Your custom function is 36 lines of very hard to digest code.  You are performing a battery of if-elseif-else conditionals on the same variable -- for this reason, it is most appropriate to employ a switch case (even though I have a strong bias against them) as a matter of best practice.  If the goal is to obfuscate the output AND the code, I reckon you've found a winner.

I'll offer a comparison using tests 5, 11, and 987654321.

Test Results:

5 -> [!+[] + !+[] + !+[] + !+[] + !+[]]
11 -> +!+[] + [+!+[]]
987654321 -> [+!+[] + [+[]] - !+[]] + [+!+[] + [+[]] - !+[] - !+[]] + [+!+[] + [+[]] - !+[] - !+[] - !+[]] + [+!+[] + [+[]] - !+[] - !+[] - !+[] - !+[]] + [!+[] + !+[] + !+[] + !+[] + !+[]] + [!+[] + !+[] + !+[] + !+[]] + [!+[] + !+[] + !+[]] + [!+[] + !+[]] + [+!+[]]

Alternatively, you might leverage Javascript-native calls to base64 encode: btoa() and atob().  Because you are dealing purely with integers, you don't need to concern yourself with "The Unicode Problem".
To encode a number use btoa(num) and to decode it back use atob(num).

Test Results:

5 -> NQ==
11 -> MTE=
987654321 -> OTg3NjU0MzIx

Benefits include:

Future developers of your code will be able to instantly research what your process is doing.
There is no need to write a custom function
The output is far, far better compressed
The process of decrypting the generated string is just as simple as encrypting it
If you want to further obfuscate the generated strings, you can cleanly add your own "special sauce" that will offer more "entertainment" for crackers.


Instead of an array, and having to do a $.grep to check if the year is already in the array, consider using an object. That way, it's a key-value pair, and it's easier and faster to look up. You can convert the data to the final array later on.

Consider using promises instead of callbacks. It's much more flexible and allows better flow control than callbacks.

nameOfObject is misleading when all it is is just the year. Name it to year instead.

There's probably little sense breaking out that function unless something else uses it. It's better to inline operations in this case, making the code easier to trace.

Be wary of the use of new Date. Every time you do that, you create a date object. Since your timestamps are uniformly formatted, you might want to consider slicing off the first 4 characters and use it as year.

Here's an alternative approach. Probably not the most performant, but probably is easier to wrap your head around. Imagine that it's just transformation of data from one form to the other.

$(document).ready(function () {
  $.post("myEndPoint").then(data => {

    // {"2017-05-01T23:59:27":100.0, ... }
    // to
    // { "2017": [100.0, ...], ... }
    const dataByYear = Object.keys(data).reduce((c, t) => {
      const year = timestamp.slice(0, 4);
      c[year] = c[year] || [];
      c[year].push(data[t]);
      return c;
    }, {});

    // { "2017": [100.0, ...], ... }
    // to
    // [ { name: "2017", values: [100.0, ...] }, ... ]
    const dataPerYear = Object.keys(dataByYear).map(year => {
      return { name: year, values: dataByYear[year] }
    });

  })
});


Too long for a comment:
Please do not use the approach given in @Yann's answer:

var random = Math.random() * (1 - Number.MIN_VALUE) + Number.MIN_VALUE;

The reason is that Number.MIN_VALUE == 5E-324. As numbers in javascript are doubles with 52 bit mantissa and the largest number smaller than 1.0 that can be represented is somewhere around 1.0 - 2^(-52). The expression (1 - 5e-324)  is not representable and will truncate to exactly 1.0.
The addition of Number.MIN_VALUE to the random value will also truncate for large parts of the number range, skewing your distribution.
The correct (and fastest) way to do this is by using the original code in OP's question (as also pointed out by @200_success's answer).
Addendum:
Even if we let: almost_one be the largest value smaller than 1.0 and then did:
var random = Math.random()*almost_one + Number.MIN_VALUE;

then the value would still be wrong.
To achieve a uniform distribution Math.random() must only return values with the same exponent (i.e. only the mantissa differs). Otherwise you'd have many more numbers between [0, 0.01]  than you would between [0.01, 1.0].
So for any return value of Math.random() besides 0.0 the addition of Number.MIN_VALUE will truncate. However if Math.random() returns 0.0 you will get the smallest value larger than 0.0 that is representable (5e-324) as your result. But then there will be a huge gap to the next number that you can get as a result, so your distribution will not be uniform any more.
The following is also wrong:
var random = Math.random()*almost_one + (1.0 - almost_one);

This can easily be seen by assuming that Math.random() returns its maximal value which is almost_one, then you would have:
var random = almost_one*almost_one + (1.0 - almost_one);

which is not equal to almost_one (it's close, but not correct).


Java Native Solution

The solution Java offers for adding two BufferedImages should be faster than anything that you will program yourself:

 /**
  * prints the contents of buff2 on buff1 with the given opaque value.
  */
 private void addImage(BufferedImage buff1, BufferedImage buff2,
         float opaque, int x, int y) {
     Graphics2D g2d = buff1.createGraphics();
     g2d.setComposite(
             AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opaque));
     g2d.drawImage(buff2, x, y, null);
     g2d.dispose();
 }

Your Code

As I said, if you remove the unnecessary x3 checks, you would at least save two comparisons for each loop of y2 (and those can really add up).

You can also move the onheight - 1 and onwidth - 1 computations outside the loop.

If most of the time the smaller image does fit into the larger image, you can also remove the bounds check completely. Create two new methods. One for when the image fits - no bound checks necessary - and one for when it does not fit (here you obviously still need the check). Then in your main method, you check once if the image would fit and use the quicker method without bounds check. If it does not fit, you use the method with bounds check.

If the smaller image does not fit most of the time, you could also first crop the smaller image (if it does not fit), so that it does always fit. I doubt that it will be faster, but it is worth a try.


lodash filter array of objects by array of exclude property values

You can do it with filter:

let users = [
  {name: 'bob', project: 1},
  {name: 'sam', project: 2},
  {name: 'ted', project: 3},
];
let excludeProjects = [1,3];
_.filter(users, (v) => _.indexOf(excludeProjects, v.project) === -1) // assign it to some variable
// Returns [ { name: 'sam', project: 2 } ]

OR other way of doing it is suggested in comments, this is more elegant:

_.filter(users, (v) => !_.includes(excludeProjects, v.project));
// Returns [ { name: 'sam', project: 2 } ]


List Comprehension in Pythonic answer to LPTHW ex48

That's normal, because with the list comprehension you're generating a whole
list of results instead of returning the first time the check succeeds.

If you want to have the equivalent code to the loop version, that is, just
compute the first value or return None if no check succeeds, you can use a
generator as follows:

return next(((label, word)
             for label, type in word_types.items()
             if word in type),
            None)

where the generator is exactly as the list comprehension, but with parentheses
instead of square brackets and next is a built-in method to get the next value
from an iterator or return the default value if the iterator is exhausted.

Note: if you don't pass a default value you'll get a StopIteration when the iterator is exhausted.


You should collect all imports at the beginning of the file. You have strange card numbers and why is choice 10 special? Normally, card games have decks, and not random constructed cards, e.g. you could have 10 equal cards.

import time
import random

SUITS = ('Spade', 'Hearts', 'Diamonds', 'Clubs')
NUMBERS = (1,2,3,4,5,6,7,8,9,10,'Jack','Queen','King','Ace')

def card():
    return random.choice(SUITS), random.choice(NUMBERS)

def store10Cards():
    return [card() for _ in range(10)]

def yourCards():
    cards = store10Cards()
    choice = int(input('Which of your cards would you want to see? You have 10 cards : '))
    print('Your chosen card is', cards[choice - 1])
    if choice == 10:
        time.sleep(5)
    return cards

print('Hi')
time.sleep(2)
print('You have 10 cards')
time.sleep(2)
choice = input('Would you like to see them? Y/N  : ').upper()
if choice == 'Y':
    yourCards()
elif choice == 'N':
    print('Too bad')
    time.sleep(1)


Client for many similar kinds of REST requests

I don't see a reason for having a readonly _url in this class. In addition I don't see a reason to have a class level _url variable neither.
I would like to suggest having two constructors, one having a string url argument and one being argumentless. In this way it is easy without changing the AppSettings to have some flexibility.

Applying this would look like so

private readonly RestClient _client;

public ApiRestClient()
    : this(ConfigurationManager.AppSettings["webapibaseurl"])
{ }

public ApiRestClient(string url)
{
    _client = new RestClient(url);
}

It is not obvious from its name what the method public TokenDto Get(Guid id) will get. It seems from the resource that this would be a cart. Having a methodname, which makes it clear what the method is about, would be much better.

The GetLayout() method should be splitted into a GetCustomer() method (which you may need anyway) to only take the Layout of that returned CustomerDto.

The default Method for RestRequest is Method.Get so you could use the constructor which only takes string resource as a parameter.

The creation of this requests could be extracted to a method which takes a string and an object as parameter. Something along this lines

private RestRequest GetGetRequest(string resource, object value, string name)
{
    var request = new RestRequest(resource) {RequestFormat = DataFormat.Json};

    request.AddParameter(name, value, ParameterType.UrlSegment);

    return request;
}

if you by any chance are using C# 6 you could use the nameof operator like so

private RestRequest GetGetRequest(string resource, object id)
{
    var request = new RestRequest(resource) {RequestFormat = DataFormat.Json};

    request.AddParameter(nameof(id), id, ParameterType.UrlSegment);

    return request;
}

In the same way you could implement a GetPostRequest() method like so

private RestRequest GetPostRequest(string resource, object value)
{
    var request = new RestRequest(resource, Method.POST) { RequestFormat = DataFormat.Json };

    request.AddObject(value);

    return request;
}

You could also add a generic method ProcessRequest<T> like so

private T ProcessRequest<T>(RestRequest request)
{
    var response = _client.Execute(request);
    return JsonConvert.DeserializeObject<T>(response.Content);
}

(I don't really know if I like this).

Applying the mentioned points will lead to

public class ApiRestClient : IApiRestClient
{

    private readonly RestClient _client;

    public ApiRestClient()
        : this(ConfigurationManager.AppSettings["webapibaseurl"])
    { }

    public ApiRestClient(string url)
    {
        _client = new RestClient(url);
    }

    private RestRequest GetGetRequest(string resource, object value, string name)
    {
        var request = new RestRequest(resource) { RequestFormat = DataFormat.Json };

        request.AddParameter(name, value, ParameterType.UrlSegment);

        return request;
    }

    private T ProcessRequest<T>(RestRequest request)
    {
        var response = _client.Execute(request);
        return JsonConvert.DeserializeObject<T>(response.Content);
    }

    public TokenDto GetCart(Guid id)
    {
        var request = GetGetRequest("/cart/{id}", id, "id");

        return ProcessRequest<TokenDto>(request);
    }

    public string GetLayout(int? id)
    {
        var customer = GetCustomer(id);

        return customer.Layout;
    }

    public CustomerDto GetCustomer(int? id)
    {
        var request = GetGetRequest("/customer/{id}", id, "id");

        return ProcessRequest<CustomerDto>(request);
    }

    public IEnumerable<TokenDto> GetInvoices(Guid id)
    {
        var request = GetGetRequest("/receipt/{id}", id, "id");

        return ProcessRequest<IEnumerable<TokenDto>>(request);
    }

    public TokenDto GetInvoice(Guid id)
    {
        var request = GetGetRequest("/receipt/invoice/{id}", id, "id");

        return ProcessRequest<TokenDto>(request);
    }

    private RestRequest GetPostRequest(string resource, object value)
    {
        var request = new RestRequest(resource, Method.POST) { RequestFormat = DataFormat.Json };

        request.AddObject(value);

        return request;
    }

    public void SaveOrder(OrderDto order)
    {
        var request = GetPostRequest("/order/", order);

        _client.Execute<TokenDto>(request);
    }

    public void UpdateUser(UserDto userMap)
    {
        var request = GetPostRequest("/user/", userMap);

        _client.Execute<UserDto>(request);
    }

}


Movie info website (React, axios and Semantic UI)

Some things I would change:

Make initial state look like this:

this.state = {
    movie: null
};

Instead of making the api request in componentWillMount, do it in componentDidMount because componentWillMount is considered legacy.
In componentDidMount be more declarative, which means to be more descriptive of what you are doing, so call a method that gets the movie like this:

componentDidMount() {
    this.getMovie();
}

getMovie() would look like this:

getMovie() {
    axios
      .get("http://www.omdbapi.com/?i=tt0096895")
      .then(response => {
        const movie = {
          title: response.data.Title,
          year: response.data.Year,
          poster: response.data.Poster,
          plot: response.data.Plot,
          rating: response.data.imdbRating,
          genres: response.data.Genre,
          runtime: response.data.Runtime
        };
        this.setMovie(movie);
      })
      .catch(err => {
        console.log(err);
      });
}

setMovie(movie):

setMovie(movie) {
    this.setState({ movie });
}

Lastly, in your render, I would check if there was a movie on state before rendering anything, if there is no movie, display some text saying no movie.

render() {
    if (!this.state.movie) {
      return
No movie found.
;
    }

    return (
        ...what you currently have
    );
}


Pushing all non empty items to the end of a list

Your code is incorrect, for example for input [' ', 'X', 'Y'] you get into an infinite loop.

You could just sort by emptiness, which with your apparent definition can be done like this:

>>> list_ = [" ", " ", "X", " ", " ", "Z", " ", "Y", " "]
>>> list_.sort(key=' '.__ne__)
>>> list_
[' ', ' ', ' ', ' ', ' ', ' ', 'X', 'Z', 'Y']

Or more generally (though slower) with a lambda or other self-made function:

list_.sort(key=lambda x: x != ' ')
list_.sort(key=is_non_empty)
list_.sort(key=is_empty, reverse=True)

If you actually had empty strings instead of strings containing a space character, or in general if your objects followed Python's usual thing of empty objects being false and non-empty objects being true, then you could also do this:

list_.sort(key=bool)


Use named functions

It's very common to write event handlers inline as anonymous functions, but as code gets more complex, this leads to deeply nested code that can be hard to follow. The inner event in particular could be something like $aantalKeuze.bind('keyup mouseup', handleAantalKeuzeChange); (apologies for the mix of languages).

Register events only once

At the moment, you seem to be registering the keyup mouseup handler every time the user changes the parent select. If the HTML it's checking isn't being replaced, this is going to end up with duplicate handlers. If the HTML is dynamically created (which doesn't show in this code) you could use a .on() "delegated event" to bind it in advance.

Separate UI logic from calculations

Try to separate your workflow into:

Get data from HTML
Calculate values (totals etc)
Populate new HTML

This might mean more (named!) functions, or it might just mean moving lines around and more variables. The aim is that you should be able to examine and change the "business logic" in step 2 separately from the "display logic" in steps 1 and 3.

Be consistent

You mostly use the convention that variables prefixed with $ are jQuery DOM objects and others are values, but you have var $totaal = 0; instead of var totaal = 0;. This is closely related to the previous point - the business logic part of the code should have no $ variables in it.

You mostly scope your variables with var, but have it missing on $parent. Because of how JS "hoists" variables, it may be sensible to declare all your variables close to the top of the function as possible. Again, this may encourage you to split out some sections into their own function - if a set of variables is only used within a tight section of code, that code might be asking to become a separate function, with defined inputs and outputs.

You mostly use $parent.find(...), except in $('.productprijzen', $parent). Standardise on one or the other, unless I'm mistaken and there's a significant difference.


Let me give you some advice:

First of all you should make your code much more rideable. I am struggling to actually read this code. You should name your variables meaningfully, so the code can be read like English.

Don't write multiple commands on a single line. It is easier to keep track of code when single command per line is used.

When writing PowerShell scripts don't use cmdlet aliases, use full names of cmdlets. Different people use different aliases, but all of them know full names of similes.


Well, it is a little bit late to answer this question but I will do it nevertheless, because it's winterbash!
I had a hard time to read your code because of the level of indentation. I would suggest using the default of 4 spaces instead of 1 space.
Another problem with the code had been at first glance the countT variable but just because of the name. Abbreviations makes the code so much harder to read and understand. If the variable would have been named countedTabs its purpose would have been cristal clear.
One should use var if the type is easy to see by the right hand side of the assignment.
Manipulating a loop variable (i) if one can avoid is a bad habit and can lead to hard to find bugs. A simple else if (input[i] == '\t') { ++countedTabs; } would have been the way to avoid this.
If one need to know if a key exists in a Dictionary<TKey, TValue> ContainsKey() is the way to go, but only if the possible value isn't needed. If one needs the value one should use Dictionary<TKey, TValue>.TryGetValue(TKey, out TValue) because accessing the value later by calling Dictionary<TKey, TValue>[TKey] will internal call the ContainsKey() as well.
Instead of doing if (booleanVariable == true) one should use if (booleanVariable). One doesn't need to compare a boolean to true because the result of the comparison is just a boolean value as well. That beeing said, you can safely remove the isFile = false; at the end of that if block because it won't be used anymore. A last word about this if: The comment you placed above the if is a good comment because it describes why you have the if in place.
One last point to make, don't declare multiple variables in one line. This just hurts the readability of the code.
Summing up leads to
public static int LengthLongestPath(string input)
{

    var prefixLength = new Dictionary<int, int>();
    var countedTabs = 0;
    var lengthSoFar = 0;
    var maxLength = 0;
    var isFile = false;

    for (var i = 0; i < input.Length; i++)
    {
        if (input[i] == '\n')
        {
            if (prefixLength.TryGetValue(countedTabs - 1, out int value))
            {
                prefixLength[countedTabs] = lengthSoFar + value + 1;
            }
            else
            {
                prefixLength[countedTabs] = lengthSoFar;
            }

            if (isFile == true)
            {
                maxLength = Math.Max(maxLength, prefixLength[countedTabs]);
                isFile = false;
            }
            lengthSoFar = 0;
            countedTabs = 0;

        }
        else if (input[i] == '\t')
        {
            ++countedTabs;
        }
        else
        {
            ++lengthSoFar;
            if (input[i] == '.')
            {
                isFile = true;
            }
        }
    }
    // To handle cases where file occours in the end of the string.
    if (isFile)
    {
        if (prefixLength.TryGetValue(countedTabs - 1, out int value))
        {
            maxLength = Math.Max(maxLength, value + lengthSoFar + 1);
        }
        else
        {
            maxLength = Math.Max(maxLength, lengthSoFar);
        }
    }
    return maxLength;
}


Use the tools you have
The first thing I notice is that you're doing some work you don't need to. You're using a std::map to hold your keys and values, but you aren't utilizing the built-in method for finding an entry. (In other languages maps are actually named dictionary!) Your entire search_term() method could look like this:
bool dictionary::search_term(const std::string& term){
    std::map<std::string, std::string>::iterator it = entries.find(term);
    return it != entries.end();
};

Likewise, the erase_entry() method could just call the std::map::erase() method.
Naming is hard
For the most part your variable and method names are pretty good! There are a few that I'd change, though. The exists() function should be something like file_exists() so it's not confused with checking if an entry exists in the dictionary.
Also, ofs_entries() and ifs_entries() are odd names. I'd call them something like write_entries_to_file() and read_entries_from_file().


Testing PersonFirstName class as a Value Object

A few notes:

The argument exceptions contain an incorrect parameter name ("Surname"). Use nameof(firstName) instead: this allows the compiler to verify that you're referencing an existing identifier, and the refactoring tools of your IDE can automatically update it when you rename that parameter.
Why are you setting both this._firstName and FirstName in the constructor? That's doing double work.
A read-only automatic property seems appropriate here: public string FirstName { get; }. This can only be assigned within a constructor, similar to readonly fields, and doesn't require you to explicitly create a backing field.
I see a disabled property with a public setter. If it wasn't disabled, then FirstName instances could not guarantee that their GetHashCode would always return the same value. That could lead to subtle bugs such as failing dictionary lookups, so you did well to make your class immutable.
You may want to implement IEquatable<T>. It's not a replacement for Equals and GetHashCode, but it lets you provide a strongly-typed equality check, which can prevent unnecessary type-checks or boxing/unboxing, and it clearly signals intent. Likewise, if you need to order or sort these first-names, take a look at IComparable and IComparable<T>.
Why does IsValid not allow names longer than 255 characters? If there's a good reason for that, then why isn't it documented? And does that restriction always apply, or only in a certain context? And is a simple false or ArgumentException sufficient for the caller, or do they need to distinguish between different validation failures?
The test method is incorrectly named: according to the name, it's testing object creation, but it's actually testing equality. Domain_EqualFirstNameValues_Equals would be more accurate.
Assert.True has an overload that accepts a failure message. A good message (perhaps including the values that are involved) can make it easier to determine why a test is failing.


Protecting Vue page based on the API response

In theory what you do here works, but there are a few caveats:

You declared your beforeCreate lifecycle hook as async, but you do not await any statement. It serves no particular purpose.
Be very careful with declaring lifecycle hooks as asynchronous, because when you await something that rejects the promise, you cannot catch the resulting error. You will end up with a component that cannot render, which makes for a bad user experience.
Vue router has global navigation guards, but you can actually also just declare a route guard on the component that is being mounted. They are called in-component guards and one that would be useful to you is beforeRouteEnter. You can redirect someone to the login page before this component even renders.

beforeRouteEnter (to, from, next) {
  axios.get('api/user', {})
    .then(_ => {
      next();
    }).catch(_ => {
      next('/login');
    });
}

While you could rely on the endpoint returning an error of some sort, there are more reasons why your endpoint might return an error. Some of those reasons might include rate limiting of the api, a bad connection or an overloaded server. Having someone redirect to the login page everytime that happens will get old fast. If you want to protect multiple components this way, you are spamming your server with unnecessary api calls. Also keep in mind that frontend security is essentially no security at all. You only "protect" stuff in the frontend to help the user experience, but your api should never return data or save data from a user that has no permissions/is not logged in. You are likely better off catching 403 errors and only redirecting them, while showing a generic error message on anything else.

You have already mentioned it, but you could use Vuex for state management. Arguably, something like "isAuthenticated" is not something every singular component should manage. Setting up a vuex store is usually less than 5 minutes work and I would still recommend managing something like that there.


Count of anagrams of a text in a given string

You code is quite efficient and well designed. I think you can get a little bit more efficiency at the cost of making the code more specific to this particular task. In particular there are some shortcuts:

your pattern is always the same so you could cache the computation of the array b[26]. This would double the speed
when you fill array a[] you could stop whenever a[i]>b[i]. This could speed up your algorithm a lot in some scenarios. For example you skip a position at once if the letter in the text is not in the pattern.
you are making copies of strings just to add the null terminator. You can avoid this by adding the length of the string as a parameter to your first function. This would help point 2 to be quite fast in the scenario already mentioned.
you can update the array a[26] incrementally. You decrease the count of character which exit the window and increment the count of characters entering it.

Putting all together (not tested):

int check(const char *text, const char *pattern) {
    int pattern_frequency[26];
    int text_frequency[26];
    int matches = 0;
    int pattern_length;
    for (int i=0; i<26; ++i) {
        pattern_frequency[i] = 0;
        text_frequency[i] = 0;
    }
    for (pattern_length=0; pattern[pattern_length]; ++pattern_length) {
       int i = pattern[pattern_length]-'a';
       assert(i>=0 && i<26);
       pattern_frequency[i]++;
    }
    for (int i=0; text[i]; ++i) {
        if (i>=pattern_length) {
            text_frequency[text[i-pattern_length]-'a']--;
        }
        int c = text[i]-'a';
        assert(c>=0 && c<26);
        text_frequency[c]++;
        if (text_frequency[c] != pattern_frequency[c]) continue; // shortcut
        int j;
        for (j=0;j<26 && text_frequency[j]==pattern_frequency[j];++j);
        if (j<26) continue;
        matches ++;
    }
    return matches;
}

If n is the length of the text and m the length of the pattern, your algorithm is O(nm) while this one is O(n+m) which cannot be improved further.


Style review

I think numberOfGuys should be a parameter obtained in the main args, so that you respect the possibility to obtain n from an external source.

As pointed in the comments, don't do isTrue = false, that's... weird. True is always true, period. You could rename it hasRemainingGuys or something like that.

Data structure
Using an ArrayList probably isn't the best data structure for your problem. This data structure is fast when it comes to obtaining data, but removing elements form it, which you do a lot, is slower. You'd want a structure where Remove is an \$O(1)\$ operation and, obviously, where it's easy to navigate from one element to the next. The LinkedList sounds like a good idea, as I'll point out below.
Alternative algorithm
I'd recommend creating some sort of circular linked list, so you wouldn't need to recreate the iterator when you reach the end of the list and to simplify some conditions. The idea is to have a linked list, where the last node's "next node" is the first one. This way, your generator could run until there's no next values.
Iterator<Integer> iterator = circularLinkedList.iterator();
//To start with the "first guy"
int k = -1;
while (iterator.hasNext()) {

    //Move on to the next shooter
    k = iterator.next();

    if (!iterator.hasNext()) {
        break;
    }

    //Move to the next shoot...ee?
    iterator.next();
    iterator.remove();
}

And... yeah, that's all. k contains the last guy standing.
Now, you need to implement a circular linked list and create an iterator that works with it. There are many examples on internet on how to do this.
You could also explore an option where you don't actually remove the element from the list, but simply keep a boolean where an index is flagged as dead or not. This might also be faster.