Here you go. I made Range inclusive only, but it's easy to modify. I also extracted a few interfaces for easy unit testing and use IEnumerable<T> instead of IList<T>.

public interface IPriceComparison
{
    bool Evaluate(decimal price, params decimal[] valuesToCompare);
}

public abstract class PriceComparison : IPriceComparison
{
    private static readonly IPriceComparison under = UnderPriceComparison.Create();

    private static readonly IPriceComparison above = AbovePriceComparison.Create();

    private static readonly IPriceComparison range = RangePriceComparison.Create();

    public static IPriceComparison Under
    {
        get
        {
            return under;
        }
    }

    public static IPriceComparison Above
    {
        get
        {
            return above;
        }
    }

    public static IPriceComparison Range
    {
        get
        {
            return range;
        }
    }

    public abstract bool Evaluate(decimal price, params decimal[] valuesToCompare);
}

public sealed class AbovePriceComparison : PriceComparison
{
    private AbovePriceComparison()
    {
    }

    public static IPriceComparison Create()
    {
        return new AbovePriceComparison();
    }

    public override bool Evaluate(decimal price, params decimal[] valuesToCompare)
    {
        return (valuesToCompare == null) || (valuesToCompare.Length != 1) || (price > valuesToCompare[0]);
    }
}

public sealed class UnderPriceComparison : PriceComparison
{
    private UnderPriceComparison()
    {
    }

    public static IPriceComparison Create()
    {
        return new UnderPriceComparison();
    }

    public override bool Evaluate(decimal price, params decimal[] valuesToCompare)
    {
        return (valuesToCompare == null) || (valuesToCompare.Length != 1) || (price < valuesToCompare[0]);
    }
}

public sealed class RangePriceComparison : PriceComparison
{
    private RangePriceComparison()
    {
    }

    public static IPriceComparison Create()
    {
        return new RangePriceComparison();
    }

    public override bool Evaluate(decimal price, params decimal[] valuesToCompare)
    {
        return (valuesToCompare == null)
            || (valuesToCompare.Length != 2)
            || ((price > valuesToCompare[0]) && (price < valuesToCompare[1]));
    }
}

public interface IBuyOrder
{
    int Price
    {
        get;
    }
}

public sealed class BuyOrder : IBuyOrder
{
    private readonly int price;

    private BuyOrder(int price)
    {
        this.price = price;
    }

    public static IBuyOrder Create(int price)
    {
        return new BuyOrder(price);
    }

    public int Price
    {
        get
        {
            return this.price;
        }
    }
}

public interface IBuyIndicator
{
    IEnumerable<IBuyOrder> Apply(IEnumerable<int> productPrices);
}

public sealed class PriceIndicator : IBuyIndicator
{
    private readonly IPriceComparison comparison;

    private readonly decimal[] values;

    private PriceIndicator(IPriceComparison comparison, params decimal[] values)
    {
        if (comparison == null)
        {
            throw new ArgumentNullException("comparison");
        }

        this.comparison = comparison;
        this.values = values;
    }

    public static IBuyIndicator Create(IPriceComparison comparison, params decimal[] values)
    {
        return new PriceIndicator(comparison, values);
    }

    public IEnumerable<IBuyOrder> Apply(IEnumerable<int> productPrices)
    {
        return productPrices.Where(price => this.comparison.Evaluate(price, this.values))
            .Select(BuyOrder.Create)
            .ToList();
    }
}


Conversion of hexadecimal string to string

I don't think there is a built-in method. Yours is pretty good but we could make some improvements:

Parameters should be camelCase => hexString.
You should favour StringBuilder when building up strings.
You should step through the string in increments of 2 to cut down on the maths.
You should validate the argument.
You should prefer var when the type is obvious.

Result of those points:

string HexStringToString(string hexString)
{
    if (hexString == null || (hexString.Length & 1) == 1)
    {
        throw new ArgumentException();
    }
    var sb = new StringBuilder();
    for (var i = 0; i < hexString.Length; i += 2) {
        var hexChar = hexString.Substring(i, 2);
        sb.Append((char)Convert.ToByte(hexChar, 16));
    }
    return sb.ToString();
}


Largest palindrome made from the product of 3-digit numbers

You already got some advice on coding style. however there is a big flaw in your algorithm which is not addressed by the accepted answer.

you try to iterate downward to get an effective implementation but you got the inner loop wrong. while you expect the outer loop to do few iterations your inner loop does check relatively low numbers early. you tried to limit that by stopping the iteration at 900, a magic value without reasoning. so your implementation may give wrong results as a pair of 901*901 is much smaller than a lot of untested pairs. you need at least a check if your product is bigger than the biggest untested one 999*900.

on the other hand if we do the inner loop right all problems are gone. we use the outer loop for the lower value and the inner loop for the greater one. we do not need an arbitrary limit any more and we are quite efficient.

for i in range(999,99,-1):
    for j in range(999,i-1,-1):
        # check palindrome

again we do not want to collect all palindromes but only the biggest one. we can abort safely when we cannot get a bigger product than the current maximum one.

def is_palindrome(n):
    s = str(n)
    return s == s[::-1]

def get_biggest_palindrome():
    max_product = 0
    for i in xrange(999, 99, -1):
        if max_product >= 999*i:
            # no need to iterate further down
            break
        for j in xrange(999, i-1, -1):
            p = j * i
            if max_product >= p:
                # no need to iterate further down
                break
            if is_palindrome(p):
                max_product = p
    return max_product

I did some other minor changes:

is_palindrome - i like to name functions after what they return so the usage reads like a natural language sentence.

in python2 you should use xrange() instead of range() if you do not need a real list but just an iterator.

what you could do also:

make the magic numbers 999 and 99 constants and/or pass them as parameters. if it is about the number of digits you could define them as 10**(digits+1)-1, 10**digits-1 and pass digits as single parameter.


A geometry Sector Solver, Value finder for my calculator's micropython

Naming

Variable and function names should be snake_case, not This_Format or This. Uppercase and PascalCase are reserved for class names.

Checking inside lists vs strings

If you're checking for a single character, it's better to use a string rather than a list. Have a look:

if unit in "+-":
    ...

The walrus operator

If you're using python-3.8 you can use the walrus operator. It's another way of saying assignment expressions. It's a way to assign a variable within an expression. In your case, you can utilize the walrus operator to assign input to a variable, and use that. Have a look:

while unit := input("For Degrees, enter '+',\nFor Radians, enter '-'\n: "):
    if unit in "+-":
        ...

So unit is assigned whatever the output of the input  call is.

Unneeded function

If your function is simply an input call, you don't really need it. Just put it at the end of the while loop.

Ternary operators

You can use these to greatly shorten the length of your code. It's an easier way to assign values based on conditions. Take a look at the final code to see what I'm saying.

f-strings

You should use f"" to directly implement variables in your strings. It's a cool feature that keeps you from having to + or call a .format on your strings. Have a look:

print(f"Area of Sector = {sector_area}")
print(f"Area of inner Triangle = {triangle_area}")
...

Final code

After all these suggestions, you code would look something like this:

from math import pi, sin

def input_pi_replacer(prompt):
    return float(eval(input(prompt).replace("pi", str(pi))))

print("Sector Quantities Calculator:\n")
while True:

    while unit := input("For Degrees, enter '+',\nFor Radians, enter '-'\n: "):
        if unit in "+-.":
            if unit == ".":
                raise SystemExit
            c_factor = (pi / 180) if unit == "+" else (180 / pi)
            break

    radians = input_pi_replacer("\nEnter Radius: ")
    angle = input_pi_replacer("Enter Theta/Angle: ")

    c_angle = angle * c_factor if unit == "+" else angle

    print()
    sector_area = 1 / 2 * (radians ** 2) * c_angle
    triangle_area = 1 / 2 * (radians ** 2) * sin(c_angle)
    arc_length = radians * c_angle
    chord_area = sector_area - triangle_area
    chord_length = 2 * radians * sin(c_angle / 2)
    perimeter_sector = 2 * radians + triangle_area

    print(f"Area of Sector = {sector_area}")
    print(f"Area of inner Triangle = {triangle_area}")
    print(f"Arc Length = {arc_length}")
    print(f"Chord Area = {chord_area}")
    print(f"Chord Length = {chord_length}")
    print(f"Sector Perimeter = {perimeter_sector}")
    print()

    if input("Stop?: ").lower() == "x":
        raise SystemExit


You don't need to indent your $ser_ value assignments.  Indentation should be left for within a class, method, loop, etc as you do for most of your other code.  I notice that you separate your MySQL statement, which can be done, but on such a simple query, really isn't needed as the only purpose for doing that is to help readability when it is a complicated query. ^^

On a side note, mysql_ functions are deprecated now, and you should switch to mysqli_ (or the MySQLi class), or (preferably) PDO.


Don't do this:

using namespace std;

See: Why is “using namespace std” considered bad practice?

Its a bad habits you should not get into doing (even for small programs). Bad habits bite you in the butt when you get to larger projects and forget to stop doing them.

Comments

There are a couple of things I would do differently. But I can't say you are doing them wrong.

I prefer not to use unsigned for numeric values.

double polynom(unsigned, double);

There is no way to check that what was passed was not negative. I can easily call this with:

polynom(-1, 2); // Compiler is happy to convert that -1 to a very large
                // positive number without an y errors. On the reciving
                // side you can not tell if it was an error.

There are very few times when you need the extra bit for larger positive numbers. Any time I have come across this type of case I have just used a larger integer type (not swapped to the unsigned version).

Unsigned values should be reserved for bit masks in user code.

Don't use return in main.

int main(void)
{
    return 0;
}

If you don't put a return at the end of main() then the compiler will automatically plant code to return 0. So it is not technically needed.

Additionally not using the return 0 is a way to indicate that your application can never fail. Note: return 0 indicates a success to the OS and the compiler is planting it by default to indicate successful termination.

So when I see a return 0 at the end of main() I also start to scan the rest of main() to see if there are any other returns (with non zero value) that will indicate the error conditions of the application.

Initialization

This is fine.

    double currentAdd(x);
    double res(0);

But personally I think the = sign provides more context.

    double currentAdd = x;
    double res        = 0;

Prefer for() over while()

This is so 50/50. Its just that for() loops can be slightly more compact.

    while (n)
    {
        --n;
    }
    // over
    for(;n; --n)
    {
    }

Would not worry too much about it though.


