Display four random entries from an array

I think the function is not named properly.  You are NOT shuffling an associative array.  You are shuffling a numerically indexed array (whose values happen to be associative arrays).

As such, I don't see a great need for this function.  You could use array_rand() to pick random keys from the array.

Now, assuming you did want to keep such a function, for example to actually get array of values not just keys.  I would consider a few things:

Consider throwing an exception or logging error if function is passed a non-array value.  This can help make sure you are invoking this function properly in your code vs. just returning the passed value unchanged.
Consider passing "limit" value to the function vs. hard-coding for 4 return elements.

This might yield something like:

function array_rand_values($arr, $limit = 1) {
    if(!is_array($arr)) {
        throw new InvalidArgumentException('Array expected for first argument.');
    }
    if(!is_int($limit) || $limit < 1) {
        throw new InvalidArgumentException(
            'Positive integer value expected for second argument.'
        );
    }
    if(count($arr) <= $limit) {
       shuffle($arr);
       return $arr;
    }
    $keys = array_rand($arr, $limit);
    $values = array();
    for ($i = 0; $i < $limit; $i++) {
        $values[] = $arr[$keys[$i]];
    }
    return $values;
}

Note that this function does not preserve keys if passed an associative array.  This should probably be the logical behavior in such a case, as "shuffling" an associative array typically makes zero sense.  This would however still pick X random values from an associative array.

If one needed to pick X random key/value pairs from an associative array, I would suggest a separate function, so that intent of caller is clear.  That function may be implemented in very similar manner  to the one above, with single line of code change.

function array_rand_values_assoc($arr, $limit = 1) {
    // same code as above until assignment in loop

    for ($i = 0; $i < $limit; $i++) {
        $values[$keys[$i]] = $arr[$keys[$i]];
    }
    return $values;
}


In terms of number of properties, I wouldn’t worry about that. There are situations where you can have lots of properties. As the philosopher says, “it is what it is.”

Obviously, from a data modeling perspective, what doesn’t feel quite right is to combine product info, coupon info, shop info, etc. into a single object. E.g. products sometimes are eligible for multiple coupons. Or perhaps you’ll be repeating the “shop” information multiple times in your result set.

That having been said, it depends upon what this feed is for: If this is a search result employed within a particular view within the app, then perhaps a fairly flat structure, like yours, is fine (though I might call the object a “search result” rather than a “product”). But if this is for populating a local data store that users can search locally, then I might expect separate objects for the different entity types (a product object, a shop object, etc.). I’d ask myself how often can the same information be repeated in a particular result set. But whether you have a denormalized/flat result set, or a more normalized product database, just depends upon the nature of the API and how this is being used within the app.

The only change that really jumps out at me is that there are several properties that would appear to be numeric types that are captured as strings (e.g. prices, rates, fees, income, etc.). Perhaps your feed returns them as strings, but within your app, you don’t want to have to sprinkle your code with string-to-number conversions so that you can do things like show the user grand totals, convert rates to totals, or the like. I might be inclined to do that string-to-number conversion while parsing the feed (or, better, change the feed to actually return numeric types) and then I’m working purely with numeric types within the app.


Subset sum simple iterative implementation

Again has \$O(n*2^n)\$ complexity

This program, like the recursive solution in the previous question, has \$O(n*2^n)\$ complexity.  It is simple to see that you iterate \$2^n\$ times, and on each iteration you compute the sum in \$O(n)\$ time.

Using Gray code to achieve \$O(2^n)\$ time

The key to reducing the run time of this iterative solution is to remove the \$O(n)\$ summation loop.  You can only do this if you can compute the next sum from the previous sum in \$O(1)\$ time.  Unfortunately, between one iteration and the next, up to \$n\$ numbers might need to be added/subtracted.  For example, if you were on this bit pattern:

0 1 1 1 1 = arr[0] + arr[1] + arr[2] + arr[3]

The next bit pattern would be:

1 0 0 0 0 = arr[4]

You would need to add one number and subtract 4 numbers to get from the previous sum to the next sum.  This is where the Gray code comes in to play.  The Gray code is a numerical sequence where each number in the sequence differs from the previous by only 1 bit.  So if you counted upwards using a Gray code sequence, then the next sum can be computed from the previous sum by only adding/subtracting one number.

Luckily, it is easy to count upwards in a Gray code sequence.  You can just count upwards in the normal way and then convert your normal number to the corresponding Gray code number using the formula:

grayCode = n ^ (n >> 1)

Then to find the bit that changed, you can xor the new gray number with the previous one:

bitChanged = oldGray ^ newGray;

One tricky part is that you need to know the bit number of the bit that changed.  Normally, I would do:

bitIndex = 31 - CLZ(bitChanged);

where CLZ() is a builtin "count leading zeros" function.  I couldn't find a builtin function in C# for that though, so I wrote my own.  There are fast versions of CLZ() that can be done in constant time using a lookup table, but I decided to use a looping version.  In the case of counting upwards using Gray numbers, bitChanged will be 0x1 50% of the time, 0x2 25% of the time, 0x4 12.5% of the time, etc.  Because of this, the looping variant will take amortized constant time since it operates faster on smaller bit numbers.

Sample Gray code implementation

I took your program and changed two functions: FindSubsetSum() and PrintSubset().  I also added my own clz() function.  Here is the modified parts of your code:

    private static void FindSubsetSum(int[] arr, int targetSum)
    {
        int length     = arr.Length;
        int iEnd       = 1 << length;
        int currentSum = 0;
        int oldGray    = 0;

        for (int i = 1; i < iEnd; i++)
        {
            int newGray    = i ^ (i >> 1);
            int bitChanged = oldGray ^ newGray;
            int bitNumber  = 31 - clz(bitChanged);

            if ((newGray & bitChanged) != 0)
            {
                // Bit turned to 1 = Add element.
                currentSum += arr[bitNumber];
            }
            else
            {
                // Bit turned to 0 = Subtract element.
                currentSum -= arr[bitNumber];
            }
            // Check for sum and print if equal
            if (currentSum == targetSum)
            {
                PrintSubSet(arr, newGray);
            }
            oldGray = newGray;
        }
    }

    private static void PrintSubSet(int[] arr, int bits)
    {
        Console.Write("(");
        for (int i = 0; i < arr.Length; i++)
        {
            if ((bits & (1 << i)) != 0)
            {
                Console.Write(arr[i]);

                if (i < arr.Length - 1)
                {
                    Console.Write(" ,");
                }
            }
        }
        Console.WriteLine(")");
    }

    // This can be replaced with a better variant, but this variant
    // will do the job for the Gray code sequence since the low
    // bit numbers will appear the vast majority of the time.
    private static int clz(int x)
    {
        int lz = 32;

        while (x != 0) {
            x >>= 1;
            lz--;
        }
        return lz;
    }


Implementation of Scytale cipher (encryption and decryption)

I have some suggestions for your code.
Use java.lang.StringBuilder to concatenate String in a loop.
It's generally more efficient to use the builder in a loop, since the compiler is unable to optimize it by itself while translating your code into bytecode; The compiler will not use the java.lang.StringBuilder in complex loops and your method will take more time and more memory to execute, since the String Object is immutable (a new instance will be created each iteration).
StringBuilder encrypted = new StringBuilder();
for (int i = 0; i < kth; i++) {
   for (int j = 0; i + j < textLength; j += kth) {
      encrypted.append(text.charAt(i + j));
   }
}
return encrypted.toString();

When concatenating a primitive into a string, you don’t need to convert it.
You can add the primitive (int, double, float, char, ect) directly into the string by using the assignment operators (+, +=).
Before
encrypted += String.valueOf(text.charAt(i+j));

After
encrypted += text.charAt(i+j);


Activator with simple dependency injection

You are putting pretty strong limitations on classes you can activate this way - a single .ctor, no default .ctor(which can make serialization troubles later) and all .ctor arguments should have different types, otherwise .Join will go crazy. No nested dependencies support, too. No named registrations.

So, all in all, your DI is rather stupid, and if you try to make it smarter, you'll unavoidably end up with "another Autofac".

I went this way once and two months later I wished I hadn't... unless you need to save every byte of RAM, home-made DI surrogate simply doesn't pay off.


There is not enough information in your question to get a clear picture of where there may be a problem.

Your code

You code does not have any glaring performance issues. Some minor changes would be...

Use for loops rather than forEach. (Minor performance increase but when animating its always good to use the fastest style)
Don't use 3D transforms if you are only doing 2D animation. Better yet, if only 2d dont use the transform ate all. Set thestyle.positiontoabsoluteand use thetop,left` CSS style attributes to set position.
You only use jQuery to get the onload event. Its just bloat so don't load it if you don't need it.

Animating elements.

Some points related to animating elements.

Its not just the elements that you are animating that add to the total load of an animation. Other elements may require rendering (compositing) and they may also be triggering reflow/s. Composites and reflows are expensive operations

The order of the animated elements in relationship to other content can have a big impact on performance due to inefficient compositing. For example you may be animating items A and B, and on the page you have c, A, d, B, e (where c,d,e are other elements) . In the worst case the compositing of the content will be as follows... render c, composite c with background, render A, composite A with previous composite, render b, composite b with previous composite, and so on.

So you just change and move 2 items but that may trigger 5 renders and 5 composites, and depending on the layout, they may be the 5 full screen composites and renders each frame.

