My binary search algorithm implementation in JavaScript

Parsing command line arguments

I mentioned this in a previous review,
it seems I wasn't specific enough,
but this is an inefficient and unnatural way to parse command line arguments:

    process.argv.forEach(function (val, index, array) {
        var idx = 0, ar = undefined;

        try{

            // get the commandline argument for
            // array values
            if(index === 2){
                myArray = myArray.concat(val.split(",").map(function(num){
                    return parseInt(num);
                }));
            }

            // third index is the number to be searched.
            if(index === 3){
                searchNum = parseInt(val)
            }

        }catch(e){
            console.log(e)
        }

    });

What's wrong with it?

For each index 0, 1, 2, 3, the loop compares the index against 2 and 3 repeatedly
If there are not enough arguments, the loop should not even begin
The command line parsing logic fails its purpose by not failing in case the arguments are invalid

The natural way to parse would be:

Check process.argv.length and fail if invalid
Check the type of each argument and fail if invalid

Consider this alternative, no looping, nice and simple:

function parseArgs(prog, argv) {
  if (argv.length != 2) {
    throw `usage: node ${prog} NUMS_CSV NUM`;
  }

  function validInt(s) {
    var num = parseInt(s, 10);
    if (isNaN(num)) {
      throw "Not a valid number: " + s;
    }
    return num;
  }

  return {
    nums: argv[0].split(',').map(validInt),
    target: validInt(argv[1])
  };
}

var args = parseArgs(process.argv[1], process.argv.slice(2));

Parsing integers

When using parseInt, it's recommended to specify the radix parameter, because although base 10 is a common default, it's not guaranteed across different implementations.
So to parse base 10 numbers, write parseInt(x, 10) instead of parseInt(x).

API design

The binary_search function searches for an element and returns two kinds of strings as result:

can't be found
Number N found at position X

This is very limiting.
It would be better to have binary_search return an index or -1 if not found,
and move the logic of formatting a string result into a dedicated function.


int i = 0;
    while(i < nthWeekday && currentDay.Month == date.Month)
    {
        if (currentDay.DayOfWeek != DayOfWeek.Saturday && currentDay.DayOfWeek != DayOfWeek.Sunday)
        {
            i++;
            if(i == nthWeekday)
                return currentDay;
        }
        currentDay = currentDay.AddDays(1);
    }

Your while loop is a little messy let's clean that up first, and you should also have an early continue statement in there.

Let me show you what I mean:

int i = 1;
while(i <= nthWeekday && currentDay.Month == date.Month)
{
    bool isWeekendDay = currentDay.DayOfWeek == DayOfWeek.Saturday || currentDay.DayOfWeek == DayOfWeek.Sunday;

    if (isWeekendDay)
    {
        currentDay = currentDay.AddDays(1);
        continue;
    }
    if (i == nthWeekday)
    {
        return currentDay;
    }
    currentDay = currentDay.AddDays(1);
    i++;
}

This is a lot cleaner, and shows exactly what our intent is.  It is much easier to read.

You shouldn't nest if statements inside of other if statements if you don't have to, it can get very confusing.


Google News scraper to fetch links with similar stories

Instead of constructing the google_news_search_url with two string concatenations, use string formatting.
The other_news_sources_links line is very dense. Please split it up.
In addition to the defaults for all your args being None, you're calling all of your functions with keyword arguments, which seems unnecessary.
But before you fix that, consider why you need these 2 line functions in the first place. They don't seem to do anything complicated enough to warrant having to jump around in the code.


Checking Object keys set with value against another Object keys

Function and parameter names The function name areValuesSet could be more precise. It returns an array of incorrect property names, not a boolean of if values are set. Maybe call it getIncorrectProperties? Also, the argument named obj is uninformative. You want to indicate that it's the target value being checked. Maybe call it validateTarget or something similar.
Avoid any any is type-unsafe. Unless you have a really good reason for it, better to type something you don't know about as unknown instead. unknown is similar to any, but requires you to do type-narrowing first. In this case, using unknown will point out a bug in your current logic:
typeof null gives object You have:
if (typeof rules[key] === "object" && typeof obj[key] === "object") {
  return areValuesSet(obj[key], rules[key]);
}

This will result in the recursive call throwing if one of the values happens to be null, since null is an object. Add in and call:
const isObject = (arg: unknown) => typeof arg === 'object' && arg !== null;

!obj[key] excludes false Your current logic permits values of true but forbids values of false due to this check:
!obj[key] || (isEmpty(obj[key]) && typeof obj[key] !== 'boolean')

Is that deliberate? It's OK if it is, but it may well be a logic bug. If false should indeed be excluded, then typeof obj[key] !== 'boolean' simplifies to obj[key] !== true.
Nested property bugs
(1) The recursive call is only entered if both the rules and target are objects. If the rule is an object, and the target is a non-empty non-object, the target will pass, when it probably shouldn't. Eg:
// rules:
{
  prop: { val: 'val' }
}

// target:
{
  prop: 'foo'
}

should probably fail, but won't. If the rule is an object and the target value is not an object, you probably want to push the property to the array of errors.
(2) When a sub-object is found as a value, your reduce callback does:
return areValuesSet(obj[key], rules[key]);

Whatever may have been put into the accumulator array on prior iterations will be lost, since it's not being factored into the return value. For example, if you had a data structure for which the first 5 properties were wrong, but the 6th property is nested and correct, the function would return an empty array.
But reduce arguably isn't very appropriate in these sorts of situations anyway - see that link for a video by Chrome developers on the subject. It introduces an annoying amount of boilerplate code, especially in TS, and even well-formulated reduces like these often aren't entirely trivial to understand at a glance.
Consider creating an array outside the function and pushing to it instead - or use a recursive function which creates the array to return as a default argument when not passed. Including all the other suggestions as well:
type GenericObj = { [propKey: string]: unknown };
const isObject = (arg: unknown): arg is GenericObj => typeof arg === 'object' && arg !== null;

const getIncorrectProperties = (
  validateTarget: GenericObj,
  rules: GenericObj,
  incorrectProperties: string[] = [],
) => {
  for (const [key, ruleValue] of Object.entries(rules)) {
    const targetValue = validateTarget[key];
    if (isObject(ruleValue)) {
      if (!isObject(targetValue)) {
        incorrectProperties.push(key);
      } else {
        getIncorrectProperties(targetValue, ruleValue, incorrectProperties);
      }
    } else if (!targetValue || (isEmpty(targetValue) && targetValue !== true)) {
      incorrectProperties.push(key);
    }
  }
  return incorrectProperties;
};

Live snippet of compiled code including example validation, to show that it's working:

"use strict";
const isObject = (arg) => typeof arg === 'object' && arg !== null;
const getIncorrectProperties = (validateTarget, rules, incorrectProperties = []) => {
    for (const [key, ruleValue] of Object.entries(rules)) {
        const targetValue = validateTarget[key];
        if (isObject(ruleValue)) {
            if (!isObject(targetValue)) {
                incorrectProperties.push(key);
            }
            else {
                getIncorrectProperties(targetValue, ruleValue, incorrectProperties);
            }
        }
        else if (!targetValue || (_.isEmpty(targetValue) && targetValue !== true)) {
            incorrectProperties.push(key);
        }
    }
    return incorrectProperties;
};
console.log(getIncorrectProperties({
    prop2: {
        nested: 'val',
    }
}, {
    prop1: true,
    prop2: {
        nested: true,
        nested2: {
            deeplyNested: true
        }
    },
    prop3: true
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

The only issue I have with the above code is the incorrectProperties argument. Although the approach works to create an array on initial call and return it at the end, having it as a parameter might be confusing, since the initial call should not take 3 arguments, only 2. If you think that's not acceptable, you could create an array in the function body on every call and return it at the end, and spread the result of the recursive call into that array.


1) In a language like C or C++, you wouldn't do something like this:

foo           (1,2);
x = bar       (2.5);

It makes it harder to read the code because the function name makes no sense without its parameters. The same is true for assembly. Basically, this:

xor       EAX, EAX

Should be this:

xor EAX, EAX

2) In a language like C or C++, you wouldn't do something like this:

b = a * 5 + 2298;
c = b / 9;

Instead, you might do this:

kelvin_x9 = fahrenheit * 5 + 2298;
kelvin = kelvin_x9 / 9;

In assembly, because you can't give registers descriptive names (in the same way that you can give variables descriptive names in higher level languages) and because often you do things that are semantically wrong (e.g. using shifts when you mean multiplication, using LEA when you're not loading an effective address, etc) it's extremely important for code maintainability to use comments. Basically this:

calc_lcm:
     mov   EAX, [num1_cpy]
     mov   EDX, [num2_cpy]
     mul   EDX

     mov   EDI, EAX

     xor   EBX, EBX

     mov   EDX, EDI
     shr   EDX, 16
     mov   EAX, EDI
     mov   BX, [gcd]
     div   BX

     mov   SI, AX
     mov   [lcm], SI

     ret

Should be this:

calc_lcm:
     mov EAX, [num1_cpy]   ;eax = number1
     mov EDX, [num2_cpy]   ;edx = number2
     mul EDX               ;edx:eax = number1 * number2

     mov EDI, EAX          ;edi = number1 * number2, high 32-bits of number discarded

     xor EBX, EBX

     mov EDX, EDI          ;edx = number1 * number2
     shr EDX, 16           ;edx = number1 * number2 / 65536, dx:ax = number1 * number2
     mov EAX, EDI          ;eax = number1 * number2, (can be deleted as EAX already contained this value)
     mov BX, [gcd]         ;bx = GCD
     div BX                ;ax = number1 * number2 / GCD, dx = number1 * number2 % GCD

     mov SI, AX            ;si = number1 * number2 / GCD
     mov [lcm], SI
     ret

For assembly there's only 2 types of bugs - comments that don't describe sane logic, and code that doesn't do what the comments say it should. This allows you to debug the code effectively and drastically reduces the chance of missing mistakes (in addition to the hopefully obvious massive improvement in code readability).

3) In a language like C or C++, you would create lots of bugs caused by things like integer overflows because the language doesn't provide a sane/easy way to detect these bugs. In assembly you should not create lots of bugs caused by things like integer overflows because you can easily test for overflows.

For example, this:

calc_lcm:
     mov EAX, [num1_cpy]   ;eax = number1
     mov EDX, [num2_cpy]   ;edx = number2
     mul EDX               ;edx:eax = number1 * number2

     mov EDI, EAX          ;edi = number1 * number2, high 32-bits of number discarded

Should be this:

