Checking for all query parameters before inserting into a database

Use a validation function
There are many possible solutions, one thing you can do is use a separate function to validate your data:
public function submitCoil($data)
{
    ...
    if (!$this->validates($queryData['values'])) {
        return false;
    }

    return $db->insertFew("coils", $queryData['fields'], $queryData['values']);
}

protected function validates($values)
{
    $mandatoryFields = ['name', 'resistance', 'description', 'wraps'];

    $return = true;

    foreach ($mandatoryFields as $field) {
        if (empty($values[$field])) {
            // Consider doing something like this so you can know/say
            // what the problem is.
            // $this->validationErrors[$field] = "This is empty";
            $return = false;
        }
    }

    return $return;
}

This function simply loops on all the keys that you specify as needing to be not-empty and returns true only if they are all populated.
Many simple functions
Always strive to have simple functions, that do one thing - for example:
public function submitCoil($data)
{
    $queryData = $this->translateData($data);
    if (!$this->validates($queryData['values'])) {
        return false;
    }
    return $this->insert($queryData);
}

protected function translateData($data)
{
    $uniqueID = $this->hash("id");
    return [
        'fields' => [
            'uniqueid',
            'uploaded',
            'name',
            'resistance',
            'wrapped',
            'category',
            'description',
            'wraps',
            'images',
            'wire_one',
            'wire_two',
            'wire_three',
            'wire_four',
            'wire_five',
            'wire_six'
        ],
        'values' => [
            'uniqueID' => $uniqueID,
            'uploaded' => date("F j, Y", time()),
            'name' => $data['name'],
            'resistance' => $data['resistance'],
            'wrapped' => $data['wrapped'],
            'category' => $data['category'],
            'description' => $data['description'],
            'wraps' => $data['wraps'],
            'images' => "coils/" . $uniqueID . "/",
            'wire_one' => $data['wire_one'],
            'wire_two' => $data['wire_two'],
            'wire_three' => $data['wire_three'],
            'wire_four' => $data['wire_four'],
            'wire_five' => $data['wire_five'],
            'wire_six' => $data['wire_six']
        ]
    ];
}

protected function validates($values)
{
    $mandatoryFields = ['name', 'resistance', 'description', 'wraps'];

    foreach ($mandatoryFields as $field) {
        if (empty($values[$field])) {
            return false;
        }
    }

    return true;
}

protected function insert($data)
{
    $db = Database::getInstance();
    return $db->insertFew("coils", $data['fields'], $data['values']);
}

This allows the building-blocks to be changed - or used individually. It also aides readability/maintainability as it is much clearer at a glance what a function does (assuming methods are well-named).
Avoid repetition
The fields and array keys for the values key in $queryData look to serve the same purpose - although they are different. You don't need 'fields' if the keys can be used i.e.:
$queryData = [
    'uniqueid' => $uniqueID,
    'uploaded' => date("F j, Y", time()),
    'name' => $data['name'],
    'resistance' => $data['resistance'],
    'wrapped' => $data['wrapped'],
    'category' => $data['category'],
    'description' => $data['description'],
    'wraps' => $data['wraps'],
    'images' => "coils/" . $uniqueID . "/",
    'wire_one' => $data['wire_one'],
    'wire_two' => $data['wire_two'],
    'wire_three' => $data['wire_three'],
    'wire_four' => $data['wire_four'],
    'wire_five' => $data['wire_five'],
    'wire_six' => $data['wire_six']
];

$db->insertFew("coils", array_keys($queryData), array_values($queryData));

This alone makes the method body much shorter.


Function in a board game with chests and bandits

We're definitely missing some context here to run your code or understand what it is supposed to do, but there is enough to detect a few things that could be easily improved.

        Coins = Coins-Coins #Removes all coins

This should be:

        Coins = 0  #Removes all coins

Also

        Coins = Coins+10 #Adds an additional 10 points

can be written

        Coins += 10  #Adds an additional 10 points

Don't perform the same operations more than needed. In particular when handling the user input, you can limit the number of index accesses, to call to lower function, to call to int function:

    user_input = input('Enter the direction followed by the number Ex:Up 5 , Number should be < 8 \n').split()
    if len(user_input) != 2:
        print('Wrong command, please input again')
        continue
    direct, number = user_input
    direct = direct.lower()
    number = int(number.lower())
    if direct not in ['up','left','down','right']:#Validates input
        print('Wrong command, please input again')
        continue
    elif direct == 'up':
        up(number, 8)  #Boundary is set to 8 as the 'easy' grid is a 8^8
    elif direct == 'down':
        down(number, 8)
    elif direct == 'left':
        left(number, 8)
    elif direct == 'right':
        right(number, 8)

Then, you can actually change the condition order so that you don't need to list twice the valid directions:

    if direct == 'up':
        up(number, 8)  #Boundary is set to 8 as the 'easy' grid is a 8^8
    elif direct == 'down':
        down(number, 8)
    elif direct == 'left':
        left(number, 8)
    elif direct == 'right':
        right(number, 8)
    else:
        print('Wrong command, please input again')
        continue

You could probably rewrite the comparisons to have something like:

    if current == Treasure1_Pos\
       or current == Treasure2_Pos\
       or current == Treasure3_Pos\
       or current == Treasure4_Pos\
       or current == Treasure5_Pos\
       or current == Treasure6_Pos\
       or current == Treasure7_Pos\
       or current == Treasure8_Pos\
       or current == Treasure9_Pos\
       or current == Treasure10_Pos:
        print("Hooray! You have found booty! +10 gold")
        Coins += 10  #Adds an additional 10 points
        print("Coins:",Coins)

    if current == Bandit1_Pos\
         or current == Bandit2_Pos\
         or current == Bandit3_Pos\
         or current == Bandit4_Pos\
         or current == Bandit5_Pos:
        print("Oh no! You have landed on a bandit...they steal all your coins!")
        Coins = 0  #Removes all coins
        print("Coins:",Coins)

And you could even define a data structure (list, set) to hold all the relevant positions and write something like:

    if current in Treasure_Positions:
        print("Hooray! You have found booty! +10 gold")
        Coins += 10  #Adds an additional 10 points
        print("Coins:",Coins)

    if current in Bandit_Positions:
        print("Oh no! You have landed on a bandit...they steal all your coins!")
        Coins = 0  #Removes all coins
        print("Coins:",Coins)

Then more things look wrong/improvable about boardeasy but we'd need to see what it does.


Simulation for repeatedly taking gloves until a matching pair is found

Make the glove types an enum

public static enum GLOVE {
  RED_LEFT, RED_RIGHT,
  YELLOW_LEFT, YELLOW_RIGHT,
  GREEN_LEFT, GREEN_RIGHT
}

this has several benefits:

with the current String solution, you can have a typo and you will not detect this until run time.  With an enum, the compiler checks values for you
the matchList.contains... if statement can be replaced by iteration on enum values
checking equality on enum values is faster then String comparison

if you want an even better solution, you should make a Glove class with two attributes, color of type enum and hand of type enum.  then, implement equals() and hash() methods so you can put Glove instances in various Collections. The benefit if this solution is that it allows for future modification to Glove specifications (like, adding colors, adding material attribute, etc)


int length=0,min_heapified=0,start_length=0,index=0;

I prefer one declaration per line because it's easier to read and find the type of variables. Furthermore, min_heapified is only used inside the do-while loop, so declare it there:

do {
    int min_heapified = 0;
    do {
...

Change

if(x<=(length-1))

to

if (x < length)

It's more common and simple.

Instead of

int swap=array[left];
array[left]=array[root];
array[root]=swap;

you should create a swap function. Maybe it already exists in a library.

int swap(array, index, rootIndex) {
    int swap = array[index];
    array[index] = array[rootIndex];
    array[root] = swap;
}

If I'm right you could extract the following to a new function:

if(array[left]<array[root])
{
    int swap=array[left];
    array[left]=array[root];
    array[root]=swap;
    min_heapified=1;
}

It looks for me that the other if do the same. The only difference is the used index, so I'd write something like this:

int swapIfLess(array, index, rootIndex) {
    if (array[index] < array[rootIndex]) {
        swap(array, index, rootIndex)
        return 1;
    }
    return 0;
}

if (left < length) {
    if (swapIfLess(array, left, root)) {
        min_heapified=1;
    }
}
if (right < length) {
    if (swapIfLess(array, right, root)) {
        min_heapified=1;
    }
}

The i variable looks unnecessary:

int root=i;

Use the root variable in the for loop:

for (int root = 0; root < length; root++)

Maybe you should rename it to rootIndex.

Extract more functions. The for loop (inside the do-while loops) looks as a good candidate for this. Additionally, you should have a readInputArray function and a printResults function too.


Compile a string into a callable object in C++: a simple JIT based on system, dlopen and dlsym

Make better use of constructors
Make your constructor take the program source as well as the function name as arguments, and have it compile the code at construction time. This avoids having to manually call compile(), which avoids errors such as forgetting to call that function or calling it twice.
The destructor already calls close() and removeSo(). You should make the latter two functions private, so one cannot accidentily call them manually.
Avoid unnecessary member variables
You should only declare member variables to hold information that you need for a longer period of time. Variables like source, cxx and so on are only used during the compilation step, they are not needed for anything else. Just remove them, and pass them as parameters to compile(), or better to the constructor, as mentioned above.
Avoid using <<EOF with user-provided content
There's a potential issue: what if I do the following?
f.source = R"CODE(
extern "C" {
int timestwo(int a) {
    return 2 * a;
}
}
EOF
sudo rm -rf /
)CODE";

It's better to write the source code to a temporary file, and point the compiler to that temporary file. This way, you won't accidentily execute shell code.
Use cases for JIT compilation
This looks very powerful, but what use cases do you have in mind for it? The example you gave is a bad use case; you could just have written timestwo() directly in the program. The main use case I can think of is to provide some way to evalute expressions provided by a user at runtime. In that case, you really want to sanitize the input. Because even if you avoid the shell exploits mentioned above, what happens if you do:
f.source = R"CODE(
extern "C" {
int timestwo(int a) {
    system("sudo rm -rf /");
    return 2 * a;
}
}
)CODE";

If the code you compile is in any way provided by the user, you have to be extremely careful to avoid potential misuse. So I would only use this if I am absolutely sure I need this functionality and if I can make sure it cannot be abused.


In sample1, as you call it, you have an instance field which you change. Therefore, the Person class you are using is mutable. Mutable classes are prominent to concurrency issues if a single instance is manipulated by multiple threads, unless explicit synchronization mechanism is properly involved.