Are you using filters? Depending on the filters (and the GPU's abilities) they can add to the workload. Use filters sparingly, don't make more than one change to filters during a frame.

Can all the image and pixel related content fit into GPU RAM. If not reduce the number of pixels. Low end devices can have very low amounts of GPU RAM and if you exceed the capacity of the GPU the browser will swap it in and out of CPU RAM as needed. This is SLOW... very SLOW...

Take charge of the rendering.

It can be very difficult to locate animation bottle necks when animating elements.

One way to remove the rendering/compositing ambiguity is to use the canvas. You then get to efficiently control the rendering compositing process. The canvas 2D and WebGL API's use the same code (there abouts) as the browsers rendering and compositing systems.

With some minor changes your animation items can be rendered on a canvas, needing only one render pass and one composite (if you also render the background you can eliminate composite)

The snippet is an example of canvas rendering performance. There are 500 bugs
each rendered with a full transform scale, position, and rotated. This you would never be able to do using HTML elements.

requestAnimationFrame(update); // Start animation when ready

const image = new Image;
image.src = "https://i.stack.imgur.com/C7qq2.png?s=328&g=1";
const canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.style.position = "absolute";
canvas.style.top = "0px";
canvas.style.left = "0px";
document.body.appendChild(canvas);

const mouse  = {x : 0, y : 0}
document.addEventListener("mousemove", (e) => {
 mouse.x = e.pageX;
 mouse.y = e.pageY;
});

var w,h;
function resize(){
    w = canvas.width = innerWidth;
    h = canvas.height = innerHeight;
}
resize();
addEventListener("resize",resize);
const rand  = (min = 1, max = min + (min = 0)) => Math.random() * (max - min) + min;
const DO = (count,callback) => { while (count--) { callback(count) } }
const sprites = [];
DO(500,()=>{
    sprites.push({
       x : rand(w),
       y : rand(h),
       xr : 0,
       yr : 0, // actual position of sprite
       r : rand(Math.PI * 2),
       scale : rand(0.1,0.25),
       dx : rand(-2,2),
       dy : rand(-2,2),
       dr : rand(-0.1,0.1),
    });
});

// Draws a sprite.
function drawImage(image, spr){
    ctx.setTransform(spr.scale, 0, 0, spr.scale, spr.xr, spr.yr); // sets scales and origin
    ctx.rotate(spr.r);
    ctx.drawImage(image, -image.width / 2, -image.height / 2);
}

// Main animation loop
function update(time){
    var ihM,iwM,dx,dy,spr,i,iw,ih,dist;
    ctx.setTransform(1,0,0,1,0,0);
    ctx.clearRect(0,0,w,h);
    const runHalf = time / 3000;
    if(image.complete){
      iw = image.width;
      ih = image.height;
      const size = (iw * iw + ih * ih) / 2;
      for(i = 0; i < sprites.length; i ++){
          spr = sprites[i];
          dx = mouse.x - spr.xr;
          dy = mouse.y - spr.yr;
          dist = dx * dx + dy * dy;
          if(dist/ spr.scale < size){
              const dir = -Math.atan2(dy,dx) -0.2 + rand(0.4);
              const speed = rand(18);
              spr.dx += Math.cos(dir) * speed;
              spr.dy += Math.sin(dir) * speed;

          }else if(((i + runHalf) | 0) % 2){ // half run away
              spr.dx += dx * 0.001 + Math.cos(spr.r) * 0.1;
              spr.dy += dy * 0.001 + Math.sin(spr.r) * 0.1;
          }else{
              spr.dx += -dx * 0.001 + Math.cos(spr.r) * 0.1;
              spr.dy += -dy * 0.001 + Math.sin(spr.r) * 0.1;
          }

          spr.dx *= 0.99;
          spr.dy *= 0.99;
          // limit speed
          dist = spr.dx * spr.dx + spr.dy * spr.dy;
          if(dist > 54){
              spr.dx *= 0.9;
              spr.dy *= 0.9;
          }

          spr.x += spr.dx;
          spr.y += spr.dy;
          spr.r += spr.dr;
          iwM = iw * spr.scale * 2 + w;
          ihM = ih * spr.scale * 2 + h;
          spr.xr = ((spr.x % iwM) + iwM) % iwM - iw * spr.scale;
          spr.yr = ((spr.y % ihM) + ihM) % ihM - ih * spr.scale;
          drawImage(image,spr);
      }
    }
    requestAnimationFrame(update);
}


Is there a better way to condense the while loop?

Miscellaneous notes:

you don't need a break after a return
you could (attempt to) return directly from the input; "except" will still catch and cycle errors
inputNumber() explicitly returns an integer; no need to cast again.
temp_range isn't really needed - you can just use max_range, no loss to readability.
no need to add one to max_range (in the validation loop) - randint() includes the top limit.
random_number is an unhelpful variable name - I've called this target
using inputNumber() for the guess also seems sensible.
guess should be checked against the inclusive range - min and max are possible values.
personally I think the temperature categories should reflect the size of the range, rather than the size of the chosen number... however
your calculation is wrong anyway; you are testing the difference between guess and target so you should test against the small fraction of target, not target reduced by a fraction (or should just check guess against the numbers you calculate).
the "hot" range (outside "super hot") is actually smaller than the "super hot" range - I adjusted this out to 1/4 of target
after correction, there's a range that gets no message, which can be covered in an else clause. I reordered so all tests are for "in this range" and the else covers the "cold" option.

To condense the message selection, you could set up a list of boundaries changing from one condition to another, and step through (or search) to find the applicable message. However I'm not sure that's a lot clearer in this case.
With updates reflecting most of these:
import random
CHEATING = True

def inputNumber(message):
    while True:
        try:
            return int(input(message))
        except ValueError:
            print("Not an integer! Try again.")

#ranges must be integers
min_range = inputNumber("Please insert the min range: ")
max_range = inputNumber("Please insert the max range: ")

#max range must be bigger than min
while min_range >= max_range:
    max_range = inputNumber("Please insert a max range which is bigger than min range!: ")

target = random.randint(min_range, max_range)

guess = inputNumber("Please enter your guess: ")
counter = 1;  # you guessed once already
while guess != target:  # 1 guess incorrect
    if CHEATING: print(f"{target} is the random number")# to see for myself which is the random numb
    if min_range <= guess <= max_range:  # WITHIN THE RANGE
        if  -target / 12 < guess-target < target / 12:  # 3 super hot
            print("Please try again, you are super hot!")
        elif  -target / 4 < guess-target < target / 4:  # 3 hot
            print("Please try again, you are hot!")
        elif -target / 2 < guess-target < target / 2:   # a bit meh
            print("Not great, not terrible - please try again")
        else:                                           # 3 cold
            print("Please try again, you are cold!")

    else:  # OUTSIDE RANGE
        print("You are outside the range, try again!")
    guess = inputNumber("Next guess? ")
    counter += 1
if guess == target:  # guess correct
    print(f"Congratulations, you guessed correctly in {counter} tries!")```

PS: "please criticize the hell out my work" is an excellent attitude, if you have the fortitude for it, and a great way to learn.


Building array of 'truthy' rule conditions

First up, you should really be using more modern variable definitions (using let and const instead of var).

As for your conditional processing for the mongoDB clauses, the simpler way to process the data would be to accumulate all the clauses in to a single temporary array, and then filter that array in to the actual query clause. For example, consider:

const clauses = [
    mongoRequestsHelper.getFromConditions(rule.A),
    mongoRequestsHelper.getFromConditions(rule.B),
    mongoRequestsHelper.getFromConditions(rule.C),
    mongoRequestsHelper.getFromConditions(rule.D),
    ......
];

const ruleConditions = {
    // filter out non-truthy clauses
    $and: clauses.filter(clause => clause)
};


Split mp3 of album into individual tracks

I'll consider answering your last question (at least at the moment) about subprocess.run().

There's a similar method you can use for this kind of situations named subprocess.check_call(). The difference between the two is that call() already gives you the return code —
 not as an attribute, just as the return value of the function. The reason you might want to use check_call() is that it takes care of checking that return code for you, raising a CalledProcessError.

Anyway, either one will raise an OSError for the program not being found.

So, a first solution to your problem might look like this:

try:
    subprocess.check_call(track.setargs(infile, metadata))
except subprocess.CalledProcessError:
    pass  # handle errors in the called executable
except OSError:
    pass  # executable not found

Now, I don't necessary like this solution because sincerely I don't know about those specific exception cases, or check_call() / run() (which apparently they both block). What I learned from my previous projects is that .run() basically merges all the old functions — call(), check_call(), check_output() — into one friendlier function.

You should know that subprocess will raise an exception, OSError, when a command is not found. So, if you catch OSError you can handle the non-existent command, and if you check the result code you can find out whether the command succeeded or not.

As a personal advice, If you have no good way to handle it, let it raise. If you want to continue the execution even if this fails, log it somewhere:

try:
    subprocess.run(track.setargs(infile, metadata))
except OSError as e:
    logger.WARNING("Error: {}".format(e))

Depending on what track.setargs() raises, you can change the Error type.

It's worth mentioning that you might want to use except Exception which will cover any runtime exceptions. With except Exception you can remove the OSError except since Exception will cover those as well. This way of exception handling is kind of hand wavey (and it's best avoided) but will keep your program running.

Other aspects:

you're reading the entire file into memory before processing it.  If the file is very large, that will be slow; and if it's very large, it'll fail. Consider reading the file line by line.
I wouldn't bother writing a setEnd method. Calling it is no simpler than just saying tk.endtime = 3.
you can test if a string has '=' with:   if '=' in line:

PEP8

methods are usually snake_cased so if you'll keep your setEnd(self, endtime) it should be renamed to set_end(self, endtime)

Overall, nice job! You did pretty well! Keep going the good work.


Converting the comma seprated numeric string into int array

Basic improvements

Instead of setting the size of the int array to 10, it would be better to derive the right size from the size of String array
Instead of int number[] the more conventional way to write is int[] number
For structures that contain multiple values it's more natural to give plural names, for example "number" -> "numbers" for an array of numbers
The variable names are very poor in general, and should be improved to better reflect their purpose, making the code easier to understand

Something like this:

String line = "1,2,3,1,2,2,1,2,3,";
String[] parts = line.split(",");
int[] ints = new int[parts.length];
for (int i = 0; i < parts.length; i++) {
    ints[i] = Integer.parseInt(parts[i]);
}

Split to logical steps

It's good to get into the habit of decomposing tasks to their small steps. That is, instead of having all the logical steps in a single main method, it would be better to split to multiple functions, for example:

static int[] toIntArray(String[] arr) {
    int[] ints = new int[arr.length];
    for (int i = 0; i < arr.length; i++) {
        ints[i] = Integer.parseInt(arr[i]);
    }
    return ints;
}

static int[] parseLineToIntArray(String line) {
    return toIntArray(line.split(","));
}

public static void main(String[] args) {
    String line = "1,2,3,1,2,2,1,2,3,";
    System.out.println(Arrays.toString(parseLineToIntArray(line)));
}


Perform the UTF-8 conversion outside of score_text. With a name like _text, it should probably accept a &str anyway. Note that types are a kind of static assertion about the data; &str is a way of saying "UTF-8 encoded bytes". This also helps highlight that the UTF-8 check was being done twice.
Use expect instead of unwrap. When the code fails, you will be thankful.
The tracking of the maximum is annoying. Ideally, you'd be able to just say max_by_key on the iterator, but f32s don't implement Ord. There's the possibility of creating a wrapper type that ensures it is never NaN, but that feels like overkill here. You could use max_by, but that's not currently stable, and would still involve an unwrap. Instead, I'd note that all of the strings are the same length here, so dividing them by the length is unnecessary. Adjust the score function to return the previous numerator as a usize and then you can use max_by_key.
Making this change shows that you didn't just want "max", you were relying on finding the first one. Evidently, the max_by_key algorithm returns the last-most equal value. This causes your tests to fail and pick x instead of X as the key. You would have seen this problem previously if the key had been x. You should probably include spaces in the scoring function. "In English, the space is slightly more frequent than the top letter (e)".
Speaking of the scoring function, it appears to only have 25 characters? And the order doesn't make any sense to me. The highly-recognizable "etaoin" is missing. You may wish to double-check your work there.
I'd adjust your tests to assert on the properties of the scoring function that you care about. You don't care about a specific value, you care that:

a more-common letter has a higher score than a less-common one
ASCII case differences do not change the score
unknown letters don't crash

This makes me realize that unknown letters will have the same score as 'z', which seems incorrect.

use std::ascii::AsciiExt;
use std::str;

use utils::hex_to_bytes;
use s1c2::fixed_xor;

/// Scores ASCII test represented by byte array. The higher the score, the more common
/// English characters the text contains. Letter frequencies are taken from
/// https://en.wikipedia.org/wiki/Letter_frequency.
fn score_text(text: &str) -> usize {
    let frequencies = "zqxjkvbpygfwmucldrhsnioate ";
    text.chars().map(|letter| {
        frequencies.find(letter.to_ascii_lowercase()).map_or(0, |score| score + 1)
    }).sum()
}

/// Tries to decrypt text encrypted with a single character XOR
/// encryption.
pub fn decrypt_xor(ciphertext: &str) -> Option<(char, String)> {
    let cipherbytes = hex_to_bytes(ciphertext);

    // 32 to 127 should cover printable ASCII characters
    (32..128).map(|character| {
        let cipher = vec![character; cipherbytes.len()];
        let plaintext = fixed_xor(&cipherbytes, &cipher);
        (character as char, String::from_utf8(plaintext).expect("Wasn't UTF-8"))
    }).max_by_key(|a| score_text(&a.1))
}

#[test]
fn test_score_text() {
    assert!(score_text("e") > score_text("x"));
    assert_eq!(score_text("e"), score_text("E"));
    assert!(score_text("$") < score_text("a"));
}

#[test]
fn test_decrypt_xor() {
    assert_eq!(decrypt_xor("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"),
               Some(('X', "Cooking MC's like a pound of bacon".to_string())));
}

The scoring idea is interesting, but I'm not in love with it. Something with two X shouldn't count the same as one Z. You could probably make better use of the relative frequencies.


The register keyword will do nothing. Current day compilers are smart enough to find a good register allocation themselves without you running in its way.

Why calloc? you initialize the values through memcpy anyway so no need for the zero initialization, malloc will work fine. Speaking of you need to free what you allocate otherwise you'll get a memory leak.

You should only need to allocate a single extra array for the merge.

When the amount left to sort is small (amount < 5) you can switch over to another sort that is more efficient for small numbers like insertion sort.

Finally brace position on your else is a bit odd:

    if(*pos1 <= *pos2) {

    }
    else {

    }

I'd expect either the opening braces to also be on its own line or else to be on the same as the closing brace of the if.


Will anything behave unexpectedly with this code?

For that to answer we would need the expectations. Most users will expect a number type to behave like the ints do.

What does that mean in your example?

your type should be usable in an if(number) (this also includes if(!number))
your type should be comparable with other int types, nobody wants to write number == board_t{0, 3} instead of number == 3  (this probably means you should write an implicit conversion from int to board_t

Surely there are other things you need to mimic from the ints.

Do I need to create a constructor? Is the usage of the {} struct initializer good form?

Given the fact that you should provide something like board_t(int) you will need to provide the other constructors as well.

Internal functions (that know about the internal format of board_t might use the "struct initialize" but in general I would avoid it as it introduces dependencies on the inner layout.

Do I need to override the assignment operator?

No, the default generated one will simply call the assignments on the members as well which is fine.

Are there other ways to improve this code, style, correctness and speed?

Yes:

why is the type called board_t?
if the user should be able to supply values you could generate an own literal for this purpose
define binary operators like operator+ outside the class to get "more symmetric" code (this makes both operands eligible for automatic conversions instead of only the right hand side)
the previous point may also be applied for unary operators that don't change the internal representation of the object (like operator~())

All in all your design should be:

If the platform supports uint128 the type should only be an alias of it and if it does not support this type, then your class should behave as much as uint128 as possible (so on platforms that support it your code should do the same for both "implementations").


I am not convinced that your code works correctly. For example if I run it with the {5,3,15,1,1,3,1} input it will result in 6 what is definietly wrong. (Nothing can have a common divisor with 1 greater than 1).

My other concern is that you only move the chip forward, although it might be necesarry to move it backwards. For example:

{5, 3, 15, 9, 1, 3, 1}

You can get to the 3 on index 5, but only if you step back from the 15 to the 3. Here is the route:

0 -> 2 -> 1 -> 3 -> 5

Your approach is to simulate the optimal route of the chip and the return the result. A cleaner approach would be to calculate all visitable positions and then return the rightmost.

This problem can be naturally interpreted as a graph traversal. The nodes are the cells, and an edge is defined between two nodes if the difference of their indices are at most 2, and they have a common divisor greater then 1.

For this you need a function that finds the greates common divisor. For example:

int gcd(long a, long b) {

    if (b==0)
        return a;
    else
        return gcd(b, a % b);
}

One that tells you if an edge exists between two nodes:

boolean edge(int[] a, int i, int j){
    return gcd(a[i], a[j]) > 1;
}

You need to mark all visited cell using a breath first traversal:

private static boolean[] getVisited(int[] a) {
    boolean[] visited = new boolean[a.length];

    Queue<Integer> toVisit = new LinkedList<Integer>();
    toVisit.add(0);

    while (!toVisit.isEmpty()) {
        int i = toVisit.remove();
        if (visited[i])
            continue;
        visited[i] = true;
        if (i - 2 >= 0 && !visited[i - 2] && edge(a, i, i - 2))
            toVisit.add(i - 2);
        if (i - 1 >= 0 && !visited[i - 1] && edge(a, i, i - 1))
            toVisit.add(i - 1);
        if (i + 2 < a.length && !visited[i + 2] && edge(a, i, i + 2))
            toVisit.add(i + 2);
        if (i + 1 < a.length && !visited[i + 1] && edge(a, i, i + 1))
            toVisit.add(i + 1);
    }
    return visited;
}

And then find the rightmost visited cell:

int chipMoving(int[] a) {
    boolean[] visited = getVisited(a);

    for (int i = visited.length - 1; i >= 0; --i)
        if (visited[i])
            return i;

    return 0;
}

The runtime characteristics of finding the visited cells is \$O(N)\$, searching for the rightmost visited is also \$O(N)\$. That makes together \$O(N)\$.


High execution time to count overlapping substrings

overlapping_occurrences has \$O(MN)\$ complexity where \$M\$ and \$N\$ are the sizes of the string and the substring respectively. You can reduce it to \$O(M+N)\$ using KMP algorithm. However, looking at the constraints, I feel that even that might not be sufficient - the highest score for the problem is only 50.


The function you want is replace:

function link_ats(text) {
    return text.replace( /@(\w+)/g, '@$1' )
}

document.getElementById("bio").innerHTML = link_ats("The coolest company to work for is @github!  There is also @aws and @microsoft.", "bio");


First I suggest you to split your logic into several function, it will help you to see what is essential and what you could optimize / remove.

import random
print("Rock, Paper, Scissors")

AVAILABLE_CHOICES = ['rock', 'paper', 'scissors']

def rps():
  try:
    userInput = getUserInput()
    computerChoice = getComputerChoise()
    result = getResult()
    tryAgainMaybe()
  except Exception as err:
    print(err)

  def getUserInput() :
    userInput = input("Please enter your choice: ")
    userInput = userInput.lower()
    if userInput not in AVAILABLE_CHOICES:
        raise Exception('Your choice is invalid')
    return userInput;

  def getComputerChoice():
    return random.choice(AVAILABLE_CHOICES);

  def getResult():
    result = ''

    if userInput == computerChoice:
      result = "DRAW!"
    elif userInput == 'rock'     and computerChoice == 'scissors' or \
         userInput == 'paper'    and computerChoice == 'rock' or \
         userInput == 'scissors' and computerChoice == 'paper':
        result = 'USER WINS!'
    else:
        result = "COMPUTER WINS!"
    return result

  def tryAgainMaybe():
    print("Would you like to try again?")
    try_again = input("Y/N  ")
    try_again = try_again.lower()
    if try_again == "y":
        print("\n")
        rps()
    else:
        print("\n")
        print("Thank you for using my Rock, Paper, Scissors Program")

Create a list of available choices instead of writing them everywhere. it will be easier to modify and to test for your input values.
random allow you to select ramdomly a value in a list.
you don't need to calculate every single possibility. You can either have a draw, a win or a loose. if you don't win or draw, you loose, no computation needed here.
when you name something, try to use the same name for the same thing everything, otherwise it could be missleading. eg (userInput / computerChoice) why do we have input and choice two different words for the same kind of value ? i would choose userChoice and computerChoice instead.
Your coding convention does not respect pep8 standard. You should be using snake_case.


Extract code that makes class shared_ptr construct-able only

If I follow you correctly, you're looking for a clean way to have a private constructor that can only be invoked by std::make_shared or std::allocate_shared. Unfortunately this does not appear to be portable or easy, and I don't see a way to avoid your request to avoid friendship. However you can make the friend something that other people cannot easily co-opt. I'd call this mildly better, but it definitely has some downsides.

As this is not portable, the scenario I'm showing here is specific to the compiler I had handy: Visual Studio 2012. First I created a class like this:

class SomeClass
{
public:
    int GetValue() const { return m_val; }
    // optionally provide Ptr like yours?
    // static std::shared_ptr<SomeClass> Ptr(int val) { return std::make_shared<SomeClass>(val); }

private:
    SomeClass(int val) { m_val = val; }
    SomeClass(const SomeClass&); // = delete;
    SomeClass(SomeClass&&); // = delete;
    ~SomeClass() {}

    int m_val;
};

This is enough to prevent usage like SomeClass thing(5); Then I wanted to try to befriend std::make_shared. When I tried to compile code using this definition and std::make_shared<SomeClass>(5), I got an error pointing to what needed access:

  error C2248 [...] cannot access private member [SomeClass::~SomeClass ...]
  while compiling class template member function 'void std::_Ref_count_obj<_Ty>::_Destroy(void)'

After befriending class std::_Ref_count_obj<SomeClass> (I first tried befriending the specific method, but that created worse problems), I also decided to fix the warning by befriending std::_Get_align<SomeClass>:

  warning C4624: 'std::_Get_align<_Ty [= SomeClass]>' : destructor could not be generated because a base class destructor is inaccessible

This left me with the following additions to this class that allows std::make_shared<SomeClass>(5) but not SomeClass obj(5).

class SomeClass
{
    : : :
    // Allow use in VS2012 implementation of std::make_shared
    friend class std::_Ref_count_obj<SomeClass>;
    friend struct std::_Get_align<SomeClass>;
    : : :
};

I'll leave other compilers up to you as you need them. It may be worth collecting a series of macro alternatives that you can put in any class that needs this capability.


Getting the previous sibling of a node using Roslyn

You could iterate over the ChildNodes only once with the Zip extension where the first collection starts at the first element and the other one at the second element with Skip(1). This will produce tuples with pairs such as Previous & Current. Now you can filter it and pick at the same time the Last element that satisfies the condition:

var childNodes = new[] { "a", "a", "b", "c", "a" };

var previousSibling =
    childNodes
        .Zip(childNodes.Skip(1), (p, c) => (Previous: p, Current: c))
        .Last(t => t.Current == "c").Previous; // b


Extract numbers from the head of a string in BASH script

bash is slow to append and index into strings: both operations are \$O(n)\$.  Your approach does as many indexes and appends as there are digits in the input, making it \$O(n^2)\$.  And processing a string by chomping the first character repeatedly will be \$O(n^2)\$ in almost every language.

Have a look at these timings for large inputs, using your code:

$ for x in 10000 20000 40000 80000; do echo $x; time bash dig.sh $( tr -dc 0-9 < /dev/urandom | head -c $x ) >/dev/null ; done

input size (1000's of digits)  runtime (seconds)
         10                      1.1
         20                      4.4
         40                     17.7
         80                     71.6

Almost perfectly quadratic!  It's possible to do better, and in fewer lines.

Your code is implementing a state machine, just like a regular expression would, but much less efficiently.  So the regex isn't needless overhead; it's very necessary  (and profitable) "underhead":

dig() {
    [[ $1 =~ ^([0-9,]*)(.*) ]] # this always matches
    digits="${BASH_REMATCH[1]//,}"
    remain="${BASH_REMATCH[2]}"
    printf "input\t'%s'\tdigits\t'%s'\tremain\t'%s'\n" "$1" "$digits" "$remain"
}

+ dig ''
input   ''      digits  ''      remain  ''
+ dig 1234
input   '1234'  digits  '1234'  remain  ''
+ dig 1,234
input   '1,234' digits  '1234'  remain  ''
+ dig abc12
input   'abc12' digits  ''      remain  'abc12'
+ dig 12z34
input   '12z34' digits  '12'    remain  'z34'

$ for x in 10000 20000 40000 80000; do echo $x; time dig $( tr -dc 0-9 < /dev/urandom | head -c $x ) >/dev/null ; done

input size (1000's of digits)  runtime (seconds)
         10                      0.006
         20                      0.010
         40                      0.018
         80                      0.032

Behold: a two-thousand-fold speedup of the slowest case!


Propagate a default parameter of a function among several files

I would create a shared.py module somewhere (I'll let you handle the import directory tree). It would just contain

args = None

Import it in all your modules and assign args from argparser directly to it.
Now shared.args contains all the information (even device that you did not ask for :))

Of course this is not reentrant because of the shared global structure, but if you need reentrancy, you just have to pass 1 parameter: a fake args structure like argparse created (see the FakeArgs in syncfile.py)

And when you're ready to create one single python singleton object to avoid too much parameter passing, just yell :)

in auto code

#!/usr/bin/env python

import argparse
import shared
import project.sync.sync_file as logic_sync

def sync(args):
    shared.args = args
    logic_sync.main()

parser = argparse.ArgumentParser(description='Info on my project')
subparsers = parser.add_subparsers()

sync_parser = subparsers.add_parser('sync', help='synchronize')
sync_parser.add_argument('--device', default='nas', help='specify the device name')
sync_parser.add_argument('--verbose', action='store_true', help='increase the output verbose')
sync_parser.set_defaults(func=sync)  # set the default function to sync

if __name__ == '__main__':
    args = parser.parse_args()
    args.func(args)

sync_file.py code:

from .. import helper
import shared

def main():
    helper.play()

if __name__ == '__main__':
    #Test here the logic

    # we don't have argparse module creating the structure
    # for us ? what the heck? create a fake one

    class FakeArgs:
        def __init__(self):
           self.verbose = False
           self.device = 'omv'

    shared.args = FakeArgs()
    main()
    shared.args.verbose = True
    main()

helper.py code:

import shared
def play():
    if shared.args.verbose:
        print shared.args.device + " with verbose on"
    else:
        print shared.args.device + " verbose off"


Changing the background color when a link is clicked

The opening and closing tags don't match in your JSFiddle.

It's not a good idea to use presentational like highlighted for a CSS class name.  It would be better to use current or selected, and let the stylesheet decide how to indicate which item is currently selected — whether by highlighting, underlining, or whatever visual hint it chooses.

It would be a lot simpler if you removed the highlighted class from all items, then added it back for just the selected item.

$(document).ready(function() {
    $(".nav > li").click(function() {
        $(".nav > li").removeClass('current');
        $(this).addClass('current');
    });
});
* {
 margin: 0px;
 padding: 0px;
}

nav {
 background-color: #e4801c;
 height: 100%;
}
.nav > li {
 text-align: center;
 text-transform: uppercase;
}

.current {
 background: #faaf5e;
}

Clients

Services

Add

Time

In addition, I suggest using text-transform: uppercase to make the text all caps, as that is also a presentation style choice.


Is this a good approach for a BayeuxClient class?

I have no idea how to type the last character on my keyboard which makes modification harder:

public boolean GetIfHandIsShaken£()

It's better to use only ASCII letters.
See Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions and The Java Language Specification, Java SE 7 Edition, 6.1 Declarations:

  Class and Interface Type Names

  Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed
  case with the first letter of each word capitalized.

  [...]

  Names of fields that are not final should be in mixed
  case with a lowercase first letter and the first letters of
  subsequent words capitalized.

CometD_Client could have a more descriptive classname too. Every CometD client could have been called CometdClient. Why is it special? Try to put that into the name.

TransportOptions = new HashMap<String, Object>();

This could be in the same line as the declaration:

private Map<String, Object> transportOptions = new HashMap<String, Object>();

HttpClient has a stop() method. I suppose you should call it somewhere.


Binary search optimization: Kernighan & Ritchie 3-1

You're not really changing the number of comparisons inside the loop here: all you've done is move it from the loop body to the loop termination condition. Note that in many situations, comparisons on the array elements (which could be strings or more complex objects) are a lot costlier than comparisons on the indices.

You can find several solutions to this exercise on the clc-wiki. I think one of them (Paul Griffith's) misses the point (it's pretty much the same as yours); I'm going to show  explain the reasoning behind Andrew Tesker and Colin Barker's solutions.

In the original function binsearch, inside the loop, there are three possible situations: x<v[mid], x==v[mid] and x>v[mid]. Sometimes, a comparison function has three outcomes: less than, equal or greater than; in such cases, the approach in the original function is best. For example, if we were comparing strings with strcmp:

    int cmp = strcmp(x, v[mid]);
    if (cmp < 0) high = mid - 1;
    else if (cmp > 0) low = mid + 1;
    else return mid;

In other cases, the only primitive you have is a less-than or less-or-equal-to, and to test for equality requires a second comparison. Thus the method presented in K&R requires two calls to the comparison function per iteration through the loop. It is more efficient to require a single comparison. Now we absolutely need to distinguish between the less-than and the greater-than case, so this means we're not going to be able to deal with the equality case inside the loop. So we'll keep going either up or down in the equality case. Since we haven't vetted the value v[mid] in one of the cases, we need to keep it inside the search space.

    if (x < v[mid]) high = mid - 1;
    else low = mid;

What happens to the loop termination? Now, we can get stuck with low == high and x >= v[low]. However, this is easily resolved by ending the loop when low == high.

while (low < high) {
    mid = (low + high + 1) / 2;
    if (x < v[mid]) high = mid - 1;
    else low = mid;
}

Note that I set mid to low + high + 1. In the case where low + 1 == high, (low + high) / 2 is low, and if x is still too small we'd set mid to low and loop forever (thanks to Elyasin for noticing that my original answer had this bug). Instead in this case we arrange for mid to be set to high. If low <= high we exit the loop anyway, and in other cases we'll continue looping and this change only causes the middle to be rounded up instead of down.

At the exit of the loop, if there is a matching element in the array, then v[low] is equal to it. So we perform a final equality test:

return x == v[low] ? low : -1;

The number of element comparisons performed by the original version is anywhere from 1 to 2*ceil(log₂(n)+1) where n is the number of elements in the array. The number of element comparisons in the version with a single comparison within the loop is always ceil(log₂(n))+2. That's a smaller maximum, but not necessarily a gain, because the original version will terminate earlier if it finds the element. The original version is preferable when there is a good chance that the element will be in the array. The modified version is preferable when the element is rarely present.


Switching some text labels when the first image of a carousel is active

You could do this:

$(function () {
    var $carousel = $('#carousel');
    var $switch = $('#switch');
    var $headerSubmit = $('#header, #submit');
    var $submit = $('#submit');
    var text_strings = [ 'Sign In', 'Sign Up' ];
    var form_strings = [ 'sign_in', 'sign_up' ];

    $carousel.bind('slid', function() {
        var index = $('#carousel .item').index($('#carousel .carousel-inner .active'));
        var sign_in = (index == 0);
        $headerSubmit.text(text_strings[sign_in ? 1 : 0]);
        $switch.text(text_strings[sign_in ? 0 : 1]);
        $submit.attr('form', form_strings[sign_in ? 1 : 0]);
    });
});

If you want to reduce the lines of code (with a slight negative impact to performance if this function gets called a lot), you could do this:

$(function () {
    var text_strings = [ 'Sign In', 'Sign Up' ];
    var form_strings = [ 'sign_in', 'sign_up' ];

    $('#carousel').bind('slid', function() {
        var index = $('#carousel .item').index($('#carousel .carousel-inner .active'));
        var sign_in = (index == 0);
        $('#header, #submit').text(text_strings[sign_in ? 1 : 0]);
        $('#switch').text(text_strings[sign_in ? 0 : 1]);
        $('#submit').attr('form', form_strings[sign_in ? 1 : 0]);
    });
});


Python Script: Converts .tsv to TFRecord

I am no expert in TensorFlow (even though started to grasp), but here are some things I noticed:

if this is a proper valid TSV file, you should not be worried about checking the length of each row - each row should have the same amount of columns
you may also try to use TextLineReader to read features from a csv file like noted here, this may lead to "unpacking" the features and avoiding getting them by index:

rate, sent1, sent2 = tf.decode_csv(value)

if, for some reason, TextLineReader is not applicable, you may unpack in the for loop:

for rate, sent1, sent2 in read_tsv:

you can also look into applying some micro-optimizations, like avoiding name lookups in the loop by pre-lookuping things before the loop - e.g. setting Example = tf.train.Example and then using Example in place of tf.train.Example
there is also a possibility of that classic trading off memory for the speed. Depending on how unique your features are, you, for instance, can "cache" the word tokenization results in a dictionary to avoid re-tokenizing the same sentences over again

Also check out the TensorFlow Performance Guide and Performance Tips.

There are also some minor PEP8 code style violations, like extra spaces around = in the keyword argument definitions - run your code through a static code analyzer like flake8 or pylint.


Moving all .xlsx files from the last five days (but not today)

First, if you are using Python 3, you can use pathlib to make your life regarding paths a lot easier (especially if you want your scripts to work on both Windows and Linux). If you are not using Python 3 by now, well, you should.

While your approach works (and could be made a bit shorter maybe using a complex RegEx), you might want to look into different methods of doing this. Instead of manually using the format of your file names, you can use the time the file was last modified (or accessed) and just filter on that:

from datetime import datetime, timedelta
from pathlib import Path
import shutil
from typing import Iterable

def old_files(dir: Path, pattern: str, start: int = -5, end: int = -1) -> Iterable[Path]:
    """List all files in `dir` matching `pattern` modified between
    `start` and `end` (both inclusive) days from today.
    """
    today = datetime.today()
    start = (today.replace(hour=0, minute=0, second=0, microsecond=0)
             + timedelta(days=start)).timestamp()
    end = (today.replace(hour=23, minute=59, second=59, microsecond=999999)
           + timedelta(days=end)).timestamp()
    return (file for file in dir.glob(pattern)
            if file.is_file() and start <= file.stat().st_mtime <= end)

Which you can use like this:

if __name__ == "__main__":
    dir = Path(r"C:\Users\GuilhermeMachado\Documents\Carteiras")
    new_dir = dir / "Historico/"
    new_dir.mkdir(exist_ok=True)
    for file in old_files(dir, "*.xlsx", start=-5, end=-1)
        shutil.move(str(file), new_dir)

Note that I used the fact that when you divide a path by a string (`dir / "Historico") it just joins the path (with the correct path separator depending on your OS).