calc_lcm:
     mov EAX, [num1_cpy]   ;eax = number1
     mov EDX, [num2_cpy]   ;edx = number2
     mul EDX               ;edx:eax = number1 * number2

     test EDX, EDX         ;Will the result fit in 32 bits?
     jne .overflow         ; no, error
     mov EDI, EAX          ;edi = number1 * number2

Note: A better idea would be to do "movzx ebx,word [GCD]" and "div ebx" to divide EDX:EAX by the GCD instead of pointlessly converting the 64-bit value you had in EDX:EAX into a 32-bit value in DX:AX.

4) A compiler will check if (e.g.) functions are being called with the correct number of parameters, and will make sure that various registers are saved/restored, etc where necessary. In assembly there is none of that; so you have to do it manually, so you have to be able to do it manually. To be able to do it manually you need to document routines properly. For example, this:

calc_lcm:

Should be this:

;Calculate Lowest Common Multiple
;
;Input:
; [num1_cpy]  Some number
; [num2_cpy]  Some other number
; [GCD]       The GCD
;
;Output:
; [lcm]       The result
;
;Trashed:
; eax, edx, ebx, esi, edi

calc_lcm:

Normally, you'd pass parameters in registers and return parameters in registers to avoid wasting time on loading/storing where avoidable. For example, the entire "calc_lcm" code might be:

;Calculate Lowest Common Multiple
;
;Input:
; eax         Some number
; edx         Some other number
; ebx         The GCD
;
;Output:
; eax         The result
;
;Trashed:
; edx

calc_lcm:
     mul EDX               ;edx:eax = number1 * number2
     div EBX               ;eax = (number1 * number2) / GCD, edx = (number1 * number2) % GCD
     ret

5) If you're writing assembly you should write assembly; and not attempt to obfuscate the code by inventing your own language that makes it difficult read the code and impossible to effectively optimise the code.

For example, this code:

 nwln
 nwln
 PutStr   num_lbl
 nwln
 nwln
 GetLInt   [num1]
 GetLInt   [num2]

Is 100% meaningless gibberish.

I don't know what this code should be (and am completely unable to see ways of optimising it that would have been obvious if it was assembly) because I have no idea what any of these macros do. I can't tell which registers get trashed, I can't see which pushes/pops/moves are redundant. I might be able to assume that it'd be safe to delete the first 2 nwln lines and change the string to num_lbl:   DB   "\n\n> Numbers (2): ", 0 but then that could introduce all sorts of bugs because I didn't bother with the hassle of finding and reading the macros that may do more (or less) than whatever I've assumed they might do.


It is always a best practice to use constructor only for initializing default values. Whatever logic or the function which you want to use is good to call directly from main method or separate method.


Unnecessary type conversions

There are a couple of unnecessary type conversions, for example:

index_y = int((len(kernel[0]) - 1) / 2.0) * -1

Casting to int truncates, but so does integer division.
So you can simplify the above with:

index_y = -(len(kernel_offset_y) - 1) // 2

In Python 2 integer division truncates by default,
so ... / 2 would work too.
But not in Python 3, where the behavior was changed.
Using // works in Python 2.7 and Python 3 consistently.

I also replaced the * -1 with a simpler - prefix.

On this line, x, index_x, y and index_y are all integers,
so no need to convert them to int:

temp_r, temp_g, temp_b = img.getpixel((int(x + index_x), int(y + index_y)))

This is also unnecessary:

outputIm.putdata([tuple(pixel) for pixel in d])

Since d is already a list of tuples, you could write simply:

outputIm.putdata(d)

Simplify

The default start value of range is 0, so instead of range(0, k) you could write range(k).

Instead of x = x / y you could write x /= y.

The parentheses are unnecessary in if (expr):.

Formatting

Instead of this:

kernel = [[1]*10]*10

PEP8 recommends this writing style:

kernel = [[1] * 10] * 10


Name for mconcat implementation for applicative monoid

I wouldn't give this a name. It is equal to foldMap pure and feels to me like it might be refactored away with more context.


Design

You could remake this using Object-Oriented-Programming. For example, you could make a Question object, like this.

function Question(description, choices, correctChoiceIndex) {
    this.description = description;
    this.choices = choices;
    this.correctChoiceIndex = correctChoiceIndex;
}

