Overview
Templated classes "normally" should provide all the code at the point of usage. As a result you should probably not have a separate shared.cpp. Though some people put the definitions in a separate shared.tpp file that is included by the header file.
Code Review:
You are missing a constructor for nullptr.
Though nullptr can be converted to any other type the compiler can not know what type you want in this situation so you would need to be explicit. But it would be nice to allow auto conversion from nullptr to the correct shared pointer type.
 void myFunc(smp::shared_ptr<int>&& ptr) { /* Stuff */}

 int main()
 {
     myFunc(nullptr); // This fails.
                      // as you defined an explicit constructor.
                      // But this is totaly safe so it would be nice if it
                      // simply worked rather than forcing the long hand.
 }

So I would add a constructor for this situation.
 smp::shared_ptr::shared_ptr(std::nullptr_t);

Non standard copy constructor and move constructor:
            shared_ptr(shared_ptr& ptr);           // Would expect const ref
            shared_ptr operator=(shared_ptr& ptr); //

In the current state these can not catch temporary values.

Most people forget the noexcept. So well done.
            shared_ptr(shared_ptr&& ptr) noexcept;
            shared_ptr operator=(shared_ptr&& ptr) noexcept;

You should probably return a reference here:
            T operator*();

Otherwise you are going to force a copy of the internal object as it is returned. Just like the operator-> this does not affect the state of the shared pointer so this is const.
In std::shared_ptr this is a noexcept operation. I could personally argue over that. But smarter people than me wrote the standard so I would go with them.
            T&       operator*() const noexcept;

Good.
T* operator->() const;
But like the operator* can be noexcept.
            T* operator->() const noexcept;

You don't want this accidentally converting in non boolean contexts.
            operator bool() const;

In this situation:
      smp::shared_ptr<int>   x(new int{6});
      smp::shared_ptr<float> y(new float{5});

      if (x == y) {
          // Because of your bool operator
          // they are converted to bool (for both this is true)
          // resulting in this code saying they are equal.
          std::cout << "Equal\n";
      }

Use the explicit here:
      explicit operator bool() const;

The issue I have hear is that if the new fails (for RefCount) then you leak the pointer.
Once you had the pointer to the constructor of a shared pointer you are seeding all responsibility of the pointer. That mean if the object fails to correctly construct you need to make sure the passed pointer is deleted. So in the situation of new failing you need to call delete on the pointer.
template<typename T>
shared_ptr<T>::shared_ptr(T* ptr)
    : obj_ptr{ptr}, ref_cnt{new RefCount()}
{
    ref_cnt->object_ = ptr;
    if(ptr)
        ++ref_cnt->use_count_;
}

Add a try catch block to the initializer list:
template<typename T>
shared_ptr<T>::shared_ptr(T* ptr)
try
    : obj_ptr{ptr}
    , ref_cnt{new RefCount()}
{
    ref_cnt->object_ = ptr;
    if(ptr)
        ++ref_cnt->use_count_;
}
catch(...)
{
    delete ptr;
}

If you are copying a shared_ptr then you should be using the same ref_cnt not a brand new one.
You should prefer to do as much work in the initializer list as possible to prevent multiple initializations.
    shared_ptr<T>::shared_ptr(shared_ptr& ptr)
        : ref_cnt{new RefCount()}
    {
        obj_ptr = ptr.obj_ptr;
        ref_cnt = ptr.ref_cnt;

        ++ref_cnt->use_count_;
    }

// Fixed:
    shared_ptr<T>::shared_ptr(shared_ptr& ptr)
        : obj_ptr(ptr.obj_ptr)
        , ref_cnt{ptr.ref_cnt}
    {
        if (obj_ptr) {
            ++ref_cnt->use_count_;
        }
    }

Here you forget to decrement the ref_counter of the previous object (so potentially allowing a leak). I would use the copy and swap idiom to provide the strong exception guarantee (it also covers self assignment).
    template<typename T>
    shared_ptr<T> shared_ptr<T>::operator=(shared_ptr& ptr)
    {
        obj_ptr = ptr.obj_ptr;  // Old object potentially leaked.
        ref_cnt = ptr.ref_cnt;  // Old ref count potentially leaked.
        ++ref_cnt->use_count_;

        return *this;
    }

Again incorrectly increment the counter.
    template<typename T>
    shared_ptr<T>::shared_ptr(shared_ptr&& ptr) noexcept
        : obj_ptr{nullptr}, ref_cnt{new RefCount()}
    {
        obj_ptr = std::move(ptr.obj_ptr);
        ref_cnt = std::move(ptr.ref_cnt);

        ptr.reset();
    }

The reset will decrement the counter. Since you have moved the object there has been no decrement.
Simpler to simply set this one up as null and then swap.