I also added a if __name__ == "__main__": guard to allow importing from this script without the code running, made the number of days to select parameters of a function to which I also added typing hints and a docstring and followed Python's official style-guide, PEP8, by having spaces around the = for assignments.

Of course this assumes that you have no other Excel spreadsheets modified during the last five days in that folder. In that case you might be able to adapt the pattern to only match the files you want, or you will have to use a different method for filtering the files. But that would just mean modifying the function, not your whole script. This way the changes are localized, which makes it easier to track.


Counting which numbers fall in a certain bracket

Notes:

Creating so many variables is a warning sign that they should be grouped  somehow (an object, a dictionary, ...). I'd use a dictionary here.
Consider learning some functional programming (as opposed to imperative programming) to apply it when it improves the code (IMO: most of the time). Here it means basically using collections.counter and generator expressions.
Don't read whole files, read them line by line: for line in file_descriptor.
There are programmatic ways of detecting intervals of numbers (simple loop, binary search). However, since you have here only 5 intervals it's probably fine just to write a conditional as you did. If you had, let's say 20 intervals, a conditional branch would be a very sad thing to see.
Conditional branches are more clear when you use non-overlapping conditions with if/elif/else (effectively working as expressions instead of statements).

I'd write:

from collections import Counter

def get_interval(x):
    if x > 70:
        return "greater70"
    elif 60 <= x < 70:
        return "sixtys"
    elif x >= 50:
        return "fiftys"
    elif x >= 40:
        return "fortys"
    elif x == -1:
        return "nomarks"