You could then extend it with some methods, like askQuestion. For example, you could do something like this (Using prompt and alert because I'm on mobile.)

Question.prototype.askQuestion = function() {
    return prompt("Choices:\n" + this.choices.join("\n"));
}

You could then supply an additional method, checkAnswer, to see if the user got the answer correct.

Question.prototype.checkAnswer = function() {
    if(parseInt(this.askQuestion(), 10) === this.correctChoiceIndex) {
        alert("You got the question right!");
    }
    else {
        alert("Sorry, wrong answer.");
    }
}

Nitpicks

Some of your naming is not great. For example, firstFunc is an awful name for a function. It doesn't describe the purpose of the function in any way.

Preferably, names for variables/functions/classes should exhibit the following characteristics:

Describe the variable/function/class in detail.
Not have unnecessary abbreviations.
Not be too short.
Not be too long. (Unless you're programming in objective-c.)

Most of your variable names exhibit these characteristics, I just saw a few, like submitBtn that could be expanded to something like submitButton.

Moving on, I saw this line I your code:

var index = [i];

It isn't used anywhere in it's scope, and even if it was used, it would serve no purpose at this point.

Finally, when using the increment, ++, and decrement, -- operators, remember the differences between how they're placed.


It's hard to review just a small part of your code like this (for example, the way you're using Items and isInitialized looks like code smell to me, but it's hard to tell like this), so I'll focus on what I can actually see.

protected async Task PerformInitInternal(string okMessage, string koMessage, Func<Task<IList<T>>> function)

It's an asynchronous method, so its name should end with Async. Also, PerformInit is pretty vague, maybe a more concrete name could be better, for example, LoadData?
While the symmetry between OK and KO is fun, I don't think koMessage is a good name. successMessage and errorMessage would be better.
Speaking of which, do you actually need both messages? Or any messages at all? I would consider a completely generic message, assuming the rest of the message can be inferred from other parts of the log, like the type name.
function is too vague.


Return a key when a function returns true

Needs more LINQ:

return classifications.FirstOrDefault(item => item.Value.Invoke(input)).Key;

This has the advantage (IMO) of highlighting the fact that you're discarding all but the first match (note that iteration order is not guaranteed!).

Classify doesn't really convey the fact that you're returning a Key from a dictionary. Seems FindKey would be a much better name.

A generic extension method seems like a good idea -  call your source source, and stick to TKey and TValue:

public static TKey FindKey<TKey, TValue>(this IDictionary<TKey, Func<TValue, bool>> source, TValue input)
{
    return source.FirstOrDefault(item => item.Value.Invoke(input)).Key;
}

That one-liner makes use of the fact that KeyValuePair<TKey,TValue> is a struct (and therefore can't be null), so you can just return .Key and that will be default(TKey).


Multiplication of 3×3 and N×N square matrices

A factor of 3 is large, but in my opinion not unexpected or abnormal. The functions that can handle a variable size matrix in their natural form (ie as they would be compiled without knowledge of the size, for example if the functions are defined in a different compilation unit than they are used in and LTO is not applied) have a lot of overhead: non-linear control flow (3 nested loops), more complicated address computation (involving multiplication by a variable).

Basically, that is the cost of generality .. but there is more to it.

From your use of QueryPerformanceCounter I assume you use MSVC (other compilers aren't much different for the following considerations). MSVC likes to unroll loops such as the one in dotMatrix by 4. It does not like to unroll such loops by 3, though it can be persuaded to do so anyway, for example by giving it a loop that makes exactly 3 iterations. So the cost of generality would work out much differently if the relevant matrix was of size 4x4 or 8x8, as in those cases only the faster unrolled codepath would be used (this still comes with overhead, but less). 3 is a bad case, only ever using the fallback codepath.

Additionally, the general matrix multiply implemented by multiplyMatrix is not scalable: it does not implement cache blocking, so for any matrix that does not fit in L1 cache it will perform badly (and even more badly when going beyond the L2 and L3 sizes). That is normal for code in general, but matrix multiplication is special in that it does not have to suffer significantly from that common effect thanks to its "O(n2) data in O(n3) time" property.

Both the general matrix multiply and the special 3x3 one could use SIMD intrinsics for extra efficiency. 3x3 is an awkward size that would cause some "wasted lanes", but it would still help. For example, it could be done like this (not tested):

#include <xmmintrin.h>

class Matrix3x3
{
public:
float32 m11, m21, m31,
        m12, m22, m32,
        m13, m23, m33, padding;

void multiply(float32 ma11, float32 ma12, float32 ma13,
              float32 ma21, float32 ma22, float32 ma23,
              float32 ma31, float32 ma32, float32 ma33) {

    __m128 col1 = _mm_loadu_ps(&m11);
    __m128 col2 = _mm_loadu_ps(&m12);
    __m128 col3 = _mm_loadu_ps(&m13);
    __m128 t1 = _mm_add_ps(_mm_add_ps(
        _mm_mul_ps(col1, _mm_set1_ps(ma11)),
        _mm_mul_ps(col2, _mm_set1_ps(ma21))),
        _mm_mul_ps(col3, _mm_set1_ps(ma31)));
    __m128 t2 = _mm_add_ps(_mm_add_ps(
        _mm_mul_ps(col1, _mm_set1_ps(ma12)),
        _mm_mul_ps(col2, _mm_set1_ps(ma22))),
        _mm_mul_ps(col3, _mm_set1_ps(ma32)));
    __m128 t3 = _mm_add_ps(_mm_add_ps(
        _mm_mul_ps(col1, _mm_set1_ps(ma13)),
        _mm_mul_ps(col2, _mm_set1_ps(ma23))),
        _mm_mul_ps(col3, _mm_set1_ps(ma33)));

    _mm_storeu_ps(&m11, t1);
    _mm_storeu_ps(&m12, t2);
    _mm_storeu_ps(&m13, t3);
}
};

The padding is a bit unfortunate (and shouldn't be private, because that makes its positioning relative to the actual matrix elements undefined), but simplifies the SIMD logic, chunks of 16 bytes are easier to deal with. It is possible to avoid the padding if required. Anyway, this results in a significant reduction in code and should be more efficient (without AVX the set1s cost more, that shouldn't be enough to undo the improvement but I didn't try it). The dllexport in the code on godbolt is not really part of the code, I just put that there to force code to be generated for an otherwise unused method.

Column-major order is used here because the columns of the result are a linear combination of the columns of the left hand matrix, which we have access to in packed memory. Similarly, the rows of the output are a linear combination of the rows of the right hand side, but we have no packed access to the rows of the right hand side, so they would be inefficient to gather. A row-oriented version of the above could be arranged for example if the right hand side was passed in as a reference to a Matrix3x3.

Passing the right hand side as matrix is probably a nicer interface anyway, with 9 separate arguments there is no choice but to write them all out separately even if the RHS is available as a matrix object, as you already experienced in your benchmark code.


I guess roundup is something like
(defun roundup (x y) (* (ceiling x y) y))?

For the reason you stated I'd probably go with loop (or alternatives,
iterate comes to mind) instead of the do... family of macros, e.g.:

(defun indentation (line)
  (loop
    with spaces = 0
    for index below (length line)
    do (case (char line index)
         (#\Space (incf spaces))
         (#\Tab (setf spaces (roundup (1+ spaces) 4)))
         (T (loop-finish)))
    finally (return (values spaces index))))

Depending on the choice of input you might want to use char for
strings instead of aref.
otherwise is pretty long, but of course it's somewhat of a personal
choice - t is a bit shorter.


The items and the inventory can be modelled intuitively with classes:

You can define an Item class that has attributes like name, weight, attack
You can define an Inventory class that has a collection of items, and knows how to print them

Something like this:

class Item(object):
    def __init__(self, name, attack, armor, weight, price):
        self.name = name
        self.attack = attack
        self.armor = armor
        self.weight = weight
        self.price = price

class Inventory(object):
    def __init__(self):
        self.items = {}

    def add_item(self, item):
        self.items[item.name] = item

    def print_items(self):
        print('\t'.join(['Name', 'Atk', 'Arm', 'Lb', 'Val']))
        for item in self.items.values():
            print('\t'.join([str(x) for x in [item.name, item.attack, item.armor, item.weight, item.price]]))

inventory = Inventory()
inventory.add_item(Item('Sword', 5, 1, 15, 2))
inventory.add_item(Item('Armor', 0, 10, 25, 5))
inventory.print_items()

UPDATE

Based on a suggestion by @jonrsharpe you could move the printing logic from print_items to the __str__ method:

def __str__(self):
    out = '\t'.join(['Name', 'Atk', 'Arm', 'Lb', 'Val'])
    for item in self.items.values():
        out += '\n' + '\t'.join([str(x) for x in [item.name, item.attack, item.armor, item.weight, item.price]])
    return out

This way, instead of inventory.print_items(), you can print the inventory more intuitively with print(inventory).


Multiple search filter like the one in freshdesk

I would advise you to implement search in Index action. If there are no search filters passed, then simply return everything (both for HTML and JSON).

You should rebuild a bit of the form so search params are nested, and you won't have to filter them.

Finally, you can move the search logic to model:

class Request
  def self.search(opts={})
    #reject empty filters
    filters = opts.reject(&:blank?)
    where(filters)
  end
end

class RequestsController
  def index
    @requests = Request.search(params[:search])
  end
end

Now you need to worry only about passing correct params (form fields should match db columns). Some transformations may be necessary depending on how you expect to build the query.

Be sure to fully test the form with integration spec; you are relying on view a lot.


Replacing elements from a list and its sublists

Separate your concerns

Think of it this way - as we walk through the input, we do one of two things. If the next thing is a list, we recurse. If it's not a list, we do the equality checking. You're doing everything in one check, which makes it a little hard to follow.

Let's just define a maybe-swap:

(define (maybe-swap val old new)
    (if (equal? val old) new val))

And use that directly:

(define (substitute lst old new)
    (if (list? lst)
        (map (lambda (elem) (substitute elem old new)) lst)
        (maybe-swap lst old new)))

This does all the same thing that you're doing, but once you split it up, there's less logic to have to reason about. You can even move maybe-swap into substitute directly:

(define (substitute lst old new)
    (define (maybe-swap elem) (if (equal? elem old) new elem))
    (if (list? lst)
        (map (lambda (elem) (substitute elem old new)) lst)
        (maybe-swap lst)))

This also reduces the code duplication. You're currently recursing via (subl X) in four different places. I'm recursing in just one spot - effectively for lists I'm calling (map subl lst).

map

I think in a previous review you didn't want to use map, which we can easily implement like:

(define (map f lst)
    (if (null? lst) lst
        (cons (f (car lst)) (map f (cdr lst)))))


Calculate subtotals and totals from a form with many decimal values

Two words: loops and arrays.

There a bunch of variable names that differ only by a number. Whenever you see code like this, you can probably clean it up by creating a collection of those things and looping over them. Basically, you have a checkbox and text field repeated multiple times, and one field where you display the total of all checked fields.

Create a user control to encapsulate the checkbox and text field
Make sure this user control has a public property decimal TotalCost { get } that will:

Return the decimal-parsed values of total - cost for the fields when checked, and zero when unchecked.
Throws an exception if the decimal cannot be parsed

Expose a boolean property bool IsValid that returns true when the user as entered a valid decimals
Expose a public property bool IsChecked that returns whether or not the checkbox is checked
Create a collection of these user controls, one for each checkbox/text field combo on screen

Now loop and process:

decimal purchaseTotal = 0m;
decimal totalAmount = 0m;

foreach (var control in PurchasedItems.Where(p => p.IsChecked && p.IsValid))
{
    purchaseTotal += control.TotalCost;
}

I left some details out, but your code isn't really clear on what the UI looks like, or what the business use case is, but it really just boils down to:

Create an abstraction for what each combo of controls represents (e.g. create a new user control)
Create a collection of these controls
Loop and calculate


Compile-time Lagrange polynomials in C++

struct evaluate ⋯

Compile-time computation is much easier today using constexpr!  Rather than going for a pre-2014 TMP library, start by writing normal code and see if there is any reason why it can’t simply be declared as constexpr.  Since it is a pure math function, it really should be.

I really think you can write this with no TMP whatsoever.  Edit: Thanks papagaga for doing so!


Shell command to output all plugins that exist across multiple wordpress installations

If plugins only contain directories, list every unique entry in plugins:

shopt -s globstar
\ls -- **/wp-content/plugins |sort -u

Otherwise, include the final targets in the glob, plus a trailing slash to limit globbing to directories.

That will yield paths relative to ., with trailing slash like siteA/wp-content/plugins/anotherplugin/.  We clean it up with basename (shorter, easier) or awk (faster if there are very many results EDIT: nope, awk is slower in spite of the algorithmic efficiency).

The backslash ignores aliases, just in case an aliased ls would mess up the output.

shopt -s globstar

# probably easier to remember
\ls -d -- **/wp-content/plugins/*/ |xargs -n1 basename -- |sort -u

# slower, fancier
\ls -d -- **/wp-content/plugins/*/ |awk -F/ '!u[$(NF-1)]++ { print $(NF-1) }'


Your naming is funny and all but quite counter-productive - names primary goal is to explain what the code does, not to give a lol moment (I know, boring).

  The atomic sub calls for the definition of the cards names

then call it DefineCards

  The lime sub basically restarts everything

then call it Restart

  The versive sub actually draws cards

then call it DrawCards


fetch() with status code checking and re-routing

I don't see many example for status code checking

I think this way of thinking is a remnant of jQuery.ajax where anything not 2xx rejects the promise. On the other hand, fetch makes a request, and returns an object that represents the response. It's up to you and your app to decide what's a "correct" response from a "wrong" response.

Coming from an Angular background, the task of capturing 403s and doing redirects is the job of an HTTP interceptor service and not your component. This way, your component is not aware of this logic (it simply makes requests) and the behavior is applied globally on all your API calls. But since React doesn't have the same service structure, we'll make do with wrapping functions.

So ideally, what your component should only ever contain is:

someWrappedVersionOfFetch(...)
  .then(response => response.json())
  .then(data => {
    this.setState({
      data: data,
      loaded: true,
      isModalActive: false,
      selectedElement: null,
      selectedId: null,
    }))
  })

Then the wrapped fetch would be like:

export const someWrappedVersionOfFetch = (...args) => {
  return fetch(...args)
    .then(response => {

      if (response.status !== 200) {
        // Update your history and reject the promise
        history.pushState( APP_LOGIN_PATH )
        return Promise.reject(response)
      } else {
        // Just pass response through.
        return Promise.resolve(response)
      }
    })
}

The above answers your first question. For your second question, you could do it like the second snippet. You put the conditional on the first then, have it conditionally return a resolved or rejected promise. Then just chain the one with setState after it.


Although the description claims that most C++ types are supported, I see only int and two kinds of string.  The std::hash class is specialized for quite a few more types than that:

template<> struct hash<bool>;
template<> struct hash<char>;
template<> struct hash<signed char>;
template<> struct hash<unsigned char>;
template<> struct hash<char16_t>;
template<> struct hash<char32_t>;
template<> struct hash<wchar_t>;
template<> struct hash<short>;
template<> struct hash<unsigned short>;
template<> struct hash<int>;
template<> struct hash<unsigned int>;
template<> struct hash<long>;
template<> struct hash<long long>;
template<> struct hash<unsigned long>;
template<> struct hash<unsigned long long>;
template<> struct hash<float>;
template<> struct hash<double>;
template<> struct hash<long double>;
template< class T > struct hash<T*>;

In addition, the std::string hash is very collision-prone, as it uses only the length of the string (and the char* version doesn't even use std::strlen() - are you intending to even reinvent that wheel?).

std::size_t is missing its necessary include (usually <cstdlib>) and is consistently misspelt.

We need to include <stdexcept> for std::out_of_range and std::invalid_argument.

The compiler-generated copy constructor won't do what we want with hash_entries or filled_positions - that's dangerous, and will lead to multiple objects believing they own the pointers, and double deletion.

cbegin() and cend() functions ought to be usable on a const hash_map (and begin() and end() ought to be overloaded suitably, too).  Other const methods are lacking (such as find()) which make const maps much less useful than they ought to be.


1. Missing GCD

You didn't give the code for your gcd function, so I'll assume it's something like this:

def gcd(m, n):
   """Return the greatest common divisor of positive integers m and n."""
   while n:
       m, n = n, m % n
   return m

2. Decomposition: primitive Pythagorean triples

You're having trouble finding the error here because your program consists of a single block of code. You have to run all of it in order to run any of it. It would make your program easier to debug if you split it up into functions with straightforward inputs and outputs, that can be tested individually. This technique is known as functional decomposition.

The first bit of functionality to pull out is the computation of the primitive Pythagorean triples. It's convenient to write this kind of function in the form of a generator — a function that produces its results one by one using the yield statement.

So, we could start with a function like this:

def f(LIMIT):
    for m in xrange(1, LIMIT):
        for n in xrange(m + 1, LIMIT):
            a = n ** 2 - m ** 2
            b = 2 * m * n
            if (m - n) % 2 == 0 or gcd(m, n) != 1:
                continue
            yield a, b

There are some immediate improvements that can be made:

The function needs a descriptive name and a docstring.
It's conventional to use ALL_CAPITALS only for global constants (see the Python style guide, PEP 8, for this and other recommendations).
It would be make sense to generate all three sides of the triangle (you only use two of them here, but the third one is useful for testing, and it
will come in handy in other Project Euler problems).
The continue statement can be avoided by reversing the sense of the condition.
itertools.combinations can be used to reduce the two nested loops to one.

Here's the improved code:

from itertools import combinations

def primitive_pythagorean_triples(limit):
    """Generate the primitive Pythagorean triples whose shortest side is
    no longer than 2 * limit - 3, together possibly with some other
    primitive Pythagorean triples whose shortest side is longer than
    that.

    """
    for m, n in combinations(xrange(1, limit), 2):
        if (m - n) % 2 and gcd(m, n) == 1:
            a = n ** 2 - m ** 2
            b = 2 * m * n
            c = n ** 2 + m ** 2
            yield a, b, c

The hardest part of doing this was writing the docstring. (a might be as large as (limit - 1) ** 2 - (limit - 2) ** 2 which is 2 * limit - 3.) When it's hard to write a docstring, this is often a hint that the function is poorly specified. In this case, surely it would be more convenient to pass in the actual maximum shortest side?

Let's check that these are really Pythagorean triples:

>>> all(a ** 2 + b ** 2 == c ** 2 for a, b, c in primitive_pythagorean_triples(100))
True

and have a quick look at the output:

>>> list(primitive_pythagorean_triples(8))
[(3, 4, 5), (15, 8, 17), (35, 12, 37), (5, 12, 13), (21, 20, 29), (45, 28, 53),
 (7, 24, 25), (9, 40, 41), (33, 56, 65), (11, 60, 61), (13, 84, 85)]

Does that list include all the primitives triples with shortest side no more than 13? It's hard to tell. It would be easier to read the output if each triple were sorted by side length, so that (15, 8, 17) appears as (8, 15, 17). It would also be convenient to reject triples whose shortest side is too long.

Making these changes gives us a third version of the function:

def primitive_pythagorean_triples(max_side):
    """Generate the primitive Pythagorean triples whose shortest side is
    no longer than max_side.

    """
    for m, n in combinations(xrange(1, max_side // 2 + 3), 2):
        if (m - n) % 2 and gcd(m, n) == 1:
            a = n ** 2 - m ** 2
            b = 2 * m * n
            c = n ** 2 + m ** 2
            if a < b and a <= max_side:
                yield a, b, c
            elif b < a and b <= max_side:
                yield b, a, c

And now we can take the output:

>>> sorted(primitive_pythagorean_triples(13))
[(3, 4, 5), (5, 12, 13), (7, 24, 25), (8, 15, 17), (9, 40, 41), (11, 60, 61),
 (12, 35, 37), (13, 84, 85)]

and compare it to, say, OEIS sequence A020884. This looks good so far, but to be more certain that this is correct, let's write a naïve version of the function (one that would be far too slow to solve the Project Euler problem) and compare the output of the two functions.

from math import hypot

def primitive_pythagorean_triples_slow(max_side):
    for a in xrange(1, max_side + 1):
        for b in xrange(a + 1, (a ** 2 - 1) // 2 + 1):
            c = hypot(a, b)
            if gcd(a, b) == 1 and c == int(c):
                yield a, b, int(c)

>>> sorted(primitive_pythagorean_triples(300)) == sorted(primitive_pythagorean_triples_slow(300))
True

3. Decomposition: all Pythagorean pairs

The next bit of functionality to decompose is the computation of the Pythagorean pairs. Your code looks like this:

pyt = {}
k = 1
while True:
    temp_a = a * k
    temp_b = b * k
    max_pyt = max(temp_a, temp_b)
    min_pyt = min(temp_a, temp_b)
    # I only need the minimum to be smaller than the LIMIT
    # but the maximum can't be larger than 2*LIMIT (check below)
    if min_pyt > LIMIT:
        break
    pyt[min_pyt, max_pyt] = 1
    k += 1

There are lots of small improvements we can make here:

Make it into a function we can test separately.
Write a docstring.
Generate these pairs instead of storing them in a dictionary.
Use itertools.count to simplify the loop.
Choose better names for the variables. For example, what's temporary about temp_a and why is that important? I'd prefer a name like ka to remind us that this variable holds the value k * a.

Here's the improved code:

from itertools import count

def pythagorean_pairs(max_side):
    """Generate pairs of integers (a, b), where a is the short leg and b
    the long leg of a Pythagorean triangle, and where a <= max_side
    and b <= 2 * max_side.

    """
    for a, b, _ in primitive_pythagorean_triples(max_side):
        for k in count(1):
            ka, kb = k * a, k * b
            if ka > max_side or kb > 2 * max_side:
                break
            yield ka, kb

Again, at this point it is useful to have a naïve computation of the same set of pairs, to test the faster version of the code.

def pythagorean_pairs_slow(max_side):
    for a in xrange(1, max_side + 1):
        for b in xrange(a + 1, 2 * max_side + 1):
            c = hypot(a, b)
            if c == int(c):
                yield a, b

>>> sorted(pythagorean_pairs(1000)) == sorted(pythagorean_pairs_slow(1000))
True

4. Decomposition: counting cuboids

Your code for counting the cuboids contains a lot of comments, which is a sign that it's not very clearly written. Let's pull out the body of the loop into a function and see if we can make sense of it:

def count_cuboids(a, b, LIMIT):
    """Given a Pythagorean pair (a, b), return the number of cuboids (p, q, r)
    such that 1 <= p, q, r <= LIMIT and ????

    """
    counter = 0
    temp = b // 2
    if temp >= LIMIT:
        return 0
    elif b < LIMIT:
        counter += (a // 2)
    if temp <= a:
        counter += (a - temp)
        if (a - temp) % 2 == 0:
            counter += 1
    return counter

Now, the problem I have here is that I can't figure out exactly which cuboids this is supposed to count, so I don't know how to write the docstring.

Your comment at the top says:

# 1, 5, 8 | 2, 4, 8 | 3, 3, 8 (when decomposing 6)
# 6, 2, 6 | 6, 3, 5 | 6, 4, 4 (when decomposing 8, although 6, 1, 7 are not
# good, the largest of the 3 needs to be a member of the Pythagorean triplet)

and indeed:

>>> count_cuboids(6, 8, 100)
6

so this suggests that the docstring for count_cuboids might need to be:

"""Given a Pythagorean pair (a, b), return the number of cuboids (p, q, r)
such that 1 <= p, q, r <= LIMIT and
either: p <= q <= r and p + q == a and r == b
    or: p == a and q <= r <= p and q + r == b."""

but then I tried the simplest example:

>>> count_cuboids(3, 4, 100)
2

which doesn't match your specification. According to your specification, there ought to be three possible cuboids here, not two: (1, 2, 4), (3, 1, 3) and (3, 2, 2).

So your code for counting the cuboids does not match your specification. One or both of them is wrong.

5. Conclusion

I don't want to spoil the Project Euler problem, so I'll leave you to take it from here. I'll finish by repeating the key points:

Use functional decomposition to split your code up into parts that you can test separately.
Write docstrings explaining what each function does. If you are having trouble writing concise and clear docstrings, this is a sign that the way you  have decomposed your code was poorly chosen and needs to be reconsidered.
Make use of generators to produce and consume sequences of results without having to store them in intermediate data structures.
When you have a complicated, optimized function, also implement a naïve, straightforward version of the same function that you can use to test it.


Removing whitespace in self-closing node and keeping UTF-8 hex entity values intact?

You can do something like this (using your previously posted question code as demo)

Regex regex = new Regex(@"(?<=\\tag\s?\{)[^\}]+(?=\})");
string xml = escape_string(File.ReadAllText(@"C:\Users\Temp\Desktop\test.xml"), 0);
var xdoc = XDocument.Parse(xml, LoadOptions.PreserveWhitespace);
xdoc.DocumentType.InternalSubset = null;
foreach (var formulaNode in xdoc.Descendants("disp-formula"))
{
    var matches = regex.Matches(formulaNode.Value);
    if (matches.Count == 0)
    continue;

    var id = "deqn" + matches[0].Value;
    if (matches.Count > 1)
    id += "-" + matches[matches.Count - 1].Value;

    formulaNode.Attribute("id").Value = id;
}
xdoc.Save(@"C:\Users\Temp\Desktop\test.xml", SaveOptions.DisableFormatting);
File.WriteAllText(@"C:\Users\Temp\Desktop\test.xml", escape_string(xdoc.ToString(), 1));
}

private static string escape_string(string input_string, int option)
{
    switch (option)
    {
        case 0:
        return input_string.Replace("&", "&amp;");
        case 1:
        var x=input_string.Replace(" />", "/>");
        var y=x.Replace("&amp;", "&");
        var z=y.Replace("\r\n<!DOCTYPE","<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<!DOCTYPE");
        return z;

        default:
        return null;

    }
}

The code xdoc.DocumentType.InternalSubset = null; is to stop the Parse() method to create a extra [] in the dtd declaration and also the xml declaration was getting deleted so I added that to a replace in the method escape_string.

Not sure whether it is faster than your posted method though :)

Code for operating on multiple files in a given path (assuming the xml files inside sub-folder 'xml' are only to be processed)

using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;

namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string path = textBox1.Text;
            var files = Directory.GetDirectories(path, "xml", SearchOption.AllDirectories)
                .SelectMany(d => Directory.GetFiles(d, "*.xml")).ToArray();
            foreach (var file in files)
            {
                try
                {
                    Regex regex = new Regex(@"(?<=\\tag\s?\{)[^\}]+(?=\})");
                    string xml = escape_string(File.ReadAllText(file), 0);
                    var xdoc = XDocument.Parse(xml, LoadOptions.PreserveWhitespace);
                    xdoc.DocumentType.InternalSubset = null;
                    foreach (var formulaNode in xdoc.Descendants("disp-formula"))
                    {
                        var matches = regex.Matches(formulaNode.Value);
                        if (matches.Count == 0)
                            continue;

                        var id = "deqn" + matches[0].Value;
                        if (matches.Count > 1)
                            id += "-" + matches[matches.Count - 1].Value;

                        if (formulaNode.Attribute("id") != null)
                        {
                            formulaNode.Attribute("id").Value = id;
                        }
                        formulaNode.SetAttributeValue("id", id);

                    }
                    xdoc.Save(file, SaveOptions.DisableFormatting);
                    File.WriteAllText(file, escape_string(xdoc.ToString(), 1));
                }
                catch (Exception ex)
                {
                    string filePath = path + @"\Error.log";
                    using (StreamWriter writer = new StreamWriter(filePath, true))
                    {
                        writer.WriteLine(file + ":\r\n---------------------------------------------------\r\n" + ex.Message);
                    }
                }
            }

            MessageBox.Show("Process Complete!");

        }

        private static string escape_string(string input_string, int option)
        {
            switch (option)
            {
                case 0:
                    return input_string.Replace("&", "&amp;");
                case 1:
                    var x = input_string.Replace(" />", "/>");
                    var y = x.Replace("&amp;", "&");
                    var z = y.Replace("\r\n<!DOCTYPE", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<!DOCTYPE");
                    return z;

                default:
                    return null;

            }
        }
    }
}


The regex silently fails on inputs that don't have length a multiple of 4; i.e. no results are returned. Things that fail silently are incredibly hard to debug. It's easy to imagine trying to figure out why no rows are being inserted for the input

jvqbjqbxvvlxlcwkuivasoeljaxamrthcecbudnxvqdboxroudfvrwoureqisaldcduhauoqtxdclcw

until you realise that it only has 79 characters.

You would want to measure the performance, but I would suggest not using a regex and writing a simple method, like so

private static IEnumerable<string> ToBuckets(string input)
{
    const int Length = 4;
    for (var i = 0; i < input.Length; i += Length)
    {
        yield return input.Substring(i, Length);
    }
}

We should add input validation to make it easier to find out exactly what went wrong.

if (input == null)
{
    throw new ArgumentNullException("input");
}

if (input.Length % Length != 0)
{
    throw new ArgumentException(string.Format("Argument length must be a multiple of {0}", Length));
}

I made a microbenchmark comparing the two methods that you can find here. For 100,000 calls, the regex solution takes ~2.5s compared to ~0.2s for this version.

It looks like you're using exceptions for control flow with the FormatException. I would suggest making the try-catch more specific, both in the code that is executed within the try, and in the exceptions that you're catching.

If we split out the OutputSizesBuffer parts to its own method, we end up with something like this, which I find a bit cleaner (illustrative code only)

var buckets = ToBuckets(Row.Sizes).Select(bucket => bucket.Trim()).ToArray();
for (int index = 0; index < buckets.Length; index++)
{
    // Don't output a row for empty buckets.
    if (bucket.Length == 0)
    {
        continue;
    }

    if (bucket.Contains(' '))
    {
        // Size codes don't contain whitespace; something went really wrong if that's the case.
        FireError(string.Format(Resources.BucketContainsWhiteSpace, bucket));
        return;
    }

    try
    {
        AddRow(index + 1, bucket);
    }
    catch (SomeSpecificException e)
    {
        FireError(e.Message);
        return;
    }
}


Node2D and Node3D classes implemented using a shared decorator

One thing that I don't like, and doesn't seem to make sense, is that I had to move the list of valid keys from the validator to the parent class itself

That's not only something to dislike -- it is actually broken. If you do this...

n3 = Node3D()
n2 = Node2D()
n3.coords = {'x':1,'y':2,'z':3}

...you will get Exception because the second line has caused Node.valid_keys to be overwritten. To fix that, you could eliminate all three __new__ methods and instead define the subclasses like this:

class Node3D(Node):
    valid_keys ='x','y','z'

class Node2D(Node):
    valid_keys ='x','y'

However, the whole approach is not very good because one can still do for example this:

>>> node = Node2D()
>>> node.coords = {'y': 2, 'x': 1}
>>> node.z = 3
>>> node.coords
{'y': 2, 'x': 1, 'z': 3}

Using a namedtuple as discussed in comments is a better idea.


Localisation
It's fine to localise your user-facing strings (e.g. print('Die Buchstaben in diesem Wort bilden ein Palindrom'), but it is not advisable to write the code itself in a language other than English. For better or worse, English is the de-facto language of programming. Thus, buchstabe would be better as letter.
For-loop
The loop is not necessary:
    name_reversed = name[::-1]

name is a string, which is itself a sequence of one-character strings. Applying a slice, as is done here, reverses the sequence but does not change the type: the output of the expression is still a string.


Word/expression list frequency distribution

One obvious improvement: you call elif k in sample_text.split(): inside the loop over sorted(vocabulary_dict), so this operation happens multiple times. Instead, you could create a set (which has more efficient membership tests) outside the loop, so it only happens once:

samples = set(sample_text.split())
for k in sorted(vocabulary_dict):
    ...
    elif k in samples:
        ...

Also, does it really matter if you iterate over vocabulary_dict in sorted order?


Date formatters, lazily instantiated once

This isn't the way to compare two dates...it violates one of my commandments.  We can & should use NSCalendar's compareDate method:

extension NSDate {
    func isSameDayAs(date: NSDate) -> Bool {
        let calendar = NSCalendar.currentCalendar()
        let dif = calendar.compareDate(self, toDate: date, toUnitGranularity: .DayCalendarUnit)
        return dif = .OrderedSame
    }
}

Moreover, your date formatter methods don't have any business in the view controller.  These make more sense also as NSDate extension methods.  However, creating NSDateFormatters is actually a pretty expensive operation.  We don't want to do it more often than necessary.  So, let's make a struct to handle one formatter per style we want:

extension NSDate {
    private struct Formatters {
        static let timeFormatter = { (Void) -> NSDateFormatter in
            let formatter = NSDateFormatter()
            formatter.dateFormat = "hh:mm"
            return formatter
        }()

        static let yearMonthDayFormatter = { (Void) -> NSDateFormatter in
            let formatter = NSDateFormatter()
            formatter.dateFormat = "yyyy/MM/dd"
            return formatter
        }()
    }

    var timeString: String {
        get {
            return Formatters.timeFormatter.stringFromDate(self)
        }
    }

    var yearMonthDayString: String {
        get {
            return Formatters.yearMonthDayFormatter.stringFromDate(self)
        }
    }
}

Importantly, using this approach makes unit testing (which you should definitely be doing) quite easy.  And, we've put code in places where it makes sense.


Read text and return lists of different parts of speech

For some more typing up front, you can make the parsing slightly easier.

This uses the fact that two variables can point to the same (even mutable) object:

def find_pos(tokens):
    tagged = nltk.pos_tag(tokens)
    # Define all lists (just like before), here with tuple unpacking:
    common_nouns, verbs, adjectives, pronouns, adverbs, proper_nouns, conjunctions, prepositions, interjections, modals, tagged_others, other = [
        [] for _ in range(12)]

    # Define a dictionary mapping from the positions to the lists:
    d = {'NN': common_nouns, 'NNS': common_nouns,
         'VB': verbs, 'VBD': verbs, 'VBG': verbs, 'VBN': verbs, 'VBP': verbs, 'VBZ': verbs,
         ...}

    # Use it like this:
    for token in tagged:
        d[token[1]].append(token)
    ...

Alternatively, do the calculations afterwards:

from collections import defaultdict

def find_pos(tokens):
    tagged = nltk.pos_tag(tokens)

    d = defaultdict(list)
    for token in tagged:
        d[token[1]].append(token)

    def t(*pos):
        return sum([d[x] for x in pos], [])

    return [t('NN', 'NNS', 'NNP', 'NNPS'),
            t('NN', 'NNS'),
            t('VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ'),
            ...]


I was never a fan of a "fake first element"-approach. And here is why:

Begin...
Enter 1 to delete, 2 to insert, 3 to locate, 4 to print_all, or 0 to quit: 2
Enter value: 17
Inserting 17...
Enter 1 to delete, 2 to insert, 3 to locate, 4 to print_all, or 0 to quit: 3
Enter value: 0
Locating 0...
Value 0 in list!

So, if you're going to do that approach, be careful not to "locate" it or do anything else with it.

My second complaint is that you traverse your list using recursions. This is both slow and memory consuming on large lists. Just imagine a list with 1000 elements. Your insert_node will have 1000 recursive calls, each with its variables node and value on stack, which takes time to create there, and - when done - remove from there. I suggest you do all the list traversing using for or while loops. For example:

int locate_node(struct Link_Data *node, int value) {

    node = node->next; /* skipping the fake first node */

    while (node && node->value != value) node = node->next;

    if (node) {
        printf ("Value %d in the list!\n", value);
        return 1;
    } else {
        printf ("Value %d not in the list!\n", value);
        return 0;
    }
}

Another thing I have added here is the return value. You should either have void functions or make their return values meaningful. I've used 1 as "there is an element in the list" and 0 as "there is no such element in the list".

I'd also suggest removing output from such functions. They should get the job done (delete, insert, locate) and return a meaningful value, while any user output should be done outside of them.

Last, you create a doubly-linked list, but you don't seem to use prev anywhere except when deleting (which can be done without it), and even there you do not use it properly:

Begin...
Enter 1 to delete, 2 to insert, 3 to locate, 4 to print_all, or 0 to quit: 2
Enter value: 17
Inserting 17...
Enter 1 to delete, 2 to insert, 3 to locate, 4 to print_all, or 0 to quit: 2
Enter value: 19
Inserting 19...
Enter 1 to delete, 2 to insert, 3 to locate, 4 to print_all, or 0 to quit: 2
Enter value: 23
Inserting 23...
Enter 1 to delete, 2 to insert, 3 to locate, 4 to print_all, or 0 to quit: 1
Enter value: 19
Deleting 19...
Enter 1 to delete, 2 to insert, 3 to locate, 4 to print_all, or 0 to quit: 1
Enter value: 23
Deleting 23...
Enter 1 to delete, 2 to insert, 3 to locate, 4 to print_all, or 0 to quit: 3
Segmentation fault

The problem is that you do not fix your prev field of a node after the deleted one, so when you delete two consecutive nodes, the second delete works with a prev that was already freed.

I suggest you make a completely new, recursion-less program, using an ordinary singly-linked list, and without a fake header, and then open a new review request. This seems like a decent tutorial for the lists in C.

One final comment: a print_list function (and the option) would really make it easier for you to test your program.


Rock, Paper, Scissors game made in python

Move more of your code out of the function. Make a find_winner function.
You don't need to add _rps to the end of every variable name. It only makes it harder to read the code.
PEP 8 doesn't say which string delimiter to use, but says to stick to one. I use ', you may prefer ".
You can use random.choice rather than random.randint to select from a list.
There is a bug in your code. I suggest you keep using string literals to a minimum to prevent this.

player_rps == 'sicssors' and com_rps == "paper"

You can simplify your yn check by using in.

This in all got me:

WIN_VALUES = {
    'rock': 'scissors',
    'paper': 'rock',
    'scissors': 'paper'
}

def find_winner(choice1, choice2):
    if choice1 == choice2:
        return 0
    if WIN_VALUES[choice1] == choice2:
        return 1
    if WIN_VALUES[choice2] == choice1:
        return 2

def rock_paper_scissors(name):
    play = True
    while play:
        player = input('Rock, Paper, or Scissors: ').lower()
        com = random.choice(list(WIN_VALUES))
        print(com)

        winner = find_winner(com, player)
        if winner == 0:
            print('Tie')
        elif winner == 1:
            print('Chatter Bot Wins!')
        elif winner == 2:
            print(f'{name} Wins!')
        else:
            print(f'Invalid input {player}')

        yn = input('Do you want to play again. Y/N: ').lower()
        if yn in ('n', 'no'):
            play = False


Akka streams: Bidirectional flow that completes the stage when one side is completed

Maybe talk a bit about the "tricks to prevent object allocation."

Based on the current examples in the Akka docs, the shape should be override val. My understanding is that the accepted pattern when designing traits is to def your contract, and implement with val wherever possible.

As they say - naming is hard and often a matter of taste. The pattern reminds me of a fuse, or breaker - but fuse has a particular meaning in Akka, so that's probably not a great choice. Maybe BreakerFlow?


Stack implementation using a growing array

Your code looks very good, except for one bug in the constructor:

public Stack(int capacity)

You should really do a bounds check on capacity. It should not be allowed to be negative, of course.
But also, if capacity is zero, you will get an exception when you call Push. It will try to resize to count * 2, which is zero.

_values.Length << 1

Code should be clear. If you mean to multiply by 2, say * 2, not << 1

I would really implement a GetEnumerator() method, so you can iterate over the Stack items, even if you're not going to implement any collection interface. Implementing IEnumerable<T> is handy if you want to use LINQ.


No, it's not very efficient...  There are operations you typically want to minimize if you want a performing solution, and memory allocation is one of the top ones.  But your merge_arrays function is creating a new list every time it gets called, which is not a good thing.  An efficient implementation of mergesort will do the sorting in-place (with a copy of the list before if the original has to be kept unchanged), and will reuse the merge buffer for all merging operations.

def mergesort(array, left=0, right=None):
    if right is None:
        right = len(array)
    if right - left <= 1:
        return

    mid = left + (right - left) // 2
    mergesort(array, left, mid)
    mergesort(array, mid, right)
    merge(array, left, mid, right)

def merge(array, left, mid, right):
    buffer = array[left:mid]
    read_left = 0
    read_right = mid
    write = left
    while read_left < len(buffer) and read_right < right:
        if array[read_right] < buffer[read_left]:
            array[write] = array[read_right]
            read_right += 1
        else:
            array[write] = buffer[read_left]
            read_left += 1
        write += 1
    while read_left < len(buffer):
        array[write] = buffer[read_left]
        read_left += 1
        write += 1

Notice how the left part is the only one copied out into the buffer, as that is all that is needed.  Notice also the loop structure, which is substantially different from yours.  It is a matter of taste, but the single while loop for the merging, with an extra loop to copy items that could be left in the buffer (notice that any item left on the right side is already in the right place) seems to be preferred in most production implementations I've seen, and I find it more clear, but YMMV.

The above code is creating a new buffer for every merge operation, which makes the code a little simpler.  A possible way of reusing a buffer is to have it be a static variable of merge.  Static variables are a little funny in Python, but it could look something like this:

def merge(array, left, mid, right):
    left_len = mid - left
    if len(merge.buffer) < left_len:
        merge.buffer.extend([None] * (len(buffer) - left_len))
    for write, read in enumerate(range(left, mid)):
        merge.buffer[write] = array[read]
    read_left = 0
    read_right = mid
    write = left
    while read_left < left_len and read_right < right:
        if array[read_right] < buffer[read_left]:
            array[write] = array[read_right]
            read_right += 1
        else:
            array[write] = buffer[read_left]
            read_left += 1
        write += 1
    while read_left < len(buffer):
        array[write] = buffer[read_left]
        read_left += 1
        write += 1
merge.buffer = []

I wouldn't be surprised though if, this being Python, the explicit looping took longer than the previous version.  But this would be preferred in a lower level language.

Another possible optimization is to scan the left half of the array prior to the copying into the buffer, to avoid moving around items that are already in the right place:

def merge(array, left, mid, right):
    while array[left] < array[mid]:
        left += 1
    ...

and the rest of the code would stay the same.


Shortest path via two intermediate points

The key reasons for the poor performance are:

Representing queue as a list. This is slow because popping an item off the beginning of a list takes time proportional to the length of the list.

What you need here is a collections.deque.
Computing shortest distances many times over. The shortest distance from a to clinique is computed again for every clinique2, even though it will be the same each time. Similarly, the shortest distance from clinique2 to b is computed again for every clinique.

What you need here is to compute these distances once and remember them.

If the number of cliniques is large compared with the number of cities, you should use the Floyd–Warshall algorithm to compute distances between all pairs of cities in one go (instead of using Dijkstra's algorithm many times, as in the posted code).

If I were implementing this, I'd use scipy.sparse.csgraph.floyd_warshall and write:

import numpy as np
from scipy.sparse.csgraph import floyd_warshall

def shortest_distance_via(graph, a, b, c1, c2):
    """Return the shortest distance in graph from a to b via C1 and C2 (in
    that order), where C1 and C2 are nodes in c1 and c2 respectively.

    Arguments:
    graph -- NxN array of distances between nodes.
    a, b -- nodes in the graph.
    c1, c2 -- arrays of nodes in the graph.

    """
    d = floyd_warshall(graph)
    ab = d[a, c1, np.newaxis] + d[np.meshgrid(c1, c2)] + d[np.newaxis, c2, b]
    return ab.min()


Don't use wildcard imports

PEP8 advises against this:

from game import *

Rewrite like this:

import math
import itertools

from game import Game

Use elif for mutually exclusive ifs

These if statements cannot all be true:

if action == "left":
    b = Game.left(b)
if action == "right":
    b = Game.right(b)
if action == "up":
    b = Game.up(b)
if action == "down":
    b = Game.down(b)

But they will all be evaluated, even if action is "left",
it will be checked against "right", "up", "down", pointlessly.

if action == "left":
    b = Game.left(b)
elif action == "right":
    b = Game.right(b)
elif action == "up":
    b = Game.up(b)
elif action == "down":
    b = Game.down(b)

Avoid shadowing variables

In this code, the parameter b of aimove is going to be shadowed by the parameters in fitness, and the many other methods where you reuse this name:

def aimove(b):
    # ...

    def fitness(b):
        # ...

    def search(b, d, move=False):
        # ...

This can be confusing and can lead to errors.

Dealing with long lines

This is just a small tip.
I don't like using \ for breaking new lines like this:

alpha += .9 * search(c1, d - 1, True) / len(zeros) + \
         .1 * search(c2, d - 1, True) / len(zeros)

I prefer to put the expression within parentheses,
which is another way of breaking a long line, like this:

alpha += (.9 * search(c1, d - 1, True) / len(zeros) +
          .1 * search(c2, d - 1, True) / len(zeros))

Easier way to make deep copies

c1 = [[x for x in row] for row in b]
c2 = [[x for x in row] for row in b]

An easier way:

from copy import deepcopy

c1 = deepcopy(b)
c2 = deepcopy(b)

Other simplifications

This expressions can be written simpler:

(b2[3][0] != m) * abs(b2[3][0] - m)

When b2[3][0] is not equal to m,
the expression becomes:

1 * abs(b2[3][0] - m)
abs(b2[3][0] - m)

When b2[3][0] is equal to m,
the expression becomes:

0 * abs(b2[3][0] - m)
0 * abs(m - m)
0 * abs(0)
0 * 0

Since the multiplication with (b2[3][0] != m) doesn't change the outcome,
you can simply write:

abs(b2[3][0] - m)

Game shouldn't be a class, in its present form

The posted code doesn't really use a Game instance.
It just takes the initial board out of the Game instance it receives,
but that's all the data a Game instance contains,
and it's never used again.
All the calls involving Game are static Game.some_function calls.
This is not a normal practice, and confusing.

As such, it would be better to move all the functions of Game to package scope,
do import game,
and call the methods like game.actions, game.over, and so on.

You point out in a comment that you like to use a class for logical grouping purposes. But classes are not the only thing that can do that, packages can do that too, in fact it's a very good way of using packages.

However, the option is probably to keep the Game class,
but make its methods non-static,
and work with instances, instead of calling static methods.
Instead of manipulating a board directly,
let the Game class contain the board,
and hide within the details of all the operations on the board.
It will be good encapsulation.
For example,
the static call Game.over(b) should be replaced with the instance method call game.over(), with no more board parameter.


Yours is simpler and therefore better.  However, I would simplify it further as:

$('.success').on('mouseover', function() {
    $(this).removeClass('success').addClass('delete');
});

Is shouldn't matter much whether you call .addClass() first or .removeClass() first.


Learning Javascript OOP with a Collapsing Item Class

This seems over-engineered. If really all you need is this.content.classList.toggle("bb-collapsed"); then I would simply go for
class Collapsible {
  constructor(link, content) {
    this.link = link;
    this.content = content;
    this.content.classList.toggle("bb-collapsed");
    this.link.addEventListener("click", e => content.classList.toggle("bb-collapsed"));
  }
}

And from there, there really isn't much of a point in having a class. You could do that straight in your checkForCollapsibles.
Something like this
function wireCollapsibles() {
  const links = document.querySelectorAll(".bb-collapsible");
  const contents = document.querySelectorAll(".bb-collapsible-content");

  links.forEach((link, index) => {
    new bb_Collapsible(collapsibleLinks[index], collapsibleContents[index]);
    link.addEventListener(e => contents[i].classList.toggle("bb-collapsed"));
  });
}

Note that I drop the console.log thing, ideally you dont have log statements in your production code.


Printing some metrics from a Windows machine

Some general pointers:

Refrain from using tmp as variable names. raw_output will do the job better.

Working with arrays as object replacement (x[0] is the caption, x[1] is the type...) is cumbersome, unreadable, and difficult to maintain. I suggest moving to Hash:

tmp.map(&:split).select { |_, drivetype, _, _| drivetype.to_i == 3 }.map do |caption, drivetype, freespace, size|
  {
    caption: caption,
    drivetype: drivetype,
    freespace: (freespace.to_f/bytes_to_gbytes).round(2),
    size: (size.to_f/bytes_to_gbytes).round(2),
    usedspace: ((size.to_f - freespace.to_f)/bytes_to_gbytes).round(2)
  }
end

This code returns an array of hashes, one for each disk with drivetype '3'. The variables (caption, drivetype, etc...) are created when ruby translates the array to the list of variables declared, so actually the tmp.map(&:split).map { |caption, drivetype, freespace, size| ... } is like saying:

tmp.map do |disk|
  disk = disk.split
  caption = data[0]
  drivetype = data[1]
  freespace = data[2]
  size = data[3]
  ...
end


Find the number of times that the difference of array values are equal to the number

I think you should look at the problem in a different way and come up with a simpler solution.

Try thinking at having a set of elements. What you want to know is if there is any pair of elements such that a - b = x.

You're given x, so for a given value of a in your set you should check whether it also contains x + a.

Your implementation should first move the content of the list to a Set. Then you have to iterate through the set and for each element a check if the set contains also x + a. If it is true then you should add (a,b) to your solution.

In your example, x = 11. If you consider a = 10 you'll check if it contains 11 + 10 = 21. It does so you can the pair (21,10) is a valid solution. Conversely, when you consider a = 21, you obtain b = 32, which is not part of the set and therefore you have to discard that pair.

int checkDifferences(Set<Integer> numbers, int difference) {
    int occurrences = 0;
    for (Integer number : numbers) {
        if (numbers.contains(number + difference)) {
            occurrences++;
        }
    }
    return occurrences;
}


Printing random lines from a file in Python

First, you should always close your files. Or, use the with keyword, which takes care of this for you.

Then, the 'r' mode is already the default mode for opening a file. Also, consider storing your words in a set, instead of a list (gets rid of duplicate words, which might be wanted, or not if you want a higher probability for some words).

You should consider using random.choice to get a random element from an iterable (actually an iterable with len defined).

I would also separate the file reading into a separate method. and make it more explicit what the prompt actually means (the number of words to generate).

I would use str.join and give it a generator expression rather than multiple calls to print.

import random

def get_words(file_name):
    with open(filename) as word_file:
        return list(set(word.strip() for word in word_file))

def random_words(n, words)
    return " ".join(random.choice(words) for _ in range(n))

def main(file_name):
    words = get_words(file_name)
    while True:
        n = int(raw_input("Number of words:"))
        print(random_words(n, words))

if __name__ == "__main__":
    file_name = "20k.txt"
    main(file_name)


The code's pretty straightforward, but it could still be simplified a bit:

There's no reason to have multiple levels of while loop; you already run your write() function in an inner loop until it's time to exit, so the outer loop only ever gets executed once.
The code to append to the file is duplicated.
The file deletion behavior is very strange and seems like a bug -- if the file exists, you delete it, but you do that after every line, making it impossible to write a multi-line file (but only in the case where the file existed when you started the editor).  Seems like you probably meant to only delete it once but forgot to update your files list?
The write() function doesn't necessarily always write something; sometimes it exits (which is generally considered bad form since it makes reuse and testing difficult).  It also has the extra responsibility of deleting the existing file, which is why that deletion is maybe happening more often than you meant it to.  Separating the setup from the core editing loop would make this much easier to reason about.
cprint doesn't return a value, so assigning it to title and controls (which you don't use anyway) is confusing.
When an if block breaks the control flow (e.g. by exit() or return or break) it's not necessary to have everything else under an else.  In some cases the code may be more clear with a redundant else (e.g. when the two branches are similar in length and/or when you want to make it more obvious that they're mutually exclusive), but when the bulk of your code is indented unnecessarily it tends to make it harder to follow rather than easier.
It's generally better to use file handles as context managers (with open ...).  It makes it impossible to forget to close the file, and it makes it very obvious what you're doing while the file is open.
This is more of a note on the UX than the code, but I suggest (A) telling the user when you're deleting their file (and only doing it on startup rather than after every autosave) and (B) not having so many blank/repeated lines in the interface (it makes it harder to see what you've already entered).

Below is the result of applying the above notes -- now there are two functions (init and run), with one in charge of everything that happens up front, and the other in charge of everything that happens on each subsequent input.

import os
from termcolor import cprint

def init() -> str:
    """
    Start the editor by prompting for a filename and printing
    usage information.  If the file already exists, remove it.
    Returns the filename.
    """
    filename = input("File name: ")
    if filename in os.listdir():
        print("Deleting existing file to give you a blank slate.")
        os.remove(filename)
    cprint("Ganesha Editor v1.0", "green")
    cprint("Type $exit to exit text editor. It autosaves.", "blue")
    print("Compose Something Below:")
    return filename

def run(filename: str) -> bool:
    """
    Prompts for input and writes it to the file.
    Returns True as long as it's still running,
    returns False when it's time to exit.
    """
    text = input()
    if text == "$exit":
        return False
    with open(filename, "a") as autosave:
        autosave.write(text)
        autosave.write("\n")
    return True

if __name__ == "__main__":
    filename = init()
    while run(filename):
        pass


Standard deviation of hourly temperatures of 2 days

You are doing fine, other than a few simple nitpicks.

You are not using read-nth-line (which is a crazy thing to do anyway), please drop it.

You should fix your indentation, it would make your code much easier to read.

You probably want to divide by N-1, not N, in standard-dev and you probably want to simplify the code there by dividing by N-1 instead of multiplying by the reciprocal; also expt is relatively expensive, so, if you were not i/o bound anyway, you might want to replace it with multiplication.

Function split-in-half should probably return multiple values instead of a list.

Global variable l1 should be local to process-file.

Function parse-string-to-float should probably be called parse-string-to-floats (it read the whole list).


Return true from enumerable that calls function unless that function ever returns false

Usually positive conditions are much easier to understand than negative ones and even easier then two negatives in the same expression. You can flip it and get rid of both negations by using All instead:

return processNames.All(process => launch(process));

Now that the nagations are gone you can further shorten this by removing the lambda:

return processNames.All(launch);

This is possible because the launch method signature matches the delegate  Func<string, bool> required by All.


Adding elements of 2 linked list in reverse order

Here are a list of improvements:

Use ECMAScript features and syntax
Create own implementation of BigInt
Don't use strings !
Create functions to regroup similar code and reduce code duplication

Detailed Explanation:

Generates a ListNode from a given array (array should already be reversed).

generateListNode = (list) => {
 const [ele] = list;
 //create the sentinel (starting point of the node list)
 const sentinel = new ListNode(ele);
 let current = sentinel;
 for(let i = 1; i < list.length; i++){
   //update the next with the new list node
   //set the current to the new next
   current = current.next = new ListNode(list[i]);
 }
 return sentinel;
}

Convert a ListNode to an Array

const convertToValueList = (list) => {
  const res = [];
  //as long as the value "list" is not null it'll continue the loop
  //push the list.val to the result array
  do { res.push(list.val); } while(list = list.next);
  return res;
}

addTwoNumbers has it's own implementation of BigInt

const addTwoNumbers = function(l1, l2) {

  //Convert the ListNode to arrays
  const l1Values = convertToValueList(l1);
  const l2Values = convertToValueList(l2);

  //find the longest of either list
  const len = Math.max(l1Values.length, l2Values.length);

  //when adding a column, value should not exceed 9, otherwise it'll be set to the remainder
  //i.e.: 10 -> 1, 23 -> 2, 30 -> 3
  let remainder = 0;
  //final result in reverse
  const sum = [];
  for (let i = 0; i < len; i++) {
    //add the sum of each value of the list at the "i" position
    //if the value does not exist (i.e.: undefined) use default 0
    //add the remainder if it exists
    const tempSum = (l1Values[i] || 0) + (l2Values[i] || 0) + remainder;
    //update the remainder (any value under 10 is set to 0 because of Math.floor)
    remainder = Math.max(Math.floor(tempSum/10), 0);
    //add the value (modulo 10 so only numbers 0 - 9 are added)
    sum.push(tempSum % 10);
  }

  console.log(sum);
  //generate the list node and return final result
  return generateListNode(sum);
};

Working Example:

class ListNode {
  constructor(val){
    this.val = val;
    this.next = null;
  }
}

generateListNode = (list) => {
  const [ele] = list;
  const sentinel = new ListNode(ele);
  let current = sentinel;
  for(let i = 1; i < list.length; i++){
    current = current.next = new ListNode(list[i]);
  }
  return sentinel;
}

const list1 = generateListNode([2, 4, 3]);
const list2 = generateListNode([5, 6, 4]);

const convertToValueList = (list) => {
  const res = [];
  do { res.push(list.val); } while(list = list.next);
  return res;
}

const addTwoNumbers = function(l1, l2) {

  const l1Values = convertToValueList(l1);
  const l2Values = convertToValueList(l2);

  const len = Math.max(l1Values.length, l2Values.length);

  let remainder = 0;
  const sum = [];
  for(let i = 0; i < len; i++){
     const tempSum = (l1Values[i] || 0) + (l2Values[i] || 0) + remainder;
remainder = Math.floor(tempSum/10);
     sum.push(tempSum % 10);
  }

  console.log(sum);
  return generateListNode(sum);
};

const res = addTwoNumbers(list1, list2);
console.log(res);

Additional:

The best case scenario is if you have the option to add methods to ListNode.

class BodyNode {
  constructor(val){
    this.val = val;
    this.next = null;
  }
}

class ListNode extends BodyNode {

  static FromArray(list){
     if(list.length === 0) throw new Error("Array cannot be of length 0");
     const clone = list.slice();
     const instance = new ListNode(clone.shift());
     while(clone.length > 0){
       instance.add(clone.shift());
     }
     return instance;
  }

  constructor(val){
    super(val);
    this.last = this;
  }

  add(val){
    this.last = this.last.next = new BodyNode(val);
  }

  toArray(){
    const res = [];
    let current = this;
    do { res.push(current.val); } while(current = current.next);
    return res;
  }

}

const list1 = ListNode.FromArray([2, 4, 3]);
const list2 = ListNode.FromArray([5, 6, 4]);

const addTwoNumbers = function(l1, l2) {

  const l1Arr = l1.toArray();
  const l2Arr = l2.toArray();

  const len = Math.max(l1Arr.length, l2Arr.length);

  let remainder = 0;
  const sum = [];
  for(let i = 0; i < len; i++){
     const tempSum = (l1Arr[i] || 0) + (l2Arr[i] || 0) + remainder;
     remainder = Math.floor(tempSum/10);
     sum.push(tempSum % 10);
  }

  console.log(sum);
  return ListNode.FromArray(sum);
};

const res = addTwoNumbers(list1, list2);
console.log(res);


Just a quick glance.
But:

std::cout << XXXX
while(!(std::cin >> age))
{
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "Invalid input.  Please enter a number: ";
}

That could be a function.
This would reduce code and make the application easier to read.

Remember code should be DRY.

The formula is the same here:

if ('m' == gender)
{
    bmr = 66 + (6.3 * weight) + (12.9 * height) - (6.8 * age);
}
else if ('f' == gender)
{
    bmr = 655 + (4.3 * weight) + (4.7 * height) - (4.7 * age);
}

So why not pick the constants from some indexed value:

bmr = bmrconst[gender].base
      + (bmrconst[gender].weight * weight)
      + (bmrconst[gender].height * height)
      - (bmrconst[gender].age    * age);

but pick better names than I did.

Don't like magic numbers (230).

const double numBars = bmr / 230;

Use a constant that has a name that makes this have meaning.

Don't declare all your variables at the top:

double weight = 0;
double height = 0;
double age = 0;
double bmr = 0;
char gender = 'm';

Declare them as you need them as close to the point of first use as possible.


Good stuff!

I definitely see a few improvements you could make here:

Prefer using std::function to function pointers

There is a tiny bit more overhead invovled, but the extra flexibility is well worth it.

using FactoryFunc = std::function<std::unique_ptr<Base>(Args...)>;

Another advantage is that it lets you get rid of constructDerived entirely, and replace it with a nice lambda in registerClass.

Nitpick: registerClass should invoke registerFactory.

Since registerClass is just a specialization of registerFactory, it should invoke it instead of reimplementing it. This is preferable because having a single point of entry makes refactorings like adding logging or debug monitoring a lot less error-prone.

Prefer using instead of typedef

The semantics of type alisases are just a lot more legible that way.

Wrong function definition for forwarding args

If you want to use forwarding as you do, construct needs to be declared in a way to use universal references, like so:

template<typename... CtrArgs>
std::unique_ptr<Base> construct(const Key &key, CtrArgs&&... args)

Otherwise, your std::forward<> call is useless and might as well be a std::move.

Personal opinion: The custom exception type is not necessary here.

Letting the out_of_range exception bubble up is perfectly acceptable here, and lets your code be cleaner.


UserScript that summarizes Stack Exchange flag counts

I don't particularly have an issue with your HTML, however your JavaScript could be improved.

Currently, you have a lot of duplicate logic. You should move it to a function that each case can call.

Like the following:

function flagCount(selector){
    var count = 0;
    $(selector).parent().prev().each(function () {
        count += parseInt($(this).text().replace(",", ""));
    });
    return count;
}

If I pass 0 into parseInt without the second parameter, it will return a hex number...

Using Number is better, and more readable.

Leaving you totally with:

function flagCount(selector){
    var count = 0;
    $(selector).parent().prev().each(function () {
        count += Number($(this).text().replace(",", ""));
    });
    return count;
}
var helpful = flagCount("td > a:contains('helpful')");
var declined = flagCount("td > a:contains('declined')");
var disputed = flagCount("td > a:contains('disputed')");
var aged = flagCount("td > a:contains('aged')");
var total = flagCount("td > a:contains('flags')");

Note, you could string concatenate the selector inside the function, but that limits the use case that you select another DOM element.


Since this is code review, I would like to point out that your variable naming scheme makes your code hard to read. Why abbreviate anything? Why not call fC as just fourthCall? etc.


Compressing a vector into a specific range

Algorithm improvements
I really don’t understand what this algorithm is supposed to be doing. Your description of it is incomplete and vague (for example, you say vector[index1] < vector[index2]… but what is index1 and index2?), and the single example is not illuminating. It looks like you’re just trying to get the sorted position of each element in the vector. So it’s very possible that there is a much better algorithm that can solve this; there’s no way for me to know when what you’re trying to do makes no sense to me.
However, I can look at what your existing implementation is doing and at least improve on that a bit.
You use a set to get all the unique elements in the vector, and then you use a map to get… I dunno, something something count (the sorted index?). I can’t help you with the second part. But I can help you with the first part, because you don’t need the set. You can use the map to get the unique values, like so:
auto compress_vector(std::vector<int>& vec)
{
    auto m = std::map<int, int>{};

    // You don't need the set. You can use the map's keys to get the unique
    // values.
    for (auto i : vec)
        m[i] = 0;

    // And then you can recover the "set" of unique values by just iterating
    // on the map's keys.
    auto counter = 0;
    for (auto [i, _] : m)
        m[i] = counter++;

    // The above loop may be optimized by avoiding the duplicate lookup:
    //  for (auto& p : m)
    //      p->second = counter++;

    for (auto& i : vec)
        i = m[i];

    return m.size();
}

You could also go the other way, and keep the set but ditch the map:
auto compress_vector(std::vector<int>& vec)
{
    auto s = std::set<int>{};

    for (auto i : vec)
        s.insert(i);

    // The values of the map are just the indices of the set.
    for (auto& i : vec)
        i = std::distance(s.begin(), s.find(i));

    return s.size();
}

Depending on a lot of factors, it might be more efficient to ditch the set and use a sorted vector instead:
auto compress_vector(std::vector<int>& vec) {
    // Take care of the degenerate case of an empty input vector first.
    //
    // Not strictly necessary, but will save a lot of work.
    if (vec.empty())
        return 0;

    // You could also do this:
    //  if (vec.size() == 1)
    //  {
    //      vec[0] = 0;
    //      return 1;
    //  }

    // A second container, either a map, set, or second vector, is probably
    // unavoidable, because we need to keep track of the original values while
    // also changing the vector's contents, in order to know the sorted
    // indices.
    //
    // Note that this is the lazy way of building the sorted vector. If there
    // are a lot of duplicate values, it *might* be faster to:
    //  1)  reserve vec.size()
    //  2)  for each element in vec, do a lower_bound() search, to find if
    //      it's already in sorted, and if not, then you have the insert
    //      position
    auto sorted = vec;
    std::sort(sorted.begin(), sorted.end());
    sorted.erase(std::unique(sorted.begin(), sorted.end()), sorted.end());

    // Transform each element in the input vector into the index of the
    // element in the sorted vector.
    std::transform(vec.begin(), vec.end(), vec.begin(),
        [&sorted](auto i)
        {
            // Instead of std::find(), you could also use a binary search,
            // like std::lower_bound().
            return static_cast<int>(
                std::distance(
                    sorted.begin(),
                    std::find(sorted.begin(), sorted.end(), i)
                )
            );
        }
    );

    return sorted.size();
}

Code review
using namespace std;

This is always a bad idea. You can probably get away with it in simple, toy programs, but you should never do it in real code.
int compress_vector(vector<int>& vec)

“Out” parameters (function parameters taken by non-const reference, and then modified with the “return” value) are generally not a great idea. They usually make functions harder to use, because they put the onus on the user to set up space for the return. What if I want the original vector and the “compressed” vector? Now I have to deal with the pain of setting up the result manually, rather than just writing auto result = compress_vector(input);. And if the vector I want to “compress” is already const (which is often the case), it’s on me to make a copy again.
I know there is an argument that out parameters can be more efficient, but that doesn’t really apply here, because you’re creating whole maps, sets, and/or copies of the vector in the function anyway.
An even better design would be to take an output iterator argument.
for (auto i : vec) s.insert(i);

Don’t do this. Saving a single line in the function just isn’t worth the risk of missing the hard-to-spot loop body and introducing bugs. If your function is so long that you actually need to save a line or two in order to fit it on screen, your function is too long in any case, and should be broken up.
for (auto i : vec) s.insert(i);
int counter = 0;
for (auto i : s) {
  m[i] = counter;
  counter++;
}
for (auto& i : vec) i = m[i];

Space out the code. There are THREE loops here, jammed all together. That is three entirely separate logical sections of the function. Each section should be separated from the others by a blank line, to make it clear where the function’s “paragraphs” are. (And, of course, both the first and last loops should not be single lines.)
You should also consider using algorithms instead of naked loops, for two reasons. First, they make your code clearer: a naked loop could be doing ANYTHING… but an algorithm spells out exactly what is happening. Also, algorithms are much easier to optimize.
So the big glob of code above could be:
std::for_each(vec.begin(), vec.end(), [&s](auto i) { s.insert(i); });

auto counter = 0;
std::for_each(s.begin(), s.end(), [&m, &counter](auto i) { m[i] = counter++; });

std::for_each(vec.begin(), vec.end(), [&m](auto& i) { i = m[i]; });

Of course, all three algorithms are for_each() here, because I don’t really understand what the loops are supposed to be doing. for_each() is what you use when nothing else makes more sense. You’ll note that in the modified algorithm I wrote above, I used more specific algorithms, like transform(), unique(), and find() because I understood what was going on.
return s.size();

You have a bug here. s.size() gives an unsigned type, which is problematic enough, but the real issue is that the type may be (and often is) larger than an int. But you are forcing it to be crammed into an int, which may cause truncation, or other weirdness. If you’re absolutely sure you want compress_vector() to return int, then you should at least assert that the size of the vector is smaller than the maximum value of int. Or, on the other hand, maybe you don’t really want compress_vector() to return int? I don’t understand what you want from this function, so I can’t guess which is the right answer.
In main():
for (auto i : vec) cout << i << " ";

Once again, this should not be on a single line. Also, you probably don’t want a whole string constant for just a space; you probably mean ' ', not " ".
cout << endl;

std::endl really makes no sense here. If you want a newline, use a newline: std::cout << '\n';.
return 0;

You don’t need this in main().
Summary
Because your description of the problem is so vague and incomplete, and your examples of the intended usage are so limited and unrevealing, it’s impossible to give good recommendations. There is just so much about this function that is unexplained, and so many unanswered questions: Does it really need to modify the input vector; could it not simply return a new vector instead? Why does it return the number of unique elements; is that really important information? Why does it return that value as an int, rather than std::size_t or std::vector::size_type? And so on and so forth.
The best I can do is offer base-level suggestions going by the literal operations in the given code; in other words, I can only give suggestions for tuning the existing algorithm… I can’t suggest better algorithms, if there are any.
That said, there are certainly some corners you could cut, and some inefficiencies you could remove. You don’t need a set and a map… that’s just overkill in just about any situation. You might even get away with a sorted vector, which should be way more efficient than either a map or a set… especially if you do a binary search.


Coding Challenge: Return The Smaller String

if (!isNaN(str1[i]) && !isNaN(str2[i])) { // if both chars are numbers, return str with numerically smaller number
          return parseInt(str1.slice(i)) < parseInt(str2.slice(i)) ? str1 : str2;
        }

seems like a bug. In case the numbers compare equal the code blindly returns the first string. Consider (a10c, a10b).

return str1; // if we get here then both strings are equal and either can be returned

seems like another bug. At this point we only know that the strings are equal up to the length of the shortest one, and the shortest one should be returned. Which one is shortest is not tested here.

The overall logic looks overcomplicated. Consider testing for numbers first; that would eliminate the need for a confusing toUpper/toLower mess, and the special case of special characters.