This can fail.
    template<typename T>
    shared_ptr<T> shared_ptr<T>::operator=(shared_ptr&& ptr) noexcept
    {
        if(obj_ptr)
            reset();

If ptr is the only copy. Then calling reset is going to free the object. Thus any other code is going to now manipulate a freeed object.
        obj_ptr = std::move(ptr.obj_ptr);
        ref_cnt = std::move(ptr.ref_cnt);

        ptr.obj_ptr = nullptr;
        // If you don't reset the ref count object then
        // eventually `ptr` is going to go out of scope and
        // its destructor is going to mess with the ref count object.

Simpler to simply set this one up as null and then swap.

Why does the shared object have to be copied constructed?
    template<typename T>
    shared_ptr<T> make_shared(T object)
    {
        return shared_ptr<T>(new T{object});
    }

Would be nive to allow the type T to be constructed using any of its normal constructors that take parameters.
    template<typename T, typename... Args>
    shared_ptr<T> make_shared(Args...&& args)
    {
        // Though this is the simplist way to do it.
        // The standard version tries to make the whole thing more efficient.
        // by allocating the space for the object T and the ref-count
        // in a single allocation (thus removing the need for an extra
        // call to new).
        return shared_ptr<T>(new T{std::forward<Args>(args)...});
    }

    template<typename T>
    T* shared_ptr<T>::operator->() const
    {
        return &*obj_ptr; // Not sure why that is rewquired.
    }

This implies you don't keep a reference count object for nullptr. But your object always has a reference counter and you will need to make sure it is updated correctly.
template<typename T>
shared_ptr<T>::~shared_ptr()
{
    if(obj_ptr) // Always call reset.
                // Otherwise you are potentially leaking
                // the reference count object.
        reset();
}

Which leads us to the reference count object handling. In reset you need to call delete on the object managed and the reference count object if the count reaches zero.
template<typename T>
void shared_ptr<T>::reset()
{
    obj_ptr = nullptr;

    if(ref_cnt)
        --ref_cnt->use_count_;

    if(ref_cnt->use_count_ == 0)
        // This is not correct.
        // You have called the destructor but leaked the object space.
        ref_cnt->object_->~T();

        // You need to delete the object and the memory used by the
        // reference count object
        // delete ref_cnt->object_;
        // delete ref_cnt;
}

Self Plug: Wrote a lot about shared pointers here:
https://lokiastari.com/series/
Read three articles on shared pointers.


First of all, there is a bug in the code - if an array is empty, you'll get a "maximum recursion depth exceeded" error. Improve your base case handling:

if len(array) <= 1:
    return array

Other improvements:

the merging logic can be simplified - loop while where are elements in both arrays and append what is left after the loop
extract the merging logic into a separate merge() function
improve the variable naming - e.g. use left_index and right_index as opposed to i and j, result instead of ret
no need to enclose if conditions into outer parenthesis
Python 3 compatibility:

use print() as a function instead of a statement
use // for the floor division

Improved version:

def merge(left, right):
    """Merge sort merging function."""

    left_index, right_index = 0, 0
    result = []
    while left_index < len(left) and right_index < len(right):
        if left[left_index] < right[right_index]:
            result.append(left[left_index])
            left_index += 1
        else:
            result.append(right[right_index])
            right_index += 1

    result += left[left_index:]
    result += right[right_index:]
    return result

def merge_sort(array):
    """Merge sort algorithm implementation."""

    if len(array) <= 1:  # base case
        return array

    # divide array in half and merge sort recursively
    half = len(array) // 2
    left = merge_sort(array[:half])
    right = merge_sort(array[half:])

    return merge(left, right)


Loop through array of files and rsync to Dropbox

Not much to complain for your first script, congrats.

I'd perhaps change it so that all files are rsynced with the same
command, if you look at the rsync documentation multiple sources may
be specified for a single target.  This would be more relevant for
bigger programs - you usually want to avoid running multiple processes
when you can have a single one do all the work, it makes bookkeeping
easier in the long run (and it's faster).  I'll leave that as an
exercise for the reader though.

Since expanduser will perform tilde expansion I'd not split off home
like this, just expand it twice, it's more readable IMO if you know what
~ means for paths (and most readers will know).  If you do keep it
like this, then consistently use os.path.join instead of concatenating
/ manually.  Actually the one use of os.path.join in the script is
wrong, it should be os.path.join(src, item).

The isatty is a nice touch.

For executing the process you're concatenating all arguments and then
also run them through a shell - the concatenating is problematic when
you have filenames with spaces in them, so in general I'd really rather
go with the list argument approach.  (Also see the security notes on the
documentation page of subprocess.)  If you're going through the shell
there's also no need for the manual expanduser; you can easily test
this if you prefix the rsync with echo (like I did to test the
script).

Looking at the documentation Popen can of course be used like this,
but it's not the most convenient option, I'd say either call or
check_call are more appropriate here - both wait for the process to
complete, while the latter also checks the exit status, which is vital
for more complex programs (without it you don't know if the process
completed successfully)!

#!/usr/bin/python

import os
from os.path import expanduser
import sys
import subprocess

dotfiles = [
    '.ackrc',
    '.tmux.conf',
    '.vimrc',
    '.zshrc',
    '.gitconfig',
    '.ssh/config',
    '.zsh/MyAntigen.hs',
    '.vim/colors/dracula.vim'
]

src = expanduser('~')
dest = expanduser('~/Dropbox/Dotfiles')

rsync = ['rsync', '--times']
if sys.stdout.isatty():
    rsync.append('--progress')

for item in dotfiles:
    subprocess.check_call(rsync + [os.path.join(src, item), dest])


PrimeFactors why do you do output there? It would be much better if you return an IEnumerable<long> with all the prime factors of the number passed as input. Let the client decide what it needs to do with the result. It might need to output it but it might need to do something with all the prime factors instead.

Why do you create an object for that class? It should not hold any state. What you need is a static method. It should be something purely functional. static IEnumerable<long> PrimeFactors(long number).
With your code, the client of your code has to instantiate a new PrimeFactors instance, which is useless.

Holding the state also causes it to produce wrong results in cases such as the following:

var primeFactorFinder = new PrimeFactorFinder();
primeFactorFinder.PrimeFactors (33);
primeFactorFinder.PrimeFactors (5);

which outputs:

All prime factors of 33 are :
3,11,
Largest Prime Factor = 11
All prime factors of 5 are :
3,11,5,
Largest Prime Factor = 5

clearly something went wrong because _myPrimeFactors, which should really be local to FindPrimeFactors never got cleared between the first and the second invocation of PrimeFactors.

Your algorithm looks ok. If you need more performances you probably need to trade some memory for a better execution time and adopt a solution based on a Sieve of Eratosthenes-like approach.


Image gallery.
To be completely honest, if you're wanting to make an image gallery, you would save yourself a lot of time and trouble by using Wordpress.org
Example: http://psychoproductions.net/psychographics/

That said...
Assuming your images are stored server-side, and you really want to code this yourself, unless you want to type every image URL one by one, you may want to look into a server side language that can scan through your image folder(s), parse the paths and wrap it into HTML tags. It really varies what you can do depending on your server environment...

A few other things

There's no point declaring class is there is not one to assign to it.
Another example:

alt="..." may as well be left out, if an ellipsis will be its content. Why not class="something meaningful"?


We need to do some basic sanity checking of the inputs - alias names can't contain whitespace, for example, and any newlines in the expansion will be treated as the end of the alias definition (and the following text will then be a new command in your .bashrc).

The source ~/.bashrc in the call to os.system() looks pointless, as that shell terminates immediately after.


I made a Python program to calculate price based on Inflation Rate

The code itself is clear enough, the spacing and variable naming is ok. You mix camelCase and snake_case. Stick to one. PEP-8 advises snake_case for function and variable names and PascalCase for classes.

Only the abbreviation of principal_amt is rather futile. Just use the full name, it costs 3 characters more.

functions

You better separate your program in functions:

read the data
get the user input
calculate the difference
present the results

That way your program is easier to understand, test and reuse

My rule of thumb on where to split the program, is on where data is exchanged from one part to another.

testing

Now you've separated your program in logical blocks, you can start testing the individual parts.

read the data

Make a small function, passing in the filename as argument and getting the index per year back. Here you can use pandas further. For starters, you can make the year a pandas.Period, so you can index the year immediately. Then you can do the division by 100 already. Since pandas has a nice cumprod function, you can already add 1 to each index

def get_inflation_rate(
    filename: typing.Union[Path, str, typing.IO]
) -> pd.Series:
    """Read the inflation data from `filename`"""
    inflation_rate = (
        pd.read_csv(
            data_file,
            skiprows=16,
            parse_dates=["date"],
            usecols=[0, 1],
            index_col=0,
        )
        .div(100)
        .add(1)
        .rename(columns={" Inflation Rate (%)": "inflation_rate"})
    )["inflation_rate"]
    inflation_rate.index = inflation_rate.index.to_period()
    return inflation_rate

This returns a Series with the year as index and the inflation ratio as value

date
1960    1.017799
1961    1.016952
1962    1.036322
1963    1.029462
...
2014    1.063532
2015    1.058724
2016    1.049410
2017    1.024909
2018    1.048607
Freq: A-DEC, Name: inflation_rate, dtype: float64

I included a docstring and typing information so the user of this function and his IDE can know what to expect.

user input

If your user returns some nonsense, your program will do little useful. Better to warn the user as clearly as possible. You can define a function like this:

def get_input(
    *, message, possible_values: typing.Optional[typing.Collection[str]] = None
) -> str:
    while True:
        value = input(message)
        if possible_values is None or value in possible_values:
            return value
        print("Not one of the possibilities")

A more generic one, which can also convert to float if needed can look like this:

T = typing.TypeVar("T")

def get_input(
    *,
    message: str,
    possible_values: typing.Optional[typing.Collection[T]] = None,
    converter: typing.Optional[typing.Callable[[str], T]] = None,
) -> typing.Union[T, str]:
    """Get and convert the user input.

    Tries to call `converter` on the input value.
    If this raises a `ValueError`, asks again.

    If `possible_values` is defined, checks whether the returned value is in
    this collection. If it is not, asks again.

    Args:
        message (str): The message to present to the user.
        possible_values (typing.Collection[T], optional):
            A selection which must contain the user input. Defaults to None.
        converter (typing.Callable[[str], T], optional):
            A function to try to convert the user input. Defaults to None.

    Returns:
        typing.Union[T, str]: The converted user input.

    """
    while True:
        value = input(message)
        if converter is not None:
            try:
                value_converted = converter(value)
            except ValueError:
                print("Invalid value")
                continue
        else:
            value_converted = typing.cast(T, value)
        if possible_values is None or value_converted in possible_values:
            return value_converted
        print("Not one of the possibilities")

calculate the difference

Since you have a series with all the inflation ratios already with periods as index, this becomes easy calculate the cumulative product, or even accept datetime.datetime objects as arguments.

import datetime
def calculate_inflation(
    amount: float,
    start: typing.Union[datetime.datetime, str],
    end: typing.Union[datetime.datetime, str],
    inflation_rates: pd.Series,
) -> typing.Tuple[float, typing.Dict[str, float]]:
    inflation_over_period = inflation_rates[start:end]

    return (
        amount * inflation_over_period.product(),
        {
            str(year): amount * index
            for (year, index) in inflation_over_period.cumprod().iteritems()
        },
    )

bringing it together:

if __name__ == "__main__":
    data_file = Path("<my path>")
    inflation_rates = get_inflation_rate(data_file)
    start_year = get_input(
        message="Enter the starting year:",
        possible_values=set(inflation_rate.index.map(str)),
    )
    end_year = get_input(
        message="Enter the ending year:",
        possible_values={
            year for year in inflation_rate.index.map(str) if year > start_year
        },
    )
    amount = get_input(message="Specify the amount:", converter=float)
    print(
        calculate_inflation(
            amount=amount,
            start=start_year,
            end=end_year,
            inflation_rates=inflation_rates,
        )
    )


Native T-SQL
I don't know enough about linq to do a proper code review for that, however as far as performance is concerned I think T-SQL would take care of the expensive part of your query more efficiently.
The following query will not get you all the information from your entire query, but it would take care of at least this section:
Year = date.Year,
Month = date.Month,
AllIncidents = incidentsByMonth.Count(),
Flagged = incidentsByMonth.Count(ibm => ibm.IsSerious),
SentToHospital = incidentsByMonth.Count(x => x.Treatments.Any(it => it.TreatmentTypeId == (int)TreatmentTypes.Senttohospital)),
FallsWithInjuries = incidentsByMonth.Count(ibm => ibm.IncidentTypes.Any(it => it.IncidentTypeId == (int)IncidentTypes.Fall) && ibm.InjuryTypes.Any(inj => inj.InjuryTypeId != (int)InjuryTypes.None)),
FallsWithFracture = incidentsByMonth.Count(ibm => ibm.IncidentTypes.Any(it => it.IncidentTypeId == (int)IncidentTypes.Fall) && ibm.InjuryTypes.Any(inj => inj.InjuryTypeId == (int)InjuryTypes.Fracture)),

Note that I made assumptions about your schema design and you may need to make some adjustments. Also please note that I used more descriptive table aliases as well to make it easier for Mr. Maintainer.
DECLARE @dateStart DATE = '2014-01-01'; -- or whichever date you want
DECLARE @dateEnd DATE = DATEADD(MONTH, 6, @dateStart); -- 6 months later e.g. July 1 2014
SELECT
    DATEPART(yyyy, incd.date) AS Year,
    DATEPART(mm, incd.date) AS Month,
    COUNT(incd.IncidentId) AS AllIncidents,
    COUNT(incd.IsSerious) AS Flagged,
    (SELECT COUNT incd.IncidentId
        FROM incd
        WHERE treat.TreatmentType = 'SenttoHospital') AS SentToHospital,
    (SELECT COUNT incd.IncidentId
        FROM incd
        WHERE incdType = 'Fall'
        AND injuType.InjuryType <> 'None') AS FallsWithInjuries,
    (SELECT COUNT incd.IncidentId
        FROM incd
        WHERE incdType = 'Fall'
        AND injuType.InjuryType = 'Fracture') AS FallsWithFracture,
FROM Incidents AS incd
LEFT JOIN IncidentTypes AS incdType ON inc.IncidenTypeId = incdType.IncidentTypeId
LEFT JOIN InjuryTypes AS injuType ON inc.InjuryTypeId = injuType.InjuryTypeId
LEFT JOIN Treatments AS treat ON inc.TreatmentTypeId = treat.TreatmentTypeId
WHERE incd.date >= @dateStart
AND incd.date < @dateEnd;


Suggested parameter names for utility class function

public class MySuperUtil {
    public static List<Long> updateAndSubtract(List<Long> first, List<Long> second) {
        List<Long> updated = updatePlaceholdersWithLargestIds(second, first);
        Collection<?> difference = CollectionUtils.subtract(first, updated);
        return castCollectionToListUsingClass(difference, Long.class);
    }

My assessment of the code is that, as a Util method, it is poorly named too. The methods are not self-documenting.

I read updatePlaceholdersWithLargestIds, and with two lists as inputs, where is the Id? What does 'updated' look like? I am at a loss.

What I can say is that there is some black-box function that does some update, but, does it manipulate the data in first, or second? Why is 'second' specified first? Why is it not: updatePlaceholdersWithLargestIds(first, second);

Also, why does an update* function return a value, and not update something? it should be called get* or just largestIds. Or, does the function do both? Does it update values and also return values? Yuck!.

The subtract function. Does it subtract the first value from the second, or the other way around?

castCollectionToListUsingClass I presume this method has the signature:

public static <U> List<U> castCollectionToListUsingClass(Collection<?> collection, Class<U> clazz);

Why all the redundancy? That method name duplicates all the signature components. It is tautology. Also, why does it take a collection, and return a List? It should return a Collection too, or it should be parameterized too.... at minimum, just rename the method to something like (I like the word coerce):

public static <U> List<U> coerceMembers(Collection<?> collection, Class<U> clazz);

So, I would agree that naming is a concern in your code, but it extends beyond just your method.

Your method does not tell me what it does, and the code in the method does not help much either. The code in the method does not help me help you rename the method.


If you don't want to recompute the overlapping sub-problems, you could use a cache.

Create the cache in your class:

private HashMap<int, int> resultCache = new HashMap<int, int>();

Then check it at the top of the function:

if (resultCache.contains(goldCoinAmount)) return resultCache.get(goldCoinAmount);

And before returning a result, cache it:

if(goldCoinAmount > totalIntermediate)
    resultCache.put(goldCoinAmount, goldCoinAmount);
    return goldCoinAmount;
else{
    int maxHalfPortion = ByteLandianConversion(halfValue);
    int maxThirdPortion = ByteLandianConversion(thirdValue);
    int maxFourthPortion = ByteLandianConversion(fourthValue);

    int result = maxHalfPortion+maxThirdPortion+maxFourthPortion;
    resultCache.put(goldCoinAmount, result);
    return result;
}

Otherwise, your code is really fairly straightforward and thus fairly readable/maintainable. Readability is far more important than raw performance most of the time.


Enabling or disabling buttons on certain events

I would write it as something like:

jQuery(document).ready( function($) {

    function updateDisabled() {
        var test     = $('label.setting[data-setting=alt] input:visible').val();
        var test2    = $('input[data-setting=alt]:visible').val();
        var disabled = !test && !test2;
        $('.media-modal .media-button-insert').prop("disabled", disabled);
        $('.media-modal .media-button-select').prop("disabled", disabled);
    }

    $(document.body).on( 'DOMNodeInserted click', '.media-modal', updateDisabled);
    $(document.body).on( 'input propertychange paste', 'label.setting[data-setting=alt] input, input[data-setting=alt]', updateDisabled);

}

You could also rewrite:

$('.media-modal .media-button-insert').prop("disabled", disabled);
$('.media-modal .media-button-select').prop("disabled", disabled);

As

$('.media-modal .media-button-insert, .media-modal .media-button-select').prop("disabled", disabled);

(Although I prefer keeping them separate) or maybe better giving your buttons an extra class and writing:

$('.media-modal .media-button').prop("disabled", disabled);


Email notifications system in Rails project

# TODO: refactor this bullshit

While amusing to devs, swear words probably don't belong in production code.

In your copypasta of schema.rb, I do believe you forgot to paste the end keywords.

As a side note, you can also write null: false instead of :null => false; as far as I can tell, this is the accepted syntax. You can do the same thing with through: :email_notifications and anything of the form Symbol => BasicObject. This syntax was added after this question was posted, but if you're still interested in updating it, that's what I'd do.

Personally, I prefer to use Symbols instead of Strings as table names, though that's entirely personal preference.

In your models, you also forgot an end at the end of your first class.

Aside from that... Well, honestly, it looks good to me. Since I can't really tell what Setting and Notification are supposed to represent on a more concrete level than their names alone can give, I can't give good advice on how to link them together. However, I don't see why you need a many-to-many, if I'm understanding the purpose of Setting and Notification correctly. It seems like it could be a one-to-many relationship, though I'm not sure which side should be the one.


Abstracting device IO / glue logic in a CPU emulator

Overhead of std::function
The main problem is that you are using std::function, and this comes with some overhead. In particular, it will allocate storage (using new internally) since your lambdas are capturing variables. Since memory allocations can have side effects (they might even throw exceptions if memory could not be allocated), the compiler cannot optimize them away.
Consider just storing the state of a pin as a  bool
The state of an output pin is just true or false. Instead of storing a function that calculates the state, consider just storing the current state in a bool. It seems unlikely to me that always ensuring the state of the pin is set correctly is less efficient than having a function that calculates it whenever you need the value. An InputPin should then not store a copy of an OutputPin, but either a reference to an OutputPin, or if you want to still be able to have an expression assigned to an InputPin, have it store the function that calculates the input value.
Once you do this, everything simplifies enormously, and the compiler will have no trouble optimizing this code.
Here is an example:
#include <functional>

using OutputPin = bool;

template<typename Function>
class InputPin {
    Function f;

public:
    InputPin(const Function &f): f(f) {}

    operator bool() const {
        return f();
    }
};

int main()
{
        OutputPin   a(true), b(true), c(true);
        InputPin    i([&]{return !a & b & c;});

        return i;
}


Redirect for subdomains and secondary domains

Your third rule…

# Prevent access to staging through secondary.com/staging and instead use staging.secondary.com
RewriteCond %{HTTP_HOST} ^secondary.com [NC]
RewriteRule ^(.*)$ http://www.secondary.com$1 [L,R=301]

… is basically a sloppier version of your first rule with a misleading comment.

The remaining two mod_rewrite rules can be combined as:

# Canonicalize hostname of secondary domain
RewriteCond %{HTTP_HOST} ^$secondary\.com$|^(www\.)?secondary\.primary\.com$ [NC]
RewriteRule (.*) http://www.secondary.com/$1 [R=301,L]

Note that if your site supports HTTPS, the rule would redirect HTTPS requests to unencrypted HTTP.


I think you can remove all of the comments you have here, as I think you are already using mostly meaningful variable names (a few minor comments on this below) and the code is clear in intent.  The comments here mostly seem like clutter. This is not to mention that comments at the end of a line of code are generally hard to read.  Comments should typically be before the line/section of code to which they apply on their own line(s).
Typically jQuery plug-ins are applied like $([selector]).slider(). Such that inside the plugin code this refers to a jQuery collection.  You are not treating this as a collection but rather as an individual element.  Think of this as a collection.  Also, I don't think selector setting is relevent for this reason.  Typically element selection has already been applied by the point you are in the plug-in code.  Keeping this philosophy of potentially working with a collection of elements, would also allow you to invoke multiple sliders with one pass.

For example:

// every element with slider class will be turned into a slider
$('.slider').slider();

Typically jQuery plug-ins are designed to maintain chaining so a return statement should be applied to allow the collection that the plug-in is acting against (or some filtered subset of it depending on the logic of the plug-in) to be returned for further method chaining.
Should $children be named $slides to indicate the selected children represent the slides to be displayed?
Regarding var $currentChildIndex, why not just currentChildIndex?  The styling approach of prepending $ to variables is typically to help identify jQuery collections.  This is not a jQuery collection. This variable name is probably also unnecessarily long.  Perhaps just currentIndex which still conveys clear meaning.
I don't think you need $current at all.  You can directly reference members of the $children collection directly using $children.eq(currentIndex)
No need to iterate $children to remove class from inactive children.  You can simplify this.

For example:

$children.removeClass('active');
$children.eq(currentIndex).addClass('active');

You can simplify your if-else (to avoid unnecessary else code paths).

For example:

currentChildIndex++;
if(currentChildIndex === $children.length) {
    currentChildIndex = 0;
}

I would recommend using strict comparisons (===, !==) as your default means to compare rather than loose comparisons.  Loose comparisons tend to introduce bugs around truthy/falsey behavior (though in this case there should not be concern as you are clearly only comparing integer values).  IMO, this is just a good habit to get into with one's coding.  Only use loose comparisons where there is a specific reason to do so.

Putting it all together you might have something like:

(function($){
    $.fn.slider = function(options){
        var settings = $.extend({
            speed:3000
        }, options);

        return this.each(function() {
            var $slides = $(this).children();
            var currentIndex = 0;

            setInterval(function(){
                $slides.removeClass('active');
                $slides.eq(currentIndex).addClass('active');
                currentIndex++;
                if (currentIndex === $slides.length) {
                    currentIndex = 0;
               }
            },settings.speed);
        });
    }
}(jQuery));


Your lines are too long which makes things a little difficult to read. The next few points will help with that.
In my opinion your variable names are too verbose. current_index could be replaced with i and most programmers will understand that as an indexing variable.
When generating your current index, there is no reason to take the length of an array slice. The length of array[start:end] will generally be end -
start. When that isn't true its because you are slicing outside of array bounds which probably means your search is over anyway. In any case, you don't really care about array length. You just want the mid point between the two indexes.
there is no reason to pass the result of math.floor to int since both do essentially the same thing (int(2.6) gives 2). In fact, you can avoid both of these entirely by just using the integer division operator // (in python2 integer division is the default for 2 integers: 3/2==1
while True is ok in some limited cases but I generally avoid it when I can because it can easily create infinite loops if you forget a break somewhere... and here you have a lot of breaks. Its not too hard to come up with a condition that will effectively bound your search, and reduce the number of conditions that you have to check for.

Following the above points gives much lighter looking code thats for the most part functionally the same:

def binary_search(input_array, value):
    result = -1
    # simplified variable names and index initializer
    down = 0
    up = len(input_array)
    i = (up - down+1) // 2
    while down < i < up:    # refactored out `while True`
        if input_array[i] == value:
            result = i
            break
        # remove `break` conditions now handled in `while`
        elif input_array[i] > value:
            up = i
            # remove unnecessary string slice, int cast, and math.floor calls
            i = i - (up+1 - down) // 2 # integer division
        elif input_array[i] < value:
            down = i
            i = i + 1 + len(input_array[down+1:up]) // 2 # integer division!

    return result


Get an array of currency exchange prices based on asset

A common convention used in TypeScript/Javascript and other C-based languages is to use all uppercase letters for constants. This makes it easy to spot values that cannot be changed.

So instead of lowercase constants:

const nomicsAPI = 'https://api.nomics.com/v1/';
const nomicsKey = '8feb...;'

make them uppercase. The naming also could be improved - e.g. NOMICS_API_BASE_URL would better describe that the value is the base URL of the API than NOMICS_API.

const NOMICS_API_BASE_URL = 'https://api.nomics.com/v1/';
const NOMICS_KEY = '8feb...;'

You could also consider using the readonly modifier with those constants.

This code (as well as the updated code in your self-answer) is quite repetitive. It would be wise to abstract the common code. That way if something needs to be updated, it can be done in one place. This adheres to the Don't Repeat Yourself
 (i.e. D.R.Y.) principle.

I would first recommend storing each currency in an array:

const currencies = ['USD', 'USDC', 'USDT'];

And abstract out the common code of making the request and throwing an error if the request fails:

const getCurrencyPrice = async (currency) => {
  try {
    const request = prepHeaders(currency);
    const response =  await request.get(NOMICS_PRICES_ENDPOINT);
    if (!response) {
      throw new Error('USD Markets unavailable.');
    }
    return response.data;
  }
  catch(err) {
    console.error(err);
  }
};

That way if any of the requests fail, the Error will be thrown immediately. Also, this function has one job and could easily lend itself to unit testing.

Then use that function to iterate over the array of currencies - optionally with a for...of loop, Array.prototype.reduce(), Array.prototype.forEach(), etc

const getMarkets = async _ => {
  const returnObj = {};
  for (let currency of currencies) {
    const key = 'market' + currency;
    returnObj[key] = await getCurrencyPrice(currency);
  }
  return returnObj;
};

Notice that the code above uses a new constant - NOMICS_PRICES_ENDPOINT - this can be defined with the other constants:

const NOMICS_PRICES_ENDPOINT = 'exchange-markets/prices';

That way if the endpoint needs to be updated, in can be done in one place. Additionally, if the constants were stored in a separate file, you wouldn't need to alter the file that contains all of this code.


Unduplicating prox_pass in nginx location blocks

You may move proxy settings to 'server' block. But proxy_pass should stay at 'location' block

upstream foo {
    server 127.0.0.1:8080;
}

server{
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    location /admin {
        allow 123.90.250.0/24;
        allow 123.66.148.0/24;
        proxy_pass http://foo;
    }

    location / {
        proxy_pass http://foo;
    }
}


Parsing an XML File for a single word/phrase

Linq to XML is your friend

var serverName = XDocument.Load(response.GetResponseStream()).Element("Server").Value;

Your code will be easily broken if someone adds a node to the XML, and your code should be as flexible as possible. Never do such an assumption (It's gonna be the first node)

Your method is blocking, consider making it asynchronous.

using (var response = await request.GetResponseAsync()){

}

And by the way, C# got type inference, so why bother typing the type? Use var instead

var request = WebRequest.Create(xmlLocation);


As @chrfin mentioned, this type of question is best suited for CodeReview.

This is the wrong way to use connections. Keeping a connection open indefinetely is bad because it accumulates locks, transactions remain open,it wastes server resources due to blocking  and forces you to use more connections than you actually need.

ADO.NET (and ADO before it, way back to the late 90s) support connection pooling so that whenever you close a connection, it terminates any existing transactions, frees up all locks and remains dormant until the next time you need a connection with the exact same string. This way, a couple of connections can handle commands from multiple classes.

The difference in speed and scalability can be orders of magnitude because you drastically reduce blocking issues:

The proper way to connect is something like this:

using(var con=new SqlConnection(myConnectionString))
using(var cmd=new SqlCommand(myCommand,con))
{
    cmd.Parameters.Add ...
    ...
    con.Open();

    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(results);

}

You don't need to close the connection explicitly because it's closed automatically when execution exits the using block, even if an exception occurs.

A better solution would be to use an ORM like Entity Framework or NHibernate to handle connections and map the results to objects.

You can find numerous tutorials on using Entity Framework with ASP.NET MVC at Microsoft's ASP.NET site


I want to most efficiently use array values and variables in a WordPress template while abiding by PHP/WordPress best practices and standards

I would not use the pkav function. Beside the fact that the name means nothing (which was stated in the comments) it also restricts the default value to false.
This is wrong when you might expect strings or something else for a certain variable.
From the looks of it, the footer text and button vars look like strings.
I would go with this
<?php
    $options = get_fields('options');
    $footer_text = $options['footer_text'] ?? '';
    $footer_button = $options['footer_button'] ?? '';
?>

I would also go with declaring all variables at the top of the file. It makes the code more readable and will allow a frontend developer to focus on the html part instead of trying to navigate in the if statements.
<?php if ($something) :?>

<?= esc_html($something) ;?>

<?php endif;?>

is easier to read than
<?php if (!empty( $options['footer_text'])) : ?>

<?php echo esc_html($options['footer_text']); ?>

<?php endif; ?>


Using a WCF service client and handling its exceptions

Although paritosh's answer is very helpful, there is additional useful information to take into account when using a service client, as found in this MSDN article :

  It is recommended that a calling application open the channel, use it,
  and close the channel inside one try block.

Let's look at the original try/catch block that was used for the solely purpose of closing the channel :

    try
    {
        myServiceClient.Close();
    }
    catch
    {
    }

This is useless, as stated in the article :

  Datagram channels never fault even if exceptions occur when they are
  closed.

About handling exceptions, MSDN suggests that no unexpected exceptions (like OutOfMemoryException, ArgumentNullException or InvalidOperationException) should be caught when using a service client, as stated in this MSDN article :

  Exceptions that are thrown from communication methods on a Windows
  Communication Foundation (WCF) client are either expected or
  unexpected. Unexpected exceptions include catastrophic failures like
  OutOfMemoryException and programming errors like ArgumentNullException
  or InvalidOperationException. Typically there is no useful way to
  handle unexpected errors, so typically you should not catch them when
  calling a WCF client communication method.

Recommended exceptions to catch while using a service client are TimeoutException and any other exception that derives from CommunicationException.

As the article states :

  One way to handle such errors is to abort the client and report
  the communication failure.

In addition, as this particular project handles it's own FaultException (of type ServiceErrorDetails), the recommended method to catch exceptions while using this service client would be to first catch any TimeoutException, then any FaultException and finally any CommunicationException.

The rewritten code would then look like this :

MyServiceClient myServiceClient = new MyServiceClient();

try
{
    documents = myServiceClient.GetDocuments();
    // More code that isn't useful including here ...
    myServiceClient.Close();
}
catch (TimeoutException exception)
{
    MessageBox.Show(exception.Message, "Timeout error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    myServiceClient.Abort();
}
catch (FaultException<ServiceErrorDetails> error)
{
    MessageBox.Show(error.Detail.Message, "Service error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    myServiceClient.Abort();
}
catch (CommunicationException exception)
{
    MessageBox.Show(exception.Message, "Communication error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    myServiceClient.Abort();
}


Automating heap dumps from an Android device or emulator

First of all, your code passes on http://www.shellcheck.net/# with flying colors, congrats!

Simplify variable initializations

Here you can drop all the "", it will be the same thing but easier to write:

SERIAL=""
PACKAGE=""
FILE=""

That is, like this:

SERIAL=
PACKAGE=
FILE=

Check if a regular file exists with -f instead of -e

I admire your paranoia, with all the --:

mkdir -p -- "$dir" && touch -- "$file"

if [ ! -e "$file" ]; then
    err "File $file could not be created."
fi

But I would also recommend to use -f instead of -e,
as you are really expecting a regular file,
and -e is not necessary a regular file, can be a directory too.

Avoid putting commands into variables, especially when used only once

About this code:

local adbinfo="$adbcmd shell ls -l $file"

$adbinfo | awk '{print $4}'

When the command in $adbinfo becomes anything non-trivial,
running the command with $adbinfo | ... may not work as expected.
As long as you keep that in mind, this is fine.
However, since you only use this command once in the file_size_on_device function,
I recommend to not use $adbinfo at all, but the command directly:

$adbcmd shell ls -l $file | awk '{print $4}'

Even so, just keep in mind that the same dangers exist for $adbcmd as for $adbinfo earlier. But at least we removed one layer of danger ($adbinfo),
so that's a good thing.

Simplify ls | grep, use just ls when it's good enough

In dump_heap, I'm wondering if this actually works as expected:

# Remove any existing tmp files we created. Ideally, there should be none.
local exists=$($adbcmd shell ls "$dir" | grep "$file")
if [ -n "$exists" ]; then
    $adbcmd shell rm "$file"
fi

In particular, it seems to me the rm command should be like this:

$adbcmd shell rm "$dir/$file"

Because ls "$dir" | grep "$file" suggests that $file is just a filename,
not an absolute path, inside the directory $dir.

Also, the call to grep seems unnecessary, a single ls command should do:

local exists=$($adbcmd shell ls "$dir/$file")

Simplifying conditions

Still in dump_heap,
when checking if $exists is non-empty, instead of -n "$exists",
you can just drop the -n, simply [ "$exists" ] is the same thing.

Lastly, I'm wondering if the whole thing can be simplified to:

# Remove any existing tmp files we created. Ideally, there should be none.
$adbcmd shell ls "$dir/$file" &>/dev/null && $adbcmd shell rm "$dir/$file"

Prefer printf over echo for non-trivial printing

The various flags of echo are unreliable.
Depending on your system, they might work as expected or not.
Rather than using any of the flags of echo, I prefer printf.
So instead of:

echo -n "Dumping heap "

I recommend:

printf "Dumping heap "

However, I prefer echo when printing trivial text,
without using any flags,
and when I want a terminating newline.

Prefer fewer processes

In this pipeline there are 3 processes: adb, grep and awk

local pid=$($adbcmd shell ps | grep $PACKAGE | awk '{print $2}')

Especially in cases when an awk follows a grep,
one begs the question if the task of grep can be included in the awk command.
And in this case yes:

local pid=$($adbcmd shell ps | awk -v pkg=$PACKAGE '$0 ~ pkg {print $2}')

However, a little laziness is not against the spirit of good shell scripting.
Your version with grep is shorter and simpler,
and on most days I would go with it too.
So this remark is just for the record, and for the meticulous.

Simplify condition

Instead of this:

if [ -z "${SERIAL}" ] || [ -z "${PACKAGE}" ] || [ -z "${FILE}" ]; then

I suggest to simplify like this:

if ! [ "$SERIAL" -a "$PACKAGE" -a "$FILE" ]; then


You can generalize bodies of ifs:

private static void MoveCamera(float x, float y, float moveScale)
{
    Camera.Move(new Vector2(x, y) * moveScale);
}

private void repositionCamera(GameTime gameTime, Vector2 moveAngle)
{
    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
    float moveScale = playerSpeed * elapsed;

    if ((playerSprite.ScreenRectangle.X < scrollArea.X) && (moveAngle.X < 0))
    {
        MoveCamera(moveAngle.X, 0, moveScale);
    }

    if ((playerSprite.ScreenRectangle.Right > scrollArea.Right) && (moveAngle.X > 0))
    {
        MoveCamera(moveAngle.X, 0, moveScale);
    }

    if ((playerSprite.ScreenRectangle.Y < scrollArea.Y) && (moveAngle.Y < 0))
    {
        MoveCamera(0, moveAngle.Y, moveScale);
    }

    if ((playerSprite.ScreenRectangle.Bottom > scrollArea.Bottom) && (moveAngle.Y > 0))
    {
        MoveCamera(0, moveAngle.Y, moveScale);
    }
}

Also I suggest to extract all those conditions to properties with clear names like:

private static bool IsCameraOutOfLeft =>
    playerSprite.ScreenRectangle.X < scrollArea.X && moveAngle.X < 0;

private static bool IsCameraOutOfRight =>
    playerSprite.ScreenRectangle.Right > scrollArea.Right && moveAngle.X > 0;

...

Then finally the repositionCamera method will be

private void repositionCamera(GameTime gameTime, Vector2 moveAngle)
{
    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
    float moveScale = playerSpeed * elapsed;

    if (IsCameraOutOfLeft || IsCameraOutOfRight)
    {
        MoveCamera(moveAngle.X, 0, moveScale);
    }

    if (IsCameraOutOfTop || IsCameraOutOfBottom)
    {
        MoveCamera(0, moveAngle.Y, moveScale);
    }
}

Also a method's name should be PascalCased – RepositionCamera.


Simple pool of threads which calculate the sum of a given number from the main process

It's hard to tell without seeing the code for InsertHead and PopTail, but I would not be surprised if you've got a race condition between the main thread's InsertHead and the worker thread's PopTail. The workers take mutex in order to prevent data races among themselves; but the main thread blithely pushes new data onto the list without taking mutex, which seems like it would cause a race in the case that the list had only one element.

Stylistically, I'd replace

int threads = 4;
int number, i;

pthread_t *threads_tab;
int *thread_args;

threads_tab = malloc(threads * sizeof(pthread_t));
thread_args = malloc(threads * sizeof(int));

with

pthread_t threads_tab[4];
int thread_args[4];

to save those heap allocations (which, by the way, you never free).

The variable i should be declared within the for loop:

for (int i = 0; i < threads; i++) {

and the variable number should be declared where it's used:

int number = rand() % 100;

thread_args[i] = i;
pthread_create(&threads_tab[i], NULL, sum, (void*) &thread_args[i]);
[...]
printf(..., *(int *)ptr);

This is fine (and 100% correct, because it avoids implementation-defined casts!), but you should know that in practice most codebases will do simply

pthread_create(&threads_tab[i], NULL, sum, (void*) i);
[...]
printf(..., (int)ptr);

The latter is technically implementation-defined, but on common platforms it works, and it works without any memory loads or stores, which is nice, so that's why people end up doing it.

You fail to check the return value of pthread_create, which is a pretty big deal in real code; it's easy for a process to run out of threads. See man pthread_create.

In English, accumulator has two cs.


I'd just like to note that use of the mysql_* functions are going to be deprecated in the next version or the one after than(link at the end). You should start using mysqli or PDO.

http://news.php.net/php.internals/53799


Optimization of Hibernate DAO in desktop application

Wrong Transaction Management

Transactions are not a Data Access Layer concern, they are Business Logic Layer concern.

Consider how you would delete an entity, (any operation updating the database is similar) :

public class WidgetManager {
    public void deleteWidget(int widgetId) throws BusinessException{
        Widget widget = dao.get(Widget.class, widgetId);

        if (widget == null) throw new BusinessException("WidgetNotFound");

        if (!widget.isDeletable()) throw new BusinessException("WidgetCannotBeDeleted");

        dao.delete(widget);
    }
}

this method should be run in a transaction.

I would suggest you use Spring for transaction management as @ohiocowboy. (But using Hibernate API or Hibernate through JPA API (for example EntityManager) is not relevant to your current question.)

Repetitive Code

The following snippet is repeated in each method:

    Session session = HibernateUtil.openSession();
    try {
        session.beginTransaction();

        // do something with `session`

        session.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
        session.getTransaction().rollback();
    } finally {
        session.close();
    }

This situation arises quite frequently, mostly when you deal with resources such as Hibernate sessions, DB transactions, connections, resultsets, files, sockets, ...
You can use Execute Around Idiom to alleviate this problem.

Common code can be factored thus:

interface Function<T, R> {
    R apply(T t);
}

<R> R execute(final Function<Session, R> func) {
    R result = null;

    Session session = HibernateUtil.openSession();
    try {
        session.beginTransaction();

        result = func.apply(session);

        session.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
        session.getTransaction().rollback();
    } finally {
        session.close();
    }

    return result;
}

Now get reads like this [Annotations omitted for clarity]:

public E get(final Class<E> c, final int id) {
    return execute(new Function<Session, E>() {
        public E apply(Session session) {
            return (E) session.get(c, id);
        }
    });
}

If you have Java 8, you already have Function interface. And above can be written even more concisely as follows:

public E get(final Class<E> c, final int id) {
    return execute(session -> (E) session.get(c, id));
}

For methods that return void, you can avoid unnecessary return null; statements with:

interface Consumer<T> {
    void accept(T t);
}

void execute(final Consumer<Session> cons) {
    execute(new Function<Session, Object>() {
        @Override
        public Object apply(Session t) {
            cons.accept(t);
            return null;
        }
    });
}

Now insert reads like this:

public void insert(final E t) {
    execute(new Consumer<Session>() {
        public void accept(Session session) {
            session.save(t);
        }
    });
}

If you have Java 8, you already have Consumer interface. And above can be written even more concisely as follows:

public void insert(final E t) {
    execute(session -> {session.save(t);});
}

Evil Singleton

HibernateUtil is either a singleton or, less likely and much worse, a real utility class that creates a SessionFactory that loads Hibernate mappings on each call to openSession. A utility class should not have any state, such as a SessionFactory.

EDIT: What to do about HibernateUtil singleton?

Let me tell you first how I would fix it: I would delete the static modifier from the openSession method and fix all the compile errors. But this style depends on how familiar you are with the compiler, your IDE and the code base you are currently working on, not to go out of hand.

However you do it in the end HibernateUtil and BaseDAOImpl should look similar to these:

public class HibernateUtil {
    private SessionFactory sessionFactory;

    public HibernateUtil (SessionFactory sessionFactory, ...) {
         this.sessionFactory = sessionFactory;
    }

    public openSession() { // <----- not static
        // The contents should not change much, if at all
    }
}

public class BaseDAOImpl .... {
    private HibernateUtil hibernateUtil;

    public BaseDAOImpl(HibernateUtil hibernateUtil) {
        this.hibernateUtil = hibernateUtil;
    }
// Later use `hibernateUtil` instance to call `openSession`
    Session session = hibernateUtil.openSession();

If you are using a DI framework, you make HibernateUtil another component and inject it to DAO instances.

If, instead, you are bootstrapping your application from main or some init method:

void initMyApp(.....) {

     // create SessionFactory once
     SessionFactory sessionFactory = .......

     // create HibernateUtil once
     HibernateUtil hibernateUtil = new HibernateUtil(sessionFactory) .......

     // Use the same `hibernateUtil` many times

     FooDAO fooDAO = new FooDAOImpl(hibernateUtil);
     BarDAO barDAO = new BarDAOImpl(hibernateUtil);
     BazDAO bazDAO = new BazDAOImpl(hibernateUtil);
}


idle

As coded, idle is false when thread is in fact idle. Either rename it to working/running/whatever active or swap the true/false values.
Control flow

Unless I am missing something crucial, there is no need to goto neither in Worker nor in ThreadPoolAddTask.

Similarly, found seems redundant:

do {
    for (i = 0, i < MAX_WORKERS; i++) {
        if (...) {
            ....;
            return true;
        }
    }
} while (retry);
return false;

As a side note, retry shouldn't be handled here. It is a caller business logic when and how to retry. I don't see any value added.
Worker argument

I recommend passing a pointer to a worker instead of pointer to its index. It simplifies both ThreadPoolNew and Worker to:

void *Worker(void *arg)
{
    struct threadpool * t = (int*)arg;
x:
    sem_wait(t->sem);
    __sync_synchronize();
    t->func(t->arg);
    t->idle = false;
    goto x;
}

bool ThreadPoolNew()
{
    for (int i = 0; i < MAX_WORKERS; i++) {
        sem_init(&threads[i].sem, 0, 0);
        pthread_create(&threads[i].thread, NULL, Worker, &threads[i]);
    }
    return true;
}

and removes the need for thread.id. BTW, notice that assert(threads[i].id == i) always holds, so you may post your semaphore as

    sem_post(&threads[i].sem);

You may want to __sync_synchronize() after announcing the thread idle (there is no barrier between setting idle and subsequent sem_wait).


“Removing” reference from its ReferenceQueue

I believe there is a flaw in your logic that is insurmountable......

SoftReferences, once they are added to the queue, have already lost the Referent instance. I cannot think of any reason why you would want to handle an 'active' queued (the value has been GC'd) softreference in any way differently from an 'inactive' one.

Once the reference has been queued it's too late to do anything about the instance it was softly referencing.

On the other hand, if you want to 'process' a referant, and make sure it is not GC'd during the processing, then jsut keep a reference to it:

V referent = softref.get();
if (referent == null) {
    // it's already been GC'd (and at some point we will see it poll'd from the Q)
    return;
}
// do things with our referent
// since our referent varaible is a hard-reference,
//      nothing can happen to the soft reference.
....

// then clear our reference (or return from our method,
// or clear our hard reference in some other way)
referent = null;
// after this the referent can (possibly) be GC'd again

EDIT after comments:

From the Javadoc for SoftReference:

  Suppose that the garbage collector determines at a certain point in time that an object is softly reachable. At that time it may choose to clear atomically all soft references to that object and all soft references to any other softly-reachable objects from which that object is reachable through a chain of strong references. At the same time or at some later time it will enqueue those newly-cleared soft references that are registered with reference queues.

The GC will only nequeue newly cleared soft references. Further, from the SoftReference.get() method, we have:

  Returns this reference object's referent. If this reference object has been cleared, either by the program or by the garbage collector, then this method returns null

Finally, here is a third-party 'reference' on 'references' ... heh. It appears to be quite good.

EDIT 2: how to keep a value 'active' (responding to comments)

If the requirement is to prevent a particular Soft reference referent from being GC'd, the answer is relatively simple: create a hard reference and keep it.... For example:

private static final IdentityHashMap<MyType, Object> active = new .....;
private static final Object token = new Object();

private static final boolean forceActive(SoftReference<MyType> reference) {
    MyType referent = softref.get();
    if (referent == null) {
        // it's already been GC'd ... and ...
        // if the reference was created with a ReferenceQueue, we can
        // expect to 'poll' the reference from that queue at some point
        // maybe we have already done that....
        return false;
    }
    // referent is now a hard reference, we are guaranteed that `reference`
    // is not on any Queue, and that it will not be GC'd (since we have a hard reference)

    // we want to keep our referent 'active', so we need to keep a hard reference:
    // the key in the identity hash map is our hard link.
    active.put(referent, token);
    // we exit our keep-active method, but the hard reference remains.
    return true;
}

private static final boolean deActive(SoftReference<MyType> reference) {
    MyType referent = softref.get();
    if (referent == null) {
        // it's already been GC'd ... and ... that means it was not
        // in our active map (otherwise it would not have been GC'd).
        return false;
    }
    // if the map contains the referent as a key, then it will return 'token'.
    // and we have now successfully removed the hard-reference to the referent.
    return token == active.remove(referent);
}


'algorithm' is not correct at all and will fail at runtime. please make sure your code works before posting it. start and end are never read. time is never defined. 'row' is never defined--it is typo-d as 'job_row' the second time. use 'for job in robs', not 'for job_row in range(len(jobs)) together with 'jobs[job_row]'. I would generally recommend a linter, which should catch all these errors.

Add a docstring to "algorithm", describing what its inputs are, and what it returns. Make sure to describe what it returns in terms of MEANING, and not what the algorithm does. ("returns the best way to schedule..." and not "loops through...")
Change the name of 'algorithm' to reflect what it does (ex. 'schedule').

I personally think it's fine to put the contents of 'main' directly in the if __name__ == "__main__" block, but I've seen it both ways.

For the output_ methods, consider returning a string, and printing the string, as two steps. " ".join() may help.


LeetCode Reverse Words in a String without using any java library

First: if you look into StringBuilder.reverse() you'll encounter some extra work for some Unicode symbols needing two chars for a symbol (called a surrogate pair), which should not be reversed.

But let's not consider that.

Provide exactly the needed capacity for StringBuilder.
sb.append(' ') is faster than for " ".
end - 1 not needed.

So:

public String reverseWords(String s) {
    int length = s.length();
    if (length <= 1) {
        return s;
    }
    StringBuilder sb = new StringBuilder(length);
    int start = 0;
    int end = 0;
    while (start < length) {
        while (end < length && s.charAt(end) != ' ') {
            ++end;
        }
        doReverse(s, start, end, sb);
        start = ++end;
    }
    return sb.toString();
}

private void doReverse(String s, int start, int end, StringBuilder sb) {
    if (start > 0)
        sb.append(' ');
    while (end > start){
        --end;
        sb.append(s.charAt(end));
    }
}

In general using toCharArray could be faster:

public String reverseWords(String str) {
    char[] s = s.toCharArray();
    int length = s.length;
    if (length <= 1) {
        return s;
    }
    int start = 0;
    int end = 0;
    while (start < length) {
        while (end < length && s.charAt(end) != ' ') {
            ++end;
        }
        doReverse(s, start, end);
        start = ++end;
    }
    return new String(s);
}

private void doReverse(char[] s, int start, int end) {
    while (--end > start){
        char ch = s[start];
        s[start] = s[end];
        s[end] = ch;
        ++start;
    }
}

If you would inline doReverse for extra speed, you would need a copy of the changing parameters.

    // doReverse(char[] s, int start, int end)
    int end2 = end;
    while (--end2 > start){
        char ch = s[start];
        s[start] = s[end2];
        s[end2] = ch;
        ++start;
    }

Now we should be twice as fast (wild guess).


Using jQuery to set the class of an element corresponding to the selected radio button

You could use labels for your radio inputs and use the actual class names for the values. Then on change, you'd just remove all the option classes and pass in your inputVal for the class to add. See the snippet below (colors added to the classes via CSS and text added in .img-wrapper to show it working).

$('input[name=choice]').change(function(){
 var inputVal = $('input[name=choice]:checked').val();

 $(".img-wrapper")
  .removeClass('option-a option-b option-c option-d')
  .addClass(inputVal);
});
.option-a
{
  color: red;
}

.option-b
{
  color: green;
}

.option-c
{
  color: blue;
}

.option-d
{
  color: yellow;
}

   Option A
   <input type="radio" name="choice" value="option-a" checked>
   Option B
   <input type="radio" name="choice" value="option-b">
   Option C
   <input type="radio" name="choice" value="option-c">
   Option D
   <input type="radio" name="choice" value="option-d">

Blah


Parsing Bitcoin binary data file with Python

Some suggestions:

Every single line should at least be comprehensible on its own. Single letter variables destroy that comprehension, meaning that anyone reading the code needs to read the entire code and mull it over for a while to even understand what it's meant to do. Something like current_byte = file_handle.read(1) is a lot more readable than b = f.read(1).
All the top-level code should be in either functions, methods or classes, and the file should have a main function, so that the pieces of this code can be understood and reused.
Running this through at least one linter such as flake8 and pycodestyle will give several tips to produce more pythonic code. For example, return (Res); should be written as return res - no parentheses or semicolon, and snake_case variable names.
There are several magic values like 80 and 4 which are hard to guess the meaning of. They should be pulled out as named variables or constants.
Instead of closing the file handle explicitly you should use a context manager like with open(…) as file_handle:. This ensures that the file handle will be closed even if there is an exception.
Rather than checking whether the current position in the file is at the end you should read until reading returns nothing.
There are assignment operators such as //= which can simplify some of your expressions.
A helpful exercise for detecting "hacky" code is to add type hints to it, and verifying it with mypy using strict settings (like not allowing Any). For example, it looks like the type of b would be Union[byte, str], which is a code smell - the variable is literally used for two different types of things.


Unless I'm missing something, your selectRows and insertRows can be used for other operations as well, because you don't actually check that the queries are SELECT or INSERT respectively.  In fact you call insertRows when the consuming code calls deleteRows or updateRows so why have all these functions?

In deleteRows and updateRows, you accept an argument ($bindParams) that you don't use. Why?

  would it be better to have pre-built functions for returning specific
  data (Eg..getFriends())?

In my own work, I put such functions in the User class which can in turn call selectRows with the right parameters.  It still meets your requirement that only the Database class interacts directly with the DB engine. The Database class has no information about other objects. It just executes queries and returns results. The core of my class is similar to:

public $error; //holds text of error if a query fails
private $results; //holds results of most recent query
private $conn; //holds db connection used by all queries

//connects to the database and saves the connection in $conn property
public function __construct($host, $port, $user, $pwd, $db_name)

//disconnect from the database
public function __destruct()

//executes query after binding params. Return TRUE on success or FALSE on error
//stores results in $results property so it can be accessed by other functions
public function query($sql, array $params = null)

//executes a query and returns a row. If no sql is provided,
// returns row from $results property. Return FALSE on error
public function fetch_row($sql = null, array $params = null)

//executes a query and returns the full results table. If no sql is provided,
// returns table from $results property. Return FALSE on error
public function fetch_array($sql = null, array $params = null)

//executes a query and returns the column of interest. If no sql is provided,
// returns column from $results property. Return FALSE on error
 public function fetch_column($column, $sql = null, array $params = null)

At the start of each function, I set $error to null. If there is an error, I fill $error with the details. So the consuming code can check this variable after executing a query to check for errors:

$result = $db->query(...); // or $db->fetch_array(...)

if($error_msg = $db->error):
  //query failed. Details are in $error_msg
else:
  // query succeeded
endif;

Does that help?


For your current purposes, the biggest problem is that you are relying on global variables exclusively.  This makes it a lot tougher to understand, maintain, and debug your code.  This question actually has some great answers that discuss why this can cause real problems in code:

https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil

As a specific example, this bit of code had me confused for a few minutes:

while number_pool:

Because number_pool wasn't used anywhere in your while loop, and so I had no idea why this wasn't just an infinite loop.  I eventually realized that it is getting modified inside the lotto_choice method which is called within the while loop.  This is pretty much exactly why you don't want to use global state: if any bit of code can modify any variable anywhere, you can quickly lose track of who modifies what and when it happens, and bugs can creep in very quickly.  You also will have your own trouble if you come back to the code after a while and find that you no longer remember exactly what gets modified by what functions.

So, always make sure and keep input into functions and output out of functions clear.  In the case of lotto_choice you could easily do something like this:

def lotto_choice( number_pool ):
    choice = random.choice(number_pool)
    number_pool.remove(choice)
    return ( choice, number_pool )

Then you would call it like this inside your while loop:

( choice, number_pool ) = lotto_choice( number_pool )

Now you can easily see where number_pool gets modified.  Since you are just now getting started, now is the time to establish good habits.  So take the time and understand how variable scope works and (especially in a learning exercise like this) make sure not to use any global state.  My biggest suggestion is to fix that and then post a new code review question with your updated code.

Also, small change. You want to only execute your game if called in the 'main' context, like this:

if __name__ == '__main__':
    the_game()


Censor the middle of words of length N from a text file

create_censor_file should really be called create_censored_file.
I'd rename source to source_file for consistency and clarity.
You should use with for both files.
Why not use just w instead of w+?
This is probably one of the few things that regexes are actually useful for. You can just use re.sub(r'(?<=\b\w)\w{' + ','.join(map(lambda x: str(x-2), LENGTHS_TO_CENSOR)) + '}(?=\w\b)', lambda match: CENCOR_CHAR * len(match.group(0)), source.read())

A couple other things:

Good job with the main function and if __name__ == '__main__' check!
I have not yet tested this code.

Result:

LENGTHS_TO_CENSOR = {4, 5}
CENSOR_CHAR       = '*'
CENSOR_EXT        = "-censored"

def create_censor_file(filename):
    with open(filename + CENSOR_EXT, "w") as output_file, open(filename) as source_file:
        output_file.write(
            re.sub(
                r'(?<=\b\w)\w{'
                    + ','.join(map(lambda x: str(x-2), LENGTHS_TO_CENSOR))
                    + '}(?=\w\b)',
                lambda match: CENSOR_CHAR * len(match.group(0)),
                source_file.read()))

def main():
    filename = input("File to be censored: ")
    create_censor_file(filename)

if __name__ == "__main__":
    main()


I think that a more idiomatic C interface would be

ssize_t file_get_content(const char *file_name, char *content[]);

Returning the number of bytes actually read would be analogous to read(2) and printf(3).  On error, the return value could be -1, and the reason would be in errno.  For consistency, I would have file_save_content() return the number of bytes written, or -1 on error.

It would be convenient if you allocated an extra byte and appended a \0 terminator to the result.  Then the caller has the option to treat the buffer as a null-terminated string, if it believes the file to contain text.  It would still be able to treat it as binary data (possibly containing NUL bytes) based on the return value.

When getting the contents of an empty file, I would expect it to produce an "empty" buffer, not a NULL pointer.

There is a possibility of a race condition: the file could be truncated between the stat() and the fread().  You could actually handle that case a bit more gracefully.

int file_get_content(const char *file_name, char *buf[]) {
    struct stat file_stat;
    if (0 != stat(file_name, &file_stat)) {
        return -1;
    }

    if (NULL == (*buf = 1 + malloc(file_stat.st_size))) {
        return -1;
    }

    FILE *file;
    if (NULL == (file = fopen(file_name, "rb"))) {
        free(*buf);
        return -1;
    }

    ssize_t bytes_read = fread(*buf, 1, file_stat.st_size, file);
    (*buf)[bytes_read] = '\0';
    fclose(file);
    return bytes_read;
}

In file_save_content(), avoid tmpnam(), which allows a race condition between the time you call tmpnam() and fopen().  Also, rename() would fail unless the temporary file and the destination are on the same filesystem.  As an alternative, I would recommend mkstemp() with the destination filename plus a ".XXXXXX" suffix, followed by fdopen().

As a nitpick, I'd prefer unlink() over remove(), since the former refuses to remove directories.

In the error handlers of file_save_content(), save and restore errno, because it would be more useful for the caller to see the original reason for the failure rather than a problem with the subsequent cleanup.


Redundancy in while loops

Your while loop has a condition that never gets used because there is an if statement inside the loop that actually ends the loop.  For example:

while (count != m)
{
    ++count;
    if (count == m)
    {
        break;
    }
    prev = cur, cur = cur->next;
}

You could simplify this by merging the increment into the loop condition.  Also, I don't using the comma operator to put two statements on one line.  So I would write your loop like this:

while (++count < m)
{
    prev = cur;
    cur  = cur->next;
}

And your other loop would look like this:

while (++count < n)
{
    struct ListNode* temp = cur->next;
    cur->next = prev;
    prev      = cur;
    cur       = temp;
}

Use typedef

I suggest using a typedef so you don't have to use struct so much.  For example:

typedef struct ListNode {
     int val;
     struct ListNode *next;
} ListNode;

And then use just ListNode instead of struct ListNode everywhere.


Ok, now that I have a firm grasp on what you're doing, I think I have what you're looking for. The below still applies in terms of optimizing what you posted, but I think what you want is more along the lines of the following:

fiddle

var paper = Raphael("canvas", 500, 500);

var rectangles = {
   1 : paper.rect(100,100,90,40).attr({fill: "#44ddff"}) ,
   2 : paper.rect(200,100,90,40).attr({fill: "#4488ff"}) ,
   3 : paper.rect(100,200,90,40).attr({fill: "#44ddff"}) ,
   4 : paper.rect(200,200,90,40).attr({fill: "#4488ff"})
};

function repeat() {

    var runOnce = 0;

    for (var i in rectangles) {
        rectangles[i].animate(
            {transform:'...R' + (i%2===0?'':'-') + '360'} ,
            2000 ,
            function() {

                runOnce++;

                if (runOnce==4)
                    repeat();

            });
    }
};
repeat();

It still needs some tweaks for your cogs, but I think this is a more adept to the capabilities of the Raphael framework.

Kudos on tackling Raphael at an early stage of learning. It's quite advanced, but definitely fun.

The first recommendation I will make is that you shouldn't repeatedly call "setInterval". It is a large waste of resources. Also, you are not creating multiple papers, you are overwriting the existing variable. Honestly, between that and the reuse of angle I'm somewhat confused this code is working for you at all... I certainly cant get it to run on fiddle.

var w = window.innerWidth;

if (w>=960) {window.direction = -1; }
else {window.direction = 1; }

window.onresize=function(){
var w = window.innerWidth;
if (w>=960) {window.direction = -1; }
else if (w<960 && w>=715){window.direction = 1; }
};

window.onload = function() {

    var paper = new Raphael(document.getElementById('canvas_container'), 730, 750);

    var tandwiel1 = paper.image( "tandwiel-1.png",0,0,480,240);

    var tandwiel2 = paper.image( "tandwiel-2.png",0,0,720,240);

    var tandwiel3 = paper.image( "tandwiel-3.png",0,0,960,240);

    var tandwiel4 = paper.image( "tandwiel-4.png",0,0,1200,240);

    var tandwiel5 = paper.image( "tandwiel-5.png",0,0,1440,240);

    var angle = 0;

    setInterval( function() {

        angle += 2;

        tandwiel1.stop().animate( { "transform": "R" + angle }, 1000, "<>" );

        tandwiel2.stop().animate( { "transform": "R" + -angle }, 1000, "<>" );

        tandwiel3.stop().animate( { "transform": "R" + angle }, 1000, "<>" );

        tandwiel4.stop().animate( { "transform": "R" + -angle }, 1000, "<>" );

        tandwiel5.stop().animate( { "transform": "R" + direction*angle }, 1000, "<>" );

    }, 150 );
}

Next I would swap out the unreliable setInterval for a recursive setTimeout. But that is not necessary for this experiment. I use setInterval plenty when whipping up little tests such as this, it's a bit easier to set up.

Additionally, have you tried using a Raphael set to perform your animation with only one animate directive? It might speed it up a bit.

UPDATE:

Upon reconsideration, I realize why it would work. Even though you are overwriting the paper variable, the object has already been added to the DOM. This is not undone when the variable is modified/removed within JavaScript. Ether way, you would want to encapsulate all of your elements on one paper if they are related/displayed-near-each-other

UPDATE:

A further consideration. What I like to do is first create the Raphael objects so that I can access them by themselves

var myObjects = {

    tandwiel1 : paper.image( "tandwiel-1.png",0,0,480,240,

    tandwiel2 : paper.image( "tandwiel-2.png",0,0,720,240),

    tandwiel3 : paper.image( "tandwiel-3.png",0,0,960,240),

    tandwiel4 : paper.image( "tandwiel-4.png",0,0,1200,240),

    tandwiel5 : paper.image( "tandwiel-5.png",0,0,1440,240)
};

And then, if I need to animate them as a group, I create a set for easy manipulation.

var allTanwiels = paper.set(myObjects.tandwiel1 , myObjects.tandwiel2 , myObjects.tandwiel3 , myObjects.tandwiel4 , myObjects.tandwiel5)

allTanwiels.forEach(function(tanwiel) {
    tanwiel.stop().animate( { "transform": "R" + angle }, 1000, "<>" );
});


Preventing SQL injection by converting all characters to their ASCII values

There's a common credo believed when evaluating the security of software:

If it's homemade, it's unlikely secure.

Sec.SE has a Q&A about homemade algorithms, which is somewhat germane to your circumstance.

I suggest you look into preparing your queries, as that would be your best action to take in this situation. It's essentially what you're trying to do anyways. Again, the PHP docs contain more information on mysqli::prepare.

I just noticed your comment to Mat's Mug, and prepared queries will not reach the database twice as you've said. When they're implemented correctly, they will be 100% secure (in doing their job, you might have to protect against other faults).

If you're worried about performance or efficiency, you might find the following select quotes helpful:

  Prepare is followed by execute. During execute the client binds parameter values and sends them to the server.

The database is not reached twice.

  A prepared statement can be executed repeatedly. Upon every execution the current value of the bound variable is evaluated and sent to the server. The statement is not parsed again. The statement template is not transferred to the server again.

I know you said it's only a single query per page, but things change in the future, and it's better to know you'll be safe then too.

  Prepared statements are using the so called binary protocol. The MySQL server sends result set data "as is" in binary format. Results are not serialized into strings before sending. The client libraries do not receive strings only. Instead, they will receive binary data and try to convert the values into appropriate PHP data types.

If you happen to be curious as to how and why paramterized queries are so much safer!

These quotes are from the PHP manual on prepared statements.


Reverse Polish Notation (RPN) Calculator

The initial approach is full of redundant if conditions for capturing float numbers and duplicated set of statements (stack.append, for loop, del ...) for all 4 arithmetic operations.

The whole idea is achievable with a single traversal facilitated by operator (provides convenient equivalents of mathematical operations) and ast.literal_eval feature (to evaluate both int and float types):

import operator
from ast import literal_eval

math_operators = {'+': operator.add, '-': operator.sub,
                  '*': operator.mul, '/': operator.truediv}

def calc(expr):
    tokens = expr.split()
    res = []
    for t in tokens:
        if t in math_operators:
            res[-2:] = [math_operators[t](res[-2], res[-1])]
        else:
            res.append(literal_eval(t))

    return res[0] if res else 0

Test cases:

exp = '5 1 2 + 4 * + 3 -'
print(calc(exp))   # 14

exp = '5.5 10.6 -'
print(calc(exp))   # -5.1

exp = ''
print(calc(exp))   # 0


PHP, would this class pass the single responsibility principle?

I don't think the user class you provided satisfies the Single Responsibility Principle.

I can see a few situations that may require changes to the user class.

You want to change what information about the user is stored. This could happen if you need to allow a title (Mr., Mrs., etc.) and/or a middle name. Doing so would require a change to the user class.
You want to create a new class that also contains address information. The new class would likely duplicate code that is already present in the user class.
You want include the user's country with the physical and mailing addresses. Doing so would require a change to the user class. It would also require changes to the class in #2.
You want to change where the information is stored. You may decide you want to be able to test your class without needing to connect to the database (assuming you're connecting to a database). Doing so would require a change to the CRUD methods (insert, update, delete, lookup, and search) of your class.

(1) is related to the user class and changing the class is expected. No problem here.

(2), (3), and (4) are really not the responsibility of the user class, yet they would probably require changes to the user class.

You should consider creating an additional "address" class that can be reused for the physical and mailing addresses for the user. The user class could contain instances of the address class, and would not require changes if the address functionality changed. Any new classes that need address information could reuse this class.

You should also consider creating a new class (let's call it userProvider) that is responsible for the CRUD functions. This class could have the CRUD methods with a user object as a parameter. Your user class could still define the CRUD methods if you want, but would simply pass the user instance to the userProvider class, which would be responsible for storing/retrieving the user information.


Indeed, this factory pattern is not right. A factory should have the single responsibility of creating instances. You violated that the moment you made it a subclass of ISheetIO, which is an entirely different responsibility.

The first step to make this better is to change the factory to be more factory-like:

Rename it to SheetIOFactory
Extend object (stop extending ISheetIO)
Rename the _factory method to create_sheet method: this will become the official way to create sheets

The methods that remain, read_sheet, write_sheet, _orient_data, _transpose belong in another class. Let's call it SheetIOHelper.
This class should not extend ISheetIO.

Why? You would rightfully ask:
it has read_sheet and write_sheet methods.
It even uses the same kind of parameters (uhm, more or less).
But a crucial (and somewhat subtle) difference is that the methods in the helper class and the methods in ExcelSheet have completely different contracts:

The methods in ExcelSheet are designed to work with Excel sheets
The methods in SheetIOHelper are designed to work with whatever kind of sheet you throw at them

That is, the methods in SheetIOHelper are expected to detect appropriate source / target sheet type, the methods in ExcelSheet are just not designed that way, they work with only a specific type of sheet.
In strongly typed languages,
these two interfaces wouldn't be compatible, the code wouldn't compile.

In other words,
the helper and the concrete classes don't follow the same interface.
You could create a dedicated parent class for SheetIOHelper.
That might sound like overkill,
since you only plan to have just one implementation,
it might be worth it,
to make the distinction from ISheetIO loud and clear.
Or you could be lazy and just make it extend object.

And when you use the helper,
you should add "helper" in the variable name to avoid confusion:

def ConvertSheet(in_sheet, out_sheet)
    sheet_io_helper = SheetIOHelper()
    data_matrix = sheet_io_helper.read_sheet(in_sheet)
    # different functions would operate on data_matrix before writing.
    sheet_io_helper.write_sheet(out_sheet, modified_data)

Actually,
since you probably won't ever work with the concrete classes directly,
it would be better to rename the interface of the concrete classes instead.
So in the end, have this class structure:

SheetIOHelper: interface of the helper, that can read / write any types of sheet

SheetIO: implementation of the helper

ConcreteSheetIO: interface of concrete implementations that can only read / write sheets of type T

ExcelSheetIO: concrete implementation to read / write Excel sheets
CsvSheetIO: concrete implementation to read / write CSV sheets

SheetIOFactory: implementation of the factory, creates ConcreteSheetIO instances and does nothing else

In the end, the names are quite different from what I used in the beginning.
I hope you see the evolution that lead us here, and hopefully it's not too confusing.
If this is not clear,
let me know, I can restructure your original if it would help.

Code review

In this code:

def read_sheet(self, sheet, col_start=0, row_start=0, col_cnt=-1, row_cnt=-1):
    # ...
    if row_cnt < 0:
        row_cnt += sheet.nrows + 1
    if col_cnt < 0:
        col_cnt += sheet.ncols + 1

When I see row_cnt += sheet.nrows + 1 I have 2 thoughts:

What is the value of row_cnt before the += ?
Why the +1 in sheet.nrows + 1 ?

These are very easy to answer, but I still have to think of them.
It would be better if I didn't have to think.
It seems to me that this simpler variant would be just as good,
and it won't make me think:

if row_cnt < 0:
    row_cnt = sheet.nrows
if col_cnt < 0:
    col_cnt = sheet.ncols

In this code:

if sheet_type is xlrd.sheet or sheet_type is xlwt.WorkSheet:
    return ExcelSheet()
# elif CSV
#    return CSVSheet()
# elif OpenXML
#    return OpenXMLSheet()
else:
    raise TypeError("Unknown Sheet type or not a sheet")

It's a minor thing,
but since each elif branch returns,
I prefer this writing style:

if sheet_type is xlrd.sheet or sheet_type is xlwt.WorkSheet:
    return ExcelSheet()
# if CSV
#    return CSVSheet()
# if OpenXML
#    return OpenXMLSheet()
raise TypeError("Unknown Sheet type or not a sheet")


Hacker rank 30 days of code Maximum Sum of Hourglass

Reading the input data in a loop

arr = []
for _ in range(6):
    arr.append(list(map(int, input().rstrip().split())))

can be done with list comprehension, also rstrip() is not needed here because split() without arguments ignores trailing whitespace:

arr = [ list(map(int, input().split())) for _ in range(6)]

In

for i in range(len(arr)):
  for j in range(len(arr[i])):

I would assign the dimensions to separate variables, making the code
self-documenting:

num_rows = len(arr)
num_cols = len(arr[0])
for i in range(num_rows - 2):
    for j in range(num_cols - 2):

The initial value

max_total = -1073741824

looks arbitrary without an explaining comment. What about

max_total = -7 * 9 - 1  # An hourglass sum is at least 7 * (-9)

instead? And (even though @janos advised against it :) you can get rid
of both the total and the max_total variable if you use the
built-in max()
function on a generator of hourglass sums:

def hourglass_sums(arr):
    """Generate all sums of hourglasses in the array."""
    num_rows = len(arr)
    num_cols = len(arr[0])
    for i in range(num_rows - 2):
        for j in range(num_cols - 2):
            yield (arr[i][j] + arr[i][j + 1] + arr[i][j + 2] +
                   arr[i + 1][j + 1] +
                   arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2])

def max_hourglass_sum(arr):
    """Maximal hour glass sum in the array."""
    return max(hourglass_sums(arr))


Merging the frequency rankings of boys' names and girls' names

There is a number of things we can do to improve the solution performance-wise, but, most importantly, you don't need two dictionaries for boy and girl names and can have a single dictionary checking for the minimum value on the fly.

What if we use a collections.defaultdict with a default int value being a big number, such as sys.maxint, then we iterate over every row with ranks, boy and girl names and leave minimum ranks only.

We can also use re.finditer() instead of re.findall() to avoid having an extra list created in memory - you may notice the difference on bigger input files:

from collections import defaultdict
from time import time
import re

import sys

def extract_names(filename):
    names = defaultdict(lambda: sys.maxint)

    with open(filename, "r") as f:
        html_data = f.read()

    filematch_year = re.search(r"Popularity\s([\w.-]+)\s([\d.-]+)", html_data)
    year = filematch_year.group(2)

    filematch_rank_names = re.finditer(r'td>([\d.-]+)	([\w.-]+)	([\w.-]+)', html_data)
    for match in filematch_rank_names:
        rank, boy_name, girl_name = match.groups()
        rank = int(rank)

        names[boy_name] = min(names[boy_name], rank)
        names[girl_name] = min(names[girl_name], rank)

    with open("output.txt", 'w') as output_file:
        output_file.write(year + "\n")

        for name, rank in sorted(names.items()):
            output_file.write("{name} {rank}\n".format(name=name, rank=rank))

Note that the results are sorted by the names as required by your Google challenge:

1998
Aaliyah 222
Aaron 37
Abbey 408
Abbie 603
Abbigail 612
Abby 194
Abdul 970
Abdullah 897
Abel 378
...

Here is the simple timeit benchmark for both yours (extract_names) and mine (extract_names_new) solutions showing a dramatic improvement on my machine:

In [1]: %timeit extract_names("baby1998.html")
10 loops, best of 3: 103 ms per loop

In [2]: %timeit extract_names_new("baby1998.html")
100 loops, best of 3: 5.66 ms per loop


Calculate AB significance with Control and Treatment Objects

One problem here is in calcZScore, where it should be:

return z/Math.sqrt(s);

Otherwise, it looks like you successfully ported the code. More generally, there are some caveats associated with using the normal assumption for A/B tests. You want to make sure that you have a sufficient number of data points for the normality assumption to hold (often expressed as np > 5 and n(1-p)>5), which the sample size estimator doesn't always seem to satisfy.

You also should also be aware of other incorrect methods of A/B testing, such as repeated significance errors as expressed here: http://www.evanmiller.org/how-not-to-run-an-ab-test.html. In fact, I'd say getting working confidence calculation code is just scratching the surface of proper A/B testing.

Also, assuming you are doing a two-sided hypothesis test, the P-value is simply 1-confidence.

console.log("P-Value is:", 1-confidence);

I compared the results this code produces to the following online A/B calculator and it seemed to match up (although I haven't validated the sample size recommendation, so someone else should probably take a look at that).
https://vwo.com/ab-split-test-significance-calculator/


Correctness

At first, I'm afraid your code doesn't find all duplicates: If the compared materials don't use a texture or a color, they won't be marked as duplicates. In your code, if (hc) checks if the material has a color. If not, it is jumped over. If the other material has no color either, this could still be a duplicate.

Performance

The performance of your code is \$O(n^2)\$: For each additional item in allMat, the unique collection will be iterated one time. As this collection grows, this will take longer and longer. This can be certainly improved:

What you actually want to do, is "group" your Texture objects by equality. The groups with size == 1 will be your unique textures, the groups with size > 1 will contain your duplicates.

We can do this very easily using LINQ. All we need to do is implement a custom comparer, that knows how to compare two Texture instances:

public class MaterialComparer : IEqualityComparer<Material>
{
    public bool Equals(Material x, Material y)
    {
        if (ReferenceEquals(x, y)) return true;

        if (x.shader.name != y.shader.name) return false;

        var xHasColor = x.HasProperty("_Color");
        var yHasColor = y.HasProperty("_Color");

        if (xHasColor != yHasColor) return false;
        if (xHasColor && x.color != y.color) return false;

        var xHasTexture = x.HasProperty("_MainTex");
        var yHasTexture = y.HasProperty("_MainTex");

        if (xHasTexture != yHasTexture) return false;
        if (xHasTexture && x.mainTexture != y.mainTexture) return false;

        return true;
    }

    public int GetHashCode(Material mat)
    {
        unchecked
        {
            var hasColor = mat.HasProperty("_Color");
            var hasTexture = mat.HasProperty("_MainTex");

            var hashCode = mat.shader.name.GetHashCode();
            hashCode = (hashCode * 397) ^ (hasTexture ? mat.mainTexture.GetHashCode() : 0);
            hashCode = (hashCode * 397) ^ (hasColor ? mat.color.GetHashCode() : 0);

            return hashCode;
        }
    }
}

The important thing here is to get GetHashCode right: This method is supposed to return two integers that MUST be equal when the compared objects are equal.

We can use it like that:

var groups = allMat.GroupBy(m => m, new MaterialComparer())
                .GroupBy(g => g.Count() == 1)
                .ToArray();

var unique = (groups.SingleOrDefault(g => g.Key) ?? Enumerable.Empty<IEnumerable<Material>>())
    .SelectMany(m => m).ToArray();

var duplicates = (groups.SingleOrDefault(g => !g.Key) ?? Enumerable.Empty<IEnumerable<Material>>())
    .SelectMany(m => m).ToArray();

I put this in a Unit Test to measure the performance for 20,000 random materials:

[TestMethod]
public void TestMaterials()
{
    var random = new Random();
    IEnumerable<Material> allMat = from i in Enumerable.Range(0, 20000)
                                let shader = random.Next(100)
                                let color = random.Next(50)
                                let texture = random.Next(50)
                                select new Material(shader.ToString(),
                                                    color == 0 ? null : color.ToString(),
                                                    texture == 0 ? null : texture.ToString());

    var comparator = new YourImplementation(allMat.ToArray());

    var stopwatch = Stopwatch.StartNew();

    comparator.InitShaderSorting();

    Console.WriteLine(stopwatch.Elapsed);
    stopwatch.Restart();

    var groups = allMat.GroupBy(m => m, new MaterialComparer())
                    .GroupBy(g => g.Count() == 1)
                    .ToArray();

    var unique = (groups.SingleOrDefault(g => g.Key) ?? Enumerable.Empty<IEnumerable<Material>>())
        .SelectMany(m => m).ToArray();

    var duplicates = (groups.SingleOrDefault(g => !g.Key) ?? Enumerable.Empty<IEnumerable<Material>>())
        .SelectMany(m => m).ToArray();

    Console.WriteLine(stopwatch.Elapsed);
}

Result:

00:00:14.0328998  // your custom implementation
00:00:00.0712459  // LINQ


It's usually best to have the Makefile in the same directory as the build products, or at least have that as the working directory.  Then there's no need to re-write the built-in rules for compiling and linking.  Use VPATH to ensure the source files can be found.

LDFLAGS := -lpthread

That should go into LIBS (which gets expanded later in the command line), so that it gets used as needed.  LDFLAGS is for flags such as -L which need expanding further to the left.
I'm not convinced that example1 and example2 are great names for your programs - surely you can think of something more descriptive and memorable for your users?

ex1_src := $(shell find $(src) -name example1.cpp)

Do you really need to invoke a find there?  I would expect there to be few enough matches that you could simply list them, and update the list when you add a new one.  I'd do the same for srcfiles too - or create a library, so that the resultant programs only include the objects they need.
I think generally there's too much use of shells here, despite them all being in := assignments.  You want makefile parsing to be fast, so you can see all your unit test results as quickly as possible.
So I'd write
example1: example1.o object_a.o object_b.o object_c.o
example1: LINK.o = $(LINK.cc)

The target-specific LINK.o is necessary so that the C++ linker is used.  It's cleaner and more portable than adding the C++ runtime library to LIBS.
You're missing some very important CXXFLAGS:
CXXFLAGS += -Wall -Wextra

I'd likely add a few more:
CXXFLAGS += -Wpedantic -Warray-bounds -Weffc++
CXXFLAGS += -Werror

Good use of .PHONY - that's often overlooked.
You should also have .DELETE_ON_ERROR: so that interrupted builds don't cause problems.


There are a few things that I think could be improved.

Include all required imports

The code uses os.popen() but doesn't import os.  It should.

Consider other platforms

On my Linux machine, there is no getmac command, but one could get the required information via ifconfig.  Consider either passing the command in to the function or making OS-specific versions.

Don't use deprecated functions

The os.popen() command is deprecated since version 2.6.  Use the subprocess module instead.