with open("inputfile.txt") as file:
    counter = Counter(get_interval(int(n)) for line in file for n in line.split(","))
# Counter({'sixtys': 10, 'greater70': 10, None: 7, ..., 'fortys': 4})


3D plot from lm model with a nonlinear parameter

If I understand correctly, shouldn't ls$coefficients[4] * x2 be ls$coefficients[4] * x2 * x2?

These details could be easily avoided if instead of writing your function to evaluate the fit with new data, you used predict.lm. This is what I think the code should look like, making other small improvements I will comment about below:

disp.density <- 100L
qsec.density <- 100L
disp.range <- with(mtcars, seq(from       = min(disp),
                               to         = max(disp),
                               length.out = disp.density))
qsec.range <- with(mtcars, seq(from       = min(qsec),
                               to         = max(qsec),
                               length.out = qsec.density))
data.grid <- expand.grid(disp = disp.range,
                         qsec = qsec.range)

fit <- lm(mpg ~ disp + qsec, data = mtcars)
predicted.vec <- predict(ls, data.grid)
predicted.mat <- matrix(predicted.vec, nrow = disp.density,
                                       ncol = qsec.density,
                                   dimnames = list(disp.range,
                                                   qsec.range))
library(???)
persp3D(z = predicted.mat, ticktype = "detailed")