In sample2, if you pass the value in the method, and you are not modifying the state of the Person class as you do your business logic, then the code is thread safe. No other thread can access the local variable id and modify it concurrently, since it is visible to the current thread only. So there is no need to apply a synchronization mechanism.

However, sample2 may not be appropriate enough for your concrete requirements. If you give more code clues on what happens in the method in question, then a more-accurate advice can be given.


Perl module validate quoted string literal, test with Test::LectroTest

Location of your helper function

If you place the accept_string_slow function inside of your lib/QuotedString.pm, it's visible to everyone. That means that someone will use it.

There is no concept of private in Perl. We have a convention to prefix things with an underscore _ so people know it's something they should not be messing with. But that does not stop them.

If this function is really only for testing, then you have a few options. It looks like it's your expected output, which because the input is random, you built into a function. That's a good approach.

The easiest and in my opinion most appropriate way is to put it right into your test .t file. It's part of that very specific test and is not used anywhere else. Just place it under the use QuotedString and remove the name from the use line.

use QuotedString qw[accept_string_regex];

sub accept_string_slow {
    my $string = shift;
    return 0 if length($string) < 2;
    return 0 unless $string =~ /\A"/;
    return 0 unless $string =~ /"\z/;

    # ...
}

Property {
    ##[ x <- String ]##
    accept_string_slow($x) eq accept_string_regex($x);
};

And that's it. Your calls to the two functions inside of the Property now still work, because all that the use does is import the function from the QuotedString package into the local package (which is main). You don't need to worry about how that works.

I would also recommend renaming the function to something that tells the maintainer (which might well be future-you) what the heck is going on here. Maybe go with sub expected_output or similar. Since it's now contained in this test you don't need to adhere to any naming conventions that the project might have. It's your code, make it as readable as possible.

Alternative ways would be to either monkeypatch the function into the QuotedString package, which makes sense if you want to overwrite a certain behavior, or to use a separate library and put it e.g. in t/lib/Helper/QuotedString.pm, which makes sense for larger changes or if you need an entire class to help you out during your tests.

Influencing LectroTest

This is a bit more suited for Stack Overflow, but here's a run-down anyway.

You should first read the docs of Test::LectroTest::Generator. That module gives you everything you need. You can use the Paste combinator with the Unit generator and the String generator. Here's an example that just outputs 20 combinations.

use strict;
use warnings;
use feature 'say';
use Test::LectroTest trials => 20;
use Test::LectroTest::Generator ':all';

Property {
    ##[ x <- Paste( Unit('"'), String( charset=>"A-Z", length=>[1,10] ) ) ]##
    say "x = $x";
};

Unit gives you a fixed value that never changes. Kind of like a constant. String you already know, but it seems we need to be more specific if it's used with Paste. I have not figured out why yet. The arguments charset and length should be self-explanatory. You can use single characters, like abc to allow a, b, and c, character ranges like A-F to create ABCDEF automatically. Those can also be combined as in AB-EFg. The length here means between one and ten.

Paste concatenates them. Actually it's more like a join, but if you omit the last argument glue, it uses an empty string and thus it's really a concat. (Beware, there is a Concat that does something else!)

1..1
x = "YSJAQXSG
x = "WWU
x = "IVKJGLWVV
x = "TWQHU
x = "DVXJDTRTX
x = "CC
x = "SULEP
x = "NFBTM
x = "UR
x = "TKS
x = "IUXIMDLUWX
x = "WHYLRV
x = "CWIQLLGO
x = "N
x = "J
x = "FZOLCBCUZX
x = "FN
x = "ZVAQZJSN
x = "TIYUXJV
x = "SVE
ok 1 - 'Unnamed Test::LectroTest::Property' (20 attempts)

This seems to work. You can also add more than one row of input definitions. That way, you can combine several tests into one Property. This is explained in Test::LectroTest::Property.

Property {
    ##[ x <- Paste( Unit('"'), String( charset=>"A-Z", length=>[1,10] ) ) ],
    [ x <- Paste( String( charset=>"A-Z", length=>[1,10] ), Unit('"') ) ]##
     say "x = $x";
};

I've reduced the trials to 5 to make it easier to read. It will run each line of definitions 5 times.

1..1
x = "CIWNIGSNL
x = "YI
x = "GPCAEZYO
x = "EPLKF
x = "ABUD
x = HS"
x = JGW"
x = QLZJUAZ"
x = NUQEKGL"
x = RSGSVOAXAQ"
ok 1 - 'Unnamed Test::LectroTest::Property' (10 attempts)

This could now also be used to do the "foo" check where the enclosing quotes are intact.

If you want to instead of spelling all of this out, pre-build a generator and use the variable in your definitions, you can do the following. The Test::LectroTest::Generator documentation does this, but fails to explain how to use it with the comment-style syntax.

my $gen = Paste( Unit('"'), String( charset => "A-Z", length => [ 1, 10 ] ) );

Property {
    ##[ x <- $gen ]##
    say $x;
};

To go a bit further, it would also be possible to build a definition that sometimes injects " or \\ or \\" with reduced likelihood.

my $overkill = Paste(
    (
        Frequency(
            [ 95, Char( charset => "a-zA-Z0-9'!?., -" ) ],
            [ 4,  Unit('"') ],
            [ 4,  Unit('\\') ],
            [ 2,  Unit('\\"') ],
        )
    ) x 10, # the x operator needs to be used in list context here
    glue => q{},
);

Property {
    ##[ x <- $overkill ]##
    say $x;
};

__END__
1..1
"Aqgz0,n8x
uBoLq"\",hq
"zx!bfJe0l
YW1u'k5"!b
Q,?9UK\\Jw
ok 1 - 'Unnamed Test::LectroTest::Property' (5 attempts)

Now you could combine all of this together to build intricate tests. If you combine those with the advice I give below at the very end of this post, you should be more than covered.

Looking into the regression testing should also prove useful. Unfortunately the documentation is very lacking as to how this works ifyou want to include manual cases. It does talk about adding failures manually, but never says how to do that. But if you turn it on, it should record it, and from that you should be able to figure out the syntax to add cases yourself.

Also take a look at this document that I found while digging through the distribution. I couldn't find the corresponding PerlMonks post, but there is some stuff about LectroTest on PerlMonks that might help, though it's old.

Although the author's website which is supposed to have more information about the whole thing is down, I did find his blog that might also have some more information. It does seem like the author disappeared from the Perl world in 2013 though.

General style

Test conditions

When I wrote this answer I was looking at the code an saw

accept_string_slow($x) eq accept_string_regex($x);

Because I seem to have a low attention span, I then thought that the function we are testing is accept_string_slow. I copied over the _regex one into the first part of the answer and started writing a whole paragraph about getting rid of Readonly because it's then not needed any more. At some point I realized that earlier you said that you wrote the slow function for control, so I facepalmed and deleted all of that.

What I want to show with that little story is that there is a convention to put the thing that is tested first in conditions.

if ($foo eq 42) { ... }

The same goes for tests written with Test::More.

is $foo, 42, 'Foo is the answer';

Doing it the other way around is called a Yoda condition, and with two function calls it's really not obvious what's going on. While that does not affect anything in the code, your maintenance person might see it the same way I did and then stuff might break later. You should turn them around.

Property {
    ##[ x <- String ]##
    accept_string_regex($x) eq accept_string_slow($x);
};

Putting the quotes into the string

While your '"' . $x . '"' approach is valid and works and is okishly readable, it might be better to use the q{} operator, which constructs strings. q is like single quotes '' without interpolation, and qq is like double quotes with interpolation. You can choose the delimiter yourself. I prefer curly braces {}. I use those for empty strings and strings that contain non-letters or digits, especially with lengthy one. You can read more about them in perlop.

Property {
    ##[ x <- String ]##
    accept_string_slow(q{"} . $x . q{"}) eq accept_string_regex(q{"} . $x . q{"});
};

Of course you can also interpolate your $x variable if you feel that's more readable. Then you need to use qq{}.

Property {
    ##[ x <- String ]##
    accept_string_regex(qq{"$x"}) eq accept_string_slow(qq{"$x"});
};

Testing functions from a library

As I said above, the use Foo qw(bar) syntax imports the bar function from the Foo namespace into the local namespace. Importing means that a new reference to the function is created in the current namespace, so that main::bar() is the same Foo::bar() (and so is bar()).

That's useful, but in your test it might not be what you want to do. While that is a lot more typing in the tests, it might be more expressive to actually not import the function, but instead use the fully qualified name. That way, you know exactly what's going on when you look at the code (did I mention tests are code too?).

use strict;
use warnings;
use Test::LectroTest (
    trials => 2000
);

use QuotedString ""; # this now has an empty string, not an empty list

Property {
    ##[ x <- String ]##
    QuotedString::accept_string_regex($x) eq accept_string_slow($x);
};

This is also what the SYNOPSIS in the Test::LectroTest documentation does.

Name your tests

You should always give meaningful names to your test cases. If I run your tests the way they are, this is the output.

  1..3
  ok 1 - 'Unnamed Test::LectroTest::Property' (2000 attempts)
  ok 2 - 'Unnamed Test::LectroTest::Property' (2000 attempts)
  ok 3 - 'Unnamed Test::LectroTest::Property' (2000 attempts)

If one of them breaks, how should we know which one is actually broken? Especially if there are a lot of tests, it gets very confusing quickly. You can name Test::LectroTest Property tests by adding a name parameter like this.

Property {
    ##[ x <- String ]##
    accept_string_slow($x) eq accept_string_regex($x);
}, name => 'String without explicit enclosing quotes';

Try to pick names that describe your test case by explaining the business logic you are testing. A test named try with value foo is a bad name, while passing in foo does not break stuff is a lot better.

Style in your accept_string_slow

This is very good. Your code is clear, readable and well-commented. Your comments make sense, your variable names are speaking and the function fits on one screen. Well done.

The only thing I would say here is actually a moot point because the interface you are mimicking is defined like that. Usually you wouldn't do return 0 (as in return 0 if $foo), but instead just say return if $foo. Without a value, return returns undef. Both 0 and undef are false in Perl, so that's usually fine. But since the interface here explicitly uses 1 and 0, it's perfectly ok to do the same.

Have you verified your code?

Your function has 19 lines of code. That's nicely small, but it's also a lot of space to include bugs. Always remember that tests are also just code. I would include some safety checks that make sure that your function does what it is supposed to do.

The Test::LectroTest approach is a very inclusive, almost all-pairs kind of test. But simply having some predefined test cases should do the trick. At least for your helper.

use Test::More;