While you have duplicated less code than your first example, I would argue that the using some and partial are a bit overkill for this very trivial example, where or is more clear and succinct.  I like your modification if you are writing a function (which you are not) that takes an arbitrary list of factors to test for divisibility, but you aren't do that.
In general, when running from an interactive REPL, it makes no sense to println your answer.  Though you're not writing a function, we usually think of the function producing a value, given some inputs, and the value returned from the function is sufficient.  Maybe it seems picky, but since you went to the trouble to factor out a divisible-by function, it seems odd that you would unnecessarily print something.  You will find very few printlns in clojure code, generally speaking.  It makes your code harder to test, as you have side-effecting output.
The ->> threading macro is, again, overkill here in my opinion. The goal here is to sum a list of numbers, and making (reduce + ... front and center makes that clear.  You have obfuscated the intent a bit by threading this, IMO.

The above points may seem a bit picky, but they stem from the fact that your goal here is very simple: get a list of numbers and add them.  By threading the code, using partial application, and factoring out a function, you've made the solution overwhelming, compared to what the problem calls for.  What you have done is very nice, but I don't think it fits the problem such that at a glance the reader can quickly see the intent of the code.  Below is my solution, for reference.  It's not fancy, but it tells you what it does rather quickly:

(reduce + (filter #(or (zero? (rem % 3))
                       (zero? (rem % 5)))
                  (range 1000)))

Another more verbose solution, but also clear:

(reduce + (for [x (range 1000)
                :when (or (zero? (rem x 3))
                          (zero? (rem x 5)))]
            x))

One final note: many of the Project Euler problems are math-heavy and as such, often have a more math-based solution (as opposed to an algorithmic solution), or at least can be optimized in such a way.  The wikipedia page has an example using this first problem, where a constant-time (O(1)) solution can be applied which you would certainly want to use for a data set of sufficiently large size (many millions or billions, perhaps).


Project Euler 18/67: Maximum Sum from Top to Bottom of the Triangle

Generally speaking, I find that your code is clear. I just have a few remarks:

You should order your headers in alhabetical order. It will help you to quickly check whether some header is already included or not in you plan to add some:

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

You should open your file directly from the constructor, and check whether there was a problem when you tried to open the file:

std::ifstream nums.open("triangle.txt");
if (not nums.good())
{
    throw std::runtime_error("Could not open the file.");
}

You can replace this condition:

if(grid[a][b] > grid[a][b+1]){
    grid[a-1][b] += grid[a][b];
}
else{
    grid[a-1][b] += grid[a][b+1];
}

You can use std::max instead:

grid[a-1][b] += std::max(grid[a][b], grid[a][b+1]);

I don't know why you chosed , as a separator since the original file uses a space as separator. Had you kept the space as a separator in your file, you vould have rewritten the function split with std::istream_iterator, with an int template parameter:

std::vector<int> split(const std::string& line){
    std::stringstream ss(line);
    return {
        std::istream_iterator<int>{ss},
        std::istream_iterator<int>{}
    };
}

The braces after the return correspond to list initialization. The rules for list initialization are pretty complex; the curly braces after return mean that an instance of the anounced return type (std::vector<int>) should be created with the arguments between the braces. In our case, the chosen constructor is the one that matches the best two istream_iterator<int> instances:

template<class InputIt>
vector(InputIt first, InputIt last,
       const Allocator& alloc=Allocator());


Unfortunately, there is a bug in glCons. The employee's fun should get added, not replace the current fun level:
glCons :: Employee -> GuestList -> GuestList
glCons emp (GL a b) = GL (a ++ [emp]) (empFun emp)
          --     ^

But let's stay on glCons. We can expect glCons to be used via foldr. However, the ++ operator leads to quadratic behaviour. When we add a single element, we should therefore use (:) (and reverse, if the order matters):
glCons :: Employee -> GuestList -> GuestList
glCons emp (GL a b) = GL (emp : a) (empFun emp + b)

Other than that the code seems fine.


I prefer to create isValid() method instead of exceptions and getValidationErrors() to get array of all errors instead of one error message with exception.

var joel = new Person('Joel', 30);
if( ! joel.isValid() ) {
    console.log(joel.getValidationErrors());
}

Also you can create some validation function like

validate({
    name: {
        type: 'string'
    },
    age: {
        type: 'number',
        minValue: 0,
        maxValue: 150
    }
}, {
    name: firstName,
    age:  age
});

Which will return array of errors. If array length is 0 then validation passed.


In order to be able to use this plugin on a page with multiple forms, I would recommend identifying the specific form that you are operating on. I can see that you are aware of the issue because you have been using the context parameter in most of the selectors, but since the <form> is an ancestor of this, it would need to be selected differently:

$("form").append(...

should be

$(this).ancestor('form').append(...

Also, I just wanted to mention a personal preference when working with HTML snippets generated by jQuery. Instead of having HTML in JS strings, like

$(this).ancestor("form").append(
    '<input type="hidden" name="'+opts.inputId+'" id="'+opts.inputId+'" value="'+selectedValue+'" />'
);

I like to make hidden template elements, and then clone them, remove the .template class, set the attributes and inner html, and insert the clone into the document. For example:

// stylesheet:
.template { display: none; }

// html, near the end of the <body>:
<input type="hidden" id="hiddenInputTemplate" class="template"/>

// js:
$(this).ancestor('form').append(
    $('#hiddenInputTemplate')
    .clone()
    .removeClass('template')
    .attr('name', opts.inputId)
    .attr('id', opts.inputId)
    .val(selectedValue)
);

For a short example like this, it might not be worth the extra verbosity, but I do have reasons for doing it this way:

My editor can't highlight HTML code, and especially syntax errors, inside of JS strings.
I can read and understand this style a little faster, and I will read it more often than I will write it. Like I said, it's just personal preference.


Before presenting my version, I would like to make a couple of comments:

Use descriptive names. The name userAnswer gives me an impression of just getting the user's answer, nothing else. I like to suggest using names such as startScrambleGame, runScrambleGame or the like.
Avoid 1-letter names such as x -- it does not tell you much.
I don't know which version of Python you are using, but mine is 2.7 and input() gave me troubles: it thinks my answer is the name of a Python variable or command. I suggest using raw_input() instead.
Your code calls input() 3 times. I suggest calling raw_input() only once in a loop. See code below.
The if checkSubset()... logic should be the same, even if you drop == True.

Here is my version of userAnswer, which I call startScrambleGame:

def startScrambleGame(letters):
    print("Can you make a word from these letters: {}?".format(letters))
    while True:
        answer = raw_input('Enter 1 to scramble, or type a word to guess: ')
        if answer != '1':
            break
        print(''.join(random.sample(letters, len(letters))))

    word = answer.lower()
    if checkSubset(word, letters) and checkWord(word):
        print("Yes! You can make a word from those letters!")
    else:
        print("Sorry, you cannot make that word from those letters")

startScrambleGame("agrsuteod")


Is there a 'better' way to find files from a list in a directory tree

In think you can do three things to improve your script(s):

Try to avoid complexity O(N^2)
Try to reuse intermediate results
Try to reduce extra process calls

The first aspects comes about because you compare the ALL files in the first directory to ALL files in the second directory. If both directories scale more or less by N you will have a rather slow algorithm for really large directories.

The second aspect relates to calling find again and again instead of calling it once and then using the output of the call for comparison.

The third aspect relates to e.g. calling sed twice in a pipe for something that can be done by the bash itself.

I have prepared a slightly different approach which is far from elegant and/or perfect but which may give you some ideas. The key features are:

It only calls find once for each directory and stores the result in files.
Instead of a nested loop (with find being the inner loop) it uses sort with complexity O(NlogN) to find the matches.
It focuses on the basenames of the filenames for comparison. Only for the result the "long" names are looked up again.

This is the script:

#!/bin/bash
dir1=$1
dir2=$2

# list all files in dir a using format "filename filepath"
find $dir1 -type f -printf "%f %p\n" > dir1.lst

# sort filename portion alphabetically and append " 1" as source
cat dir1.lst | while read filename filepath
do
    echo ${filename%.*}
done | sort -u | while read filename
do
    echo "$filename 1"
done > dir1base.lst

# list all files in dir b using format "filename filepath"
find $dir2 -type f -printf "%f %p\n" > dir2.lst

# sort filename portion alphabetically and append " 2" as source
cat dir2.lst | while read filename filepath
do
    echo ${filename%.*}
done | sort -u | while read filename
do
    echo "$filename 2"
done > dir2base.lst

# now merge the two lists together; sort them by filename first and by source second
last=""
sort -k 1 -k 2  -u dir1base.lst dir2base.lst | while read filename dir
do
    # if we find an entry from source 2 that had the same filename from source 1 just before we have a match
    if [[ $dir -eq 2 && $last == $filename ]] ; then
        # output match
        echo $filename
    fi
    last=$filename
done | while read match
do
    # now grep for matches in both original files
    echo "*** File(s)"
    grep $match dir1.lst
    echo "*** match file(s)"
    grep $match dir2.lst
    echo "---"
done

Note that the output loop still has complexity O(M^2) with the inner loop being in the grep call. However, in this case M scales with the number of matches and not the original input size. The former should be considerably smaller.

Also note the first find command will have to be adapted to be more selective than it is now.


Using the [] syntax for adding array items, allows PHP to create the array as necessary. Thus you can scrap the if statement for a modest performance increase off 10 to 15% in my own testing. (Unlike if you used array_push() which would throw a warning instead.
The unused $group variable appears to be a mistake, as the function appears to fulfill it's purpose without it. Code reduced to:

function array_group_by($arr, $key_selector) {
  $result = array();
  foreach ($arr as $i) {
    $key = $key_selector($i);
    $result[$key][] = $i;
  }
  return $result;
}

At this point, the $key could also be left out, but it's almost free in terms of performance, and increases readability, so I left it there.
I'm not sure how much misuse and error handling you need, the function is pretty simple. I would stick with type-hinting the arguments. array is available since PHP 5.1, callable since 5.4. The signature would become

function array_group_by(array $arr, callable $key_selector);

Then PHP will at run-time throw a fatal error at anyone trying to call the function with incorrect parameters. Generally I think that's good, but in this particular case, it introduces a problem.
array('class_A', 'method_B'), is a valid callable, that won't work with with the fast $function($arg);. For any valid callable to get executed, you need to use call_user_func() instead, which is a bit slower. In my testing however, the removal of the if has bigger impact than the use of call_user_func(), so if this isn't performance critical, stick with callable and call_user_func().

Final code:

function array_group_by(array $arr, callable $key_selector) {
  $result = array();
  foreach ($arr as $i) {
    $key = call_user_func($key_selector, $i);
    $result[$key][] = $i;
  }
  return $result;
}


Calculating a time in a time zone from multiple dates in SQL

First, let me restate your problem, to make sure I understand it correctly.  You want to take the NominalTime column, which is of type datetimeoffset, and replace the date part with today's date, where "today" is defined according to the timezone in which the SQL Server is running.  The time and timezone offset will remain unchanged, even across DST boundaries.

To roll one field of a datetime-like object forward or backward, use the DATEADD() function:

SELECT Id
     , NominalTime
     , SYSDATETIMEOFFSET() AS Now
     , DATEADD(day, DATEDIFF(day, NominalTime, SYSDATETIMEOFFSET()), NominalTime)
    FROM FaxQueue
    WHERE status = 0;

SQL Fiddle demonstration


It's very nice. What few qualms I have are a result of me looking really hard for things to have qualms about (furrowing my brow and going "hmm", basically).

Anyway, some thoughts:

Your unique function relies on the assumption that there are no circular references in the object passed to JSON.stringify. It's probably a fair assumption, but an assumption nonetheless. Also, from a specification standpoint, JSON representation of objects doesn't impose or guarantee any ordering of properties. I highly doubt it'll ever be an issue anywhere, but it could mean that identical objects will have different JSON representations, and unique would thus include both those objects.
Similarly edge-case'y: Your instanceof usage is vulnerable to the usual cross-frame pitfalls.
The !~array.indexOf( value ) trick is a bit arcane. It's neat, but I don't think I've actually seen it used anywhere - except in some other code you posted :)
A === -1 comparison isn't nearly as cool, but it wouldn't cause me to go "huh?". In other words: I like it, but I wouldn't call it obvious or idiomatic.
That curly-brace-on-new-line style just rubs me the wrong way, but you know what you're doing, so I'll spare you the "automatic semi-colon insertion" speech :)

On a more overall note: Like jQuery, it might be useful to always return a Hmm-wrapped array, instead of only adding unique to the array returned by collect. Of course it'd be quite a different API.


Insert str into larger str in the most pythonic way

The core code (I'd prefer the f-string if you can guarantee Python 3.6+, else the addition or "{}{}{}".format(...) if you need to support older Python versions) looks fine. However, you overwrite text each loop, but continue to use the originally provided offset's, which could be very confusing since the offsets will become incorrect after the first tag insertion. The code doesn't crash, but I'd argue it doesn't "work", certainly not as I'd intuitively expect:

In [1]: insert_tag('abc', [1, 2], ['x', 'y'])
Out[1]: 'axyyxbc'

I'd expect this to produce 'axbyc'. If that output looks correct to you, ignore the rest of this answer.

It would be better to break the original string apart first, then perform the insertions. As is typical in Python, we want to avoid manual looping if possible, and as is typical for string generation, we want to create as few new strings as possible. I'd try something like the following:

In [2]: def insert_tags(text: str, offsets: [int], tags: [str]):
   ...:     offsets = [0] + list(offsets)
   ...:     chunks = [(text[prev_offset:cur_offset], tag) for prev_offset, cur_offset, tag in zip(offsets[:-1], offset
   ...: s[1:], tags)]
   ...:     chunks.append([text[offsets[-1]:]])
   ...:     return ''.join(piece for chunk_texts in chunks for piece in chunk_texts)

In [3]: insert_tags('abc', [1, 2], ['x', 'y'])
Out[3]: 'axbyc'

Other stylistic considerations:

Your function supports the insertion of multiple tags, so it should probably be called "insert_tags" (plural) for clarity.
Type annotation are generally good (though recall that they lock you in to newer versions of Python 3.X), but getting them right can be a nuisance. E.g., in this case I'd suggest using Sequence instead of List, since you really just need to be able to loop on the offsets and tags (e.g., they could also be tuples, sets, or even dicts with interesting keys). I also find them to often be more clutter than useful, so consider if adding type annotations really makes this code clearer, or if something simpler, like a succinct docstring, might be more helpful.


The Big Issue

One of the biggest things about smart pointers is that they guarantee deletion of the pointer. EVEN when exceptions happen. My main problem here is that your constructor may leak the pointer if it fails to initialize correctly.

template <class T>
SmartPtr<T>::SmartPtr(T* iObject):
    _refCount(new RefCount()),       // This can throw.
    _ptr(iObject)
{
    this->_refCount->AddRef();
}

If the creation of the _refCount object fails you will leak the pointer. You need to guarantee that the pointer does not leak:

SmartPtr<T>::SmartPtr(T* iObject)
try                               // Add a try block
    :_refCount(new RefCount())
    ,_ptr(iObject)
{
    this->_refCount->AddRef();
}
catch(...)
{
    delete iObject;    // If there is an exception make sure the object is deleted.
    throw;             // Then re-throw the exception.
}

Minor Missing Functions

The main missing things I see are:

 T*  get();            // Sometimes its nice to just get the pointer.
 operator bool();      // Nice when you want to simply check the smart
                       // pointer has something in a boolean context.

 SmartPtr<Stuff>  data = getSmartPointer();
 if (data) {
     data->doWork();   // Need to check there is a pointer in the
 }                     // object before calling doWork().

Constructor Problems

Explicit

Your one parameter constructor should be explicit. Think of this situation.

 void doStuff(SmartPtr<Stuff> work)
 {
      if (work) {
          work->doWork();
      }
 }

Looks simple enough. When you call the function you get another reference counted version of the pointer and thus it is simple and safe to use.

But what happens when I do this:

int main()
{
    Stuff*  work = new Stuff;
    doStuff(work);
    work->moreActions();
    delete work;
}

This code compiles. But the call to doStuff() results in delete being called on the work object. Even though you though it was safe to call (as you are making a copy of smart pointer).

The trouble is that the compiler has converted the Stuff* to a SmartPtr which is deleted in this scope.

What About nullptr

Your object does not accept a nullptr!

 SmartPtr<Stuff>  value = nullptr;  // fails to compile.

It does not look like a major problem. But when you start using templatized code where things are initialized and your type can be swapped in then it becomes an issue as your type can not be used.

What About Derived Types.

On of the major things about C++ is derived types with more functionality.

Derived*    x = new Derived;
Base*       y = x;

The same should work with smart pointers.

SmartPtr<Derived>  x = new Derived;
SmartPtr<Base>     y = x;           // fails to compile.

This will be a common in most C++ code (not exactly like this). But this functionality is really needed.

Make Shared

One of the things the standard builders found was that each shared pointer required the allocation of TWO objects. One for the thing and one for the counter.

They remedied this by introducing std::make_shared<T>(). This does one allocation that allocates the object and the counter inside the same space thus reducing the overall overhead of the object.

Further Reading

I cover a lot of these details and more in some articles I wrote:

Series
Smart-Pointer - Unique Pointer
Smart-Pointer - Shared Pointer
Smart-Pointer - Constructors


Trimming strings in non-contiguous spreadsheet ranges

It's clear you're performing the same operation over different ranges of cells. So I'd separate that logic in a Function which you can call with any range you like. Using arrays achieve a speed up if the ranges are large, but for now wait until you think you need it. (Needing to check the cell for .HasFormula will slow down using an array in any case.)

The code below shows the trimming logic isolated to a single function. The logic is no different from yours with the exception of more clear variable names.

Option Explicit

Sub test()
    TrimTheseCells JHACheck.Range("M7:M32")
    TrimTheseCells JHACheck.Range("M35:M41")
    TrimTheseCells JHACheck.Range("R35:R41")
End Sub

Private Sub TrimTheseCells(ByRef thisRange As Range)
    Dim cell As Range
    For Each cell In thisRange
        If Not IsEmpty(cell) Then
            If Not cell.HasFormula Then
                cell.Value = Trim(cell.Value)
            End If
        End If
    Next cell
End Sub


A few notes:

You aren't declaring alphabet in a very readable and maintainable form.  Here's how I would do it:

static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

As you can see, I also made this variable static and const.  static renders variable local to the file, and const makes it so that we can't screw with the array somewhere along the line (and also makes things a tidbit faster).  This leads me to my next point...

Also, you don't have to specify the number of elements in the array when you declare it like this, since the compiler can determine that itself (because it is constant).
fp and len are global variables when they shouldn't be.  Arguably alphabet shouldn't be one either, but I think it is find as long as you have the static in front of it.  Anyways, they should be declared as local variables and then passed to the functions that need them.
I'm not sure your algorithm is the most optimal.  I used a method known as "backtracking" myself, which seems to be the most efficient that I could find in practice.
fprintf() isn't going to be as efficient compared to fwrite().  I would consider rewriting your code if you still want to generate a permutation table.

Time test (without compiler optimizations)

mycode.c:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const int alphabetSize = sizeof(alphabet) - 1;

static void bruteImpl(char* str, size_t index, size_t maxDepth)
{
    for (size_t i = 0; i < alphabetSize; ++i)
    {
        str[index] = alphabet[i];

        if (index == maxDepth - 1); //printf("%s\n", str);
        else bruteImpl(str, index + 1, maxDepth);
    }
}

void bruteSequential(size_t maxLen)
{
    char* buf = calloc(maxLen + 1, sizeof(char));

    for (size_t len = 1; len <= maxLen; ++len)
    {
        bruteImpl(buf, 0, len);
    }

    free(buf);
}

int main(void)
{
    bruteSequential(5);
}

$ gcc opCode.c # I took out your fprintf call so that it wouldn't be a factor
$ time ./a.out

real  0m0.170s
user  0m0.139s
sys   0m0.009s

$ gcc mycode.c
$ time ./a.out

real  0m0.043s
user  0m0.039s
sys   0m0.002s


Checking if the input is valid

You use the pattern `` to check if the input contains any non numeric characters and then return 0 if it does. There is a better way to do this, use the ISNUMERIC() function.

VARCHAR(8000)?

Your input allows 8000 characters, which seems like more than you are likely to need. I would consider lowering this to a value that makes a little more sense. I can't see you ever needing to validate numbers over a hundred characters in length. Feel free to correct me if I am wrong about this though, I don't know what kind of data you intend to work with.

Changing @x = @x + y to @x += y

I don't know if you are familiar with this syntax, but instead of doing:

SELECT @temp = @temp - 9

you can do:

SELECT @temp -= 9

which does exactly the same.

@Plus

You seem to have mistakenly left the @Plus variable in the query, you can delete it as it is not used.

A neat little trick

Here is a little tick to toggle the value of @Flag between 1 and 0:

SELECT @Flag = 1 - @Flag

This works because if @flag is one, it becomes this:

SELECT @Flag = 1 - 1

and if `@Flag1 is zero then it becomes this:

SELECT @Flag = 1 - 0

Your IF Statement

Firstly, you set @temp, then if a condition is true, you set it to something else. This would be better expressed as an IF statement to set it if the condition is true, and an else to set it otherwise. This means that @temp is set at most twice in each iteration of the loop, as opposed to the current at most three times.

Speaking of IF's

I understand that leaving out the BEGIN/END where you can is tempting, but it makes it more difficult for people to understand what the query is actually doing. I would recommend including the BEGIN/END even for the smallest IF statements.

Setting multiple variables using SELECT

According to this page, and my own testing after reading, it is more efficient to use select to set multiple variables at once. If you choose to use the little trick above to set @Flag, you can reduce this:

SELECT @Sum = @Sum + @temp

IF @Flag = 1
    SELECT @Flag = 0
ELSE
    SELECT @Flag = 1
SELECT @Index = @Index - 1

to this:

SELECT
    @Sum += @temp,
    @Flag = 1 - @Flag, --Trick to toggle @Flag between 1 and 0
    @Index -= 1

The end result

I took the liberty of combining the declaring and initial setting of the variables:

CREATE FUNCTION dbo.LuhnALGValidation
(
    @Luhn VARCHAR(8000)
)
RETURNS BIT
AS
BEGIN

IF ISNUMERIC(@Luhn) = 0
BEGIN
    RETURN 0
END

DECLARE
    @Index SMALLINT = LEN(@Luhn),
    @Multiplier TINYINT = 1,
    @Sum INT = 0,
    @Flag INT = 0,
    @temp TINYINT;

WHILE @Index >= 1
BEGIN

    IF @Flag = 1
    BEGIN
        SELECT @temp = 2 * CAST(SUBSTRING(@Luhn, @Index, 1) AS TINYINT)
        IF @temp > 9
        BEGIN
            SELECT @temp -= 9
        END
    END
    ELSE
    BEGIN
        SELECT @temp = CAST(SUBSTRING(@Luhn, @Index, 1) AS TINYINT)
    END

    SELECT
        @Sum += @temp,
        @Flag = 1 - @Flag, --Trick to toggle @Flag between 1 and 0
        @Index -= 1
    END

    RETURN CASE WHEN @Sum % 10 = 0 THEN 1 ELSE 0 END
END
GO


Need fast csv parser for Python to parse 80GB csv file

I would suggest you to create a thread pool and do line.split() in separate thread. Playing with thread pool size can give you balance between processing speed and consumed resources.


Find area of intersection between 2 squares rotated 45 degrees

You can further reduce the time spent via taking advantage of the l1norm. The l1norm is the sum of the absolute values of a vector.  We represent our coordinates as a 2d vector, the l1norm of that is the absolute value of x and y.  Using this we can use the l1norm like distance (which happens to be the l2norm) for a diamond.  Calculating the l1 norm and comparing it against the order-1 of the diamond will give us whether or not the point is inside the diamond, provided the point the diamond we are trying to figure out if the point is inside of or not is centered at 0,0.

Utilizing the l1 norm we only need to look at one diamonds xy points, not two.  Because we only need to look at one, we can pick the smallest diamond to use to check overlap and translating the coordinates of the smaller one to a system where the center of the larger one is at (0,0).

This saves a lot of time, but if both of our diamonds are larger, and are nowhere close to each other we will still have to do a lot of work.  To avoid this we can use broad phase collision techniques to reduce computational time in these scenarios, using something akin to sweep and prune.  If we accomplish this via creating a range() that at first is our new translated smaller diamonds y - (order -1) and y + (order + 1).  We then conditionally swap these values if the max y values of the larger diamond are in smaller more convenient ranges, so if the furthest upward y point on the larger one is at a shorter distance than what we use as our max y range, the we will use that instead, or with the furthest downward y point on the larger one is larger than what we use for our min y range, we will use that instead.  If our smaller diamond isn't even in range of either of the larger diamonds y min and max values, our counting loop terminates as soon as it starts.

But we can go further with this idea.   We will do something similar with the x values, except we don't need to use the bounding box version of x cutoff values.  We can actually figure out the range of x on a per larger diamond y axis value.  Since our smaller x y coordinates are with respect to the larger diamond being at (0,0) y actually corresponds to the same y location relative to the center of the larger diamond is.  In fact because of the l1norm formula, we now know how to know the width (or half width) of a (0,0) centered diamond given one of its y coordinates.  We know that our y is within the larger diamonds y range from before, so the formula is (larger_order - 1) - abs(our_calculated_y_for_smaller) since abs(x) + abs(y) = order -1 we simply do algebra to figure out that abs(x) = order - 1 - abs(y) and since we only need to know the half width, we are actually looking for abs(x).

Now that we know the half width, we can use the same method above to figure out the range we should be looking at for this y level with respect to the larger diamond, instead of niavely looking within the bounding box.

But wait a second.  Now that we both know that we are only looking at values with that match the same y level on both our smaller and larger diamond, and we've been able to make sure we don't look at x's outside of the same x level why would we still need to check for each l1norm intersection?

What we can actually do is just sum up the difference between the max x range and min x range instead of using the l1norm, since we know exactly the range of values that overlap now!

now I doubt this is necessarily the fastest for very small diamond sizes, but I think this is the fastest no parallel asymptotic time algorithm for this specific problem that I could think of.  You could theoretically do this for N dimensional diamonds as well, but you'd have to include broad phase at each dimension. This should certainly be faster than both of your solutions for any large diamonds no matter the situation.

The time complexity is now bounded by only the order of the smallest diamond, as in O((smallest diamond order*2)-1).

Here is the implementation in python

def areaOfIntersection(shape1, shape2):
    # find smaller diamond
    (smaller, larger) = (shape1, shape2) if shape1[0] < shape2[0] else (shape2, shape1)

    # use the variables for the l1norm comparison for each point
    larger_offset_order = larger[0] - 1
    x_translate = -larger[1]
    y_translate = -larger[2]

    # use these variables to create each index in the diamond
    order = smaller[0]
    smaller_offset_order = order - 1
    # making relative to larger being at (0,0) instead of (shape2[1], shape2[2])
    x = smaller[1] + x_translate
    y = smaller[2] + y_translate

    # using comp order instead of larger[0] to work with logic below, since the number will represent the actual max
    # or min x or y value possible instead of one past it.
    larger_min_range_y = -larger_offset_order
    larger_max_range_y = larger_offset_order

    # overlap number
    k = 0

    # makes sure that the calculations at least take place in the same y coordinate intersection
    y_min_range = y + (-smaller_offset_order)
    y_max_range = y + (smaller_offset_order)
    y_min_range = larger_min_range_y if larger_min_range_y > y_min_range else y_min_range
    y_max_range = larger_max_range_y if larger_max_range_y < y_max_range else y_max_range

    for nmy in range(y_min_range, y_max_range + 1):
        half_width = smaller_offset_order - abs(nmy - y)
        # the difference from the y axis to the furthest diamond point, since it is already "centered"
        # no offset math is needed
        # equation abs(x) + abs(y) = order - 1, un normalized l1 norm equation, we only are about abs(x) so
        # it becomes x + abs(y) = order or x = order - 1 - abs(y), which is what we have here
        larger_half_width_at_current_y = larger_offset_order - abs(nmy)
        larger_min_range_x = -larger_half_width_at_current_y
        larger_max_range_x = larger_half_width_at_current_y
        x_min_range = (x + (-half_width))
        x_max_range = (x + half_width)  # max value in range, since exclusive
        # sets the range to make sure only iterating over possible subsection of x that could actually contain
        # a value from both
        x_min_range = larger_min_range_x if larger_min_range_x > x_min_range else x_min_range
        x_max_range = larger_max_range_x if larger_max_range_x < x_max_range else x_max_range
        # check if possible generated x offsets are out of range.
        # no longer need l1norm, since we can just sum up values in range
        if x_min_range < (x_max_range + 1):
            k += (x_max_range + 1) - x_min_range
    return k

print(areaOfIntersection([3, 0, -1], [5, 3, 0]))
# 8

The only faster method I can think of is some how accurately transforming these diamonds into AABB (Axis Aligned Bounding Boxes) and then computing the area overlap, but I'm  not sure how one would do so with out loosing out on the exact number of pixel overlap. In floating point however, I suspect this to be the correct method to measure area overlap since you aren't going to be losing out on discrete value precision. In a floating point scenario one could also use the generalized quadrilateral intersection


Parse backslash-delimited hierarchy path into separate columns

Normalization
A fully-normalized schema would not have four path component columns in a table; it would have one table with a string column for the path component, and a foreign key to its parent (and/or child), conceptually similar to a linked list. Advantages to this approach would be support for an arbitrarily long path. Disadvantage is likely decreased performance, though the scale of your problem is not clear.
Otherwise, I find it odd that you're parsing a path, and storing the result of the parse back into the database alongside the original data. This is a fast-enough operation that surely any advantage to caching parse results is outweighed by the disadvantage of increased storage and fetch time.
The only solid justification I can think of for such a thing is when (1) you know that certain interesting strings exist in fixed locations in the path, and (2) you need very fast, indexed querying on them, and (3) such querying is too slow when doing the usual pattern-matching approach on the original path.
Iteration
Don't use range for your loop; use enumerate. Also use a raw string due to your backslash.
for i, part in enumerate(s.split(r' \ '), 1):

Bare except
Generally this is a bad idea. At the least, catch Exception instead, or more preferably the actual exception type you expect to see. If it's only an index error because you're trying to index into a split that has fewer than four components, just avoid that situation altogether:
parts = s.split(r' \ ')
for i, part in enumerate(parts, 1):
    mbo.setValue(col_prefix + str(i), part)
for i in range(len(parts)+1, 5):
    mbo.setValueNull(col_prefix + str(i))


Programming challenge "Friend Request in Social Network"

The big performance issue with the current solution is that you're relying on building a String to keep the list of persons that were sent a friend request. A String is immutable in Java so every single operation on it will result in the creation and allocation of a new String. When doing those sorts of repeated allocation in a loop, the performance degrades rapidly.

We need another approach to the problem that doesn't rely on a simple String, and with that, a better data structure.

From the problem description, we need to maintain a collection of the friends of John. To pick a suitable data structure, let's examine what we'll need to do with it: we want to add elements to it (each friend name read), and we want to check whether that collection contains a specific name (to not add it to the list of invited persons). Additionally, we don't care about a particular order for this collection. The perfect data structure  for that is a HashSet, just like the one you used: it has a constant-time add and contains methods.
Then, we also need to maintain a collection of the invited persons, those that were sent the friend request. This is where you used a String and we can do better. Like the above, we want a data structure capable of adding elements (the name of the invited persons), but we also want it to be capable of removing elements (the friend names we might read further down the input). Also, we want to keep an order here, specifically, the order in which the elements were added. For that, LinkedHashSet is perfect: add and remove are both constant-time operations, and it keeps the insertion order.

With that in mind, we can refactor the code to use those data structures:

Collection<String> friends = new HashSet<>(); // to store name of the John's friends
Collection<String> invited = new LinkedHashSet<>();
for (int i = 0; i < N; i++) {
    Scanner scanLine = new Scanner(sc.nextLine());
    String friend = scanLine.next();
    friends.add(friend);
    invited.remove(friend); // potentially remove this invited as it is actually a friend
    scanLine.next(); // ignore the number of friends, we can deduce it anyway
    while (scanLine.hasNext()) {
        String name = scanLine.next();
        if (!friends.contains(name)) {
            invited.add(name);
        }
    }
}

Notice that I changed other things in there:

When you have the line of input, that is space-separated, you don't need to read manually characters by characters. You can either split(" "), which would return an array of all the tokens space separated, or you can use another Scanner, which by default tokenizes over white spaces, meaning every call to Scanner.next() will return the next word.
The variables have a meaningful name: friends represent the collection of John's friend and invited represents the collection of persons to whom John sent a friend request.

At the end of the process, we have our wanted collection inside invited, so we can finally print it. For that, we can use String.join starting from Java 8, which is built-in.

System.out.println(String.join(" ", invited));

If you are on a lower Java version, you would need to write the for loop explicitely and use a StringBuilder to construct the result, like shown here. Don't use the old StringTokenizer, it isn't officially deprecated but it is only kept for compatibility reasons and is considered a legacy class.


Python function to fill a list based on index number

if lst[n] is not sufficient to determine if the value at index n is None, 0 will also not pass the test. Use if lst[n] is not None or if lst[n] is None, depending on which one you want.
The whole first loop is just trying to determine if you need to extend the list, but you could just do that:

lst.extend([fill_value] * (index - len(lst) + 1))

If the list is already long enough this does nothing, as a list multiplied by an integer smaller than one is the empty list, and extending with an empty list does nothing. It even works when you use negative indices.
This also guarantees that the index exists, so you don't need the try..except anymore. But if you use try and except, always try to catch the narrowest exception possible. This way you make sure you don't catch an unexpected exception. In this case it would be an IndexError instead of the more generic Exception.
The convention in Python is for functions to only do one of two things: either do not mutate the inputs and return a new output or mutate (some of) the input and return None (potentially implicitly). Your function falls into the second category.

With these changes your function could be a lot shorter:

def fill(lst, index, value, fill_value=None):
    """Place the `value` at index `index`,
    but only if the value already there is `None`.
    Extends the list with `fill_value`, if necessary.
    """
    # No-op if list long enough or index negative
    lst.extend([fill_value] * (index - len(lst) + 1))
    if lst[index] is None:
        lst[index] = value

my_list = [1, 7, 14]
# my_list = [1, 7, 14]
fill(my_list, 5, 6)
# my_list = [1, 7, 14, None, None, 6]
fill(my_list, 6, 12)
# my_list = [1, 7, 14, None, None, 6, 12]
fill(my_list, 3, 25)
# my_list = [1, 7, 14, 25, None, 6, 12]
fill(my_list, 4, 18)
# my_list = [1, 7, 14, 25, 18, 6, 12]

Note that you will not directly see the result anymore in an interactive session, since the list is no longer returned. But that's a feature, not a bug, as mentioned above.

Of course, if you need to do this multiple times directly after each other, you might want to define a function that needs to extend only once:

def fill_multiple(lst, indices, values, fill_value=None):
    lst.extend([fill_value] * (max(indices) - len(lst) + 1))
    for index, value in zip(indices, values):
        if lst[index] is None:
            lst[index] = value

Then you can use e.g a dictionary:

my_list = [1, 7, 14]
updates = {5: 6, 6: 12, 3: 25, 4: 18}
fill_multiple(my_list, updates.keys(), updates.values())
# my_list = [1, 7, 14, 25, 18, 6, 12]

I kept the indices and values separate so you can also just pass lists or anything else, not just a mapping. Depending on your usecase you might want to pass the dictionary to the function instead.


It is overall good code, but there are of course some points to improve.
Objectively wrong and severe:

Always compile with as much debug options as possible with your compiler. It detects errors such as
2 * MAX_ORDER + 3 == 2 * (size(RM_CHARS) / 2 - 1) + 3 > size(RM_CHARS)

in your initialization loop.

The function expects a number that is larger than zero and smaller than 10^6. This is nowhere documented nor checked.

Small things that could be made better:

There are unnecessary many trim calls when you build up the string. If you only append trimmed strings, you know that the result is trimmed.

There is log10 for the decadic logarithm.

It helps sometimes to introduce additional variable names for self documentation.

I would recommend to use the words magnitude, exponent, and mantissa in the code. This is more self-explaining than "order".

It is not necessary to start from Zero for the first dimension of ROMAN_STRING

I would never name a logical variable with its negated form. You can always use .not. and it quickly becomes hard to read if you doubly negate it. The name could be shorter in addition.
mRomanStringsIsNotInitialized == .not. mRomanStringInitialized
.not. mRomanStringsIsNotInitialized == mRomanStringInitialized

I would use floor instead of int. It is a common error to use int instead of nint so it is nice to explicitly say floor.

Architecture:
At the moment you have runtime checks in your function to ensure initialization of ROMAN_STRING. This is not necessary since ROMAN_STRING could be made a compile time constant (with parameter).
If you do this then your function does not depend anymore on a global variable that can be mutated at run time, can be made pure and is probably a tiny bit faster.
Opinion based:
I would add more whitespace around your operators and after commata and use an indentation of at least 4 spaces.
You can format Fortran code pretty much according to the PEP8 guidelines of python, to achieve convincing results. (Especially since a lot of people in scientific computing use both languages.)
Everything together leads to:
  module mRomanStrings

    implicit none
    private
    integer         , parameter :: MAX_MAGNITUDE = 5
    character(len=4), parameter :: ROMAN_STRING(9, 0 : MAX_MAGNITUDE) = &
          reshape([character(4) :: &
          'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', &
          'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', &
          'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', &
          'M', 'MM', 'MMM', 'Mv', 'v', 'vM', 'vMM', 'vMMM', 'Mx', &
          'x', 'xx', 'xxx', 'xl', 'l', 'lx', 'lxx', 'lxxx', 'xc', &
          'c', 'cc', 'ccc', 'cd', 'd', 'dc', 'dcc', 'dccc', 'cm'], &
          [9, MAX_MAGNITUDE + 1])
    public :: IntegerToRoman

  contains

      !> Expects an integer 1 <= n <= (10^6 - 1) and returns
      !>  the Roman number literal as string.
      pure function IntegerToRoman(n) result(rm)
          integer, intent(in) :: n
          character(len=:), allocatable :: rm
          integer :: largest_magnitude, mag, mantissa
          if (n <= 0) error stop

          largest_magnitude = floor(log10(dble(n)))
          if (largest_magnitude > MAX_MAGNITUDE) error stop

          rm = ""
          do mag = largest_magnitude, 0, -1
              mantissa = mod(n / 10**mag, 10)
              if (mantissa > 0) then
                  rm = rm // trim(ROMAN_STRING(mantissa, mag))
              end if
          end do
      end function IntegerToRoman

  end module mRomanStrings

  program ConvertIntegersToRoman
      use, intrinsic :: iso_fortran_env, only: OUTPUT_UNIT
      use mRomanStrings
      implicit none
      integer :: i
      do i = 1, 99999
          write(OUTPUT_UNIT,"(i6,x,a)") I, IntegerToRoman(i)
      end do
  end program ConvertIntegersToRoman


First things first, you can remove the if len(sortedlist) == 1.
If we do a quick run through we should get:

theList = [1]
conterofthelist = 1 / 2
medianpart = [sortedlist[0]]
median = 1

This removes the first if.
You can remove most of the code in the else:

The first medianpart is immediately overridden.
Median part could be just a number, not a list.
You don't need to loop through medianpart.
You can just return sortedlist[centerofthelist]

This means that the code you have at the moment is:

def median(thelist):
    median = 0
    sortedlist = sorted(thelist)
    lengthofthelist = len(sortedlist)
    centerofthelist = lengthofthelist / 2
    if len(sortedlist) % 2 == 0:
        temp = 0.0
        medianparties = []
        medianparties = sortedlist[centerofthelist -1 : centerofthelist +1 ]
        for value in medianparties:
            temp += value
            median = temp / 2
        return median
    else:
        return sortedlist[centerofthelist]

If we go through the if now:

You don't need the first medianparties.
You can use sum rather than your loop.
You should move the temp / 2 out of the loop, to the return.

This should result in something like:

return sum(sortedlist[centerofthelist -1 : centerofthelist +1 ]) / 2.0

This should show you that you use lengthofthelist twice, and median never.
You could probably remove these.

Python has a style guide called PEP8, it's a fancy name I know.
It gives a few rules that you should probably follow:

Variable names should be lower_snake_case.
This means that sortedlist should be sorted_list and theList should be the_list.
Binary operators need a space either side of them. centerofthelist - 1.
List slices : have to have no spaces either side.
Use good variable names.

This should result in something like:

def median(numbers):
    numbers = sorted(numbers)
    center = len(numbers) / 2
    if len(numbers) % 2 == 0:
        return sum(numbers[center - 1:center + 1]) / 2.0
    else:
        return numbers[center]


Try:

ORDER BY ep.data_termino IS NOT NULL, ep.data_termino DESC, ep.data_inicio ASC

BTW,

IFNULL(ep.data_termino,NOW())

is a cleaner way to express:

IF(ep.data_termino IS NULL,NOW(),ep.data_termino)


Dynamically loading CSS files based on URL or URI in PHP

Most of questions you are asking are not fit for this site and your code does not work as intended but this is an interesting case to review
The grave mistake
Adding anything to your code just in case there would be some imaginary "error of some kind" is the worst thing a programmer could do ever. You effectively ruined your code with adding that || $_SERVER['PHP_URL_PATH'] stuff:

there is no such thing $_SERVER['PHP_URL_PATH'] for starter: such a variable just doesn't exist
of course ['PHP_URL_PATH'] without the $_SERVER part makes no sense
neither the whole condition returns anything sensible due to PHP syntax rules you are yet to learn.

Yet this code works somehow, albeit not the way you expect.
The operator precedence
The way this code executes is a very interesting matter, once I wrote an article that explains it in detail, Operator precedence or how does 'or die()' work. Given you only started learning it could be too complex for you for the moment to wrap your head around, but in time you will find it very interesting to read.
$_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH']  === "/mainHubV8.1.php" doesn't mean "if either PHP_SELF or PHP_URL_PATH equal to /mainHubV8.1.php". It means "if PHP_SELF contains any value OR PHP_URL_PATH is equal to /mainHubV8.1.php".
In short, an expression $_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH']  === "/mainHubV8.1.php" evaluates to true when $_SERVER['PHP_SELF'] contains any value. Which means always.
Given PHP already has it's answer, it ceases to execute the further condition. This is why you can write either $_SERVER['PHP_URL_PATH'] or ['PHP_URL_PATH'] or don't even get a notice for the non-existent array index - this code is just never executed.
As a result, this code will always output just "Loading Styles for MainHubV8.1.php" no matter which page it is called on.
The right way
To elaborate on the Neoan's answer, given you have 3 styles to load, here is the proposed array structure
$stylesheets = [
    '/mainHubV8.1.php' => [
        'style1.css',
        'style2.css',
        'style3.css',
    ],
    '/advSearchV8.1.php' => [
        'style4.css',
        'style5.css',
        'style6.css',
    ],
    // and so on
];

given this structure, you will be able to get the correct styles right from $_SERVER['PHP_SELF']:
foreach($stylesheets[$_SERVER['PHP_SELF']] as $file) {
    echo "<link rel='stylesheet' type='text/css' href='$file'>\n";
}


Multithreading decouple update-logic and render-logic

No. Using sleep is the wrong way in any most cases that you can think of. Use the correct functions for this. The C++ standard does not contain a standardized way of doing so. Please use SwitchToThread for Windows and pthread_yield for Unix. To gain more information, you may ask a search engine and for context switching, this is a more common identifier than swapping.
Yes, you are right. Mutual exclusion is indeed slower than a condition variable, whereas it is not always replaceable. Since I don't know how your compiler implements mutexes, you may want to search for differences between mutex and critical sections on Windows. I don't know if there are two different ways also on Unix and other systems. But to answer your question: Yes, one can solve this with condition variables. The difference is very-well stated here.
References are as safe as pointers, since all references are pointers internally after the compiler has done his work. Just be sure not to pass references, that you are expecting to own a resource exclusively, to functions which don't own the resource at all. This leads to very unpredictable code, as wrong coding in multi threaded environments always does.
Seems to be okay. But don't count on my word in the case of the move-operator. I simply don't know if this is going to be valid.


You could use Properties and read from them... IMHO, I think almost everything that goes quoted ("like this") can be either a constant or sent to a Properties file, you could have one for messages and one for configuration for example.

Also, I've noticed that you have two return statements per method, I would recommend to have only one, you don't really need one inside the catch block since the exception is suppossed to be handled then returned. It is also good for readability.

Bear in mind that exceptions could happen before you reach the connection.disconnect(); statement so I would recommend a try, catch, finally and perform all your clean up un the finally block.

Another thing... I think it is better to handle the exception differently depending on the scenario or error that caused it, for example, a connection couldn't been stablished, wrong URL, timeout (I don't know), etc.


Ruby - Summing groups of odd and even integers in an array until no groups remain

The whole thing about sums is misdirection; you don't need to sum anything, since all you need to output is the final length of the array. So what you want to know is how many consecutive terms there are of a given parity, not what their sum is.

The trick is that only an odd number of odd terms will produce an odd sum; anything else will produce an even sum. So you can skip calculating the actual sum, because by knowing the parity and number of terms, you'll know if that sum's going to be odd or even.

Secondly, you can make it recursive instead of loop-based.

Here's my take:

def count_chunks_recursively(array)
  # get our consecutive chunks
  chunks = array.chunk(&:odd?).to_a

  # if there are as many chunks as there are elements, we're done
  return array.size if chunks.size == array.size

  # otherwise, map the chunks to 0 or 1, depending on whether they
  # sum up to something even or something odd
  mapped = chunks.map { |odd, terms| odd && terms.size.odd? ? 1 : 0 }

  # ... and repeat the process recursively
  count_chunks_recursively(mapped)
end

As for your current code:

You very, very rarely have to use plain loops in Ruby; there's almost always something in Enumerable or Array that you can use instead.
x[-1].size would be more conventionally written as x.last.size
You use the a method reference when producing the sum – inject(&:+) – but you don't use the same technique for the other parts of the same line. I.e. this

arr.chunk{|x| x.even?}.map{|x, y| y}.map{|x| x.inject(&:+)}

could just be this:

arr.chunk(&:even?).map(&:last).map { |x| x.inject(&:+) }

or in Ruby 2.4+ which has a built-in sum method:

arr.chunk(&:even?).map(&:last).map(&:sum)

Sidenote: inject (specifically) actually doesn't need the method reference, but can also take a plain symbol: inject(:+). But for consistency's sake, I'd stick to using the &.


Firstly, don't try to think of everything that could go wrong. Instead, check for what you know to be valid.

import re
directory, filename = re.match('/([A-Za-z0-9]+)/([A-Za-z0-9]+)/?', alpha).groups()

By using this method to extract the directory and filename, we can be sure that directory and filename contain nothing except letters and numbers which are perfectly safe.

Its also best to use os.path.join to produce folder paths rather then string formatting to put them together.

    return open(file).read()

This works, but not if you try and run on IronPython/Jython/PyPy. CPython depends on reference counting which will cause the file to be closed as soon as it returns. A better version is probably:

with open(file) as source:
     return source.read()

This is guaranteed to close the file even without reference counting.


A* implementation is not running efficiently but gets correct result

Oh, I see your problem all right.

The ^ operator does not do what you think it does.

So your heuristic is wrong. It is possible that for some cases it is inadmissible -- remember, a heuristic is required to under-estimate path length, and yours might sometimes over-estimate due to the error.  What's more likely though is that it is massively under-estimating, and your algorithm is little better than Dijkstra's Algorithm at finding the shortest path quickly.

Most of the time, your heuristic will give the square root of the Manhattan distance, which is going to be pretty small compared to the Euclidean distance.

The moral of the story is test your subsystems.  If you'd written a test that verifies that the heuristic gives the right answer, you'd have found the bug yourself.

(Also, there's no need to do an abs on the sum of two squares. It's already positive!)

(Also, make a constant -- it pains me to type this, but you are a Java programmer so you get the joy of SHOUTY_SNAKE_CASE -- called METERS_PER_MILE and set it to 1609. Don't litter your program with unexplained magical numbers.  Give them names.)


Benchmarking copy semantics vs. move semantics

OK if we are going to do some timing then lets fix a few things.

When I compile this with optimizations -O3 it crashes. So getting timmings will be hard.

So lets fix the copy constructor.

Member variables are initialized depending on the context.

List a;          // Members are default initialized.
List a = List(); // Members are zero    initialized.

If the members are default initialized then POD members are left in an undefined state. So the following constructor:

    List(const List& lst)
    {
        cout << "Copy constructor" << endl;
        for (size_t i = 0; i != lst.sz; ++i)
        {
            push_back();
        }
    }

leaves all its members uninitialized (and thus in an undefined state) when used like this:

List list2(list);

Thus the call th push_back() is going to start manipulating some undefined pointers.

Fix by either explicitly initializing all members in the constructor or by chaining a constructor that will do it for you. Sinve your default constructor initializes the members correctly I will chain that.

    List(const List& lst)
        : List()
    {
        cout << "Copy constructor" << endl;
        for (size_t i = 0; i != lst.sz; ++i)
        {
            push_back();
        }
    }

IO and timing do not work well.

The IO operations are notoriously complex and using IO can change a lot. You want to avoid all IO operation during any timing phase and print the results out at the end after all timing information has been generated.

Standard Idioms

There are a couple standard idioms you should follow (as most code will be written like this).

Rule of Five. You forgot a destructor. Though it will not affect your timmings you should probably write one just to be tidy.

Copy and Swap. The copy assignment operator is usually written in terms of copy and swap.

Swap on move. Movement is usually implemented as a swap operation. That way you don't have to explicitly tidy up your content at this point if you don't need to. But the moved from object will do the tidy up eventually if it needs to. Currently your move assignment will leak if used.

Noexcept: The move operators should be marked as no except. This allows containers they are used within to perform certain operations that would not otherwise be allowed to maintain the strong exception guarantee.

class List {
public:
    void push_back();
    void swap(List& other) noexcept
    {
        using std::swap;
        swap(sz,   other.sz);
        swap(head, other.head);
        swap(tail, other.tail);
    }
    List()
       : head{nullptr}
       , tail{nullptr}
       , sz{0}
    {}

    // Copy
    List(List const& lst)
        : List()
    {
        for (size_t i = 0; i != lst.sz; ++i)
        {
            push_back();
        }
    }
    List& operator=(List const& lst)
    {
        List tmp(lst);
        swap(tmp);

        return *this;
    }

    // Move
    List(List&& lst) noexcept
       : List()
    {
        swap(lst);
    }

    List& operator=(List&& lst)
    {
        swap(lst);
        return *this;
    }

    // Destroy
    ~List()
    {
        ListNode* next;
        for(auto tmp = head; tmp; tmp = next)
        {
            next = tmp->next;
            delete tmp;
        }
    }
private:

    struct ListNode {
        ListNode* next;
    };

    ListNode* head;
    ListNode* tail;
    size_t sz;
};

void List::push_back()
{
    ListNode* new_node = new ListNode{nullptr};

    if (head == nullptr)
    {
        head = new_node;
    }
    else
    {
        tail->next = new_node;
    }

    tail = new_node;
    ++sz;
}

class CurrentTime {
    std::chrono::high_resolution_clock m_clock;

public:
    uint64_t milliseconds()
    {
        return std::chrono::duration_cast<std::chrono::milliseconds>
            (m_clock.now().time_since_epoch()).count();
    }
};

List createList(CurrentTime& ct)
{
    List lst;
    constexpr size_t HUNDRED_MILLION = 100 * 1000 * 1000;

    for (size_t i = 0; i != HUNDRED_MILLION; ++i)
    {
        lst.push_back();
    }

    return lst;
}

int main() {
    CurrentTime ct;

    auto start = ct.milliseconds();
    List list = createList(ct);
    auto end = ct.milliseconds();

    cout << "Created Duration: " << (end - start) << " milliseconds." << endl;

    start = ct.milliseconds();
    List list2(list);
    end = ct.milliseconds();

    cout << "Copy Duration: " << (end - start) << " milliseconds." << endl;

    start = ct.milliseconds();
    List list3(std::move(list));
    end = ct.milliseconds();

    cout << "Move Duration: " << (end - start) << " milliseconds." << endl;

    start = ct.milliseconds();
    list = list2;
    end = ct.milliseconds();

    cout << "Copy Assignment: " << (end - start) << " milliseconds." << endl;

    start = ct.milliseconds();
    list = std::move(list3);
    end = ct.milliseconds();

    cout << "Move Assignment: " << (end - start) << " milliseconds." << endl;

}

Note: Your attempt at measuring move assignment was wrong. You were measuring the time required to create the list then move it. So I removed that output.


You haven't actually implemented a binary tree.  But I'll make some points about your existing code before explaining what is missing.

That's not a node, it's a tree

Your base class is a node when it should be a tree
Wrapping the nodes in a tree class which knows nothing other than it contains nodes is artificial and obstructive

Like many algebraic data types, a binary tree is a recursive type.  A node is a tree (one which can hold other trees).  Nil/Empty is a tree.

Instead of working with that, you have an inflexible wrapper class Tree and a set of case classes which implements nodes.  That incurs many penalties.  For a start, you have no representation in your type system of the empty tree.  Secondly, you lose the ability to create simple, elegantly recursive methods for your case classes.

Look how much simpler your code can be if you work with that, rather than fight it:

abstract class BinaryTree[+A] {
  def isEmpty: Boolean
  def isValid: Boolean
}

case object EmptyTree extends BinaryTree[Nothing] {
  def isEmpty = true
  def isValid = true
}

case class NonEmptyTree[A](
    var data: A,
    var left: BinaryTree[A],
    var right: BinaryTree[A])
    (implicit ord: Ordering[A]) extends BinaryTree[A] {
  def isEmpty = false
  def isValid: Boolean = {
    import ord._
    def isValidWith(f: A => Boolean, t: BinaryTree[A]): Boolean = t match {
      case NonEmptyTree(that, _, _) => f(that) && t.isValid
      case EmptyTree => true
    }
    isValidWith(data < _, left) && isValidWith(data > _, right)
  }
}

See how this works with the actual class hierarchy to build comprehensive tree functions simply and recursively? It should be fairly obvious how you could add depth or size methods.

You don't need that wrapper class.  What I do recommend is

Make the abstract class sealed (improves pattern matching performance and keeps the type sound).
Create a BinaryTree companion object containing an apply factory method for creating trees.
Make the constructors for BinaryTree and EmptyTree private (if the user can create them directly, they might create invalid trees).
Make the class immutable.  Turn each var into a val.

You may balk at that last point but modifying the data held at any one node is a dangerous and pointless thing to do.  The way binary trees work, it doesn't even make sense.  When adding a value, the only places you would want to change left or right is at the node where you insert the value in place of an empty tree (possibly having to move the left branch to the right branch, to preserve ordering).  Adding a value to an immutable tree is only marginally more complicated than to a mutable one and much safer.  Also, you regain the option of variance (if you want it, although I recommend against).

My final recommendation: throw away that isBST/isValid method.  It's pointless...

That's not an implementation

Nothing in your code actually implements a binary tree. All you've done is provide a shell into which data has to be manually inserted, with a validation method to check whether the manually-constructed tree looks like a binary tree.

But the rules for adding values to an ordered binary tree are simple (OK, more complex if it's a balanced tree). Your type should know how to do that. If you think about it, it shouldn't be hard to create an add method along the same lines as isValid.  I'll start it off for you

sealed abstract class BinaryTree[+A] {
  def isEmpty: Boolean
  def isValid: Boolean
  def add(a: A): BinaryTree[A]
}

case object EmptyTree extends BinaryTree[Nothing] {
  def isEmpty = true
  def isValid = true
  def add[A](a: A): BinaryTree[A] = NonEmptyTree(a, EmptyTree, EmptyTree)
}

case class NonEmptyTree[A](
// Fill in the rest here...

Assuming a non-balanced tree, for NonEmptyTree's version of add, you only need to consider

How would I add a value to a node where left and right are empty?
How would I add a value to a node where right is empty?
If neither left nor right is empty, on which of those do I call the add method?

Once you have implemented add you can throw away isBST because your tree can't be created invalidly (Well, rather than throw it away entirely, move it into your tests).

Other methods you need to consider implementing:

contains
size
depth (vital for balanced trees)
delete (rather trickier than add)
toList
toSet/toSortedSet
toString (OK, I know you've done one but it fails if, for example, type A is a string and could contain spaces).

If you add those, you can also make EmptyTree and NonEmptyTree private, further protecting the soundness of your module.


Stylish underline when input is focused, modern browsers only

Using box-shadows on the input can let you have the same underlining effect without any wrapper or unsemantic markup + strip your CSS a lot :

input[type=text] {
  height:17px;
  border: 0;
  width: calc(100% - 2px);
  margin-left:1px;
  box-shadow: -8px 10px 0px -7px #ebebeb, 8px 10px 0px -7px #ebebeb;
  -webkit-transition: box-shadow 0.3s;
  transition: box-shadow 0.3s;
}
input[type=text]:focus {
  outline: none;
  box-shadow: -8px 10px 0px -7px #4EA6EA, 8px 10px 0px -7px #4EA6EA;
}
<input placeholder="Search..." type="text" value=""/>

For browser support :

box-shadows : IE9+
transitions : IE10+
calc() : IE9+


Your config and name classes are good starts. Here are a few humble suggestions:

I highly suggest steering clear of what is called the entity-attribute-value pattern when structuring your MySQL tables. Here is an article that discusses ways of refactoring. Also, if you are interested in learning more about mysql (and sql in general) I highly recommend the book SQL Antipatterns by Bill Karwin.
In the future, if your projects grow and you want a more robust system, you may want to look into a few concepts such as dependency injection, which will help if and (hopefully) when you ever start unit testing with software like PHPUnit.

Hope this helps!


Building a Map of Set using Java Streams

Have you looked at .groupingBy() and .toSet()?

Map<Integer, Set<MyObject>> collected = Stream.of(...)
    .collect(Collectors.groupingBy(Map.Entry::getKey,
                                   Collectors.mapping(Map.Entry::getValue, Collectors.toSet())));

You possibly want .groupingByConcurrent() instead, though it is not exactly clear why.

Not a repl.it, but a JShell log:

U:\>jshell
|  Welcome to JShell -- Version 13
|  For an introduction type: /help intro

jshell> class MyObject { }
|  created class MyObject

jshell> Map<Integer, Set<MyObject>> result = Stream.of(
   ...>    Map.entry(123, new MyObject()),
   ...>    Map.entry(123, new MyObject()),
   ...>    Map.entry(234, new MyObject())
   ...> ).collect(
   ...>    Collectors.groupingByConcurrent(
   ...>       Map.Entry::getKey,
   ...>       Collectors.mapping(
   ...>          Map.Entry::getValue,
   ...>          Collectors.toSet()
   ...>       )
   ...>    )
   ...> );
result ==> {234=[MyObject@78c03f1f], 123=[MyObject@5ce81285, MyObject@52a86356]}

jshell>


Thread-safe LRU Cache Implementation in Java

I like the codestyle!
Code organization tips:

Its better to move DDLNode into LRU and make it static, because sole purpose of this class is to be used by LRU class.

If you are not going to expose DDLNode to outside world, then it make sense to make it also private. Keeping its fields as public is fine here.

If you want to expose DDLNode to outside world (for example, in iterator), you should think more thoroughly about field access. You can get inspiration from HashMap.Node class, for example: fields here have default access, so HashMap itself can manipulate them without using getter or setters. Also note, that there is no setKey() method for outside world, because if we change the key on the node it will break the map.

Maybe you just put all the classes into 1 file to make it easies for us to read , but if not - its bad practice to have more than 1 class/interface in 1 file.

Optimization tips:

In get() you are doing unnecessary .containsKey() call, because just .get(key) is enough: if key if present, it will find it; if not, then it will return null and you can then just return from method.

Unnecessary containsKey() call in put() as well: you can just check .get(key) == null instead.

head and tail will always occupy memory, event if map is empty. They could be removed, although then you should be more careful will null checks.


Welcome to Code Review!
I'll add to the other answer from Reinderien.
PEP-8
In python, it is common (and recommended) to follow the PEP-8 style guide for writing clean, maintainable and consistent code.
Functions and variables should be named in a lower_snake_case, classes as UpperCamelCase, and constants as UPPER_SNAKE_CASE.
No unnecessary whitespaces are needed around the arguments when defining or calling a function. This applies for referring array/list elements as well.
Functions
Split your code into individual smaller functions, doing singular tasks. A few examples would be, reading/parsing the fasta files, validating sequence of gene, counting occurrences (try collections.Counter package to do this).
CSV/TSV
Python comes with inbuilt package csv which can also be used to write tsv files. You do not need to modify/write each line yourself.
Glob searching for files
Python 3+ has another inbuilt package pathlib, which supports getting all files using a glob pattern. You would again, not need to manually (metaphorically) aggregate all the files with .fa or .fasta extensions.
if __name__ block
For scripts, it is a good practice to put your executable feature inside the if __name__ == "__main__" clause.


Your problem statement is a bit unclear,I'm uncertain what they mean by the children of a transition. In addition I would ask the interviewer what types (categories) of transaction it should support. Let's assume the basic ones, withdrawal, deposit and transfers.

I wouldn't store this information directly into the AccountModel, instead I would create a Transaction class which holds information regarding the transaction which is general and present for each type of transaction, namely: an id, amount, timestamp.

Then you can create subclasses Withdrawal, Deposit and Transfer, these can then be stored in a list of account which represents the history of the account's actions. An action is then performed by creating the action: account.perform(Withdrawal(10)), where accountis the an object of the AccountModelclass. In the perform()method I would check the type of transaction and update the account balance accordingly (which you store in the account directly). This way you don't need to use the sum()to run over the list of transactions each time.


Coding Style and Conventions

A nice coding style can dramatically improve readability, and thanks to IDEs, it's incredibly easy to achieve.

You should use correct indentation! This would make it a lot easier to see what blocks of code belong together (this goes for the PHP and the HTML code).
You should handle the same thing the same way: Sometimes your closing curly brackets are on the same line, sometimes the next; sometimes you use echo($var), and sometimes echo $var (the second version is how it's usually done).
be consistent with your casing. SQL keywords should always be all-uppercase, not only sometimes.
you have some unnecessary parentheses (eg $query  = (...)).

Functions

Extracting functionality to functions increases readability as it's easier to see what a block of code does. It also decreases duplication and increases reusability of your code.

You could introduce functions such as:

countComments($onlyApproved): this can remove the SELECT COUNT(comment_approved) FROM $tablename duplication.
downloadPlugin($pluginName)
extractZip($fileName)
deleteComments($types): $types can be all, unapproved or spam.

Naming

Generally, your variable names are quite clear, but some of them could be more descriptive. Eg un could be unapproved, tablename could be tableNameComments, tablename2 could be tableNameCommentsMeta, query could be deleteComments and query2 could be deleteCommentsMeta.

Misc

If you have an error (eg the database connection failed), don't just continue. Return/Redirect/Die instead.
You should not use mysql_*, as it's deprecated (since 2013). Use mysqli_* or PDO instead (or use the wrapper that WordPress supplies)).
It seems that currently your code always installs the plugin, and additionally deletes comments if the user wants to, which doesn't seem to make that much sense. If I already installed the plugin, and only want to use the comment deletion option of your code, I would need to still download the plugin, which seems like a waste of resources.

WordPress

You should check out how to write plugins for WordPress, it would be a lot nicer than a plain PHP file.

For example, this would make it easier for a reader to understand how your includes work (eg wp-config.php isn't really needed, it's loaded by wp-load.php; on the other hand, you use functions from files which you don't explicitely include).

It would also add some security. Currently, it seems that anyone can access this script, not just admin users, which would be pretty bad. An attacker could delete all comments, and can cause your website to slow down significantly (because the script downloads and unzips a big file each time it is called).


Python: count number of pairs in array(list)

From what I see you are counting all the pairs of equal numbers that can be formed. (If not, please clarify)

It can be done in another way:

Take the first element of the array.
Count the number of elements equal to it in the array. It can be done via filter, storing the result as a new array, then len.
Call pairs over the length of the filtered array of step 2.
Add the result of pairs to an accumulator (previously initalized at 0).
Repeat steps 2--5 from the next element that is not equal to the one taken previously (for the first iteration, it would be the one taken in step 1). This can be done using filter, then assignment over the original array (if you don't want to preserve it).

The accumulator will be the result.

Quickly tested code snippet:

def countPairs(nums):
    count = 0

    while len(nums):
        probe = nums[0]
        count += pairs(len([x for x in nums if x == probe]))
        nums = [x for x in nums if x != probe]

    return count

EDIT.

Filtering can be thought of as an O(n) operation (iterating and adding elements that fulfill the condition). This is done twice inside the loop. Here, n = len(nums).

On the other hand, the external loop will run as many times as unique(nums), where unique is a function that retrieves the number of unique elements inside the array. Why unique? Because on each iteration, all the elements equal to the probe are taken out of the array (including the probe). They can be 1, 3, all of them. This is done for each iteration.

Nevertheless, unique(nums) <= len(nums), so it can be said the external loop will be a O(n) operation in the worst case.

Therefore, my proposed algorithm runs in O(n^2) time, due to traversing the whole array at most as many times as elements would be in the array.


Cryptopals first challenge - hexadecimal to base64

That is a very pure solution that does not use any available feature. It is a solid solution.

However everything is String, even the conversion from a byte as two hexadecimal digits uses integer, but converts it back to a string.

The same code style of yours would allow immediately convert every hexadecimal digit to 4 bits.

    final String[] nibbles = { "0000", "0001", "0010", "0011",
            "0100", "0101", "0110", "0111",
            "1000", "1001", "1010", "1011",
            "1100", "1101", "1110", "1111" };
    int nbitsRaw = hex.length() * 4;

    // Make nbits a multiple of 6
    int nbits += (6 - (nbitsRaw % 6)) % 6;
    StringBuilder sb = new StringBuilder(nbits);
    hex.codePoints()
            .forEach(hexdigit -> {
                int value = hexdigit <= '9' ? hexdigit - '0' : 9 + (hexdigit & 0xF); // 0-9A-Fa-F
                sb.append(nibbles[value]);
            });
    for (int i = nbitsRaw; i < nbits; ++i) {
        sb.append('0');
    }

Best of course would be using the bits in an int, not needing to juggle string constants of binary numbering. Especially the loops hurt. One would indeed far better use a Map<String, Character> but I understand your requirement of not using any higher construct.

The code is necessarily slow. You can try a longer input, and will probably have to wait for a result.

String concatenation is slow; char[] or StringBuilder would be advisable.
One can always do new String(charArray).

Stylistic:

hextobase64 by java camel case convention: hexToBase64
conversion no-namer: hexByteToBits
The constants could be fields private static final String[] BASE64 i.o. base64.


Clojure solution to HackerRank Challenge 'Restaurant' under Number Theory

You've implemented a brute-force solution, trying every square dimension from 1 up to the minimum of l, b, and 1000.

The optimal square size is simply the greatest common divisor of l and b.  A very simple algorithm to calculate the GCD is the Euclidean algorithm.

(defn gcd [a b]
      (if (= b 0)
          a
          (gcd b (mod a b))))

Calculating the minimum number of slices follows easily.

(defn min-number-of-slices [l b]
      (let [side (gcd l b)]
           (/ (* l b) (* side side))))

You can try calling min-number-of-slices in this ClojureScript demo:

.code { font-family: Monaco, monospace; font-size: 10pt; } #log { height: 10em; overflow: auto; white-space: pre-wrap; } #input { width: 100%; height: 12em; }

<textarea id="input" class="code"
> (defn gcd [a b]
        (if (= b 0)
            a
            (gcd b (mod a b))))

  (defn min-number-of-slices [l b]
        (let [side (gcd l b)]
             (/ (* l b) (* side side))))

  (min-number-of-slices 6 9)
</textarea>


Using T type parameter to clone a collection

You can replace your loop with AddRange():

public T CloneCollection<T>(IEmployees employees) where T : IEmployees, new()
{
    T collection = new T();
    collection.AddRange(employees);
}

Additional thought:

Note that your solution and this solution are simply cloning the list and not the items in the list.  If you update an Employee, the employee will be modified in both lists.  If this is NOT the desired behavior, you will need to clone each employee as well.


If you can change your file format slightly (to type=value or type:value) I'd suggest using the Java Properties class. It can parse the file from a stream for you (Untested code):

final public class FileParser
{
    public static final Message parse(String text) {
        text = text.replace("/", ":");
        Properties typeValues = new Properties();
        typeValues.load(new StringReader(text));

        return MessageFactory.createFromHashTable(typeValues);
    }
}

Note that Properties extends HashTable, not HashMap. They chose HashTable because HashMap is not thread-safe. They work pretty much the same way, though.

On structure: I like the factory format, and it makes sense to use it here. You didn't mention whether the field types are known; if they are your factory code is fine. (It looks like they are, since you call several different constructors with fixed numbers of arguments.)


One point which I may suggest is reorder if statements to reduce indentation:

@Override
public int compareTo(Version o)
{
    int result = this.major.compareTo(o.major);
    if (result != 0)
    {
        return result;
    }

    result = this.minor.compareTo(o.minor);
    if (result != 0)
    {
        return result;
    }

    result = this.minor2.compareTo(o.minor2);
    if (result != 0)
    {
         return result;
    }

    return this.suffix.compareTo(o.suffix);
}

Also, I think you can omit this keyword.


What is the shortest snippet that emulates `include` in JavaScript without third-party scripts?

Here is what I do:

var a_script= document.createElement('script');
a_script.src = 'http://www.blah.com/some_script.js';
document.head.appendChild(a_script);

I should mention that in production I pretty much always combine all javascript files into one larger, minified, and google closure compiled file.


Implementation of Longest Common Subsequence

You could use an explicit memoizer rather than incorporating caching into your function.
This will make your function easier to understand.
You can use functools lru_cache if you are using Python3.
You should evaluate based on truth, rather than length. len(s1) == 0 is 'bad'.
You can use a turnery operator to reduce the repetition of your code.
Your else can be removed, to prevent the arrow anti-pattern.
And reduce the amount of indentation.

def memoize(fn)
    def inner(*args):
        try:
            return cache[args]
        except IndexError:
            cache[args] = fn(*args)
            return cache[args]
    return inner

# Natural abstracted algorithm.
@memoize
def lcs(s1, s2):
    if not s1 or not s2:
        return 0

    return (
        1 + lcs(s1[:-1], s2[:-1])
        if s1[-1] == s2[-1] else
        max(lcs(s1[:-1], s2), lcs(s1, s2[:-1]))
    )


The original solution from the question, as well as the one suggested by @oopexpert seem too complex and over-engineered.

I guess that the author of the question is trying to implement just a simple wrapper around DriverManager.getConnection(), which reads connection parameters from an expected location.

Some remarks about the original design choices:

getConnection() should return a new Connectioneach time. The huge drawback of the original solution is that the returned instance represents a sort of singleton. What happens if this instance is closed somewhere by the caller?
I don't suggest to use connection pooling here, e.g. Hikari - let this topic just remain out of scope of this review.
There is not enough reason to use stateful objects for the functionality: we need just to provide some additional expected values to the factory method and can remain in static context.
The exceptions should be re-thrown, except the I/O that might occur when the expected properties cannot be loaded: this is critical and blocking for the functionality and means a completely unwanted state of the application.
Since JDBC4, there is no need to call Class.forName to load the driver. THe driver only needs to be on the classpath.

How it could look like after refactoring:

public class Database {

  private static final String PROPS_FILE_NAME = "database.properties";
  // optionally extract prop keys in constants

  public static Connection getConnection() throws SQLException {
    Properties properties = readProperties();
    String url = String.format("jdbc:mysql://%1$s/%2$s",
                               properties.getProperty("hostname"),
                               properties.get("database"));
    return DriverManager.getConnection(url,
                                       properties.getProperty("username"),
                                       properties.getProperty("password"));
  }

  private static Properties readProperties() {
    try (InputStream input = Database.class.getResourceAsStream(PROPS_FILE_NAME)) {
      Properties props = new Properties();
      props.load(input);
      return props;
    } catch (IOException ex) {
      throw new IllegalStateException(ex);
    }
  }

}