And the same code should still work if you replace the formula mpg ~ disp + qsec with mpg ~ disp + poly(qsec, degree = 2). Some more notes:

It is recommended you avoid variable names like ls and t since they are very basic functions from R. Or you run the risk of shadowing them.
disp and qsec are not integers so using min(mtcars$disp):max(mtcars$disp) is a bit unpredictable. I feel it is better to use seq like I did, and with control over the grid density.
I was not able to test my code because you did not mention the package name for persp3D so it is possible it will need some adjustment. In the future, please make sure to give us everything we need to run your code.


Note that, if you just remove the tag Response from all your types (including unifying the types CoordinateResponse and Coordinate which seem like they ought to be a single type), it's already a lot more readable:

toCoordinate :: Geo -> Coordinate
toCoordinate (Geo (Result [Location coord]:_)) = coord
toCoordinate _ = Coordinate 0 0

Also, the Location newtype doesn't seem to be serving any purpose, so maybe Location and Coordinate should just be the same type, too, which would remove a level.

Otherwise, what you've written is pretty idiomatic.  It's possible to use coerce to "cut through" all of the newtypes, so you could write:

import Data.Coerce

toCoordinate' :: GeoResponse -> Coordinate
toCoordinate' gr = case coerce gr of
  [CoordinateResponse lat lng]:_ -> Coordinate lat lng
  _                              -> Coordinate 0 0

or if CoordinateResponse and Coordinate were the same type:

toCoordinate' :: Geo -> Coordinate
toCoordinate' gr = case coerce gr of
  [coord]:_ -> coord
  _         -> Coordinate 0 0

That's obviously shorter, though it may hide what you're doing.  It seems important that you are pattern matching against the first of (possibly many) ResultResponse values but requiring that response to consist of a single LocationResponse, and that's not so obvious from this version.


Classes to manage perks to be added and removed

It is hard to understand what this code does without context.

Strange code

I am looking at this enum and I am asking myself - why?
Is there any way to divide this enum into maybe 3 different enums? That's really strange that you use the same numbers for different elements.

enum class PERK_SLOTS
{
    COMMON_SLOT_COLUMNS = 1,
    COMMON_SCOPE_PERK_COUNT = 2,
    SCOPE_SLOT_INDEX =0,
    STATS_UPGRADE_A_SLOT_INDEX = 1,
    UNIQUE_PERK_A_SLOT_INDEX = 2,
    STATS_UPGRADE_B_SLOT_INDEX = 3,
    UNIQUE_PERK_B_SLOT_INDEX = 4,
    STATS_UPGRADE_C_SLOT_INDEX = 5,
    UNIQUE_PERK_C_SLOT_INDEX = 6
};

C++ is not C

Next, you have:

CommonPerks::CommonPerks(void)

Remove void, it is totally unneccesary. It should be simply

CommonPerks::CommonPerks()

Conventions

Your methods starts with capital letters, that mostly not popular among C++ developers.

virtual void AddPerk(IPerk* perk, int column, int row) = 0;

I suspect that IComponent has a virtual destructor. You do not need to do this.

virtual ~IPerks(void);

Bad naming

Your parameters are badly named, give some more meaningful names.

void CommonPerks::RemovePerk(unsigned int index_1, unsigned int index_2)

Pragma

Pragma is compiler dependent. I would suggest to use headers guards.


How do I optimize this Java cube root function for BigInteger?

Your current code is totally unreadable and very hard to understand.
For vs. While
You've literally packed everything inside a for-loop without a body. WHY!?
This would be a lot more readable using a while-loop.
BigDecimal s = BigDecimal.ZERO;
while (!result.equals(s.toBigInteger())) {
    s = new BigDecimal(result);

    // Convert to BigDecimal, do the tricky division,
    // and convert back.
    BigDecimal temp0 = new BigDecimal(result.shiftLeft(1));
    BigDecimal temp1 = temp0.add(valueCopy.divide(s.multiply(s), UP));
    BigDecimal temp2 = temp1.divide(THREE_D, UP);
    result = temp2.toBigInteger();
    iterations++;
}

The temp0, temp1, and temp2 stuff can be written on one line, but I thought it deserved to be broken up among a few lines to be more readable.

Comments
Some unnecessary comments:
// other statements
// BigDecimal copy
// return the value

Please don't add comments about what you're doing, add comments for explaining why you are doing it. The code often tells us what you're doing.
Explaining what you're doing is OK for totally non-understandable parts though, these comments are helpful:
// Convert to BigDecimal,
// do the tricky division,
// and convert back.

Variable names
BigDecimal s;
BigInteger r;
BigDecimal m;

Please don't use one-letter variable names!
Explain what you're variable name is used for r seems to be for result, which is a much better variable name than r. I don't understand what s and m are used for exactly so I can't come up with a better name for those. Admittedly, my tempX names used above are also bad names, I hope you can come up with better ones.

Another approach:
Your code is already faster than anything I would be able to write by hand. I don't know if you're aware of it already or not, but there is however an in-built Java method you can use for this job - If you're willing to drop some precision for huge numbers.
I tried to compute the cubic root of 4.781260832191688e49
One in-built method call returns 3.6295056667577016E16.
Your code returns 36295056667577090
So there's a difference of 74, for a number of the order 4*10^49 I think that's pretty good.
The correct result with a lot of precision is:
3.6295056667577090244467986066615526182629927485862843007... × 10^16