is accept_string_slow(q{no quotes here}),          0, 'string without quotes fails';
is accept_string_slow(q{"no quotes at the end}),   0, 'string with no final quote fails';
is accept_string_slow(q{no quotes at the start"}), 0, 'string with no initial quote fails';
is accept_string_slow(q{"too many "quotes"}),      0, 'string with unescaped quote inside fails';
is accept_string_slow(q{"foo \\ bar"}),            0, 'string with stray backslash fails';
is accept_string_slow(q{"foo \\"}),                0, 'string with escaped final quote fails';
is accept_string_slow(q{"happy case"}),            1, 'happy case';

But it seems mixing the Test::Builder (which Test::More is based on) with Test::LectroTest is a bit complicated. It's explained in Test::LectroTest::Compat, but if your whole test suite is based on Test::LectroTest and the output it produces, it's probably not worth using this just for a single function.

So it would make more sense to build your test directly with Test::LectroTest. As far as I understand that's done with the the regression tests file. That seems to be a whole different story though. I suggest you read that doc. It seems to also be the way to go to include your edge-cases.


A custom error to be thrown when numeric values are out of bounds

This seems good.
I noticed a couple of things, I will try to explain down below.

Lack of type definition
For the sake of readability, it would be great to have some type definitions to make the code look easier to read.

type ValueName = 'length' | 'index' | 'position';

interface Bounds {
    lowerBoundInclusive?: number;
    upperBoundInclusive?: number;
}

export class OutOfBoundsError extends AppError {
    // ...

    constructor(name: ValueName, value: number, bounds?: Bounds) {
        // ...
    }
}

Since Bounds is an structured type, it deserves to be an interface.
The point of defining types is not just the code itself, helps in case of documentation, code hints (code completion, parameters information, ...) and reusability.
In case of reusability, types should be separated from implementations.

message internal property misplace
Inside your constructor, you are setting the value of message. Unlike Javascript, Typescript needs placeholders for internal properties.
Maybe you had, indeed. Your code does not compile, otherwise.
Anyways, internal properties must be declared between the class definition and its constructor.

export class OutOfBoundsError extends AppError {
    private message: string;

    constructor(name: ValueName, value: number, bounds?: Bounds) {
        // ...
    }
}

Truthy and falsy assertions
Avoid checking with explicit undefined, use if (value) instead.
If value is a number type and in fact you are expecting a 0 to be a valid value, Javascript will coerce it into a false. In that case, check your value like so

if (value != null) {
   // ...
}

By checking with null with a single equal symbol, you are checking for undefined and null, as well.

Two or more depth levels
Functions should not have more than one depth level. Depth levels are done by using if, for, while and switch.
Depth levels don't apply to inner functions, object or array instantiations, ...

interface ErrorMessageArgs {
    value: number;
    upper?: number;
    lower?: number;
}

export class OutOfBoundsError extends AppError {
    private message: string = ``;

    constructor(private name: ValueName, value: number, bounds?: Bounds) {
        super();

        const lower = bounds?.lowerBoundInclusive;
        const upper = bounds?.upperBoundInclusive;

        if (lower != null) {
          this.handleTruthyLower({value, upper});
        } else {
          this.handleFalsyLower({value, upper, lower});
        }
    }

    private handleFalsyLower = (args: ErrorMessageArgs) => {
        const { value, upper } = args;
        // ...
    }

    private handleTruthyLower = (args: ErrorMessageArgs) => {
        const { value, upper, lower } = args;
        // ...
    }
}

I decide to define yet another interface to wrap the error message arguments. By doing this, I can define both functions as monadic functions (just because of Robert).

  The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification — and then shouldn’t be used anyway.
  Robert C. Martin

message property protection
I assume that a third party which manipulates this class is not allowed to modify the error message. It doesn't make any sense, in my opinion.
That is why it may define a read-only access.

export class OutOfBoundsError extends AppError {
    private _message: string;

    constructor(private name: ValueName, value: number, bounds?: Bounds) {
        super();
        // ...
    }

    private handleFalsyLower = (args: ErrorMessageArgs) => {
        const { value, upper } = args;
        // ... message is filled
    }

    private handleTruthyLower = (args: ErrorMessageArgs) => {
        const { value, upper, lower } = args;
        // ... message is filled
    }

    get message() {
        return this._message;
    }
}

Maybe, for more consistency, _message should be protected if OutOfBoundsError is not a sealed class.
And yes, I know that in some case you defined this message property inside the AppError class. I just mention, just in case.

Ternary operation
This is just a preference. When there is only one line to write inside the if and else statements, I just prefer a ternary operation. It seems cleaner to me.

export class OutOfBoundsError extends AppError {
    protected _message = ``;

    constructor(private name: ValueName, value: number, bounds?: Bounds) {
        super();

        const lower = bounds?.lowerBoundInclusive;
        const upper = bounds?.upperBoundInclusive;

        lower != null
            ? this.handleTruthyLower({value, upper})
            : this.handleFalsyLower({value, upper, lower});
    }

    private handleFalsyLower = (args: ErrorMessageArgs) => {
        const { value, upper } = args;
        this._message = upper != null
                        ? `${this.name} must be less than or equal to ${upper} but\
                            ${value} was given`
                        : `${this.name} of ${value} is out of bounds`;
    }

    private handleTruthyLower = (args: ErrorMessageArgs) => {
        const { value, upper, lower } = args;
        this._message = upper != null
                        ? `${this.name} must be between ${lower} and ${upper} but\
                            ${value} was given`
                        : `${this.name} must be greater than or equal to ${lower}\
                            but ${value} was given`;
    }

    get message() {
        return this._message;
    }
}

Even for void function calls.

Hope it helps and any suggestions are welcome.


Advent of Code 2016: Day 1 "No Time for a Taxicab"

Before starting to make timing comparisons, it's important to check that the optimized code is correct. It's no good being a hundred times faster if you get the wrong answer! So let's look at the results of the two functions on a simple test case:

>>> instructions = 'L1, L1, L1, L1, R1, R1, R1, R1'
>>> solve_set(instructions)
0.0
>>> solve_bisect(instructions)
1.0

Oops.


Python wrapper for official Hacker News API

response.json() appears repeatedly here and in other methods:

def get_item(self, item_id):
    response = self._get('{0}item/{1}.json'.format(self.base_url, item_id))

    if not response.json():
        raise InvalidItemID

    return Item(response.json())

You could simplify by getting .json() in the first place:

def get_item(self, item_id):
    data = self._get('{0}item/{1}.json'.format(self.base_url, item_id)).json()

    if not data:
        raise InvalidItemID

    return Item(data)

This could be more efficient, because you can't really know for sure if the .json() is implemented lazily (evaluating things only once), or every time you call it. In fact, the speed difference is noticeable after this change, when you iterate over a list of items.

self.base_url appears in many methods, for example:

def get_item(self, item_id):
    response = self._get('{0}item/{1}.json'.format(self.base_url, item_id))
    # ...

def get_user(self, user_id):
    response = self._get('{0}user/{1}.json'.format(self.base_url, user_id))
    # ...

def top_stories(self, limit=None):
    response = self._get('{}topstories.json'.format(self.base_url))
    return response.json()[:limit]

def get_max_item(self):
    response = self._get('{}maxitem.json'.format(self.base_url))
    return response.json()

To reduce the duplication, you could introduce some more helper methods like ._get, for example:

def _get_page(self, page):
    return self._get('{0}{1}.json'.format(self.base_url, page))

def _get_page_param(self, page, param):
    return self._get('{0}{1}/{2}.json'.format(self.base_url, page, param))

Using these new methods, you could simplify the above methods:

def get_item(self, item_id):
    response = self._get_page_param('item', item_id)
    # ...

def get_user(self, user_id):
    response = self._get_page_param('user', user_id)
    # ...

def top_stories(self, limit=None):
    return self._get_page('topstories').json()[:limit]

def get_max_item(self):
    return self._get_page('maxitem').json()


I see some issues with your code

There's a lot of repetition
Your return values should be actual Date objects, and perhaps handle the time component too. Formatting the date is outside the function's responsibilities. Who knows how the formatting or use of the start/end dates might change? But what won't change is that the function should return start and end, so stick to that.
Your arguments are a clue that something's not quite right: The 2nd argument only makes sense if the 1st argument is "this month". Why not respect the 2nd arg for weeks too?
A style thing, but by convention JS functions are lowerCamelCase unless they're constructors (i.e. classes). So Date is uppercase, as it's a constructor, but your function should be getStartAndEnd

To take a page from the ActiveSupport library for Ruby, which has excellent date/time helpers, it might be more beneficial to break everything up into the separate functions (and encapsulate them in an object to avoid polluting the global namespace).

For instance:

var DateHelper = {
  beginningOfDay: function (date) {
    var beginning = new Date(date);
    beginning.setHours(0, 0, 0, 0);
    return beginning;
  },

  endOfDay: function (date) {
    var end = new Date(date);
    end.setHours(23, 59, 59, 999);
    return end;
  },

  beginningOfWeek: function (date) {
    var beginning = DateHelper.beginningOfDay(date);
    beginning.setDate(date.getDate() - date.getDay());
    return beginning;
  },

  endOfWeek: function (date) {
    var end = DateHelper.endOfDay(date);
    end.setDate(date.getDate() - date.getDay() + 6);
    return end;
  },

  beginningOfMonth: function (date) {
    var beginning = DateHelper.beginningOfDay(date);
    beginning.setDate(1);
    return beginning;
  },

  endOfMonth: function (date) {
    var end = DateHelper.endOfDay(date);
    end.setMonth(date.getMonth() + 1, 0);
    return end;
  }

  //... more helper functions?
}

From this, you can build more complex functionality. For instance, your original function could now be written as:

function getStartAndEnd(rangeName, extendToEnd) {
  // At minimum, we'll want the range of the current date
  var range = {
    start: DateHelper.beginningOfDay(new Date),
    end:   DateHelper.endOfDay(new Date);
  };

  extendToEnd = extendToEnd || false; // default to false

  switch(rangeName.toLowerCase()) {
    case "this week":
      range.start = DateHelper.beginningOfWeek(range.start);
      if( extendToEnd ) {
        range.end = DateHelper.endOfWeek(range.end);
      }
      break;
    case "this month":
      range.start = DateHelper.beginningOfMonth(range.start);
      if( extendToEnd ) {
        range.end = DateHelper.endOfMonth(range.end);
      }
      break;
    default:
      // do nothing
      break;
  }
  return range;
}

That'll give you start/end date objects that you can format however you want (which, of course, would be a job for another tiny function).

But now that everything's broken up into separate, more focussed functions, you can mix and match to suit your needs. I'd avoid calling functions with string arguments that define what you want back. Probably better to simply have a thisWeek() function somewhere, or a thisMonth() function, and leave string interpretation at an even higher level.

Note, by the way, that time and date stuff is always tricky. For instance, all of these functions assume you're talking about the user's local time zone. Depending on your context, that might cause issues. Also, where I live the beginning of a week would be a Monday, not a Sunday. So beware of such things.


I'm sorry, but I think this is the time where it's easier to start from scratch then try to fix your code.
Let me comment on some of your styling choices:

Don't use words like smallest/anothersmallest/largest etc - use min/max.
Respect the CamelCase for long variable names.
Don't initialize your loop counter in the beginning where you initialize all other variables.
n is unnecessary and while you created it - you don't use it everywhere.

Logic
The first loop where you calculate min and max is fine.
The second loop inside the loop is not necessary. Instead you could just use something like (assuming you would use min for smallest value and counts for temp array):
for (int i=0; i<a.length; i++) {
   counts[a[i]-min]++
}

The third loop where you populate result back on what you counted so far can be written like:
int j=0;
for (int i=0; i<counts.length; i++) {
   while (counts[i] > 0) {
      result[j] = i + min;
      counts[i]--;
      j++;
   }
}


Finding unique/obsolete binary Debian packages

Your code looks very good, so I'll just propose some minor (and subjective) improvements:

Imports: PEP8 has some recommendations about grouping imports that sound pretty reasonable.
("s1" "s2"): I don't know what the orthodoxy says, but I prefer an explicit + in between.
list(): Why not []?
wheezy_packages.extend([pkg["Package"] for pkg in repo]) -> wheezy_packages.extend(pkg["Package"] for pkg in repo).
repo = a, then repo = f(repo). IMHO this is as common a pattern as is undesirable. Different values deserve different variable names (key point of functional programming).
Function too long: I'd split the code in at least two auxiliary functions, one to get wheezy_packages and another to run the commands.


Implementation of Vertex Similarity algorithm (Blondel's Similarity Measure)

private final int M, N;

It's Java. Albeit M and N may get big, you should use camelcase (small initial letters) for non-constant fields. Maybe something like width and height? Or rows and colums, or m and n, if you insist.

public Matrix(double[][] data) {
    M = data.length;
    N = data[0].length;
    this.data = new double[M][N];
    for (int i = 0; i < M; i++)
        for (int j = 0; j < N; j++)
                this.data[i][j] = data[i][j];
}

Either make the method non-public or check arguments, especially check that each row has the same length. Apart from this, the inner loop could be replaced by

this.data[i] = data[i].clone();

  What I want feedback on is memory efficiency, to not make new matrices as much as possible.

Matrix firstProduct = Y.times(Sk).times(X.transpose());

Here you're creating an new matrix, while a view of the original would do (albeit probably slower). You could instead define a timesTransposed operation and have the full speed without any allocations. That's pretty simple and you can test it nicely using the existing operations.

Matrix totalProduct = firstProduct.plus(secondProduct);

Here you can avoid allocations by implementing the equivalent of +=. It surely doesn't make you code more readable, but sometimes that's the price for efficiency.

An operation like *= could get pretty complicated for matrices (and is rather impossible for non-square matrices, so lets forget it).

    double[][] data = totalProduct.transpose().data;
    Sk = new Matrix(normalizeByRows(data)).transpose();

Here, you're refusing to use objects and I really can't why. normalizeByRows should be a method (either modifying an existing matrix or creating a new one; choose what you need, but be careful with naming).

// This is the actual algorithm.

So don't put it in main. Make a method, name it properly and save yourself that comment.


Find the next number with all different digits, and no 0 or 2

You seem to be missing some headers (<vector>, <iostream>, <cmath> and <set>), and also to be assuming the standard names are in the global namespace, rather than std.
After attempting to read from std::cin, it's important to ensure the read was successful before attempting to use the result.  (E.g. if (!(std::cin >> year)) { std::cerr << "Input failure\n"; return EXIT_FAILURE; }).
A linear search will be inefficient, especially as we may have to skip long runs containing the banned digits 0 and 2.  It would be better to construct the result using the available digits than to consider and test every possible number.  The search is flawed anyway, since std::pow(10, 8) could be larger than the maximum int, leading to overflow (which is Undefined Behaviour).


I'm going to elaborate on what I mentioned in comments.

Assuming you're using LINQ to Entities, this line:

var invoices =
        db.SellInvoices
          .Where(invoice => invoice.Date >= startDate && invoice.Date <= endDate);

does not actually execute the query. It just builds the query, execution is deferred until you call one of the methods that force the materialization of the result set. One of those methods is Sum.

That means you're calling the database 6 times per loop.

If you add .ToList():

var invoices =
        db.SellInvoices
          .Where(invoice => invoice.Date >= startDate && invoice.Date <= endDate)
          .ToList();

You'll just hit the database once, grab the full result set and the rest of the processing will be done in-memory.

In case of not-too-big datasets, that is definitely a viable way to go. Otherwise, you'd have to write a stored procedure to do the processing.


In the worst case (the repeated element occupies the second half of the array), the set will accommodate all N non-repeated elements, therefore the space complexity of the solution is \$O(N)\$.

Your intuition is correct; the solution doesn't use the important information. It is used to find out how far apart the repeated elements are. If a distance between them is at least \$d\$, the array would be at least \$d\cdot(N-1) + 1\$ long. Since we know that it is \$2N\$ long, we can conclude that \$d \le \dfrac{2N-1}{N-1}\$, which is effectively 2 for N > 2. It is enough to compare each a[i] with a[i+1] and a[i+2]. The space complexity is now constant.


Yet another implementation of malloc() in C

Design.

The trouble with your design is that you have to search a list. Where none of the sizes may match. Even if there is a block in the list of the correct size you have to search through all the blocks that don't match your size.

Step 1

Use a list of lists. The top level list is an ordered list of sizes. So you can loop across this list quickly looking for the size you want. And stop if it does not exist.

The second level list is a list of all blocks of a specific size. So if you find the list of 24 bytes. That list contains all the 24 byte blocks that have been freed (so you just take the first one).

When an object is used you remove it from a list and when it is free'd you add it back to the list of free blocks.

global->********* -->********* -->********* -->*********
        *   8   * |  *   16  * |  *  24   * |  *  32   *
        * next  *-|  * next  *-|  * next  *    * next  *
        *********    *********    *********    *********
            |            |            |            |
            \/           \/           \/           \/
        *********    *********    *********    *********
        * block *    * block *    * block *    * block *
        * next  *    * next  *    * next  *    * next  *
        *********    *********    *********    *********
            |            |            |            |
            \/           \/           \/           \/
        *********       null      *********    *********
        * block *                 * block *    * block *
        * next  *                 * next  *    * next  *
        *********                 *********    *********
            |                         |            |
            \/                        \/           \/
        *********                    null      *********
        * block *                              * block *
        * next  *                              * next  *
        *********                              *********
            |                                      |
            \/                                     \/
        *********                                  null
        * block *
        * next  *
        *********
            |
            \/
            null

Step 2 Simple Optimizations

If you don't find a block of the exact size you can re-use a block that is too large. There are two version of this. a) slightly too large and just waste a small amount of space b) twice as big as you need and split the block into two pieces.

Searching the size list can still be expensive but that can be simplified by using a skip list. This should significantly reduce the time you need to search the list.

Alternatively rather than a top level list you could use a balanced tree to hold the top level structure. That way finding a value is always O(ln(x)) where x is the number of different sizes.

Code Review

Your code is fine for handling string data. But you don't take into account the alignment of the object you are allocating for. If you allocate a block of 5 you don't guarantee that the object is aligned for a structure of 5 bytes (only aligned for an array of 5 characters).

Search across blocks that have already been allocated seems like a waste of time. Either simply remove allocated blocks from the global chain or if you absolutely must track them then keep two lists (one for allocated objects and one for freed objects).

There is no need to add blocks onto the end. It is far simpler to add new blocks to the front of a list.

Your code does not use the prev pointer!!!!


This is a good exercise in doing things in a more data-driven way. This will result in clearer separation of concepts (i.e., game logic) and allow for more customization easily.

So consider (skipping updating the main program):

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <set>
#include <map>

enum Choice
{
    Rock = 1,
    Paper = 2,
    Scissors = 3
};

enum class Result
{
    Win,
    Loss,
    Tie
};

const std::set<std::pair<Choice, Choice> > wins =
{
    { Rock, Scissors },
    { Scissors, Paper},
    { Paper, Rock }
};

const std::map<Result, std::string> result_strings =
{
    { Result::Win, "WIN!" },
    { Result::Loss, "LOSS!" },
    { Result::Tie, "TIE!" }
};

const std::map<char, std::string> play_abbreviations =
{
    { 'r', "Rock" },
    { 'p', "Paper" },
    { 's', "Scissors" }
};

std::string ResultToString(Result result)
{
    // TODO: Decide how to handle the case of input being unrecognized.
    return result_strings[result];
}

std::string DeterminePlay(char playAbbreviation)
{
    // TODO: Decide how to handle the case of input being unrecognized.
    return play_abbreviations[playAbbreviation];
}

Result DetermineResult(Choice playerPlay, Choice computerPlay)
{
    if (playerPlay == computerPlay)
    {
        return Result::Tie;
    }
    else
    {
        return wins.find(std::make_pair(playerPlay, computerPlay)) != wins.cend() ? Result::Win : Result::Loss;
    }
}

int GenerateRandomNumber(int min, int max)
{
    // TODO: Look at <random> to see how this is done better.
    srand(std::time(0));
    return (rand() % max) + min;
}

Choice GenerateComputerPlay()
{
    const int number = GenerateRandomNumber(1, 3);
    return static_cast<Choice>(number);
}

What we did here was that built the logic of who wins into a data structure, which is essentially a directed graph (more precisely, it's a directed 3-cycle). The winner determination now consist of checking whether the input is an arc in our graph; otherwise it's a loss if no such arc exists and a draw if the arc is a self-loop.

Notice also the possibilities you obtain by a having a result_strings: you could put in more "output texts" for a win for instance, so maybe sometimes you'd like to tell the user "WIN!", but other times you could print "GREAT JOB!" or "NICE!"; that'll end up a nightmare from a maintenance and logic point of view if the number of possible strings grows large.


C++ templates for sin, cos, tan taylor series

I see several issues with your code.

Your motivation should be stronger/clearer

While you may have a very good motivation for having this functionality, it is not apparent from your post hear nor from your GitHub repo. At compile time there are typically very few values I'd need the sine or cosine of; is it really clearer to write

printf("%f", apply_my_complicated_TMP_construct(PI/4, 8) )

than

auto sine_of_quarter_pi = 0,707106781187f;
printf("%f", sine_of_quarter_pi);

? I don't know that it is. Plus, the second way the reader doesn't need to think about iterations, the taylor series etc. It will also reduce compilation time.

Now, you could say "Ah, but I have a lot of these values to apply sin() or cos()" - but honestly, I doubt it. If that's the case you should just do that offline and independently of developing your C++ code.

In your repository, you list the following advantages:

  All the work is done a compile-time.
  The compile-time efficiency is actually going to be better than run-time efficiency compared to "normal,"

But, again, there isn't really any work; and there's no "efficiency" issue if you just use the value you need. Even if you had to calculate a sine or cosine a couple dozen times - that's really negligible.

Don't reinvent the wheel I

There's an M_PI constant available in POSIX-compliant system's <math.h> header (and thus, effectively, in most <cmath> headers, including MSVC's with a bit of work, see here). In case you want to be more portable, you might do:

#ifndef M_PI
    #define M_PI 3.14159265358979323846
#endif

... but, in fact, these days you can even get a better accuracy constant, M_PIl, on some systems. So you would have actually gained from not reinventing the wheel.

... and there's more. Remember my sqrt(2)/2 from the example above? That's often predefined too. Have a look at your system's <math.h>.

Don't reinvent the wheel II

Someone has already provided what looks like a more robust implementation of the same functionality - here on the site:

constexpr Sin Function C++ 14

Now, granted, I haven't scrutinized that code. Maybe it's buggy or has other problems. But I'll bet you 100 reputation you haven't read that implementation before writing yours... although you could have, if you'd have looked. I didn't know about it before I was writing this review.

Drop most template recursion in favor of C++14 constexpr functions

You use recursive template instantiation when you could just put a for loop in your function - and sometimes not even need a template:

constexpr long long factorial(int n)
{
    return (n <= 1) ? 1L : (n * factorial(n - 1));
}

(taken from here). Also, when you can't just "go constexpr", you can still iterate over multiple template arguments with for_each_argument and so on.


Here are some things that may help you improve your program.

Isolate platform-specific code

If you must have stdafx.h, consider wrapping it so that the code is portable:

#ifdef WINDOWS
#include "stdafx.h"
#endif

Make sure you have all required #includes

The code uses std::numeric_limits but doesn't #include <limits>.  A program may compile without the explicit #include because some other header might happen to include it, but that is not guaranteed by the standard.  To compile reliably, the documented #include files should be used.

Don't use system("pause")

There are two reasons not to use system("cls") or system("pause").  The first is that it is not portable to other operating systems which you may or may not care about now.  The second is that it's a security hole, which you absolutely must care about.  Specifically, if some program is defined and named PAUSE or pause, your program will execute that program instead of what you intend, and that other program could be anything.  First, isolate these into a seperate functions pause() and then modify your code to call those functions instead of system.  Then rewrite the contents of those functions to do what you want using C++.  For example:

void pause() {
    getchar();
}

Use const where practical

The name_day vector is not and should not be modified, so it should be declared const.  Better yet, it could be declared static const.

Use better naming

The vector named name_day is well named because it is descriptive of the contents.  However, flag is not a good name because it doesn't suggest the meaning of the variable in the context of the program.

Use string concatenation

The main routine includes this very long line:

std::cout << "This program takes a number in the range of" << "\n" << "[1 , 7] and prints its corresponding day." << "\n" << "............................................................." << "\n";

Each of those is a separate call to operator<< but they don't need to be.  Another way to write that would be like this:

std::cout << "This program takes a number in the range of\n"
             "[1 , 7] and prints its corresponding day.\n"
             ".............................................................\n";

This reduces the entire menu to a single call to operator<< because consecutive strings in C++ (and in C, for that matter) are automatically concatenated into a single string by the compiler.  It is also more readable.

Fix the spelling error

The error string currently says "Bad Entery !."  With corrected punctuation and spelling, that becomes "Bad entry!".  However, it would be even better if the error message suggested what was actually wrong and gave some suggestion to the user about what to do about it.

Use indexing rather than a loop

The current code has this peculiar bit of code:

for (int i = 0; i <= 6; i++)
{
    if (n-1 == i)
    {
        std::cout << name_day[i] << "\n" << "-----------------------" << "\n";;
        flag = false;
    }

}//end of for

Instead of a loop to look up the day, why not simply use an index?  Here's one way to do it:

while (true) {
    std::cout << "Input a number : ";
    std::cin >> n;
    if (std::cin && n >= 1 && n <= 7) {
        std::cout << name_day[n-1] << "\n----------------\n";
    } else {
        std::cout << "Bad entry: The number must be in the range 1-7 inclusive\n";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}

Note that this will flush the input stream on any error which differs from the behavior of the current code.

Consider the user of the code

There is currently no graceful way to end the program.  It would be nicer if, for instance, a value of 0 or maybe -1 were used as a signal to end the program.

Think carefully about using using

There is nothing inherently wrong with these lines:

using std::vector;
using std::string;

However, since each is only used once, I'd probably omit them and simply use the full namespace in the code:

static const std::vector<std::string> name_day{
    "Saturday" ,"Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" };

Consider using constexpr

Because it is a vector of strings, one can't make name_day a constexpr value, but it could be simply by making a minor change:

static constexpr const char* name_day[]{
    "Saturday" ,"Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" };

This also means that the #include <vector> and #include <string> are no longer needed.


Create Form Controls based on the properties of a class

In my commented I suggested a class that could do what you want it to do out of the box. However sometimes having a custom piece of code to show things in a better way is the goal. I can see this going in two different ways. One is to use a variation of the Visitor pattern and a list, and the other is to use a dictionary with Type and the key, and the class that represents how to view it as the value.

The first way you could make the IVisitor interface one of two ways.

public interface IVisotor
{
    //option 1
    void Accept(Control control);
    //option 2
    bool Accept(Control control);
}

then to implement you'd make a new class per type that you want to show a specific way. Here is an example with both.

public class StringVisitor : IVisitor
{
    public bool Accept(PropertyInfo property, Control control)
    {
        if(property.PropertyType != typeof(string))
            return false;

        Accept(control);
        return true;
    }

    public void Accept(Control control)
    {
        control = new TextBox();
        control.Tag = "String";
        control.Size = new System.Drawing.Size(170, 20);
    }
}

Now in your class you have two options, make a List<IVisitor> or make a Dictionary<Type, IVisitor>. Here is an example of what I mean. It is by no means complete (and might even have a compiler error as I did it in Notepad++)

public class PropertyViewer
{
    private readonly List<IVisitor> visitors1;
    private readonly Dictionary<Type, IVisitor> visitors2;

    public PropertyViewer()
    {
        visitors1 = new List
        {
            new StringVisitor(),
            //...
        };

        visitors2 = new Dictionary<Type, IVisitor>()
        {
            {String, new StringVisitor()},
            //...
        }
    }
    private void AddControl(PropertyInfo p, string name = null, Color? c = null, int count = 0)
    {
        Control control = null;
        //option 1
        foreach(var visitor in visitors1)
        {
            if(visitor.Accept(p, control))
                break;
        }
        //option 20
        if(visitors2.ContainsKey(p.PropertyType))
        {
            visitors2[p.PropertyType].Accept(control);
        }

        //do your common control stuff here.
    }
}

There are other ways as well but that should encapsulate your work some and make it easier to find where a mistake is. Because of the nature of your work on this it won't be super easy to test that everything is visually pleasing, but the code should be encapsulated enough to make it easy to adjust what you need adjusted.


One-line initialisation for a constant list with all entries except one from another list

Use EnumSet for that. From docs:

  A specialized Set implementation for use with enum types. (...) The iterator returned by the iterator method traverses the elements in their natural order (the order in which the enum constants are declared).

It's also very efficent:

  Implementation note: All basic operations execute in constant time.
  They are likely (though not guaranteed) to be much faster than their
  HashSet counterparts. Even bulk operations execute in constant time if
  their argument is also an enum set.

So in your case:

final static Set<Box> DEFAULT_BOXES =
    EnumSet.complementOf(EnumSet.of(Box.FREEMIUM));

or if you prefer immutable one, use Sets.immutableEnumSet(Iterable):

final static ImmutableSet<Box> DEFAULT_BOXES =
    Sets.immutableEnumSet(EnumSet.complementOf(EnumSet.of(Box.FREEMIUM)));

or if you insist for List (but why would you?):

final static ImmutableList<Box> DEFAULT_BOXES =
    Sets.immutableEnumSet(EnumSet.complementOf(EnumSet.of(Box.FREEMIUM))).asList();

P.S. All constants can be represented as:

final static Set<Box> FREEMIUM_BOXES = EnumSet.allOf(Box.class); // or wrap it with Sets.immutableEnumSet to make it ImmutableSet


With a query this simple, it's going to be hard to make any major improvements.

Firstly, you should use INNER JOIN as opposed to JOIN it makes the query much easier to understand at a glance.

I would argue that you don't need to alias job_stats or job, they are both already fairly short and are much more meaningful names than J and JS

You should use consistent indentation and you SQL is typically written with all the keywords in uppercase like this:

SELECT job_stats.median_runtime
FROM job_stats
INNER JOIN job
    ON job.id = job_stats.id
WHERE job.name = '%s'

Lastly, is the final statement supposed to be this:

WHERE job.name LIKE '%s'

or is it correct as is, I can not tell.


Generic method for HTTP GET/POST parameter conversion

First point, small but important: give your method a proper name. GetParam doesn't mean much and doesn't tell what it returns. Take a name like GetValueFromParameter or GetHttpRequestValue.

Secondly, did you test this method properly? I changed the code a bit to be able to test it, I removed the HttpContext value and just use the parameter as value:

protected T GetHttpRequestValue<T>(string value)
{
    if (string.IsNullOrEmpty(value))
        return default(T);

    return (T)Convert.ChangeType(value, typeof(T));
}

When I call it like this:

var longFromString = GetHttpRequestValue<long?>("0");

I get following exception:

  Invalid cast from 'System.String' to 'System.Nullable`1[[System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.

I went looking for a cause and it seems that Convert.ChangeType has problems with nullable types. You have to use the underlying type of the nullable in order to make it work:

protected T GetHttpRequestValue<T>(string key)
{
    string value = HttpContext.Current.Request[key];

    if (string.IsNullOrEmpty(value))
        return default(T);

    var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
    var convertedValue = (value == null) ? null : Convert.ChangeType(value, type);
    return (T)convertedValue ;
}

Now I get following results:

GetHttpRequestValue<long?>("0");    // 0
GetHttpRequestValue<long?>("");     // null
GetHttpRequestValue<long>("1");     // 1
GetHttpRequestValue<bool>("true");  // True
GetHttpRequestValue<bool>("");      // False

GetHttpRequestValue<long?>(null);   //null
GetHttpRequestValue<bool>(null);    //False

You also made your method dependent of an HttpContext, you cannot reuse it. Better would be to rename it to something like ConvertTo and leave out the HttpContext-line:

protected T ConvertTo<T>(string value)
{
    if (string.IsNullOrEmpty(value))
        return default(T);

    var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
    var convertedValue = (value == null) ? null : Convert.ChangeType(value, type);
    return (T)convertedValue;
}

Example usage:

protected void Page_Load(object sender,EventArgs e)
{
    var value = HttpContext.Current.Request["YourKey"];
    var converted = ConvertTo<long?>(value);
}

Your code is still clean and the method is reusable. Notice that I use var instead of explicitly declaring variables. This is not mandatory, I just prefer to use it. Hope this helps!

Update:

I updated the method to handle a fail on the conversion, in case you want to change qwerty to a bool for example. :)

protected T ConvertTo<T>(string value)
{
    if (String.IsNullOrEmpty(value))
        return default(T);

    var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
    T convertedValue = default(T);

    try
    {
        convertedValue = (T)Convert.ChangeType(value, type);
    }
    catch {}

    return convertedValue ;
}

This way of working swallows the exception. In case one occurs the default of T will be returned, otherwise the converted value. Results:

ConvertTo<int>("qwerty");    //0
ConvertTo<bool>("qwerty");   //False

Update:

As stated in the comments below, you can also take the code and throw it in an extension method. Also nice for reusability and your could will also look a bit cleaner. Here goes:

public static class Extensions
{
    public static T ConvertTo<T>(this string value)
    {
        if (String.IsNullOrEmpty(value))
            return default(T);

        var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
        T convertedValue = default(T);

        try
        {
            convertedValue = (T)Convert.ChangeType(value, type);
        }
        catch {}

        return convertedValue ;
    }
}

Usage:

var intFromString = "2".ConvertTo<int>();
//intFromString is an integer with value 2


Allocation woes. char *tmpCurrency needs enough memory for a null character terminated string.  This implies a +1 to the length + commas addition.  The cast of malloc() is not needed.  Multiplying by the size of a pointer sizeof(char*) is wrong.  It should be by the size of an element of tmpCurrency, which is a char.  length,commas should be size_t rather than int, but that make s little difference  with small strings.

// tmpCurrency = (char*) malloc((length + commas) * (sizeof(char*)));
tmpCurrency = malloc(sizeof *tmpCurrency * (length + commas + 1));

Separate out functional code from the test driver.  I'd expect some stand-alone function Devious_ICF(char *dest, const char *src) and then code in main() testing it.
Questionable space size and incorrect use of gets_s(char *s, rsize_t n).  Avoid coding naked magic numbers like 20

// char        currency[20];
// gets_s(currency);

#define CURRENCY_SIZE 20
...
char currency[CURRENCY_SIZE];
gets_s(currency, sizeof currency);

stdout is not certainly output as a prompt before asking for input.  To maintain portability, flush.

puts("Enter the Currency");
fflush(stdout);  // add
gets_s(...);

Curious use of static.  static not needed here.

// static int  i = 0, cnt = 0;
int  i = 0, cnt = 0;

Accessing code outside array bounds.

// memmove(currency, currency + n, strlen(currency));
memmove(currency, currency + n, strlen(currency) - n);
currency[n] = '\0';

Use of ?: does not certainly use a consistent type as the types of currency[0]='-' and NULL may differ.  An if() would be better anyways.

// signCount==1?currency[0]='-':NULL;
if (signCount==1) {
  currency[0] = '-';
}

Format to presentation width.  Use an auto formatter.  Weak formatting employed significantly detracts from code's presentation.

          if (length % 2 == 0)                            //When length is even comma comes after 1 digit eg 1,23,456. so what i have done adjusting length ann checking when it is becoming even and putting comma.

versus

          // When length is even, comma comes after 1 digit e.g. 1,23,456.
          //   so what i have done adjusting length and checking when it is
          //   becoming even and putting comma.
          if (length % 2 == 0)

Incorrect use of errno_t strcpy_s(char * restrict s1, rsize_t s1max, const char * restrict s2);.  Missing parameter.

strcpy_s(currency, tmpCurrency);`

Missing #include headers.
Overall - approach used is excessively complex.

Given above issues that a compiler should have reported, it implies compilation is not done with warning fully enabled or code is using non-standard C.  Recommend fully enabling all warnings.


A couple of small things to start.

var rows: List[Array[Student]] = List[Array[Student]]()

This line can be simplified slightly by doing this instead:

var rows: List[Array[Student]] = List.empty

Unless you are caching the total for performance reasons, you could calculate it as needed with something like this:

def total: Int = rows.map(_.length).sum

That would simplify addRow() to this:

def addRow(row: Array[Student]) = rows = row :: rows

One of the tenets of functional programming is the use of immutable data. ClassRoom is not very functional from this perspective: both rows and total are mutable. If you wanted to take a pure functional approach, all members would be val and functions like addRow() would return a new ClassRoom instead of modifying itself. For example:

class ClassRoom(val rows: List[Array[Student]]) {
  def total: Int = rows.map(_.length).sum
  def addRow(row: Array[Student]) = new ClassRoom(row :: rows)
  def print = rows.foreach(_ foreach println)
}


Review

all in all, this code is rather clean. I would use a generator comprehension and itertools.chain in fake_disrete_data instead of the nested for-loop, but that is a matter of taste

linewraps

I prefer to wrap lines after the ( instead of the first argument. Here I follow the same rules as black. This leads to lesser indents, but slightly longer code, for example:

dfs.append(
    pd.pivot_table(
        fake_disc,
        index=fake_disc.index.date,
        columns=fake_disc.index.hour,
        values=col,
        aggfunc=np.mean,
    )
)

list comprehension

instead of the appending, you can do

dfs = [
    pd.pivot_table(
        fake_disc,
        index=fake_disc.index.date,
        columns=fake_disc.index.hour,
        values=col,
        aggfunc=np.mean,
    )
    for col in columns
]

or even better, feed a dict to pd.concat, so you don't have to specify the keys argument

dfs = {
    col: pd.pivot_table(
        fake_disc,
        index=fake_disc.index.date,
        columns=fake_disc.index.hour,
        values=col,
        aggfunc='mean',
    )
    for col in fake_disc.columns
}
pd.concat(dfs, axis=1)

I also changed the np.mean to 'mean', so you don't have to specifically import np for this, and avoided having to create the columns list

Alternative approach

pd.pivot is a wrapper around unstack, groupby and stack. If you want to do something more complicated, you can do those operations by hand

fake_disc = fake_disrete_data()
fake_disc.columns = fake_disc.columns.set_names('variable')
df = fake_disc.stack().to_frame().rename(columns={0: 'value'})
df['hour'] = df.index.get_level_values('time').hour

this creates an intermediary DataFrame

time                variable    value   hour
2016-06-11 00:00:00 mag_sig     0.0     0
2016-06-11 00:00:00 bias        0.5     0
2016-06-11 00:15:00 mag_sig     0.0     0
2016-06-11 00:15:00 bias        0.5     0
2016-06-11 00:30:00 mag_sig     0.0     0
...

This you can group. To group the time per hour, you can use pd.Grouper

pivot = (
    df.groupby([pd.Grouper(level="time", freq="d"), "hour", "variable"])
    .mean()
    .unstack(["variable", "hour"])
    .sort_index(axis="columns", level=["variable", "hour"])
)

  value
variable  bias    ...     mag_sig
hour  0   1   2   3   4   5   6   7   8   9   ...     14  15  16  17  18  19  20  21  22  23
time
2016-06-11    0.5     0.5     0.5     0.5     0.5     0.5     0.5     0.5     0.5     0.5     ...     14.0    15.0    16.0    17.0    18.0    19.0    20.0    21.0    22.0    23.0
2016-06-12    0.7     0.7     0.7     0.7     0.7     0.7     0.7     0.7     0.7     0.7     ...     14.0    15.0    16.0    17.0    18.0    19.0    20.0    21.0    22.0    23.0
2016-06-13    1.0     1.0     1.0     1.0     1.0     1.0     1.0     1.0     1.0     1.0     ...     14.0    15.0    16.0    17.0    18.0    19.0    20.0    21.0    22.0    23.0

performance

according to the %%timeit cell magic in Jupyterlab,
the first approach (with the dict and concat) takes about 23ms, the second approach about 10ms. Depending on your usecase, this difference might be important. If it is not, pick the method which is most readable to your future self


The label element can be used for the labels of the input fields.

The placeholder attribute shouldn’t be used for labeling.

The output element can be used for the result. (You are using a label, which is not appropriate; and note that label can’t have a type attribute.)

Maybe a button with the button type is more appropriate here. (Button type “button” vs. “submit”)

This results in:

Loaded pounds
<input type="number" id="loaded">

Unloaded pounds
<input type="number" id="unloaded">

<button type="button" id="button" onclick="calc()">Convert</button>

<output for="loaded unloaded" id="result"></output>


Query to plot a histogram of song ratings

It would be better to use GROUP by in your SQL. By this way you will get rid of long SQL query.

SELECT Rating, COUNT(id) FROM list WHERE songID=:songID GROUP BY Rating;


A Note class which plays a note and stops it after specific period of time

Why is this a class? It contains no data and has no methods; the only thing it has is a constructor. This would be more suitable as a method.

Let's step back and look at the desired behaviour:

  This code plays a note for a specific period of time.

Here is the simplest way I can think of to achieve this:

public static async Task PlayNoteAsync(
    MidiOut midiOut,
    int note,
    TimeSpan duration,
    int volume = 127,
    int channel = 0)
{
    midiOut.Send(MidiMessage.StartNote(note, volume, channel).RawData);
    await Task.Delay(duration).ConfigureAwait(false);
    midiOut.Send(MidiMessage.StopNote(note, volume, channel).RawData);
}

We just:

Start playing the note
Wait the desired amount of time
Stop playing the note

Much of the original code is concerned with whether or not the MidiOut object has been disposed. I don't believe it should be the responsibility of this method to check if the MidiOut has been disposed; I would suggest instead to restructure the client code such that MidiOut is not disposed until the notes have stopped playing (or play has been cancelled, see below). Unfortunately, it's hard to be more specific about how to do this without an example of the client code. I would also recommend removing the MidiOutWrapper class.

You might want to support cancellation with a CancellationToken:

public static async Task PlayNoteAsync(
    MidiOut midiOut,
    int note,
    TimeSpan duration,
    int volume = 127,
    int channel = 0,
    CancellationToken cancellationToken = default(CancellationToken))
{
    // Consider using cancellationToken.ThrowIfCancellationRequested(); here.
    midiOut.Send(MidiMessage.StartNote(note, volume, channel).RawData);

    try
    {
        // Task.Delay will throw a TaskCanceledException if the
        // cancellationToken is signalled before the wait period is over.
        await Task.Delay(duration, cancellationToken).ConfigureAwait(false);
    }
    finally
    {
        midiOut.Send(MidiMessage.StopNote(note, volume, channel).RawData);
    }
}

Finally, I think this is a suitable candidate for being an extension method.


Generating multiple new arrays using numpy

You could use np.random.choice() to generate the states, while using a==b and a!=b as masks.
def new_states(a,b,n):
    return [
        a*(a==b) + np.random.choice(2,len(a))*(a!=b)
        for _ in range(n)
    ]

state1 = np.array([0, 1, 0, 1, 1])
state2 = np.array([1, 1, 0, 0, 1])
print(new_states(state1,state2,4))


Optimising a LinkedList data structure - Part 1

There are several small things I can see in class Node:

You have a move constructor, but no copy constructor.
You have a move assignment operator, but no copy assignment operator.
Since you use C++11, you should replace the exception specification throw () (now deprecated) by noexcept.
Your move assignment operator is not protected against self-assignment. You should add the condition if (&n != this) { ... }.
Also, if possible, your move constructor and operator= should be noexcept too.
Generally speaking, with move assignment operator, you don't want to move pointers, you only want to swap them since - I believe - your nodes own the pointed values (more information here).

Node& operator=(Node&& n) noexcept {
    if (&n != this) {
        std::swap(data, n.data);
        std::swap(prev, n.prev);
        std::swap(next, n.next);
    }
    return *this;
}


duplicated operator(or attribute) on the same input control - v-model and @change

Responding to Your question

This is good use of ref and Object.assign() but normally this would be a good place to use a watched Property, or if you need to add dashes, a computed property.

Take a look at the example below, which uses a watcher, instead of the @onchange, which means that the method applyData() can be eliminated:

const form = new Vue({
    el: '#form',
    data: function () {
      return {
        deliveryInfo: {
          receiver: ''
        }
      }
    },
    watch: {
      'deliveryInfo.receiver': function(newValue, oldValue) {
        console.log('receiver changed - deliveryinfo:', this.deliveryInfo);
        this.$emit('applyChildData', this.deliveryInfo);
      }
    },
    methods: {
      test: function () {
          console.log('set John Doe');
        this.deliveryInfo = Object.assign({}, this.deliveryInfo, {receiver: 'John Doe'});
        console.log('After change ', this.deliveryInfo);
        // It triggers applyData method and change input element value
        // But when I remove v-model in input value, it is not working
      }
    }
  });

    <input type="text" ref="receiver" v-model="deliveryInfo.receiver" />
    <button type="button" @click="test">TEST</button>

Or the snippet below which uses a computed property to add a dash between the third and fourth characters...

const form = new Vue({
    el: '#form',
    data: function () {
      return {
        deliveryInfo: {
          receiver: ''
        }
      }
    },
    computed: {
      dashedReceiver: function() {
        if (this.deliveryInfo.receiver.length > 3) {
          return this.deliveryInfo.receiver.slice(0,3) + '-' + this.deliveryInfo.receiver.slice(3);
        }
        return this.deliveryInfo.receiver;
      }
    }
  });

    <input type="text" ref="receiver" v-model="deliveryInfo.receiver" />

{{dashedReceiver}}

Other feedback

One other critique I have is this line:

let ref = this.$refs[refName];

That variable never gets re-assigned so to avoid accidental re-assignment, use const instead of let. There are some who recommend the following:

  use const by default
  only use let if rebinding is needed
  1

There may not be much of a performance difference here although after reading some SO answers like this one and this one there is a potential but that might only be if a primitive type value (e.g. 42) was used.

1https://mathiasbynens.be/notes/es6-const


Checking if switch is checked and doing something with the data

With a function:

var checkedValue = function (tdid, field) {
    if ($("." + field + "-" + tdid).is(':checked')) {
        return $("." + field + "-text-" + tdid).text();
    }
    return "";
}

and you could then simply call that with:

for(var i = 0; i < people_to_save_parse.length; i++) {
    people_to_save_parse[i].id = checkedValue(people[i].tdid, "ID");
    people_to_save_parse[i].firstname = checkedValue(people[i].tdid, "Name");
    people_to_save_parse[i].lastname = checkedValue(people[i].tdid, "Surname");
}

This removes much of the code duplication.

Note also that convention puts the { at the end of the line in JavaScript, not at the start of the next line. Also, you should add space between your operators and expressions to make them more readable. Finally, you don't need to add the == true as it is not useful in the if condition since the is(":checked") function returns a boolean already.

A concern I have is that you have two arrays, people_to_save_parse and people. You index them both with the same i index, and there is no apparent control that ensures they are 'in sync'. Are they a 1-to-1 matching pair of arrays?


Portability

First this program could be made more portable. There are 2 portability issues here

If it was ported to a system that did not define end of line as "\r\n" this program might not work. This problem could be solved by including the proper header files or using

#define EndOfLine "\r\n"

and using

    ptr = strstr(buffer, EndOfLine)

The second portability issue is the use of strdup(). It is not implemented on all systems. This Stackoverflow question discusses the use of strdup.

Consistency in Coding Style

There is one place in the code where the indentation is inconsistent:

    if (buffer)
    {
        size = strlen(buffer) + strlen(data) + 1;
        if (!(buffer = realloc(buffer, size)))
            return (NULL);
        strcat(buffer, data);
    }
    else {
        if (!(buffer = strdup(data)))
            return (NULL);
    }

The use of braces "{" and "}" should be consistent through the entire program.
Everywhere except in this code the brace starts on a new line.

It would be very nice if the headers were included for compilation and
testing. Without the headers or the calling functions it is difficult to
compile or test this code.

Complexity

It might be better if the function read_message(char *data) was separated
into multiple functions to reduce the complexity. All of the functions might
be more readable if there was some virtical spacing between blocks of code.

Possible Bug

The function parse_message(char *buffer) always returns NULL, in your
testing did the function handle_message() always get called?


For one thing, everything is just setting booleans. Condense down all those nested if blocks down into boolean statements and use good names, and it'll even make sense in "plain English".

protected void Page_Load(object sender, EventArgs e) {
    if (IsPostBack) return;
    Func<string, bool> QueryStrHas = key => !String.IsNullOrEmpty(Request.QueryString[key]);
    var isCalEvent = QueryStrHas("CalendarEventID");
    var isVacDay  = QueryStrHas("VacationDayID");
    var isUnpaidVac = QueryStrHas("VacationDayUnpaidID");

    var user = HttpContext.Current.User;
    var isGuest = user.IsInRole("Guest");
    var isAdmin = user.Identity.Name.ToString().ToLower() == "administrator";

    // guests cannot edit
    // non-guests can edit regular calendar events, but not vacation days
    // non-guests can delete vacation days
    // unpaid vacation days can only be deleted by administrators
    btnedit.Enabled = !isGuest && isCalEvent && !isVacDay;
    btndelete.Enabled = !isGuest && isVacDay;
    btndelete.Visible = !isGuest &&
                        (isVacDay||
                        (isAdmin && isUnpaidVac));
}

Make sure you double-check the boolean arithmetic by testing it though. There're some missing cases (kind of), and you should make sure it's all well-defined.

Oh, by the way, just cosmetically "hiding" the btnedit when a user isn't an Admin does not count for true security. Anybody can actually modify all these values when it reaches their browser client-side.


Summing all primes below 2,000,000 - Project Euler #10 in Assembly

Because all of your variables Sum, CurrentPrime, CurrentN, and PrimeMode reside in registers your code could/should benefit from this fact.

You've calculated CurrentPrime = CurrentN * 6 - 1 using:

mov rax, CurrentN     ; multiply it by 6 and save it to CurrentPrime
mov rbx, 6
mul rbx
mov CurrentPrime, rax
dec CurrentPrime    ; Start with 6n-1

Not only does this clobber the registers rax, rbx, and rdx, it also uses the mul instruction variant that produces an 128-bit result. Intel advices against this form when the upper 64-bits of the result are not needed which is the case in your program. A better multiplication then comes from using the 2 operand form of imul.

mov  CurrentPrime, CurrentN
imul CurrentPrime, 6
dec  CurrentPrime

This shorter and faster solution also doesn't use any additional registers!

When you reset your variables and registers you consistently use the mov instruction.

mov CurrentN, 0 ; This gets inc'ed below
mov PrimeMode, 0
mov rdx, 0

Because these variables really are registers too, and because the preferred way to zero a register is to xor it with itself, you should write instead:

xor  CurrentN, CurrentN
xor  PrimeMode, PrimeMode
xor  rdx, rdx

This produces much shorter code.

This is how you check if PrimeMode is zero.

cmp PrimeMode, 0
jne loop

Because this variable really is a register, and because the preferred way to find out if a register is zero is to test it with itself, you should write instead:

test PrimeMode, PrimeMode
jnz  loop

In next snippet you want to toggle PrimeMode when the prime at 6n-1 was found.

cmp PrimeMode, 0    ; If we've done 6n+1, then go for the next n
jne loop
mov PrimeMode, 1 ; Set plus

That's fine but you could use the fact that PrimeMode is equal to zero here and just have it incremented instead of using the space consuming immediate value:

test PrimeMode, PrimeMode
jnz  loop
inc  PrimeMode             ;Set plus

Divisions are costly.

In order to conclude that the current number is prime, you perform a division by 2.

; When divisor_to_test > (number_to_test/2), then this is prime
mov rax, CurrentPrime
mov rbx, 2
mov rdx, 0
div rbx
cmp rax, rcx
jl is_prime

You should replace this wasteful div by a simple shift to the right:

mov  rax, CurrentPrime
shr  rax, 1
cmp  rax, rcx
jl   is_prime

Why in next part of the code doesn't your division use the rcx register straight away? Why do you first move the divisor in rcx to rbx? That's just a superfluous instruction!

; Test divisor for divisor
mov rax, CurrentPrime
mov rbx, rcx
mov rdx, 0
div rbx
cmp rdx, 0
je check_next_prime

No longer clobbering the rbx register and applying many of the above tips gives:

mov  rax, CurrentPrime
xor  rdx, rdx
div  rcx
test rdx, rdx
jz   check_next_prime

Avoid redundant operations.

In your most inner loop you keep checking if CurrentPrime exceeds 2000000, but you forget that the value of CurrentPrime does not change within this inner loop. Best move the test above the next_prime_test label introducing an additional label MAYBE_next_prime_test.

    mov  PrimeMode, 0             ; Reset registers for testing
    ;;;mov  rcx, 2     <----- Remove this line
MAYBE_next_prime_test:
    cmp  CurrentPrime, 2000000    ; When the number to test is >= 2000000, then exit
    jge  finish
    mov  rcx, 2     <----- This line replaces both others
next_prime_test:

    ...

    inc rcx
    jmp next_prime_test

    ...

    ;;;mov  rcx, 2     <----- Remove this line
    add  CurrentPrime, 2          ; 6n-1 +2 = 6n+1
    jmp  MAYBE_next_prime_test    ; Check 6n+1
finish:
    mov  rax, Sum                 ; Result is in rax

I've also avoided the duplication of the mov rcx, 2 instruction that you already had in the top part of the program. Shaves off some bytes!


User agent classification using switch (true)

Assuming that you bad a bunch of boolean variables already defined, I think a chained ternary conditional expression would be even better, because it's more compact, and also emphasizes that the goal is to assigning something to browser.

var browser = isChrome ? "chrome" :
              isSafari ? "safari" :
              isFirefox ? "firefox" :
              null;

Also consider defining a userAgentContains(…) function to reduce redundancy.


There is little reason to do this. If you include the stacktrace in your logs you already know where the problem exists; the only thing you'd miss is the input which you might know from different channels (and often isn't necessary to figure out the problem).

Noting that your example returns void which is probably not what you intended, I should say that the change I would make is to use .FirstOrDefault() instead of First which will instead return the default value - null for a reference type. You can then work with a simple null check to see whether or not a record was returned instead of having to start using try-catches.

Yes, you could do all this to provide specific error messages. Personally I am not a fan of it and I prefer to derive this from the code itself (through for example the before-mentioned null check).


Regular Expressions - finding two or more vowels with a consonant before and after it, includes overlapping

Raw Strings

 r'(?<=[qwrtypsdfghjklzxcvbnm])([aeiou]{2,})(?=[qwrtypsdfghjklzxcvbnm])'

The advantage of raw strings is you don't have to escape (add a \ before) certain characters, such as quotation marks and the backslash character itself.  You aren't using any characters you need to escape here, so why use a raw string?

Redundant lists

match_obj = list(...)
if len(list(match_obj)) != 0:
    ...

match_obj is already a list; you don't need to make a new list out of it, to determine it's length.  Just use match_obj directly:

match_obj = list(...)
if len(match_obj) != 0:
    ...

Of course, a list of length zero is falsy, and any list of non-zero length is truthy, so you don't need the len(...) != 0 test:

match_obj = list(...)
if match_obj:
    ...

list(re.finditer)

The function re.finditer(...) returns an iterator, and avoids building up the complete result, so you can process a string piece by piece, distributing the memory usage over time instead of collecting and returning all results immediately.

Passing the result of re.finditer(...) to list(...) immediately runs the iterator to completion, collecting all results into the in-memory list.  Any efficiency gained by using the iterator version is lost, and may actually decrease performance because the work required to create the iterator, save temporary state, etc., has been wasted.

The only thing you do with the resulting match objects is call .group() on them, to get the matched text.

So why not use re.findall(...) which returns the list of matched strings?

    matches = re.findall(r'(?<=[qwrtypsdfghjklzxcvbnm])([aeiou]{2,})(?=[qwrtypsdfghjklzxcvbnm])', string, re.IGNORECASE))
    if matches:
        for match in matches:
            print(match)
    else:
        print(-1)

Consonants

This isn't going to make the code more compact or efficient, but it might make it more maintainable and readable:

Is "qwrtypsdfghjklzxcvbnm" the complete list of consonants?  Did you forget any?  You've ordered them in QWERTY order, which makes it hard for a reader to verify it.

Sometimes "y" is considered a vowel.  If you were to want to include it, you'd have to add the "y" to the vowel list, and remove it twice from the consonants list.

Maybe you should:

from string import ascii_lowercase

vowels = "aeiou"
consonants = ''.join(set(ascii_lowercase) - set(vowels))

Then you could generate your regex string:

double_vowels = f"(?<=[{consonants}])([{vowels}]{{2,}})(?=[{consonants}])"

and even compile it:

double_vowels = re.compile(
    f"(?<=[{consonants}])([{vowels}]{{2,}})(?=[{consonants}])",
    re.IGNORECASE)

Refactored Code

import re
from string import ascii_lowercase

vowels = "aeiou"
consonants = ''.join(set(ascii_lowercase) - set(vowels))

double_vowels = re.compile(
    f"(?<=[{consonants}])([{vowels}]{{2,}})(?=[{consonants}])",
    re.IGNORECASE)

def find_two_or_more_vowels(string: str) -> None:
    matches = double_vowels.findall(string)
    if matches:
        for match in matches:
            print(match)
    else:
        print(-1)

if __name__ == '__main__':
    find_two_or_more_vowels(input())


lodash get method equivalent in javascript

You can try the following script as alternate approch which:

Get a nested property of a complex object at any level of depth without using recursion.

This script uses replacer optional function for JSON.stringify(), basically it takes a JavaScript value (your initial object) and convert to a JSON string, and it uses that string to search within your array. The script works without any recursions, with any number of nested properties for your objects. The order of your property is important in this script, as the conversion to string take it in consideration.

Cavet: Date object is returned stringified.

let data = {
  d: 'new vale',
  a: {
    b: {
      c: {
        e: 'value'
      }
    }
  }
};

let getPropertyRecursive = function(data, name) {
  let result = {
    isFound: false,
    value: null
  };
  JSON.stringify(data, function(k, v) {
    if (k === name) {
      result.isFound = true;
      result.value = v;
      return undefined;
    } else {
      return v;
    }
  });
  return result;
};

let result1 = getPropertyRecursive(data, 'e');
let result2 = getPropertyRecursive(data, 'a');
console.log(result1);
console.log('-----');
console.log(result2 );


Useless Code

Your @memo-ization doesn't do anything of value:

Your mainline calls collatz() exactly once.  Unless given the value 1, the collatz() function calls itself with 3*n + 1 or n // 2, and since the Collatz sequence doesn't have any loops until the value 1 is reached, it will never call itself with a value it has already been called with.  So, you are memoizing values which will never, ever be used.
Your collatz() function doesn't just return a value; it has a side-effect: printing!  If you did call collatz() with a value that has already been memoized, nothing will be printed.

Tail Call, without Tail Call Optimization

You've increased the recursion limit to \$10^9\$ stack levels, which is impressive.  But the algorithm doesn't need to be recursive.  A simple loop would work.  And since Python cannot do Tail Call Optimization, you should replace recursion with loops wherever possible.  Doing so eliminates the need for the increased stack limit:

def collatz(n):
    count = 1

    while n > 1:
        if n % 2 != 0:
            n = n * 3 + 1
        else:
            n //= 2

        print(n)
        count += 1

    return count

Separate Sequence Generation from Printing

You can create a very simple Collatz sequence generator:

def collatz(n):
    while n > 1:
        yield n
        n = n * 3 + 1 if n % 2 else n // 2
    yield 1

Using this generator, the caller can print out the Collatz sequence with a simple loop:

for x in collatz(13):
    print(x)

Or, if the caller just wants the length of the Collatz sequence, without printing out each item in the sequence, you can determine the length of the sequence with len(list(collatz(13))).  Better would be to count the items returned by the generator without realizing the list in memory: sum(1 for _ in collatz(13)).

Project Euler 14

The above generator works great for determining the sequence from any arbitrary value.  If you want to compute the length of collatz(n) for \$1 \le n \le 1,000,000\$, you may want to return to memoization.  However, this is Code Review, and while you alluded to PE14, you didn't actually provide code for that, so that cannot be reviewed here.


Grep to search for array of location targets

Your questions:

Yes. Use double quotes and then drop the eval (this will also cause the script to show /path/to/prod/home instead of $PROD_HOME)
Yes, just do it once at the start of the script.
No.
Depends on your requirements.

Other issues:

Using multiple regex can be specified but won't work
Using paths with spaces doesn't work

Keeping most of your current functionality, I probably do something like this:

#!/bin/bash
shopt -s nullglob

# Allow using ** to recursively expand globs
shopt -s globstar

# Don't do any field splitting
IFS=''

if (( ! $# ))
then
    echo "specify at least one regex"
    exit 1
fi

locations=(
  "$BIN_HOME/*"
  "$PBIN_HOME/**"
  "$SH_HOME/**"
  "$PROD_HOME/psp/*.psp"
  "$PROD_HOME/sql/*.sql"
  "$PROD_HOME/sql/*/*.sql"
  "$PROD_HOME/rpt/[A-Z]*.rpt"
  "$PROD_HOME/script/*"
  "$PROD_HOME/fmb/[A-Z]*.pll"
  "$PROD_HOME/xml/[A-Z]*.pld"
  "$PROD_HOME/fmb/[A-Z]*.mmb"
  "$PROD_HOME/xml/[A-Z]*.xml"
  "$PROD_HOME/cgi/*"
  "$ELETTUS_HOME/**"
  "$PROD_HOME/guicommon/*"
)

# Quote all variables unless you specifically can't
for location in "${locations[@]}"
do
    echo "--------------------------------------------------------------------------------"
    # Printf generally works better for arbitrary data, though this is unlikely to be an issue in your case
    printf "%s\n" "$location"
    echo
    if [[ "$location" != /u2/* ]]
    then
        printf "%s is not a part of Lettus system\n" "$location" >&2
        echo
        continue
    fi

    # grep can accept multiple patterns separated by line feeds
    # Add a dummy file so non-matching globs won't cause grep to read from stdin
    # Here we want $location to glob expand, so no quotes (IFS was set earlier to prevent field splitting)
    grep -E -I -d skip "$(printf "%s\n" "$@")" /dev/null $location
done


Dynamically generating Strings (or other variables)

For something similar to your Java solution, you could have this in filetype.py:

import os.path

class FileType(object):
    HOME_DIRECTORY = "/path/to/scripts"

    def __init__(self, extension):
        self.extension = extension

    def file_path(self, name):
        return os.path.join(self.HOME_DIRECTORY, name + self.extension)

SHELL_SCRIPT = FileType(".ksh")
CONFIGURATION = FileType(".conf")

Then the usage would be

import filetype
filetype.SHELL_SCRIPT.file_path("onhand_accuracy")