So what's the secret method call then you ask?
Math.pow(4.781260832191688e49, 1.0 / 3.0);


SQL Statement with a Select Statement Inside a Where Clause

Here is what I ended up with:

Select Distinct rParent.REQ_ID
From REQUESTS rParent
Inner Join REQUESTS rChild On rChild.P_REQ_ID = rParent.REQ_ID
Where rParent.P_REQ_ID IS NULL


Finding the type of number entered by the user

Your code has several areas where it can be improved.
The first is that you should separate the parsing code from the platform code (Toast). Kotlin has a great testing framework, in which it is easy to write "parsing "1 2/3" should return listOf(1, 2, 3)". This testing code works best if you run it directly on your developing machine, and without any Toast or Activity.
The next thing is that you should not use List<Int> in places where you originally wanted to say Fraction or maybe, to be more specific, MixedFraction. The point is that listOf(1, 2, 3, 4, 5) is a valid list but not a valid fraction. By using a specifically constrained type you force the Kotlin compiler to check your code for you.
class Fraction(
    val int: Int,
    val num: Int,
    val den: Int
)

To make your parser extensible to expressions that are more complicated, you must not use contains. Instead, the best-practice way is to split the input into tokens first (often using regular expressions) and then to combine these tokens to expression trees (using a parser that only looks at the very next token to decide what to do next). The details of all of this are covered in any good book on compiler construction.
In your case, the tokens would be:

unsigned integer
fraction slash
unary minus sign

Note that there is no "space" token, as that is usually left out when defining an expression language.


Program to shutdown computer after a certain time

Your questions at the end are the most important points here, so I answer those first:

  but will any of these operations harm my computer in any way?

No, and how could it anyway?

  Will it be better if I just learn to do this via powershell?

Yes! Writing a Java program for this is overkill!

In terms of a Java implementation, I think you're really overcomplicating it:

Why use a thread to do this? As you're not going to do anything else in parallel, it's pointless.
Why use a timer? Essentially the same argument applies here too as with threads: you're not doing anything else in parallel, so what's the point? And putting a timer inside a thread seems doubly pointless.

Maybe you assumed that by running this in a thread, the application will just schedule the task and exit. That is not the case. The JVM will continue running until the task is completed, and the program will stay in the foreground. You would have to background the process in the calling shell.

As such, you could replace this with a much simpler implementation:

public static void main(String[] args) throws InterruptedException, IOException {
    if (args.length < 2) {
        System.out.println("usage: java PCShutdown HOURS MINUTES");
    }
    int hours = Integer.parseInt(args[0]);
    int minutes = Integer.parseInt(args[1]);
    Thread.sleep(hours * 60 * 60 * 1000 + minutes * 60 * 1000);
    Runtime.getRuntime().exec("shutdown -s -t 30");
}

But then, I'd return to my earlier statement: Java is overkill for this, use the shell and native scheduling features instead (for example at in UNIX).


It looks like you are trying to write object oriented code, however this is completely procedural. Remove static everywhere and use dependency injection if you want to make this OO.

Static code is hard to test. It is the equivalent of a namespaced function.

Even your new objects that you create are the equivalent of calling a function.

        case 'ControlBookmark_add':
            new ControlBookmark('add');
            break;

I'd recommend one of the following:

Spend a long while learning how to write real object oriented code.
Give up and convert to procedural code. Skipping all of the wasted classes and new's

Some people may disagree that I would suggest moving away from object oriented code, but your code is so far away from object oriented that it makes sense to me.

Response to the Edit

It does look a bit better now.  It would be a good experience for you to unit test this with PHPUnit.  I think you would find it very hard with the static and new.  That would give you a motivation to change it further.  However, I'm guessing the testing this code will receive will be based on seeing the page on the browser, which is okay for a lot of people.

One comment on the edited version:

// Do you really need the 'remove' parameter to your constructor?
// Especially when you call the add method on it?
// Also, objects aren't that special I wouldn't bother with _instance.
$control_bookmark = new ControlBookmark();


Here's another take on the powerset algorithm:

function powerset(l) {
    // TODO: ensure l is actually array-like, and return null if not
    return (function ps(list) {
        if (list.length === 0) {
            return [[]];
        }
        var head = list.pop();
        var tailPS = ps(list);
        return tailPS.concat(tailPS.map(function(e) { return [head].concat(e); }));
    })(l.slice());
}

// Test cases:
console.log(powerset([1,2,3,4]));
console.log(powerset([10,30,20]));

It works by using the following inductive observation:

$$\mathcal{P}(X \cup \{e\})=\mathcal{P}(X)\cup\left\{\{e\} \cup Y~|~Y \in \mathcal{P}(X)\right\}$$

Basically, the powerset of any set X plus another element is the powerset of X along with another copy of the powerset where every set contains the element. Concisely, every element is either in a subset or not. This recurrence captures that "obvious" statement.

To specifically critique your code: given the method above, there's no reason to do a quadratic (well, exponential in the input) scan for duplicates, so this will be much more efficient. No need for JSON conversions, which take time, too. Since JavaScript is dynamically typed, you would need to put some handling code for invalid types passed into the function. These can be done before the anonymous-function-call-return gadget (which preserves the input); see the TODO in my code above.

The lack of sorting, JSON conversion, and de-duplication allows this code to create a powerset of 20 elements quickly, whereas the implementation in your question crashes Chrome.


HackerRank Algorithm Challenge 1: Insertion sort

Two components in particular are unnecessary. This test:

        } else if (ar[j] <= i){

is redundant. else means if (ar[j] <= i), since the latter is the negation of the earlier if (ar[j] > i).

And then, the inserted variable is used to track whether i was inserted within the loop. To simplify, I'd only do it outside the loop -- we can do this because j is still useful. (If you're not using j outside the loop, as in your original code, it's better -- safer, more readable -- style to declare it in the for statement.)

This is the heart of what you're doing:

static void insertionSort(int[] ar) {
    int i, j;
    i = ar[ar.length-1];

    for (j = ar.length-2; j > -1; j--){
        if (ar[j] > i){
            ar[j+1] = ar[j];
            printArray(ar);
        } else {
            break;
        }
    }
    ar[j+1] = i;
    printArray(ar);
}

Or:

static void insertionSort(int[] ar) {
    int i = ar[ar.length-1];
    int j;
    for (j = ar.length-2; (j >= 0) && (ar[j] > i); j--) {
        ar[j+1] = ar[j];
        printArray(ar);
    }
    ar[j+1] = i;
    printArray(ar);
}

There are some style quibbles, but that's the big stuff.  I'd take the printing out of it, except that the purpose of this function doesn't seem to be "perform an insertion sort", but rather "show how an insertion sort inserts an element".  I don't see any advantage to using a binary search, since that only helps you find the insertion point, and you still need to iterate over all elements > ar[i] to move their values.


Project Euler #9 in C: Special Pythagorean triplet

Just few remarks:

Variables with meaningful names are more useful and make the code easier to read and understand.
Comments add to code clarity and could possibly point to fragments that can be optimized.
Use a more compact brace style.

int foo()
{
    for
      {
          //...
      }
}

could become

int foo(){
    for{
         //...
       }
}

Add white space between operands and operations: (a + b; a == b; a = 1).
Consistency and style: eliminate random white spaces/ indentations in expressions (p =1, p=1 or p= 1)
Brake the code into functions, each with single task.


You should be using String.prototype.replace() with a function as the second argument. Example:

str = str.replace(/{add_([A-Z]+)}/gi, function(match, id) {
  var o = Core.get_data_by_id(ex.extensions, id);
  return (o && o.status == "1") ? o.html : match;
});

str = str.replace(/{banner_([0-9]+)}/gi, function(match, id){
  var b = Core.get_data_by_id(ex.banners, id);

  if (b && b.status =="1" && b.code && b.code.length) {
    var content = '

' +
    b.code.each(function(s){
       content += '
'+s.code+'
';
    });
    content += '

';
    return content;
  }
  return match;
});

EDIT: I've added the second part.


Detect if ie10+ and edge is using inPrivate mode

Instead of blacklisting why not whitelist? If you are really just trying to post a message to the user saying your browser doesn't support something, why not just check if indexedDB is available and then if it isn't post something like:

"IndexedDB is only supported in Chrome 24.0, Firefox 16.0, IE 10/Edge, Opera 15 and Safari 7.1 or higher. It may also not work in certain 'Private' mode browsers. Please upgrade your browser to use the full power of our website."

This way you are avoiding lots of attempts of browser detection (which will more than likely break after browsers implement cross compatibility) and provides action for your user on what they can do next (try a different browser, upgrade, not be in private mode, etc).


Correct way to cover dependencies in unit tests

When unit testing a class you should focus only on the functionality in that class. For all other dependencies, mocking should be used. That is to say you should create "fake" implementations of the dependencies and use them to simulate the real thing. You can then run tests against the mocks to ensure that they are being used correctly according to the functionality of the class under test.

In order to do this you will have to inject all dependencies(this is pretty much always what you should be doing), likely in your constructor.

Your test example doesn't tell us too much and doesn't test anything. Instantiating a class then validating its type is not a test. Could you provide the class that you would like to test? Then we can give concrete examples.

I wrote a tutorial for using Moq to test dependencies, it can be found here:
http://stevemichael.net/how-do-i-use-moq-with-asp-net-mvc/


All integer sequences given amount of integers and length of sequence

I don't have time to do a style review at the moment, so until I can expand on this later, I'll just suggest a different algorithm.

Rather than depending on string manipulation and generating more items than you need, just take an arithmetic approach.

In particular, you can take a deque of ints and add 1 to it until it is equal to the max value.

std::deque< std::deque<int> > results;
std::deque<int> min(Y, 1);
std::deque<int> max(Y, X);
for (; min != max; min = increment(min, Y)) {
    results.push_back(min);
}
results.push_back(max);

As a bit more explanation, a std::deque<unsigned int> is frequently used as a make-shift arbitrary precision integer. The way this is done is to have a sign flag, and then to see each element of the deque as part of a radix = std::numeric_limits<unsigned int>::max() number.

As a concrete example, a std::deque<unsigned char> d = {95, 14, 230} would represent 95 * 255^2 + 14 * 255^1 + 230 * 255^0 in the same way common base ten 134 = 1 * 10^2 + 3 * 10^2 + 4 * 10^0.

Anyway, I'm getting carried away with this.

What you're in need of is a much more specific case of this. Rather than making a generic adder, all you have to do is just add 1, and if that causes the lowest digit to overflow, push it back down to a 1 and carry the add up the chain.

std::deque<int> increment(std::deque<int> d, int Y)
{
    bool carry = true;
    for (std::deque<int>::reverse_iterator it = d.rbegin(), end = d.rend(); it != end; ++it) {
        *it += 1;
        if (*it > Y) {
            *it = 1;
        } else {
            carry = false;
        }
    }
    if (carry) {
        d.push_front(1);
    }
    return d;
}

The above code is untested and unoptimized. It can probably be written more compactly, but it's been a long time since I've done anything like this, and I'm just trying to illustrate how it can be done arithmetically.

Also, if you're concerned about performance, you might want to have increment mutate d rather than return a modified copy.


Avoiding use of an initialized variable that will either be changed or ignored

I already explained in my other post, not to use this tempStoragevariable in this way. At least (compared to the other version) you do not change the meaning of it in this version.
If you rename it to something like removedItemFromEvenIndex it could be fine. If and really if the requirement is that all values inside the lists are >= 0.

If all values are allowed, I would suggest to stick to the solution with the boolean I suggested in the other post. Because if all values are allowed, You can not find any "check" value to see if you removed or something or not.

From where comes this problem? You try to do 2 things together with the tempStorage:

Transport the removed value
Status flag if you removed something or not

You can not address both things with the same Integer, because you already need everything from your Integer for the first part.

Rest is the same as for the other question.

To handle this one, same approach as other question:

What we want to do here? Add every second element to the new list, starting with the second.

So a simplified description could be:

function oddList(list)
  if list is empty or has only 1 element
    return empty list
  return new list(second element of list, oddList(all elements from the third to the end))

translate to algorithm in Java:

public static List<Integer> oddList(final List<Integer> list) {
    if (list.size() <= 1)
        return new ArrayList<>();

    final List<Integer> newList = new ArrayList<>(Arrays.asList(list.get(1)));
    newList.addAll(oddList(list.subList(2, list.size())));
    return newList;
}

If we take into account the other question, this could be a clever way (you should always try to reuse existing and working solutions):

public static List<Integer> oddList(final List<Integer> list) {
    final List<Integer> newList = new ArrayList<>(list); //we create a copy, otherwise list is modified for the caller
    newList.remove(0); //all indices shifted one to the left
    return even(newList);
}


There's an app for that

The nice thing about the python standard library, especially itertools is that there's always a function for what you want to do. In this case, you want to take chunks like:

['ABCD', 'EFGH', 'IJ']

and turn them into chunks like:

['AEI', 'BFJ', 'CG', 'DH']

That is, we're round robining through each row. There's a recipe for that:

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

So ultimately, we have just a couple steps:

Get our chunks.
Round robin through them.
Join the result

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i+n]

def encrypt(s):
    n = int(math.sqrt(len(s))
    chunked = chunks(s, n)
    return ''.join(roundrobin(*chunked))

Prefer to join

In your solution, you have:

string = ""
for j in range(f):
    string += my_list[j][i:i + 1]
encrpted_list.append(string)

This is inefficient though. When we're building up strings, it's much better to join them:

encrpted_list.append(''.join(my_list[j][i:i+1] for j in range(f)))

Evaluate lazily

This is inefficient:

split_list = [chunk for chunk in chunks(s, c)]

You likely only evaluated out chunks due to the way you wrote your encrypter, but you want to keep things as generators for as long as possible. It's more efficient to pass in chunks(s,c) into the zip_longest() than it would be to fully evaluate it. Though if you do, it's shorter to just write:

split_list = list(chunks(s,c))

Minor points

Excessive amounts of vertical spacing here.
encrpted_list is misspelled: should be encrypted_list.
Why do you have encrypt_list that takes a list and returns a list? You should have encrypt that takes a string and returns a string.
You don't need f,c... you can use int to get the floor, and add 1 if necessary. And avoid single-letter names.


Your code could be rewritten:

var settings = new JsonSerializerSettings {
     TypeNameHandling = TypeNameHandling.All,
     SerializationBinder = knownTypesBinder // <- see security risk below
};
var client = JsonConvert.DeserializeObject<Models.Entities.Client>(jsonResponse);
return client; // <- strongly-typed

Make sure both server and client use the settings
If you have declared  public ClientType Type { get; set; } just to enable two-phase serialisation (base entity - concrete entity), you should remove it from the code.
The two-phase serialisation hack can be replaced with a strongly-typed serialisation using TypeNameHandling = TypeNameHandling.All. Example

As suggested in the comments, we need to address the security aspect also. Hence, knownTypesBinder is used to mitigate a security risk.

// based on https://www.newtonsoft.com/json/help/html/SerializeSerializationBinder.htm
var knownTypesBinder = new KnownTypesBinder
{
    KnownTypes = new List<Type> { typeof(Customer), typeof(Account) }
};

public class KnownTypesBinder : ISerializationBinder
{
    public IList<Type> KnownTypes { get; set; }

    public Type BindToType(string assemblyName, string typeName)
    {
        return KnownTypes.SingleOrDefault(t => t.Name == typeName);
    }

    public void BindToName(Type serializedType, out string assemblyName,
        out string typeName)
    {
        assemblyName = null;
        typeName = serializedType.Name;
    }
}


Is this IF ok? Or is there a better way?

How about:

if (!defined("MEMBER_LIMIT") ||  MEMBER_LIMIT == 0 || $memcount < MEMBER_LIMIT) {
  // will do something
}
else {
  // will do something else.
}

The key is to look for both complementary (multiple items that accomplish the same thing by different means) and contradicting criteria (which would interrupt your desired flow of logic) in if statements


Fetch records that do not get matched in another table

Linting & Naming:

Your query is overflowing the box to the right. That's not good because it means I (and you) have to scroll to see it completely. Additionally while you use aliases, the table aliases are unnecessarily shortened.

After renaming them a little and reformatting the query looks as follows:

SELECT DISTINCT
    PaymentToken.Id
    , PaymentToken.AccountNumber
    , PaymentToken.CardNumber
    , PaymentToken.ExpirationDate
    , PaymentToken.CardHolderName
    , PaymentToken.AccountToken
    , PaymentToken.CreatedDate
    , PaymentToken.Active
FROM Dev_NeoGateway_DTR.dbo.PaymentToken AS PaymentToken
JOIN Dev_NeoGateway_DTA.dbo.DTA_Customer AS Customer
    ON Customer.Id = PaymentToken.AccountNumber
WHERE PaymentToken.AccountToken NOT IN (
    SELECT PaymentInstrument.CardToken
    FROM Dev_NeoGateway_DTA.dbo.DTA_PaymentInstrument AS PaymentInstrument
)

Optimizing the query

From what I can see, the Customer table is not used in your query. Joining it only slows down your query.
Other than that, the query is very straightforward. If you could restrict the subselect's result set, you could achieve better performance.

Other than that, the only thing I'd expect to improve perfomance are indices on the involved columns


Determining whether a number is positive, negative or zero

Flow control

The conditions here are mutually exclusive:

if(n>0):
    print "Number is Positive"
if(n<0):
    print "Number is Negative"
if(n==0):
    print "Number is ZERO"

It would be better to rewrite with elif and else:

if n > 0:
    print "Number is Positive"
elif n < 0:
    print "Number is Negative"
else:
    print "Number is ZERO"

Same thing here:

if (checkResult == 'Y'):
        inputAndRes()
if (checkResult == 'N' ):
        print (" !!! Program Quit !!!")
else:
    print ("Invalid Option Make sure that you type (Y / N)")
    print ("Continue..")
    wantRestart()

Should be:

if checkResult == 'Y':
    inputAndRes()
elif checkResult == 'N' :
    print (" !!! Program Quit !!!")
else:
    print ("Invalid Option Make sure that you type (Y / N)")
    print ("Continue..")
    wantRestart()

Finally, instead of raw_input(" "), it would be simpler to write as raw_input().

Writing style

There is an official coding style guide for Python called PEP8. Give it a good read and try to follow it. Your most notable coding style violations:

Spacing around operators: prefer n > 0 instead of n>0

Also, avoid unnecessary parenthesis in if statements, for example if n > 0: is better than if (n > 0):

Function naming should be snake_case instead of camelCase
Put 2 empty lines in front of a function definition

Misc

Instead of running inputAndRestart unconditionally, the common practice is this:

if __name__ == '__main__':
    inputAndRestart()

The advantage of this is that you will be able to import your module without running anything, because the if will only be true when you run the script directly.

Usability

The program wants me to enter Y to restart and N to exit, but I'm kinda lazy to press the shift. It would be great if I could use just y and n. Or even q and Q to exit. An easy way to do that:

if result in 'yY':
    input_and_restart()
elif result in 'nNqQ':
    print (" !!! Program Quit !!!")


Well, one brute force way of doing it is to recurse over the type's DeclaringType property:

public static string TypeName (Type type)
{
   if(type.DeclaringType == null)
      return type.Name;

   return TypeName(type.DeclaringType) + "." + type.Name;
}

Running the following program:

static void Main(string[] args)
{
   var type = typeof(My.Namespace.Foo.Bar.Baz);
   var name = TypeName(type);
}

returns the name Foo.Bar.Baz as you would expect.


I'm curious why you are using:

action.accept(Arrays.stream((T[]) buffer.toArray(new Object[0])));

It seems to me that action.accept(buffer.stream()) would work here, as long as the action.accept() fully processes the produced stream before returning.

Given the stream 1, 2, 3, 4 and the window size 3, the code looks like it will produce  [1,2,3], [2,3,4], and then due to the code outside the while loop, it looks like it wants to produce [3,4] as one last hurrah!

Except, tryAdvance has already returned false from return sourceIterator.hasNext(), so tryAdvance should not be called again.  So the code after the while loop looks effectively unreachable.

But it can be reached ... if the window never fill up completely in the first case, in which case it will produce exactly one stream of less than the full window size.  Is this intended behaviour?  If so, you really need to add comments explaining how that code is reached, and why it is possible not to reach it.

If less than a full window of output is possible, then shouldn't the Spliterator produce [1], [1,2], [1,2,3], [2,3,4], [3,4], [4] ... building up to the full window size and then tapering off once the end of the source stream has been reached?  Wouldn't that be more consistent?

An ArrayDeque will (based on its name) internally use an array, probably with head and tail indices.  I'm not sure how much you can improve it by implementing it with your own "plain array".  Sounds like you'd be reinventing the wheel.  Although using an array of windowSize*2-1 to avoid the wrap-around might give you a slight speedup.

estimateSize() could query the collection for its size, compute the number of windows it will be producing and return an actual value, instead of simply returning MAX_VALUE.


Idomatic way to ignore `finally` block after cancelling network request

Ignore the warning. React gives a warning when you setState after
  unmount because it indicates a memory leak (in this case, the
  lingering network request, if not canceled). If the network request
  is canceled, there is still a setState after unmount, but just to set
  a flag. There is no more lingering network request. It should be safe
  to ignore the warning in this case, but it doesn't feel right.

Bad idea. Thing is, by the time the request will resolve, setState might be triggered on an unmounted component. And warning turns to error.

  Check what error was thrown in the finally block and add the same if
  statement as the catch block. This seems incredibly hacky and would
  require extra code to save the error from the catch block.

Meh :\

  Check if the component is mounted in the finally block. This is also
  hacky and requires boilerplate code to update a this.isMounted flag.

It's an Anti-pattern

  Put the cleanup code at the end of try and after the condition in
  catch. This is not DRY. Humans are also very forgetful; I cannot count
  how many times I have forgotten to set isLoading = false in catch.

This

  Define a cleanup() function before the try and call it in try and
  catch. This is a decent option, but requires extra function calls,
  making it harder to follow.

And that, are pretty much taking the same turn with different gear.

Suggestion from React Blog

If you use ES6 promises, you may need to wrap your promise in order to make it cancelable.

const cancelablePromise = makeCancelable(
  new Promise(r => component.setState({...}))
);

cancelablePromise
  .promise
  .then(() => console.log('resolved'))
  .catch((reason) => console.log('isCanceled', reason.isCanceled));

cancelablePromise.cancel(); // Cancel the promise

Where makeCancelable was originally defined by @istarkov as:

const makeCancelable = (promise) => {
  let hasCanceled_ = false;

  const wrappedPromise = new Promise((resolve, reject) => {
    promise.then(
      val => hasCanceled_ ? reject({isCanceled: true}) : resolve(val),
      error => hasCanceled_ ? reject({isCanceled: true}) : reject(error)
    );
  });

  return {
    promise: wrappedPromise,
    cancel() {
      hasCanceled_ = true;
    },
  };
};


Much better algorithm in my view:

Consider first matrix example

1   2  3  4
5   6  7  8
9  10 11 12
13 14 15 16

R=rotations

convert in 2 circles (at least either M or N is even, thus there is no single center point):

c1 = [1,2,3,4,8,12,16,15,14,13,9,5]
c2 = [6,7,11,10]

for each position calculate actual value:

c1’[i] = c1[(i+R)%c1.length]
c2’[i] = c2[(i+R)%c2.length]
…

The number of circles is min(M, N)/2 hence this strange constraint in the task :)

This solves in linear \$O(M+N)\$ complexity rather than your cubic \$O(M\cdot N\cdot R)\$ complexity.

EDIT: of course revert the circles back to the matrix format.


Regex101.com seems to think you can simply combine \s{2,} and [\t\n] into \s{2,}[\t\n] and it should have the same effect:

$string = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $string);

into:

$string = preg_replace('/\s{2,}[\t\n]/', ' ', $string);

You should add whitespace between your binary operators in this line:

$string = iconv("Windows-1252","UTF-8",urldecode($string));

into:

$string = iconv("Windows-1252", "UTF-8", urldecode($string));

(I'm not personally familiar with iconv, so I can't give too much of a review on your usage of the function.)

Your third regex could be slimmed down from a-zA-Z into a-z with an case insensitive search.

return preg_replace('/[^a-zA-Z0-9Ã§&-©‚Âƒâ€˜\s]/', '', $string);

return preg_replace('/[^a-z0-9Ã§&-©‚Âƒâ€˜\s]/i', '', $string);

In the same way you use a preg_replace with an array, you combine the first pair, with the secondary statement into one line if you like.


You used a massive number of if and elif statments, I suggest using Math
You used no functions, I suggest using some.
You are repeating yourself very much, I suggest to say things once and only once.
You are mixing logic and user interface, I suggest not to.
You are not automatically testing your code, changing it may break it.

My implementation does not count wins and losses and is a bit hard to follow but was developed following the above principles that I believe make good code:

import doctest
import random

ROCK = 0
PAPER = 1
SCISSORS = 2
SIGNS = ['ROCK', 'PAPER', 'SCISSORS']

LETTER_TO_RPS = {
    'r':ROCK,
    'p':PAPER,
    's':SCISSORS
    }

def rps_compare(a, b):
    """
    >>> rps_compare(ROCK, SCISSORS)
    'WIN'
    >>> rps_compare(PAPER, SCISSORS)
    'LOSS'
    """
    if a == b: return 'TIE'
    return 'WIN' if (a - b) % 3 == 1 else 'LOSS'

def rps_round(letters_map=LETTER_TO_RPS):
    user_choice = LETTER_TO_RPS[raw_input("[R]ock, [P]aper or [S]cissors? ").lower()]
    cpu_choice = random.choice([ROCK,PAPER,SCISSORS])
    print("I chose {}.".format(SIGNS[cpu_choice]))
    return rps_compare(user_choice, cpu_choice)

def rps_game(welcome_message, letters_map=LETTER_TO_RPS):
    print(welcome_message)
    while True:
        print("This is a {}".format(rps_round()))

if __name__ == "__main__":
    doctest.testmod()
    rps_game('Hello')


1. Review

There's no docstring. What does memoize do, and how do I use it?
The code uses str(args) + str(kwargs) as the cache key. But this means that, for example, the number 1 and the string "1" will collide.
The code is not portable to Python 3, where there's no thread module.
It's not clear to me why functools is only imported inside memoize, but threading is imported at top level.
It's not clear to me why the code assigns to obj.cache and obj.lock_cache. What if obj already has a cache property?
The locking logic is hard to follow and needs comments. As far as I can see, lock_cache protects the cache dictionary; and item_cache protects the cache slot that is currently being computed. Its necessary to have two locks because the call to obj might be recursive and so need to re-enter memoizer.
The code uses three states for each key: (i) not present in the cache; (ii) currently being computed; (iii) present in the cache. The way it distinguishes between (ii) and (iii) is by checking to see if the type is thread.LockType. But this means that you can't use memoize on a function that might return a lock. It would be better to have a more robust mechanism for distinguishing these cases.
The naming is inconsistent: lock_cache versus item_lock.
key is looked up in cache multiple times on some code paths.

2. Revised code

from functools import wraps
from threading import Lock

class CacheEntry: pass

def memoized(f):
    """Decorator that caches a function's result each time it is called.
    If called later with the same arguments, the cached value is
    returned, and not re-evaluated. Access to the cache is
    thread-safe.

    """
    cache = {}                  # Map from key to CacheEntry
    cache_lock = Lock()         # Guards cache

    @wraps(f)
    def memoizer(*args, **kwargs):
        key = args, tuple(kwargs.items())
        result_lock = None

        with cache_lock:
            try:
                entry = cache[key]
            except KeyError:
                entry = cache[key] = CacheEntry()
                result_lock = entry.lock = Lock() # Guards entry.result
                result_lock.acquire()

        if result_lock:
            # Compute the new entry without holding cache_lock, to avoid
            # deadlock if the call to f is recursive (in which case
            # memoizer is re-entered).
            result = entry.result = f(*args, **kwargs)
            result_lock.release()
            return result
        else:
            # Wait on entry.lock without holding cache_lock, to avoid
            # blocking other threads that need to use the cache.
            with entry.lock:
                return entry.result

    return memoizer

Notes:

This is untested.
This doesn't delete result_lock after the result is computed. This simplifies the logic (for example, there's no need to take cache_lock again and no need for a type check) at the cost of 40 bytes to keep the Lock object around.


Get a random event out of a set of mutually exclusive events

Some things:

The collectively exhaustive events are not going to change or be updated. So use a tuple instead of a list:

events = (  # <<- Note: ( not [
    ('Win', 50),
    ...
)

You don't show your import of random. But I'd prefer that you not import uniform by name, and rather spell it out inside your function. You're only calling it once, so it's more efficient to the reader for you to simply say:

random_number = random.uniform(...)

than to have them search backwards for where uniform occurs. Also, of course, in this context random.uniform actually reads better than just uniform.
You have an input parameter events. You use event, prob in your loop. But event is the singular of events, so when you say return event it seems like you are returning a member of the events iterable. I'd choose a different name, like outcome, making it clear that your returning a component of the inner tuple.
You compare lower_bound <= random_number <= lower_bound + prob but you don't have to. Since your random number is pinned to 0., you could just use a comparison against the high value and get the same result.
Structurally, the lower_bound += prob shouldn't be in the else branch. Yes, it only executes when the if is not executed, but the if should not be part of the flow for that statement. I'd rather see:

if ...
    return ...

lower_bound += prob

This kind of thing comes back to bite you when you're refactoring. Or, worse yet, when someone else is refactoring. (Imagine you changed the return to a print, or something. Suddenly the code stops working.)
The Task description would (almost) make a good function docblock. Note: s/list/iterable/:

from typing import Iterable, Tuple

Name = str
Prob = float

def get_random_event(events: Iterable[Tuple[Name, Prob]]) -> Name:
    """Get a random event from a set of collectively exhaustive
    and mutually exclusive events, with this set being represented
    by an iterable of tuples (name, probability).

    """


IEnumerable of classes that implement a given interface at runtime

I only have a few minor comments about your code:

This code:

var ctor = implementor.GetConstructor(Type.EmptyTypes);
if (ctor == null) continue;

has the potential to mask a bug. Imagine you add a constructor to one of your command-factory types and accidentally forget that this implicitly removes the default constructor. This code will then silently swallow this mistake and simply not list that particular command factory. It would be preferable to throw in this case so that you notice it immediately. Even better, of course, would be to use a post-build event to turn this error into a compile-time check so that you can’t even run the program when it is invalid.
This code:

var instance = ctor.Invoke(null) as ICommandFactory;
if (instance == null) continue;

has exactly the same problem, but the consequences are much more subtle. The if (instance == null) condition should never fire because the code was written so that the instance cannot be of any other type. Imagine you have a bug in that code. This code swallows this bug and you won’t notice it directly. You will only notice some subtle/weird effects that occur much later, and it will be a pain to trace it back to this code here. You could make it throw like above, but personally I think you should change this to var instance = (ICommandFactory) ctor.Invoke(null); so that it will automatically throw if it’s not of the right type.
Your code does not allow for a class that implements ICommandFactory but is not intended to appear in your UI. If you are sure that you don’t want that to be possible, then your code is fine. Otherwise, I would declare a custom attribute — either one that allows you to explicitly exclude an ICommandFactory from appearing in the UI, or one that is required on all the ICommandFactory types to be included.
Very very minor nitpick:

i => interfaceType.IsAssignableFrom(i) && i != interfaceType

You should perform the simpler check first:

i => i != interfaceType && interfaceType.IsAssignableFrom(i)