Python: Making bowling algorithm more pythonic

Overall, there is not much sense in using a class here - you are not using player's name and you are calculating the overall shots in the frames method and returning the overall value.

Some code style specific notes:

according to PEP8, the class name should be in CamelCase, call it BowlingPlayer
there is no need for parenthesis around the expressions, you can replace:

self.overall += (shot_three_after_strike + shot_two_after_strike + shot_one)

with:

self.overall += shot_three_after_strike + shot_two_after_strike + shot_one

there is some code duplication when you calculate the overall value, you can add up shot_two_after_strike and shot_one to the overall value and only if the score is 10, add the shot_three_after_strike:

self.overall += shot_two_after_strike + shot_one
if shot_two_after_strike == 10: # you got another strike. continue the frame!
    shot_three_after_strike = int(input('how many pins on shot after two strikes:'))
    self.overall += shot_three_after_strike
return self.overall

Same for the case when shot_one < 10.
according to PEP8 commenting guidelines, there has to be two spaces before the # and once space after
there is no need for spaces around the = for keyword function or method arguments (PEP8 reference)
put the main execution code to under if __name__ == '__main__': to avoid it being executed on import
let's define 10 as a constant to avoid hardcoding things
I'd also use something like a total_points variable name instead of a more questionable overall

Improved code:

POINTS_FOR_STRIKE = 10

class BowlingPlayer(object):
    def __init__(self, name, overall=0):
        self.name = name
        self.total_points = overall

    def frames(self):
        shot_one = int(input('how many pins on first shot:'))
        if shot_one == POINTS_FOR_STRIKE:  # this is a strike
            shot_two_after_strike = int(input('how many pins on shot after strike:'))
            self.total_points += shot_two_after_strike + shot_one

            if shot_two_after_strike == POINTS_FOR_STRIKE:  # you got another strike. continue the frame!
                shot_three_after_strike = int(input('how many pins on shot after two strikes:'))
                self.total_points += shot_three_after_strike
        elif shot_one < POINTS_FOR_STRIKE:
            shot_two = int(input('how many pins on second shot:'))
            shots = shot_one + shot_two
            self.total_points += shots

            if shots == POINTS_FOR_STRIKE:  # this is a spare
                shot_three_after_spare = int(input('how many pins on shot after spare'))
                self.total_points += shot_three_after_spare
        return self.total_points

if __name__ == '__main__':
    craig = BowlingPlayer('craig')
    print(craig.frames())


How do you "sordid sort" alphanumeric strings?

I observed that the match @a = $a =~ m/$ALNUM/g always produces a sentinel pair. Is the above code relying on undocumented behaviour?

I don't know what you mean by "sentinel pair", but that will always return two values per match since you have two captures.

  Can you help simplify the sordidcmp subroutine?

You could replace sort sordidcmp with Sort::Key::Natural's natsort.


but my issue comes where I see that if the Rules take any dependency
  I have to add them to RuleSet class

You managed to find the issue yourself. Your RuleSet class shouldn't be implemented in such way that the rules are always the same (I believe?). What this mean is that when you create a new RuleSet any rules should be able to go into that set.

I don't know what is the purpose of it but it seems your kind of associating custom data to your rules (in this case integers).

So one approach to consider is to include that data in the rules themselves, per instance:

public interface IRule{
    bool IsApplicable(Command command);
    int Data{get;}
}

Another approach to consider is to provide a method on RuleSet that allows you to add a rule to the set, after this have been created:

public class RuleSet : IRuleSet
{
    private readonly Dictionary<IRule, int> _rules = new Dictionary<IRule, int>();

    public RuleSet()
    {
    }

    public Dictionary<IRule, int> GetRules()
    {
        return _rules;
    }

    public void AddRule(IRule rule, int data){
        _rules.Add(rule, data);
    }
}

I don't know what your implementation of IRule here is but you better make sure that it implements GetHashCode and Equals properly because you are using them as a dictionary key. This is true not only the existing IRule classes but all future possible implementations of IRule that can possibly lie on this dictionary.

Another approach as @Adriano suggested, would be to rely on insertion order, or using a ordered collection such as a SortedSet (presuming the rules will not repeat this will do)


You can introduce range variables to hold data which you need several times in your query:

var analystRoleId = 3;
var testAnalystIds = new[] { 130, 252, 264, 302 };

var activeAnalysts =
    from p in xdoc.Descendants("People")
    let id = (int)p.Element("id")
    let isActive = (int)p.Element("active") == 1
    let isAnalyst = p.Descendants("roleIds").Elements().Any(e => (int)e == analystRoleId)
    let firstName = (string)p.Element("firstName")
    let lastName = (string)p.Element("lastName")
    where isActive && isAnalyst && !testAnalystIds.Contains(id)
    select new PeopleClass {
        ResAnId = id,
        DpInit = (string)p.Element("clientCode"),
        ResAnFName = firstName,
        ResAnLName = lastName,
        ResAnName = $"{firstName} {lastName}",
        RoleId = analystRoleId,
        DivisionId = (int?)p.Element("divisionId")
    };

Also

You can use interpolated strings instead of String.Format
I believe id always should present in your file and it will not be null. There is no need to cast this value to nullable
I believe you should check all role ids for verifying whether person is analyst. But you can use FirstOrDeafult as well
You don't need to query for roleId second time - if person matched where clause then it's analyst and you know his role id
You don't need to access Value property of XElement. It's better to use explicit cast operator. Otherwise you can get NullReferenceExceptions
If you can change implementation of PeopleClass then start with renaming it to Person and give more descriptive names to its fields. You can also remove backing storage from ResAndName filed and make it calculated on the fly.


Optimizing Node.js http get for AWS Lambda

Is there an actual way to profile Node.JS running in AWS Lambda to inspect the possible bottlenecks?

Node Lambdas are just small Node modules. Profiling it shouldn't be any different than any other Node app. All you need is a "wrapper" app that imports your lambda script and calls handler with a fake event and context.

Your biggest enemy here won't be your code. You can only do so little with your script actually. The only bottleneck I see is that network request and that external dependency. Just ensure that endpoint responds fast.

Instead of using the request module, consider using the built-in url.format() and http.get to construct your url and do a GET request, respectively. This would remove your only dependency, whose implementation you have no control of, and probably uses both built-in modules anyways.

Also, if you have control over that endpoint, its response needs fixing. A 200 should always be successful. There shouldn't be a 200 that carries an error. Common errors include 500 (generic server error), 400 (bad input), 401 or 403 (Auth errors). Following correct headers, this would allow you to skip all the conditionals and let the status codes explain themselves. Optional body text may be added to explain the status code.


Producing variants of a password based on command-line flags

Some remarks about your code:

Use if __name__ == '__main__':
In my opinion argparse is better then the getopt way,
Divide your code into functions for seperation of control
Use string formatting
Uphold PEP8 guidelines for a cleaner code

1.

def main():
    parse_options()
    do_stuff()

if __name__ == '__main__':
    main()

2.
Example of parsing options via argparse

def parse_options():
    parser = argparse.ArgumentParser(usage='%(prog)s [options] <password>',
                                     description='Password-Tool',
                                     formatter_class=argparse.RawDescriptionHelpFormatter,
                                     epilog=
'''
Examples
'''

                                        )
    parser.add_argument('-o', action="store_true", help='output file')
    ...
    args = parser.parse_args()

3.
When dividing code into seperate functions it makes for a more readable code, and that way it can be imported by other programs.

4.
When using print formatting looks better and correct way would be:

print '{} some text here'.format(i)


Function declarations using macros to support multiple platforms

Keep the DLLExport macro on all platforms, but make the definition resolve to nothing unless you're on Windows. You might also want to rename the macro to something more neutral. Something like this:

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(WINAPI_FAMILY)
# define EXPORT __declspec(dllexport)
#else
# define EXPORT
#endif

extern "C"
{
EXPORT void initScreenPointPixel(void* buffer, int x, int y, int width, int height);
}

You should also be aware of that the extern "C" stuff is only recognized by a C++ compiler. The related statements should also be conditional, e.g.:

#ifdef __cplusplus
extern "C" {
#endif

... declarations here

#ifdef __cplusplus
}
#endif


Fully Refactored Code: see this Gist

Example Usage:

static void Main(string[] args) {
    var generator = new PasswordGenerator(new PasswordGeneratorOptions {
        MinimumNumberOfLowerCaseCharacters = 1,
        MinimumNumberOfNumericCharacters = 1,
        MinimumNumberOfUpperCaseCharacters = 1,
        OutputLength = 8,
        SpecialCharacters = new char[0] { },
    });

    Console.WriteLine(generator.Next());
}

Review Comments:

First off, using Random as a source of entropy probably isn't the best idea since it is possible (however unlikely) that an attacker could gain the underlying seed; with it they would trivially be able to deduce all of the outputs used to generate our passwords. Let's implement a generator that uses a static instance of the RNGCryptoServiceProvider class instead:

// makes it easier to replace the implementation I demonstrate with something better
public interface ISecureRandom
{
    uint Next(uint x, uint y);
}

// a possible implementation of a secure RNG, not exhaustively tested...
public sealed class SecureRandom : ISecureRandom
{
    private static readonly RandomNumberGenerator DefaultRandomNumberGenerator = new RNGCryptoServiceProvider();

    public static SecureRandom DefaultInstance => new SecureRandom(DefaultRandomNumberGenerator);

    private readonly RandomNumberGenerator m_randomNumberGenerator;

    public SecureRandom(RandomNumberGenerator randomNumberGenerator) {
        if (null == randomNumberGenerator) {
            throw new ArgumentNullException(paramName: nameof(randomNumberGenerator));
        }

        m_randomNumberGenerator = randomNumberGenerator;
    }

    public byte[] GetBytes(byte[] buffer) {
        m_randomNumberGenerator.GetBytes(buffer);

        return buffer;
    }
    public byte[] GetBytes(int count) => GetBytes(new byte[count]);
    public uint Next() => BitConverter.ToUInt32(GetBytes(sizeof(uint)), 0);
    public uint Next(uint x, uint y) {
        if (x > y) {
            var z = x;

            x = y;
            y = z;
        }

        var range = (y - x);

        if (range == 0) {
            return x;
        }
        else if (range == uint.MaxValue) {
            return Next();
        }
        else {
            return (Next(exclusiveHigh: range) + x);
        }
    }

    private uint Next(uint exclusiveHigh) {
        var range = (uint.MaxValue - (((uint.MaxValue % exclusiveHigh) + 1) % exclusiveHigh));
        var result = 0U;

        do {
            result = Next();
        } while (result > range);

        return (result % exclusiveHigh);
    }
}

Regarding maintainability, we could start by creating a proper class to encapsulate all of our settings:

public sealed class PasswordGeneratorOptions
{
    private static readonly char[] DefaultSpecialChars = new[] { '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '`', '~', '_', '+', ',', '.', '\'', '"', ';', ':', '?', '|', '/', '\\', '[', ']', '{', '}', '<', '>' };

    public int MinimumNumberOfNumericCharacters { get; set; }
    public int MinimumNumberOfLowerCaseCharacters { get; set; }
    public int MinimumNumberOfSpecialCharacters { get; set; }
    public int MinimumNumberOfUpperCaseCharacters { get; set; }
    public int OutputLength { get; set; }
    public ISecureRandom RandomNumberGenerator { get; set; }
    public IReadOnlyList<char> SpecialCharacters { get; set; }

    public PasswordGeneratorOptions() {
        MinimumNumberOfLowerCaseCharacters = 0;
        MinimumNumberOfNumericCharacters = 0;
        MinimumNumberOfSpecialCharacters = 0;
        MinimumNumberOfUpperCaseCharacters = 0;
        RandomNumberGenerator = SecureRandom.DefaultInstance;
        SpecialCharacters = DefaultSpecialChars;
    }
}

Then we can declare a PasswordGenerator class that consumes our options:

public sealed class PasswordGenerator
{
    private readonly PasswordGeneratorOptions m_options;

    public PasswordGenerator(PasswordGeneratorOptions options) {
        if (options.OutputLength < (options.MinimumNumberOfLowerCaseCharacters + options.MinimumNumberOfNumericCharacters + options.MinimumNumberOfSpecialCharacters + options.MinimumNumberOfUpperCaseCharacters)) {
            throw new ArgumentOutOfRangeException(message: "output length must be greater than or equal to the sum of all MinimumNumber* properties", actualValue: options.OutputLength, paramName: nameof(options.OutputLength));
        }

        m_options = options;
    }
}

Now we can start thinking about implementation details, I personally like the idea of breaking things up into various categories so that we can provide more complex configuration options later. Let's try classifying your characters into lower-case, upper-case, number, and special. The ASCII encoding has largely taken care of all of this for us "for free" since three of these four classes have contiguous regions in the specification; we can write a simple generator for each like so:

var randomNumberGenerator = new SecureRandom();

Func<char> GetAsciiLetterLowerCase = () => ((char)randomNumberGenerator.Next(97, 123));
Func<char> GetAsciiLetterUpperCase = () => ((char)randomNumberGenerator.Next(65, 91));
Func<char> GetAsciiNumber = () => ((char)randomNumberGenerator.Next(48, 58));

Special characters aren't as easy so we'll resort to using a table of values:

var specialCharacters = new char[] { '!', '@', '#', };

Func<char> GetAsciiSpecial = () => specialCharacters[randomNumberGenerator.Next(0U, ((uint)specialCharacters.Count))];

The only remaining thing left to do is implement the generator function. This can be accomplished by more or less following the same strategy you already have in place. I chose to implement Fisher–Yates shuffle instead of using LINQ for the final randomization step:

public string Next() {
    var index = 0;
    var length = m_options.OutputLength;
    var randomNumberGenerator = m_options.RandomNumberGenerator;
    var result = new char[length];
    var useSpecial = (0 < m_options.SpecialCharacters.Count);

    for (var i = 0; (i < m_options.MinimumNumberOfLowerCaseCharacters); i++) {
        result[index++] = m_getAsciiLetterLowerCase();
    }

    for (var i = 0; (i < m_options.MinimumNumberOfNumericCharacters); i++) {
        result[index++] = m_getAsciiNumeric();
    }

    for (var i = 0; (i < m_options.MinimumNumberOfSpecialCharacters); i++) {
        result[index++] = m_getAsciiSpecial();
    }

    for (var i = 0; (i < m_options.MinimumNumberOfUpperCaseCharacters); i++) {
        result[index++] = m_getAsciiLetterUpperCase();
    }

    for (var i = index; (i < length); i++) {
        char c;

        switch (randomNumberGenerator.Next(0U, (useSpecial ? 4U : 3U))) {
            case 3U:
                c = m_getAsciiSpecial();
                break;
            case 2U:
                c = m_getAsciiNumeric();
                break;
            case 1U:
                c = m_getAsciiLetterLowerCase();
                break;
            case 0U:
                c = m_getAsciiLetterUpperCase();
                break;
            default:
                throw new InvalidOperationException();
        }

        result[i] = c;
    }

    FisherYatesShuffle(randomNumberGenerator, result);

    return new string(result);
}

private static void SwapRandom<T>(ISecureRandom randomNumberGenerator, IList<T> list, uint indexLowerBound, uint indexUpperBound) {
    var randomIndex = randomNumberGenerator.Next(indexLowerBound, indexUpperBound);
    var tempValue = list[(int)randomIndex];

    list[(int)randomIndex] = list[(int)indexUpperBound];
    list[(int)indexUpperBound] = tempValue;
}
private static void FisherYatesShuffle<T>(ISecureRandom randomNumberGenerator, IList<T> list) {
    var length = list.Count;
    var offset = 0U;

    while (offset < length) {
        SwapRandom(randomNumberGenerator, list, 0U, offset++);
    }
}


Installing and removing kernel module RPMs

Should this be a shell script?

You mentioned that you wrote this script to push the packages to over 60 servers.  If you have that many servers, then you should have a configuration management tool to do these kinds of tasks for you and much, much more.  Typical solutions include Ansible, CFengine, Chef, and Puppet.

Instead of copying the RPMs to each machine, you should probably use a YUM repository, which may be one that you operate yourself, if those are self-built RPMs.

Version check

modinfo enic |grep "^version" |awk '{print $2}' would be better written as modinfo -F version enic 2>/dev/null.  I recommend discarding error messages there, in case no such module is available.

However, I wonder why you bother querying modinfo at all, instead of just running yum and letting it automatically decide whether anything needs to be installed at all.

The conditionals are slightly redundant.  You could just write

if [ $enic_ood -a $fnic_ood ]; then
    …
elif [ $enic_ood ]; then
    …
elif [ $fnic_ood ]; then
    …
else
    …
fi

I get the feeling, though, that nearly everything in the script is written twice.  You could write a loop that handles both packages:

need_rpms=
for module in enic fnic ; do
    rpm=$HOME/kmod-$module-*.rpm
    want_version=$(rpm -qp --queryformat '%{VERSION}' $rpm)
    installed_version=$(/sbin/modinfo -F version "$module" 2>/dev/null)
    if [ "$want_version" = "$installed_version" ]; then
        echo "$module is already up-to-date: $installed_version"
    else
        need_rpms="$need_rpms $rpm"
    fi
done

if [ -n "$need_rpms" ]; then
    /usr/bin/yum -y localinstall $need_rpms
done

Alternatively, you could have one script that takes parameters, and run it once for each package.

Program structure

There should be an install() function and a remove() function.

Don't set yum='/usr/bin/yum -y localinstall' in one place and yum='/usr/bin/yum -y remove' in another place.  I would expect it to be uniformly defined as yum='/usr/bin/yum -y', just like modinfo='/sbin/modinfo'.

This script always appears to succeed.  Fatal errors should cause the script to exit with a non-zero status, and error messages should be printed to standard error.  Exit statuses matter; even when executing the script over SSH, for example, the error status propagates all the way back to become the exit status of SSH.

install() {
    …
}

remove() {
    …
}

case "$1" in
  install|remove)
    "$1"
    ;;
  *)
    echo "$0 must be executed with either 'install' or 'remove'" >&2
    exit 1
    ;;
esac


Navigating the robot by finding the shortest way

if structure
        if map.value[x,y] != 0:
            pass
        elif x==n+1 and y==m+1 or x==n-1 and y==m-1 or x==n-1 and y==m+1 or x==n+1 and y==m-1:
            pass
        elif map.blocked(x,y) == True:
            map.value[x,y]= -1
        elif x==n and y==m:
            map.value[x,y]= number
        else:
            map.value[x,y]= number+1

is a little awkward. Rephrase if; pass into if not, delete == True since it's redundant, and you have:
if map.value[x, y] == 0 and not (
    (x==n+1 or x==n-1) and
    (y==m+1 or y==m-1)
):
    if map.blocked(x, y):
        map.value[x, y] = -1
    elif x == n and y == m:
        map.value[x, y] = number
    else:
        map.value[x, y] = number + 1

You can further simplify by checking for coordinate difference in a set membership operation, though I haven't tested its performance:
if map.value[x, y] == 0 and not (
    {x - n, y - m} <= {-1, 1}
):
    # ...

General
You have heavily nested loops that iterate over a matrix-like structure. That's a job for numpy. Vectorization may or may not make your code shorter, but it will definitely speed it up.


Archiving an SQL table of sessions and statistics

I have much more experience with SQL Server than with MySQL, but I think that some things very similar:

LEFT JOIN replacement - you are using only member_id from stats inner query. You could just have a direct LEFT JOIN with the bot_sessions_statistics table.
Cluster index candidate - bot_sessions_statistics.date_active looks like it is assigned one time with current time. As time always goes up, it should not create re-orderings. This is particularly useful when fetching multiple columns (index has all the columns) with conditions like >= date(NOW()) (faster seeks).
Possible use of partitioning - I have never used this in MySQL, but this functionality can provide increased performance when seeking data in very large tables. Partitioning by date columns might gain you some performance.
NOT EXISTS instead of LEFT JOIN / IS NULL - generally, it seems that LEFT JOIN with IS NULL is slower that NOT EXISTS.


The important thing to know about commands in Python (or any language with first-class functions) is that they're usually trivial.  Commands with only one operation (execute) are simply functions. There's no need to define classes. Even commands with two operations can be represented as pairs of functions: (do, undo). The whole, heavyweight pattern is almost never used.

Comments on the above implementation:

Command parameters such as filenames should be arguments to the constructor, not to execute. The code that calls execute doesn't know what these values should be, so they need to already be in the command.
There's no reason to keep a table of commands. Just create commands as needed.
Invoker.execute manually dispatches by command name. Instead it should blindly call execute or undo, and let method dispatch find the appropriate method.
The Invoker class does nothing useful.
Why bother getting the method name from inspect.stack when the method already knows its own name?
I might call execute do, for symmetry with undo.
ABCMeta is unnecessary complexity. If you must use it, it's clearer to write class Command(metaclass=ABCMeta) rather than assigning to __metaclass__.
The file operations don't undo properly if a file was overwritten. (This is not relevant to the pattern; it's just a bug.)


Trying to use the code

The class defines something which feels a bit weird to use. We'll see a few ways to improve this.

The constructor provides default value for all parameters which leads one to think he can just do r = InterestRate() and enjoy. It is most definitly not the case because one (and only one) of the inputs must be provided.

This suggests that maybe we should not have a single constructor doing many things but many small constructors (using alternative constructors for example).

Then, trying to use the shiftedPaymentPV method, I stumbled on a different error: the self is not part of the signature which makes it unusable as far as I can tell.

Simplifying the code

In the __init__, we set the paymentsPerPeriod attribute only to excluse it in next operation when handling all attributes. We may as well set it afterward to makes things more simple.

This also shows how subtle and fragile that piece of logic is. One could easily break the whole thing by moving an attribute which doesn't seem to be used because we use introspection magic (which is pretty cool in itself but probably better to avoid here).

Let's see how it can be improved anyway.

Instead of counting elements as we go, we could put them in a list and count them afterwards. This helps if we want to show the list to the user in the exception message.

    ratesGiven = [attr for attr, value in vars(self).items() if value != 0 and attr != 'paymentsPerPeriod']
    if len(ratesGiven) != 1:
        raise Exception("Incorrect number of inputs passed to InterestRate object")
    rateGiven = ratesGiven[0]

This could give use the following code:

import math

class InterestRate:

    @classmethod
    def from_nominal(cls, nominalInterestRate, paymentsPerPeriod=1):
        effectiveInterestRate = (nominalInterestRate/paymentsPerPeriod + 1) ** paymentsPerPeriod - 1
        return cls(effectiveInterestRate=effectiveInterestRate, paymentsPerPeriod=paymentsPerPeriod)

    @classmethod
    def from_effective_discount_rate(cls, effectiveDiscountRate, paymentsPerPeriod=1):
        effectiveInterestRate = effectiveDiscountRate / (1 - effectiveDiscountRate)
        return cls(effectiveInterestRate=effectiveInterestRate, paymentsPerPeriod=paymentsPerPeriod)

    @classmethod
    def from_nominal_discount_rate(cls, nominalDiscountRate, paymentsPerPeriod=1):
        effectiveInterestRate = (1 - nominalDiscountRate/paymentsPerPeriod) ** -paymentsPerPeriod - 1
        return cls(effectiveInterestRate=effectiveInterestRate, paymentsPerPeriod=paymentsPerPeriod)

    @classmethod
    def from_discount_factor(cls, discountFactor, paymentsPerPeriod=1):
        effectiveInterestRate = 1 / discountFactor - 1
        return cls(effectiveInterestRate=effectiveInterestRate, paymentsPerPeriod=paymentsPerPeriod)

    @classmethod
    def from_force_of_interest(cls, forceOfInterest, paymentsPerPeriod=1):
        effectiveInterestRate = math.exp(forceOfInterest) - 1
        return cls(effectiveInterestRate=effectiveInterestRate, paymentsPerPeriod=paymentsPerPeriod)

    @classmethod
    def from_effective_interest_rate(cls, effectiveInterestRate, paymentsPerPeriod=1):
        return cls(effectiveInterestRate=effectiveInterestRate, paymentsPerPeriod=paymentsPerPeriod)

    def __init__(self, effectiveInterestRate, paymentsPerPeriod):
        self.effectiveInterestRate = effectiveInterestRate
        self.paymentsPerPeriod = paymentsPerPeriod

        self.nominalInterestRate = paymentsPerPeriod * ((1 + effectiveInterestRate) ** (1 / paymentsPerPeriod) - 1)
        self.effectiveDiscountRate = effectiveInterestRate / (1 + effectiveInterestRate)
        self.nominalDiscountRate = paymentsPerPeriod * (1 - (1 + effectiveInterestRate) ** (-1 / paymentsPerPeriod))
        self.discountFactor = 1 / (1 + effectiveInterestRate)
        self.forceOfInterest = math.log(1 + effectiveInterestRate)

    def outputInterestRateData(self):
        print("\n  ----------------------------------------------------")
        print("                   Interest Rate Data                 ")
        print("  ----------------------------------------------------")
        print("   Payments per Period:        ", self.paymentsPerPeriod)
        print("   Effective Interest Rate:    ", self.effectiveInterestRate)
        print("   Effective Discount Rate:    ", self.effectiveDiscountRate)
        print("   Nominal Interest Rate:      ", self.nominalInterestRate)
        print("   Nominal Discount Rate:      ", self.nominalDiscountRate)
        print("   Discount Factor:            ", self.discountFactor)
        print("   Force Of Interest:          ", self.forceOfInterest)
        print("  ----------------------------------------------------")

    def shiftedPaymentPV(paymentAmmount, periodsShifted):
        assert False, "this can't work"
        return paymentAmmount*(1 + self.effectiveInterestRate)**periodsShifted

r = InterestRate.from_nominal(nominalInterestRate=-0.9375, paymentsPerPeriod=2)
print(r.outputInterestRateData())

Style

Python has a Style Guide called PEP 8. It is definitly worth reading it and trying to apply it.

In your case, that would mean adding whitespaces around operators and using the snake_case naming convention for variables and method names.

String conversions

Instead of a outputInterestRateData, maybe you could define the __str__ method.

Also, you could take this chance to use one of the various ways to format strings in Python.

You'd get something like:

    def __str__(self):
        return """
  ----------------------------------------------------
                   Interest Rate Data
  ----------------------------------------------------
   Payments per Period:     {}
   Effective Interest Rate: {}
   Effective Discount Rate: {}
   Nominal Interest Rate:   {}
   Nominal Discount Rate:   {}
   Discount Factor:         {}
   Force Of Interest:       {}
  ----------------------------------------------------
        """.format(self.paymentsPerPeriod, self.effectiveInterestRate,
                self.effectiveDiscountRate, self.nominalInterestRate,
                self.nominalDiscountRate, self.discountFactor,
                self.forceOfInterest)


Typically in JavaScript, when calling isNaN, it is just typed:

isNaN(...);

Not as a call from the Number class:

Number.isNaN(...);

Also, by calling it the way that you did, you are being inconsistent. If you are going to call isNaN through Number, then why don't you also call parseInt through Number?

The function parseInt takes a second parameter radix which is the base of the first parameter.

According to the MDN, you should always specify the radix parameter.

Why do you call parseInt on the arguments of range? In every single point of your code where you are calling this function, you are passing numerical arguments.

Calling this functions is just a waste.

In places like these:

if (arguments.length == 0){

and

if (arguments.length == 1){

You should be using the === comparison operator rather than the == comparison operator.

It is good JavaScript practice.
It may be a little faster.

See this SO post for more information.

As shown in this SO post, a much, much simpler way to reverse a string would be to do this:

return string.split("").reverse().join("");

This could potentially be faster, too, as this is using JavaScript's built in functions/methods/features.

Your is_palindrome function confuses me a little. A palindrome is defined as a word that is spelled the exact same as it's reverse. Therefore, why aren't you using the reverse function that you already made?

Now, your is_palindrome function becomes this:

return string == reverse(string);

This is much more simple than whatever you were doing.

The naming case for JavaScript is camelCase, not snake_case. You need to change the name of these functions:

is_palindrome --> isPalindrome

and

is_lychrel --> isLychrel

And, make sure you change the name of some of your variables to camelCase too.

You are putting too much work on your isLychrel function.

Here, you check to see that if there is no recursions specified, set it to 50:

if (arguments.length == 1)
    recursions = 50;

However, this check is going to happen every single iteration (since the function is recursive).

Is is really that difficult to just pass 50 to it in the initial time you call it in main? If you did this and removed the check from the function, this could greatly improve your performance.


Each element is the sum of itself with the next element of a List: now do this point-free in Haskell

Pointfree, eh? Let's ask lambdabot.

<DanBurton> @pl map (\(y, z) -> y + z) (zip x (tail x))
<lambdabot> zipWith (+) x (tail x)

Assuming that x is simply the input to this "function"

<DanBurton> @pl \x -> map (\(y, z) -> y + z) (zip x (tail x))
<lambdabot> map (uncurry (+)) . ap zip tail

Personally I'd go with the former; I'm not a fan of Lambdabot's gratuitous use of uncurry and ap.


Filtering cards into appropriate list elements

By simply adding the else condition to the if, the DRY warning will go away. It's just telling you that both the if and else block currently execute the same code, and can therefore be consolidated into a single block.
The comment // Find index of workcentres is misleading and should be removed.
Don't use abbreviations for naming. It makes it very hard to read and understand the code.
By extracting the condition to a separate method, you can use the Where() LINQ method and call AddRange() instead of repeatedly calling Add() .
Like @Paparazzi mentioned in a comment, you are filtering, rather than sorting, so you should change the name of the method.

Implementing the changes (except for the naming), you code will look like the following:

private void WsSorter(WorkcentreList wcl, List<WorkstationCard> wscl)
{
    foreach (Workcentre wc in wcl.WcList)
    {
        wc.CardList.AddRange(wscl.Where(workstationCard => IsDesiredWorkstationCard(workstationCard, wc.WcName)));
    }
}
private bool IsDesiredWorkstationCard(WorkstationCard workstationCard, string workCentreName)
{
    return !(workstationCard.WorkcentreNo == MAIN_WORKCENTRE_1 ||
             workstationCard.WorkcentreNo == MAIN_WORKCENTRE_2 ||
             workstationCard.WorkcentreNo == MAIN_WORKCENTRE_3 ) ||
             workstationCard.WorkcentreNo == workCentreName
}


Assuming your objects have a unique property, such as the Id property in your example, you can expand each array in a single pipeline and use Select -Unique to create a combined array, and add your tracking in the same command as such:

$result = $dev,$test,$prod|%{$_}|Select *,@{l='Dev';e={$_.Id -in $dev.id}},@{l='Prod';e={$_.id -in $prod.id}},@{l='Test';e={$_.id -in $test.id}} -Unique

That cuts the time down to a bit under half what you are seeing. I ran Measure-Command 100 times against your code vs my code (using the same test build in each, the only difference being how $result was generated), and your code on my machine took about 16.9ms on average, and my code took 7.4ms on average.

1..100|%{Measure-Command {# create test cases
$a = [PsCustomObject]@{Id='AAA';Name='Dev'}
$b = [PsCustomObject]@{Id='BBB';Name='Dev/Test'}
$c = [PsCustomObject]@{Id='CCC';Name='Dev/Prod'}
$d = [PsCustomObject]@{Id='DDD';Name='Dev/Test/Prod'}
$e = [PsCustomObject]@{Id='EEE';Name='Test'}
$f = [PsCustomObject]@{Id='FFF';Name='Test/Prod'}
$g = [PsCustomObject]@{Id='GGG';Name='Prod'}

# add to arrays
$dev = $a,$b,$c,$d

$test = $b,$d,$e,$f

$prod = $c,$d,$f,$g

$results = $dev,$test,$prod|%{$_}|Select *,@{l='Dev';e={$_.Id -in $dev.id}},@{l='Prod';e={$_.id -in $prod.id}},@{l='Test';e={$_.id -in $test.id}} -Unique

$Results|FT -Auto
}}|Measure-Object -Average -Property TotalMilliseconds|% Average

7.408363


Firstly, good job in commenting. The thing I usually look for in comments is why this thing is needed, which you really did in detail. However, your comments might need a bit of trimming. Explaining is good, making them too long though makes them visually distracting.

The onlyShowOn and pageOptions structures are redundant. You can just use pageOptions instead to check for existence.

var pageTitle = $('meta[property="og:title"]').attr('content');

I believe this can be replaced by the following, removing the dependency to jQuery.

var pageTitle = document.querySelector('meta[property="og:title"]').getAttribute('content');

In the end, your code is about getting skipHeadings and headingSubstitution based on the value of the title and falling back to default values if some parameters don't meet. So let's start with that.

var defaults = {
  skipHeadings: 1,
  headingSubstitution: {
    'A really long heading to test box size issues.': 'Long Heading ...',
    'Playing with Tocify': 'Playing ...'
  }
};

var substitutes = {
  'Some Other Page': {
    skipHeadings: 2,
    headingSubstitution: {
      'A really long heading to test box size issues.': 'Long Heading ...',
    }
  },
  'Tocify Test Page': {},
  'Tocify Page': {}
};

var pageTitle = document.querySelector('meta[property="og:title"]').getAttribute('content');

var hasSubstitute = pageOptions.hasOwnProperty(pageTitle) && substitutes[pageTitle];

// We check if there's a substitute. If not, use the default. Also, if our
// substitute has missing properties, Object.assign to fills them in with
// defaults.
var substitute = hasSubstitute ? Object.assign({}, defaults, substitutes[pageTitle]): defaults;

// In the end, substitute will always have a skipHeadings and
// headingSubstitution property, allowing us to write without checks.
var skipHeadings = substitute.skipHeadings;
var headingSubstitution = substitute.headingSubstitution;


I was going to switch it to a case statement but wanted to check if there were even better ways to reduce the clutter.

You could load the mappings from job titles to emails into a (static) dictionary, and then do a dictionary look-up (using the default value if it's not in the dictionary).

The Dictionary<string,string> can be initialized with a collection initializer.

Using a (data-driven) dictionary instead of a (hard-coded) switch statement has the additional benefit that users can configure/maintain the behaviour by editing a configuration file (e.g. a tab-delimited 'CSV file' of title/email pairs) or database, instead of editing code.


You check whether the index of the tab equals the position. If this is the case, use the selected icon, otherwise use the unselected one:

for(int i = 0; i < 5; i++) {  // maybe replace 5 with a constant declaration...
    if(i == position)
        tabLayout.getTabAt(i).setIcon(tabSelected[i]);
    else
        tabLayout.getTabAt(i).setIcon(tabsUnselected[i]);
}


Reflecting changes in the DataGridView back on the List and then updating database

I believe you will want to use a BindingList, which can notify when entries are updated.

You will need to handle the events raised in order to reflect the changes back to the original source.

See these sources for more:

Documentation : http://msdn.microsoft.com/en-us/library/ms132679%28v=vs.110%29.aspx
Previous question with some more info on List vs BindingList: https://stackoverflow.com/questions/2243950/listt-vs-bindinglistt-advantages-disadvantages
Basic example on Codeproject: http://www.codeproject.com/Articles/23222/BindingList-Example


The alternative approaches in the comments return arr.concat(arr); and return [...arr, ...arr]; are good replacements.

However, if you wrote this as part of a course, you should consider the following:

Your indentation is off, this is rule 1 in writing code: indent it
You are missing a semicolon after copy.push(arr[i])
In such a small function, I would have declared i up top in that let statement


Use std::size_t for container sizes and indices, not int.

std::size_t queueFront;
std::size_t queueRear;
std::size_t maxSize;

Use meaningful variable names. When I use your constructor, what does "x" mean? Something like queue_size is more meaningful. This can also be a std::size_t. This also doesn't need to be a reference, since it's likely the same size as a pointer, but feel free to continue passing as reference if you want. You just normally don't see that with primitive types.

queueList(std::size_t queue_size);

Similarly, pick a meaningful name for your enqueue function. Even something like value carries more meaning than x. This should NOT be a std::size_t, since obviously you do want to insert an int into your int array.

Handle the special case in your constructor where the passed-in size is 0 or less. It won't be less than 0 if you switch to size_t, but it can still be 0. Do you want to allow this? How do you manage the memory? Calling new int[0]; is undefined behavior. Also, use initializer lists when possible for constructors. It prevents variables from being double-assigned and objects from being double-constructed. You won't notice any speedup on this problem, but it's a good habit to get into.

queueList::queueList(std::size_t queue_size)
  : list(queue_size > 0 ? new int[queue_size] : nullptr)
  , queueRear(0)
  , queueFront(0)
  , maxSize(queue_size)
{ }

Explicitly delete your default constructor to avoid ambiguity.

queueList() = delete;

Your constructor manages a resource (memory allocated with new), so you must also declare a destructor that deletes the memory. Since you must declare a destructor, you must follow at LEAST the rule of 3 and define a copy constructor and a copy assignment operator. A best practice would be to follow the rule of 5 (same link as rule of 3) and define additionally a move constructor and move assignment operator.

They key with all of these is: what does it mean to create a copy of your queue? What does it mean to move your queue? Most of these questions will have to do with managing the underlying allocated memory.

~queueList() { delete[] list }; // destructor
queueList(const queueList& other); // copy constructor
queueList& operator=(const queueList& other); // copy assignment operator
queueList(queueList&& other); // move constructor
queueList& operator=(queueList&& other); // move assignment operator

Your queue is currently one-time-use. It can only ever hold queue_size (x in your code) elements ever. It can't hold more elements than what you initially allocate. The latter is surmountable, but you should make it a goal to allow the queue to grow (or have a policy of throwing some error, or letting the user know through documentation that excess values will be lost). The one-time usability of each data slot is CRIMINAL though. My suggestion is to allow queueRear and queueFront to wrap around the array using modulo arithmetic as they move to the right.

dequeue should return a value!!! This is a huge shock to anyone who will try to use your class. They don't always want to print the value. They likely want to use it in some future calculation. This is easy. However, your current code doesn't even print the current value. It just always overwrites it with 0, then prints 0. This also decouples your class from requiring iostream to work.

Change your dequeue to look like this:

int queueList::dequeue()
{
    if (isEmpty())
    {
        // figure out what to do here.
        // Throw an error? Seems appropriate.
        // Another option is to return a std::pair<int, bool>,
        // where the second value indicates whether there were
        // any items in the queue
    }
    int retval = list[queueFront++];
    queueFront = queueFront % maxSize; // talking about modulo arithmetic earlier
    return retval;
}

Your isEmpty() and isFull() functions can have their prototypes modified to be const, since neither modify the object:

bool isEmpty() const
{
    ...
}

bool isFull() const
{
    ...
}


Scan first and last name from user, then format the name as last, first initial

Methods

I'm assuming this chunk of code sits in your main() method, and I think one quick way of improving it is to break it into two methods - one that returns a validated user input (at least 5 chars with a space), and one for the actual work.

When you separate them, you will also realize that you only need to print your validation message once, instead of twice as you are doing currently (to check for length, and to check for a space).

Stricter input validation

  Type your name: Jessica Miller

  Your name is: Miller, J.

Since you actually require the initial of the first name, you also need to check that the space is not at the start or the end of the input, as otherwise you only have one name. Consider this:

private static void test(String input) {
    // A Scanner works in a similar way to the legacy StringTokenizer class
    try (Scanner scanner = new Scanner(input)) {
        while (scanner.hasNext()) {
            System.out.printf("Token: [%s]%n", scanner.next());
        }
    }
}

test("hello world");
// Token: [hello]
// Token: [world]

test(" helloworld");
// Token: [helloworld]

test("helloworld ");
// Token: [helloworld]

An example implementation to validate for this can be:

private static final int REQUIRED_LENGTH = 5;

private static String getInput(Scanner scanner) {
    String result = scanner.nextLine();
    while (result.length() < REQUIRED_LENGTH ||
            !result.contains(" ") ||
            result.startsWith(" ") ||
            result.endsWith(" ")) {
        System.out.println("Try again.");
        result = scanner.nextLine();
    }
    return result;
}

Still, this can be defeated if there are multiple spaces and they happen to also be at the start and/or the end. Perhaps a regex solution may be better here... this shall be left as an exercise for the reader.

Boolean flags

Going back to your main() method, you wouldn't require correctName if you have separated the logic that validates the user input and the actual work.


In my actions (Controllers) I handle only data that comes from the request.

If above is the case you might be better off handling validation before calling service class. In other words, prepare data into a format that business service classes can understand. Same applies about a decision on which HTTP Code to return.
I am not sure why you have single responsibility controllers, a number of files would bloat very quickly in a larger application.
Controller:
class CreateUserAction extends Action
{
    public function handle(UserCreateRequest $request): JsonResponse
    {
        return (new UserService)->create($request->validated(), $user);

        // OR
        $user = (new UserService)->create($request->validated(), $user);

        return response($user, Response::HTTP_CREATED);
    }
}

I am not sure why you are using repository unless you are doing complex DB operation. Service should have all the business logic. This way service layer/business logic can be easier extracted and reused in other applications thanks to less dependencies.
use App/Models/User;

class UserService extends BaseService
{
    public function create(array $data): User
    {
        return (new userRepository)->create($data);

    }
}


Currying addition function in ECMAScript 6

I'm unsure about this part:

if(!args1.length) {
  return sum(args1);
}

If the array's empty, you could just return zero - no need to call sum.

Secondly, you're doubling possible return types for add. You either get a new curried function, or you get a number.

This goes for the curried function as well, really, as it too will return either a sum or another function.

So either way, it's kinda tricky. Partial application/currying is kinda difficult if you have something like this, that you can "keep currying" forever.

Anyway, sticking to your current structure, it can be simplified somewhat. Notably, you don't have to create a new closure for each invocation. And you can get rid of the double !argsN.length checks and calls to sum:

function add(...initial) {
  let list = [];

  function adder(...values) {
    if(!values.length) {
      return list.reduce((sum, n) => sum + n, 0);
    }

    list.push(...values);
    return adder;
  }

  return adder(...initial);
}

Here, I've named the nested function, so it can return itself. After the initial call to add, the nested adder function is created, closes over the list array, and is invoked. It then either returns the sum or it returns itself. I.e. only one closure is created, and subsequent calls simply update the closed over list - or sums it.

adder also handles all the input checking etc.. The outer add function only exists to create and invoke it.

Also note that I renamed the argument arrays, as args1 and args2 really aren't too descriptive. And that the ...-splat works for both definition and invocation. And, lastly, since it only need to do a sum in 1 place, there's no need for a separate sum function.


Use the types you have

Why are you storing the card value as an int? You have already created a CardValue enum, so use it. Change the Card.CardValue property and the cardValue parameter in the Card constructor to be of type CardValue. That way, you don't need to cast to an int when creating a card, and you can always get the numeric card value by casting ((int)cardValue) when you need it.

Argument Validation

What happens if you use new Card((CardSuit)100, (CardValue)100). Your card will have an invalid suit and value. In order to validate the arguments, you can use Enum.IsDefined, which will cause a performance penalty since it uses reflection, or you can hardcode a valid range of values.

Type Naming

The name CardValue seems too general for such a specific type (thanks to @RickDavin). "Value" implies it may refer to any value from the card, such as its suit or rank. A better name might be CardRank.

Property Naming

As noted by @Heslacher, type names shouldn't be used as property names. For instance, in the Card class, the property CardSuit and has a redundant name. Consider a variable Card card = new Card(). Using card.Suit is much clearer and more concise than using card.CardSuit. In addition, you should change the property CardValue to Rank, since the type CardValue was renamed.

Readonly Properties

It seems Rank and Suit are supposed to be readonly. Prior to C#6, your approach was an acceptable one, so long as you remembered not to change those properties outside of the constructor. However, if you're using C#6, a better alternative is to declare them without setters. Like readonly fields, properties that have only getters can only be set inside the constructor, but not outside of it.

With that, the Card class should look like:

public class Card
{
    public CardSuit Suit { get; }
    public CardRank Rank { get; }

    public Card(CardSuit suit, CardRank rank)
    {
        if (suit < CardSuit.Spades || suit > CardSuit.Clubs) // or if (!Enum.IsDefined(typeof(CardSuit), suit))
        {
            // handle error (possibly with ArgumentException)
        }
        if (rank < CardRank.Ace || rank > CardRank.King) // or if (!Enum.IsDefined(typeof(CardValue), rank))
        {
            // handle error
        }
        Suit = suit;
        Rank = rank;
    }
}


Explicitely passing a parameter by reference in C++03

I can't see anything I would do majorly different.

I would make the member T & m_value private.
I would change the name of the method byRef() to just ref()

Note you still have a difference in identifiers.
The class is Ref while the function is ref()

The only problem I see is that at inside the function, the object is not automatically usable in its native type you need to cast it back before you can use it:

struct X { void print();};

void print(Ref<X> x)
{
    x.print();  // This fails to compile

    // To use the x object I need to cast it back to an X
    static_cast<X&>(x).print();

    // If we are going to use it multiple times then we could set up
    // a local reference to the object as this will generate an implicit cast
    X&  x1 = x;
    x1.print();
}

Thus getting at methods in the object becomes slightly on the messy side.


Find A Series of Numbers Who when Squared and Summed are equal to a given Square

Optimization starts from a sound logical process

Let's think about the problem in particular.

  Given a positive integral number n, return a strictly increasing sequence (list/array/string depending on the language) of numbers, so that the sum of the squares is equal to n².

  If there are multiple solutions (and there will be), return the result with the largest possible values

And later, it specifies

  If no valid solution exists, return nil, null, Nothing, None (depending on the language) or "[]" (C) ,{} (C++), [] (Swift, Go).

You were on the right track with your solution, but the code does not exemplify that. Your solution iterates through a map of all  pairings and removes one at a time per iteration of solutionFinder. At worst, this will go through every permutation of 1, ..., . And ideally, you should never reach a case where you're even looking at numbers that have larger squares than your remaining value.

So, how can we improve this? Well, as I said before, optimization starts from a sound logical process. There are 2 conditions in the specifications that can help us build that solution:

The sequence must be strictly increasing
If there are multiple solutions, we must return the result with the largest possible values

Because I'm pretty sure you're already within this same line of problem solving for the problem itself, I'll just jump to what I'm thinking:

   Start with  and .

 Iterating from j=i down to 1, subtract  from . Skip  particularly.

 If that value equals 0, return a list with just i.

 Otherwise, recursively call the same method with that value and j. Return a list of that call with j appended to it if it's nonnull, and null otherwise.

 If i=0, return null.

This methodology guarantees the highest number solution, and doesn't iterate through all permutations. Done right, it'll output the right list or null in order.

So how does this constitute a valid code review? Well, it points out some extraneous points in your solution.

Couple miscellaneous points

There is no need to keep a map of integers to their squares. You can iterate down from the highest possible square to 1 and lower your time complexity while maintaining the uniqueness of your output.

You should build the list through return values, rather than modification within a method parameter. The beauty of recursion is the ability to use recursive method evaluations within another call of the same method.

You have 2 variables named sol in different scopes. It's hard to determine where the solution actually goes. I would recommend removing the global scoped sol, and using the above points to return the solution from solutionFinder.


This isn't an actual solution to your problem, but I noticed that you aren't using var to declare your JavaScript variables. Doing so automatically declares them in the global scope, which is a bad idea as a general rule of thumb and can quickly lead to unpredictable behavior. Declaring variables should be done like var myvar = myvalue:

<script>
    function measure(){
        var $total_count=document.getElementById("total_product_count").value;
        for(var i = 1; i <= $total_count; i++){
            var $description_id='description['+i+']';
            var $second_description_id='description['+i+']_second';
            var $attributes_id='attributes['+i+']';
            $combined_height = document.getElementById($description_id).clientHeight + document.getElementById($attributes_id).clientHeight;

            if($combined_height>800){
                document.getElementById($description_id).style.display = 'none';
            }
            else{
                 document.getElementById($second_description_id).style.display = 'none';
            }

        }
    }
</script>

...


I have some notes on Pythonic style.

People usually instantiate an empty dict with {}, instead of actually calling dict(). Usually, the only reason you need to call dict is if you're passing some variables to create your dictionary.

There's no need to explicitly cast a value to a boolean, Python can implicitly run a boolean test on any type. So you can just do this:

if data.get('sid', None):

I don't know exactly what type data is, but assuming it's a dictionary, get will default to returning None, so there's no need to make it an explicit parameter of get.

You have a long block inside a try followed by a blanket except Exception, e. There's a few problems here. First, your try block should be as narrow as possible. You can use return to prematurely end functions from the except block if you need to. Speaking of that except block, you should ensure that it's only catching errors you specifically expect. In this case, presumably you want to catch ValueErrors from a bad data['sid'] string, as well as catching KeyError for user_sids that don't show up in the users dictionary. Blanket exceptions will just mask errors you're not expecting, instead of handling the ones you know can occur in normal execution.

Lastly, don't use except Exception, e syntax, it will lead to trouble and was removed in Python 3. It causes ambiguities when you want to catch multiple exception types, like except KeyError, ValueError, e:. How is Python supposed to interpret that? This is why you should use except (KeyError, ValueError) as e: or except (KeyError, ValueError):, as you don't have to store the result in a variable if you're not using it.


As far as performance is concerned, there are no problems in this code. It's using C++ streams in the idiomatic way, which is good.

If you're experiencing performance issues, you could try detaching from C streams at the start of your program:

int main(){
    std::ios_base::sync_with_stdio(false);

When you do this, you must then not mix C++ I/O (IO streams) with C I/O (printf and friends) in your program, but mixing these is bad practice anyway.

Here are some other comments to your code:

The names n and i don't say anything about the variables' use. I had to read through most of your code to figure out what i means. Always use descriptive names for your variables, at least for those whose value is supposed to persist for extended periods of time. I would be willing to accept the n, as it is basically one-shot, but i should be renamed at least to count or inputCount or something more descriptive.
Your looping and termination logic seems odd. You are using the correct construct while (fin >> n), looping while there's valid input left. But then you have this block:

if (!n) break;

This will cause the loop to terminate when a 0 is entered in the input. This behaviour does no match the assignment, and hence it represents a bug. Based on the assignment, you should only terminate when input ends, which will be correctly caught by the while loop. The if (!n) line should therefore be removed.

Related, your after-loop test for fin.good() is incorrect. If the loop is (correctly) terminated by being unable to read more numbers because the file has ended, both eofbit and failbit will be set on fin. The condition find.good() will therefore fail. You might want to augment the condition to check for EOF:

if (find.good() || fin.eof())

Indentation in the post-loop conditional is inconsistent with the rest of the program, and should be fixed. The same holds for the if (i++ == 0){ block (unless that was just screw-up of the code formatter here on Stack Exchange).
The return value of main is interpreted by the operating system as the return code of the program. On all OSes I know, 0 indicates success, non-zero indicates failure. You should therefore return 0 on successful program termination. Or just omit the return altogether, return 0; is implied in the main function in C++.

Or, if you want to be really beyond reproach, and comaptible even with OSes where 0 does not necessarily mean success, you can change it to return EXIT_SUCCESS;; this requires #include <cstdlib>.
Error output (such as your "plz you even tryin'\n" message) should be sent to std::cerr (standard error stream, usually file descriptor 2), not to std::cout (standard output stream, usually file descriptor 1). A more helpful error message would be in order as well. Something like

  Error when reading file 'input.txt', possibly encountered a non-number.

When printing this message, you should consider returning 1 (or EXIT_FAILURE) from main, instead of allowing fallback to the default success.
The outer if (fin.is_open()) could be removed. If the file is not open, fin >> n will fail, and you would at least print an error message instead of failing silently.
system("PAUSE"); is a very non-portable and extremely cumbersome solution looking for a problem. You're calling an external program just to wait for a key press. You should get rid of it altogether: your program is not interactive at all, it could run just fine as part of a script. Requesting input like this ruins that. Just drop that line altogether.


Queries using multiple tables and ANDs: should that be avoided?

Is this a valid approach?

FROM tissue_source_site, ampl_cols, mrna_cols

What you are doing here is to get a product of those tables, meaning that if the RDBMS is not wise it may attempt to create an intermediate structure
with size = product of the sizes of each table.

Gladly I just got a query plan execution for SQL Server and they can infer the same plan for either your where clauses, and the join operator, meaning that they are just as efficient (but I would prefer use a join anyway).

  Is there a point at which I will hit a wall, concerning the length of
  the queries (endless ANDs) or performance-wise?

You shouldn't be too concerned about the length of your queries.
Querying, after all, is the way to get your data. So you should let your query express what you want to retrieve.

Performance wise you should get a query plan as I did for SQLServer so you can choose between a join and a where. Doing many joins can also hinder performance but most of times this isn't an issue because they are done over the primary key of the tables which most of the times are indexed (you can see indexing as a way to arrange data so it's easier to retrieve it by that index)

  I did not really see this used much the tutorials I did (in a hurry).
  What are the drawbacks of doing it like that? Is it wiser to figure
  out how JOIN works?

There are many types of joins and someday you will probably be wanting the functionality of one of them, having the wisdom of picking the right tool for the job is always nice.

  Or WITH table AS? Or something else I am totally unaware of?

Your query is still pretty simple and doesn't require any "black magic". try to keep things simple and give yourself time to understand and get used to the sql querying concept.


Here are some ideas, somewhat sorted by order of importance. I hope it helps.

1) There is a problem with your second function, see that

> selsr(1:5)
[1] 2 3 4 5 1

You should be doing

j <- i - 1L + which.min(x[i:n])

2) Your choice of 1:(n - 1) will not properly handle the n == 0. Also, it does handle the n == 1 case properly but it is a bit of luck considering you are looping over 1:0... The robust alternative to the : operator is to use seq_len or seq_along. Or you could just have a if (n < 2L) return(x) near the top of your functions.

3) While on the topic of corner cases, your code assumes that x is a numerical vector. You could be checking for that by adding:

stopifnot(is.vector(x), is.numeric(x))

4) You can achieve the swaping without a temporary variable by doing:

x[c(i, j)] <- x[c(j, i)]

5) min is a questionable variable name, given it is also the name of a base function.

6) This is debatable: I would get rid of the if (j != i) condition since it won't hurt doing the swap even if j == i. IMO, the simpler code is preferable to the marginal computation time gain.

7) A nit: know the difference between 1 (numeric) and 1L (integer). Here you are using 1 when you mean to use 1L, which causes unnecessary conversions from integer to numeric (though the : operator brings you back to integers by doing the opposite conversion).


You can assume that the implementation of strcmp() is not stupid.  A lot of code out there relies on strcmp(), so rest assured that a lot of work has gone into optimizing it.  Nevertheless, you don't want to call it twice per iteration through your loop.

Interestingly, len is the only parameter that doesn't need to be declared const, since it is passed by value.  In contrast, scope and find are passed by reference, so a promise that binSrch() won't alter them would be helpful.

At the end, you don't need to test for first > last before returning false.  The only way you can get past the while loop is with first > last.

You have an unused variable c.  Avoid such mistakes by getting into the habit of assigning right away:

int first = 0,
    last = len - 1,
    middle = (first + last) / 2;

I think the braces on your else if look weird.  Either remove them, or put them everywhere consistently.  (I prefer the latter.)


Shortest (shortest by you) would be indeed to use go generate. If you don't want to do that:

You have to enumerate your source names and source values to associate them, you can't avoid that.

But this enumeration and pairing can be shorter by using a map[string]Source:

var srcMap = map[string]Source{
    "Twitter":  Twitter,
    "Facebook": Facebook,
    "Gplus":    Gplus,
    "Spotify":  Spotify,
    "Linkedin": Linkedin,
    "Github":   Github,
    "Lastfm":   Lastfm,
}

func NewSource(s string) Source {
    if src, ok := srcMap[s]; ok {
        return src
    }
    panic(ErrUnknownSourceType)
}

Also note that panicing is a little "strong" reaction for an invalid source name. I would rather return an error along with the source, or return a special UnknownSrc source instead of panicing.

And while we're at it: you should exploit the zero value of Source for representing UnknownSrc and that way you don't even have to use the comma-ok idiom when checking in the map: indexing a map returns the zero value of the value type if the key is not found.

So:

const (
    UnknownSrc Source = iota // It will be 0, zero value for the underlying type (int)
    Twitter
    // ... and your other sources
)

And this way converting a source name to the Source type is one-line:

func NewSource(s string) Source {
    return srcMap[s]
}

It's just indexing a map, you don't even need a function for that.

If you would want to return an error, it could look like this:

func NewSource(s string) (Source, error) {
    if src, ok := srcMap[s]; ok {
        return src, nil
    }
    return UnknownSrc, errors.New("Invalid Source name!")
}


Using QSqlQuery::bindValue() for variable number of placeholders

I'm not the expert for QSqlQuery, so my answer might be slightly off the mark. I see nothing wrong in not using prepare() and bindValue(). It also seems to me a bit "odd" to use these in a DELETE statement. As I said, I'm not the expert on this, there may be other guys that can shed some light on this aspect.

I see two cosmetic issues:

the way you use checked_items_ids, first time with null argument, second time iterating. A QStringList can help in constructing the SQL statement.
setting the SQL statement in the constructor. Setting it in the exec() function might be more "natural".

These are cosmetic issues only. They do, however, improve readability of your code.

QStringList querylist;
for(auto id : checked_items_ids)
    querylist << QString("id = %1").arg(id);
QString querystring = QString("DELETE FROM members WHERE ") +
                  querylist.join(" OR ");

QSqlQuery query;
query.exec(querystring);


While your merge step in mergeSort works it should be put into its own function:

// Exercise: make `my_merge` even more generic
template <typename Iterator, typename OutputIterator>
void my_merge(Iterator first1, Iterator last1,
              Iterator first2, Iterator last2,
              OutputIterator out)
{
    while (first1 != last1 && first2 != last2) {
        if (*first1 < *first2) {
            *out++ = *first1++;
        } else {
            *out++ = *first2++;
        }
    }

    while(first1 != last1) {
        *out++ = *first1++;
    }
    while(first2 != last2) {
        *out++ = *first2++;
    }
}

template<typename T>
T mergeSort(typename T::iterator begin, typename T::iterator end) {
    auto n = end - begin;
    if (n < 2) {
        return T(begin, end);
    }
    auto firstHalf  = mergeSort<T>(begin, begin + n/2);
    auto secondHalf = mergeSort<T>(begin + n/2, end);

    T merged;

    my_merge(firstHalf.begin(), firstHalf.end(),
             secondHalf.begin(), secondHalf.end(),
             std::back_inserter(merged));
    return merged;
}

Note that I had to call my_merge that way since std already contains std::merge, which we can use instead:

template<typename T>
T mergeSort(typename T::iterator begin, typename T::iterator end) {
    auto n = end - begin;
    if (n < 2) {
        return T(begin, end);
    }
    auto firstHalf  = mergeSort<T>(begin, begin + n/2);
    auto secondHalf = mergeSort<T>(begin + n/2, end);

    T merged;

    std::merge(firstHalf.begin(), firstHalf.end(),
               secondHalf.begin(), secondHalf.end(),
               std::back_inserter(merged));
    return merged;
}

The merge and the parameters begin and end are good examples why using namespace std has to be handled with care. All those names are already in std. Use using namespace std only if you know the risks.

That being said, your generic variant will only work with random access iterators. If you want to make it more generic, you have to use std::distance and std::next instead of end - begin and begin + n/2:

template<typename T>
T mergeSort(typename T::iterator begin, typename T::iterator end) {
    const auto n = std::distance(begin, end);

    if (n < 2) {
        return T(begin, end);
    }
    const auto midpoint = std::next(begin, n / 2);

    const auto firstHalf  = mergeSort<T>(begin, midpoint);
    const auto secondHalf = mergeSort<T>(midpoint, end);

    T merged;

    std::merge(firstHalf.begin(), firstHalf.end(),
               secondHalf.begin(), secondHalf.end(),
               std::back_inserter(merged));
    return merged;
}

Even if you don't want to use std::next re-use the midpoint.


A minor detail: In output it can be hard to tell the difference between (cons #f #f) and (cons #f #f) i.e. between uniq1 and uniq2. An alternative is to write (list 'uniq1) in order to get a unique value.

For comparison here is a version of merge-tail written using named let rather than using indices. Here the common tail between xs and ys are found, and two new lists using the shared tail is returned.

(define (reverse-append rxs ys)
  (if (null? rxs)
      ys
      (reverse-append (cdr rxs) (cons (car rxs) ys))))

(define (merge-tail xs ys)
  (let loop ([tail '()]
             [rxs  (reverse xs)]
             [rys  (reverse ys)])
    (cond
      [(eqv? (car rxs) (car rys))
       (loop (cons (car rxs) tail)
             (cdr rxs)
             (cdr rys))]
      [else
       ;; tail is now equal to the common tail of xs and ys
       (values (reverse-append rxs tail)
               (reverse-append rys tail))])))

This solution will fail if xs and ys are cyclic lists with equal elements.
So in the terminology of srfi 1, the solution only works for proper lists.


Objective-C doesn't have namespaces.  As such, we need to be much more careful with our class names.  The common way for dealing with this problem in Objective-C is to come up with a 2 or 3 letter prefix to put in front of all of your classes.  Apple does this with their classes.

NS for NeXTSTEP
CF for CoreFoundation
UI for UserInterface
SK for SpriteKit
CM for CoreMotion (but I think it overlaps something else maybe)
CA for CoreAnimation
CG for CoreGraphics

And there are more.

If it weren't for this naming convention, Apple would have a hard time creating class like NSView for OS X development and UIView for iOS development.

Following in this path, other good Objective-C developers come up with their own acronyms to prefix their various classes, structs, and typealiases with.  And you should do the same.  Clip just will not work as a class name (plus, it's not particularly expressive of what the class actually represents... is this like a movie clip or audio clip or something?).

I believe most Objective-C programmers prefer Egyptian braces.  You're consistent-ish with your braces though, that's fine-ish and not a necessary change.  I say consistent-ish because you use Egyptian braces for your if, but not for your methods.  Due to the way Xcode folds code, I consider Egyptian style to be vastly superior if you're developing in Xcode.

Finally... we often talk about (especially in Code Reviews), magic numbers.  You don't have any of these, but I'm going to go ahead and call @"primitiveRange" a magic string.

We should define a constant, and perhaps use reverse domain lookup for your keys:

NSString * const kKEY_PrimitiveRange = @"com.yourDomain.clip.primitiveRange";

Your using this string in 6 places.  What happens if, for whatever reason, you decide to change the string?  Now you have to change it in 6 different places.  If we'd just use a string constant, if we ever change the string, we only have to change it in one place.


Inheriting needed when only difference is performed in the constructor?

Based upon your use case, the code below is what I would recommend.  I'm sorry that it is in C#, on this computer I don't have my vb.net loaded so it was easier to express in c#.

There are 3 parts to this.  The class on the bottom should address your needs (KeySet).  the second class helps to make it more easily usable in your code (KeySetHelpers).  The first class (MyExample) is just showing a few ways that you can utilize it.  I think the direct approach is most natural.

Regarding performance and inheritance.  If you follow the process below, I don't think you need another layer of inheritance.  Performance wise, I think that the collection you choose to utilize will matter more than the KeySet.  Since in the end you are just utilizing strings anyway.

One area I would recommend that you look into is the reason why you are flipping the primary/secondary keys based upon which is greater.  Since you are already injecting which is the primary and which is secondary, they should most likely always have the same order when combined.  Otherwise it could complicate the meaning of the key.  Plus if you keep the order primary-secondary and normalize the key by stripping out anything non-alphanumeric and then adding in a parsing token like "-" between the too,...you wouldn't need to store the Key(composite), primary key, and secondary key.  I hope this helps.

public class MyExample
{
    public void Test()
    {
        // Junk Prep
        var primary = System.Guid.NewGuid();
        var secondary = System.Guid.NewGuid();
        var junkData = "blah blah";

        // Real usage
        var keysList = new List<KeySet>();

        keysList.Add(new KeySet(primary, secondary)); // as guid
        // or
        keysList.Add(new KeySet(primary.ToString(), secondary.ToString())); // as guid strings
        // or
        keysList.Add(primary, secondary);// direct as guid

        var keysDictionary = new Dictionary<KeySet, object>();

        keysDictionary.Add(new KeySet(primary, secondary), junkData); // as guid
        // or
        keysDictionary.Add(new KeySet(primary.ToString(), secondary.ToString()), junkData); // as guid strings
        // or
        keysDictionary.Add(primary, secondary, junkData); // direct as guid

        // etc.
    }
}

public static class KeySetHelpers
{
    #region Lists

    public static void Add(this List<KeySet> keyList, string primary, string secondary)
    {
        keyList.Add(new KeySet(primary, secondary));
    }

    public static void Add(this List<KeySet> keyList, Guid primary, Guid secondary)
    {
        keyList.Add(new KeySet(primary, secondary));
    }

    #endregion

    #region Dictionary

    public static void Add(this Dictionary<KeySet, object> keyDictionary, string primary, string secondary, object value)
    {
        keyDictionary.Add(new KeySet(primary, secondary), value);
    }

    public static void Add(this Dictionary<KeySet, object> keyDictionary, Guid primary, Guid secondary, object value)
    {
        keyDictionary.Add(new KeySet(primary, secondary), value);
    }

    #endregion
}

public class KeySet : IComparable<KeySet>
{
    public KeySet(Guid primary, Guid secondary) { EstablishKey(primary.ToString(), secondary.ToString()); }
    public KeySet(string primary, string secondary) { EstablishKey(primary, secondary); }

    #region Composite Key

    private void EstablishKey(string primary, string secondary)
    {
        if (string.Compare(primary, secondary) > 0)
        {
            Key = primary + secondary;
        }
        else
        {
            Key = secondary + primary;
        }

        Primary = primary;
        Secondary = secondary;
    }

    public string Primary { get; private set; }
    public string Secondary { get; private set; }

    public string Key { get; private set; }

    #endregion

    #region Functional Overrides

    public override bool Equals(object obj)
    {
        return (obj is KeySet) ? Equals((KeySet)obj) : false;
    }

    public bool Equals(KeySet obj)
    {
        return CompareTo(obj) == 0;
    }

    public override int GetHashCode()
    {
        return Key.GetHashCode();
    }

    public override string ToString()
    {
        return Key;
    }

    #endregion

    public int CompareTo(KeySet other)
    {
        return string.Compare(Key, other.Key);
    }

    public static bool operator ==(KeySet obj1, KeySet obj2)
    {
        return obj1.Equals(obj2);
    }

    public static bool operator !=(KeySet obj1, KeySet obj2)
    {
        return !obj1.Equals(obj2);
    }
}


Having a Try[Unit] is completely ok - it models the fact that there may be exceptions on a side effecting operation in a type. That your code looks ugly is not because your monad is wrong but because you used it wrong. You already started in modeling your application with monads, why just stopping in the middle?

You can easily restructure your monad a little bit:

def run(): Try[Unit] = {
  val res = for {
    fields <- getFields()
    values <- getValues()
  } yield {
    if (values.isEmpty)
      Success(())
    else for (file <- createTmpFile(fields, values))
      yield runProcessWithFile(file)
  }
  res.flatten
}

What we see here is a monad.map(f).flatten which is the same as monad.flatMap(f) which is the same as for (m <- monad) yield f(m). Applying this fact to your code snippet results in:

def processTmpFile(as: List[A], bs: List[B]): Try[Unit] =
  if (values.isEmpty)
    Success(())
  else for (file <- createTmpFile(fields, values))
    yield runProcessWithFile(file)

def run(): Try[Unit] = {
  for {
    fields <- getFields()
    values <- getValues()
  } yield processTmpFile(fields, values)
}

Operating on a deeper level of the monad (what you did with your condition) means that you can either nest the monad and unpack it later at the end or that you can unpack it immediately after the nesting happened (that is what a for comprehension does).


Headers
You're missing #include <ctime>.
Naming
Identifiers beginning with underscore are reserved for the implementation, so _tzset() is a risky choice, and may result in undefined behaviour.
Interface
What does the return value mean?  Although declared to return bool, it never returns a false value, so it's unclear how the result is intended to be used.  void may be a better choice, but I think it's more reasonable to return an arithmetic result (and thus eliminate the use of the global timezone).
It is likely that we might want to find this information for an arbitrary time value, rather than only for "now", so I suggest adding a defaulted parameter to pass in the time to be considered.
Assumptions about std::time_t
This code assumes that time_t is a signed type; if it's unsigned, then the subtraction gmt - local may overflow.  It also assumes that time_t counts in units of seconds; that is not required by the C++ standard (though it is a common implementation choice, and is perhaps required for POSIX compliance).  Instead of using arithmetic subtraction, it is portable to use std::difftime() - it is safe if time_t is unsigned, and it is defined to return its results in seconds.
Assumptions about std::mktime()
This code assumes that std::mktime() ignores the tm_isdst field of std::tm.  In my experience, implementations do not ignore it, meaning that local and gmt values are always equal in time zones such as Europe/London.
Failure around DST transitions
Even if corrected to account for tm_isdst, I'm finding it hard to reason whether the code is correct shortly before (or shortly after) a daylight-savings transition (in either direction).  I'd expect to see four unit-tests (in a specific timezone) that verify the behaviour, but there are no tests provided at all.
Alternative approach
Instead of (ab)using std::mktime() in this way, it's far safer and more transparent to use std::time_put() with a format string of %z to obtain the offset from UTC in ISO-8601 format (±HHMM) and convert that string into seconds (taking care to apply the sign to both the hours and the minutes):
#include <ctime>
#include <iomanip>
#include <sstream>

static constexpr time_t const NULL_TIME = -1;

// returns difference in seconds from UTC at given time
// or at current time if not specified
long tz_offset(time_t when = NULL_TIME)
{
    if (when == NULL_TIME)
        when = std::time(nullptr);
    auto const tm = *std::localtime(&when);
    std::ostringstream os;
    os << std::put_time(&tm, "%z");
    std::string s = os.str();
    // s is in ISO 8601 format: "±HHMM"
    int h = std::stoi(s.substr(0,3), nullptr, 10);
    int m = std::stoi(s[0]+s.substr(3), nullptr, 10);

    return h * 3600 + m * 60;
}

#include <iostream>
int main()
{
    std::cout << tz_offset() << std::endl;
}


Count the number of occurences of X's within a range in Java

Here are my comments:

Find occurences of digit in String

Instead of iterating on every character, you can harness the power of regular expression.  What we can do is replaceAll characters that are not the one we are interested in with an empty String effectively removing these characters and we are left with a String that contains all occurrences of the character.
For example, say we want to count occurrences of the digit 1 in str:

str.replaceAll("[^1]", "").length()

If you are concerned about performance, you should know that str.replaceAll() is a costly operation because the regex "[^1]" is parsed each time the method is called.  This can be solved: you can parse the regex one time into an instance of java.util.regex.Pattern:

Pattern notDigitPattern = Pattern.compile("[^"+x+"]");  // x is the digit we want to count

This is done one time only.  when you want to find occurences of x in str you do that by constructing an instance of java.util.regex.Matcher and using that to do the replaceAll() operation:

Matcher notDigitMatcher = notDigitPattern.matcher(str);
notDigitMatcher.replaceAll("").length()

Iteration on numbers

The 'main' loop iterates on the range of numbers between low and up.  However, One can calculate in advance the number of occurences of any digit within range of 10 or 100 or 1000 and so on.
let us examine the range of 10. a digit will occur only once in that range except if it is the first digit as well.
The digit 3 apears once for 0x (0-9), 1x (10-19), 2x (20-29), and so on. it apears 11 times in 3x (30-39) 10 times as 1st digit and 1 time as 2nd.
sum of the above for all ranges of 10s (0-99) is 9*1+11=20. this is true for all 10 digits.
If we look at range of 100s than the digit will occur 20 times for all 100 ranges except if it is also the first digit, in this case add 100 occurrences.
sum of the above for all ranges of 100s (0-999) is 9*20+120=300.
you can continue this calculation for 1000s and so on.

When you receive an input of 111 to 3333 you know how many times the digit occurred between 1000 and 1999 and also 2000-2999. so you just need to iterate for the first and last 1000 (between 112 and 999 and 3000 to 3332) and you can also figure out complete 100 ranges. then figure out complete 10 ranges... at the end you will need to iterate on the first and last range of 10s.

I understand this seems unclear (and maybe too complicated) but it does save time complexity for large ranges.

Coding best practices

Closing IO resources
although the stream you open on stdin will be closed when the program finishes, you should get the habbit of explicitly closing all resources, so yuo don't get resource leakage when you develop not-so-trivial programs.  Use Java 7 try-with-resources feature for that.
Declare variables in the scope where they are used
let's look at the variable inps in main().  It is used inside the loop as a kind if temporary variable for parsing the input.  It is better to declare it inside the loop (each pair of curly braces define a new scope).  There are two reasons for that: 1) declaring the variable inside the loop helps readability of your code - other developers will understand that inps is not used anywhere else. and 2) you don't run the risk of someone trying to use inps out of scope.


Random String Generator using OpenSSL in PHP

The documentation says that crypto_strong is set depending on the algorithm used. So it will never go from false to true, so yes, this might result in an infinite loop.

Use it instead to see if you should trust the result. If it is true, the string should be secure.

(you should also never design your own crypto algorithms for anything other than academic interest)

because this is codereview, I also have a couple of notes regarding your code:

Why do you divide the length by 2? Seems unnecessary. If it does have a purpose, comment on it.
false TRUE: use case uniformly. either false and true or FALSE TRUE
$hex = bin2hex($bytes);
return $hex;
just make this one line: return bin2hex($bytes)
it is convention to use camelCase for variables, so Length should be length and the function name generateRandomString


Summation calculator of integers, squares, and cubes

Refactor IO

In each case of your switch statement, you have this at the very beginning:

std::cout << restraint << std::endl;
std::cout << request_range_1;
std::cin >> range_1;

std::cout << request_range_2;
std::cin >> range_2;

Rather than re-writing this out for each case, you should refactor this to its own function that returns the two inputs. That way, you can just call that function to get the inputs.

Also, speaking of inputs...

Never trust the user!

When you are grabbing the two input numbers for an operation, you show the user a restraint message that says that the first number must be smaller than the second. While your function technically do "handle" this by returning 0, it would be good practice to not call those functions at all and to instead print out to the user if they accidentally (or purposely) entered a bigger number first.

You could include this in the extracted input-getting function described above. You can even create a loop inside this that repeatedly asks the user for proper input before actually returning the input.

early exit -- early exit -- early exit -- early exit....

    if(choice == 'd')
        break;
}
std::cout << "Calculator OFF" << std::endl;

This is a bit of code I grabbed from the end of the switch statement. Note that the only time that this bit of code is going to be reached is if the user hit d as their input.

Therefore, you can do some simplifying here. Rather than exiting from the switch statement only to do another conditional on whether or not to break the loop, just return from the entire program as soon as it is discovered that the user entered 'd':

case 'd':
    std::cout << "Calculator OFF" << std::endl;
    return 0;

This is much simpler and removes the redundancy from your code.

More refactoring and simplification

Your three _sum functions are all very similar except for a single line. These lines:

int_sum += a;

and

squ_sum += a*a;

and

cub_sum += a*a*a;

The rest of the code in the function is identical (of course, except for the variable names). This means that we can do some refactoring.

To simplify the code, let's write a blank function that follows the same format as the others:

int sum_exponent_series(int a, int b, int exp);

Notice the last parameter: this will allow the function to know whether to put a, a*a, or a*a*a... Which, in fact, can be simplified using <cmath>'s pow.

Now, the body of the function looks like this:

int sum(0);
for(; a <= b; a++) {
    sum += pow(a, exp);
}
return sum;

Note, I made two other changes:

I fixed your indentation (watch that in the future)
I turned your while loop into a for loop. An incrementation at the end of a while loop like you is a pretty good indication you need a for loop.

Now, instead of having three functions, you can just have this one function and call it with different exp values.

BUT WAIT!! You can make your program even more flexible now! Rather than having the user enter the "type" of exponent series thing they want, have them input these three things:

A number
The amount of times to add that number
The exponent to raise the number to when adding

That way, you won't even need a switch statement at all! The user could enter numbers like 3, or 8, or anything else without having to be restricted by what options you already set in place!


First regarding style. Python has an official style-guide, PEP8, which recommends having no unnecessary whitespace. It improves readability a lot if you avoid having a blank line between every line. Use them sparingly to set apart larger logical blocks.

The standard way, which is the most efficient, to test for divisibility is the modulus operator, %. This way you don't have to rely on integer division to always be around (which it will not be, it has been removed by full division in python 3.x). You can also directly return the result of the comparison:

def is_divisible_by_7(num):
    return num % 7 == 0

You should put your code in a f __name__ == "__main__" guard and into functions to allow re-usability of your code:

def main():
    N = raw_input()
    Q = int(raw_input())

    for _ in xrange(Q):
        a, b = map(int, raw_input().split())
        num = int(N[a - 1:b])
        print "YES" if num % 7 == 0 else "NO"

if __name__ == "__main__":
    main()

Here I inlined the function is_divisible_by_7, used _ as a place-holder variable which is not used in the loop as customary in Python and used a ternary expression to print the result. You also don't need to use split, in python 2.x map returns a list which can directly be used in tuple-assignment.

Alternatively, if a and b appear repeatedly, caching might help:

def memodict(f):
    """ Memoization decorator for a function taking a single argument"""
    class memodict(dict):
        def __missing__(self, key):
            ret = self[key] = f(key)
            return ret
    return memodict().__getitem__

@memodict
def is_divisible_by_7(indices):
    a, b = map(int, indices.split())
    return "NO" if int(N[a - 1:b]) % 7 else "YES"

N = raw_input()
Q = int(raw_input())
for _ in xrange(Q):
     print is_divisible_by_7(raw_input())

As a third alternative, we could not cache the indices, but the numbers for which we do the divisibility test. This is worthwhile if they repeat and are big.

@memodict
def is_divisible_by_7(n):
    return int(n) % 7 == 0

N = raw_input()
Q = int(raw_input())
for _ in xrange(Q):
     a, b = map(int, raw_input().split())
     print "YES" if is_divisible_by_7(N[a - 1:b]) else "NO"

with the same memodict class as above.

This could be made slightly faster by not printing every line, but aggregating the results first:

N = raw_input()
Q = int(raw_input())
out = []
for _ in xrange(Q):
     a, b = map(int, raw_input().split())
     out.append("YES" if is_divisible_by_7(N[a - 1:b]) else "NO")
print "\n".join(out)

A fourth possibility is to try to exploit a divisibility rule for 7. There are not very nice ones, but I did find this one:

  Double the last digit and subtract it from a number made by the other
  digits. The result must be divisible by 7. (We can apply this rule to
  that answer again) (source)

So we want to recursively test the number. But since it can have up to 10**5 digits, we have to hope that it tires small numbers first, otherwise we run into python's recursion limit. However, we can increase that limit to the number of digits, N.

import sys

MAX_INT = 2**31 - 1

@memodict
def is_divisible_by_7(n_str):
    if n <= MAX_INT:  # mod should be fast enough below this limit
        return int(n_str) % 7 == 0
    return is_divisible_by_7(str(int(n_str[:-1]) - 2*int(n_str[-1])))

N = raw_input()
sys.setrecursionlimit(MAX_INT)  # to allow processing the number
Q = int(raw_input())
for _ in xrange(Q):
     a, b = map(int, raw_input().split())
     print "YES" if is_divisible_by_7(N[a - 1:b]) else "NO"

This does a lot more processing, especially conversions between str and int. But maybe combined with the caching it might do some good.


Parallax animation, running well on Chrome but slow on Safari

The major issue that I see in your code is that you keep requestAnimationFrame no matter what. This obviously causes the browser to update the css of the element at any time.

Since your animation is based on scroll I would suggest to define an handler to window.onscroll.

While doing this you perhaps may wish to transform your animation method to be a plugin method that you would call for every parallax element.

Resulting code becomes something like this:

$.fn.parallaxAnimate = function() {
    var elements = this.find('[data-parallax-ratio]');

    var scrollPos = $(window).scrollTop(),
      offsetY = this.offset().top - 60;

    for (var i = 0; i < elements.length; i++) {
        var el = $(elements[i]),
            ratio = el.data('parallax-ratio'),
            current = el.data('parallax-current') || 0;

        var newPos = (offsetY - scrollPos) * ratio;
        var pos = current - ((current - newPos) * 0.08);

        el.css('transform', 'translateY(' + pos + 'px)');
        el.data('parallax-current', pos);
    }
}

    window.onscroll = function(){
        $('.parallax').parallaxAnimate();
    };

See a (ugly) fiddle

Edit: I was wrong on my previous attempt to solve smoothness and I was also wrong about subscribing onscroll

I tried to solve the problem that the OP is having as the animation is not smooth. On my previous attempt I tried to implement a scroll animation on a scroll event, and I got a warning on firefox (this is a free translation since I got my browser on portuguese unfortunately):

  This site appears to use a scroll-linked position effect. This may not
  work properly with asynchronous panning. See
  https://developers.mozilla.org/docs/Mozilla/Performance/ScrollLinkedEffects
  for more details...

And there you can read an explanation of what are the causes of this warning.

Meanwhile, on this same documentation page on Other effects, you can have a link to a useful site that implements many scroll effects, one of those being the parallax. All of this only with css...

I will post here one smaller example based on the implementation of the site, give props to that man please, not to me ;).

Base Layer

Base Layer

Background Layer


Code

First of all, please avoid having a static int temp: in case two or more threads call your insertion sort, they will interfere. Also, I would declare the constructor as private:

private InsertionSortNew() {}

Style

You abuse your code with empty lines. Usually people put empty lines before and after conditional blocks (if) and loops (for, while).

Performance

You can prune away like 60% of assignments in the inner loop as follows: first, you store the element being inserted; next, until sorted you keep moving the preceding larger integers one position to the right, and finally, you put the cached element into its correct position.

All in all, I had this in mind:

private InsertionSortNew() {}

public static final void sort(int [] array){
    for (int i = 1; i < array.length; ++i) {
        int key = array[i];
        int j;

        for (j = i - 1; j >= 0 && array[j] > key; --j) {
            array[j + 1] = array[j];
        }

        array[j + 1] = key;
    }
}

..., which gives me these performance figures:

Original version took 2281.41 milliseconds.
rodde's version took 1581.65 milliseconds.
Equals: true


Finding the duplicate with an array with 1,000,000 integers between 1 and 1,000,000

There is already a good answer that describes how you could improve your tests, however, I would like to offer another solution.  I had a question that was similar to this on an interview (well, I solved it using a similar method to the one I gave here).

When the interviewer asked this question, I think they wanted you to find a solution that is not only \$\mathcal{O}(n)\$ time but also \$\mathcal{O}(1)\$ space complexity.  Based on the description you gave, there is one number that appears twice but there also must be one number that does not appear.

The sum of the first \$n\$ integers is \$\frac{n(n + 1)}{2}\$, and the sum of their squares is \$\frac{n(n + 1) (2n + 1)}{6} \$.

Let

\$sn\$ = 500000500000 be the sum of all of the numbers from 1 to 1000000
\$sn2\$ = 333333833333500000 be the sum of their squares
\$sn'\$ be the sum of the elements of the array
\$sn2'\$ be the sum of their squares

Then there are numbers \$d\$ (double) and \$m\$ (missing) such that

$$sn' + m - d = sn$$
$$sn2' + m^2 - d^2 = sn2$$

Solving the first equation for \$m\$ and substituting into the second, we get

$$sn2' + (sn + d - sn')^2  - d^2 = sn2$$

Expand and collect like terms

$$sn2' + (sn - sn')^2 + 2 (sn - sn')d = sn2$$

Thus

$$d = \dfrac{(sn2 - sn2') - (sn - sn')^2}{2 (sn - sn')}$$

Here is a version of findDuplicate that uses this rule (note that I have never used C# so there may be a couple of mistakes, and I did not put in comments since you've already read the explanation of how I got the formula):

/// <summary>
/// Find the duplicate number in a length n array where all elements are numbers
/// from 1 to n, all appearing once except for one duplicate (and consequently one
/// missing).
///
/// </summary>
/// <param name="givenArray">n sized array containing ints between 1 - n inclusive</param>
/// <returns>The duplicate number</returns>
public static int findDuplicate(int[] givenArray)
{
    ulong n = givenArray.Length, dsn, dsn2;
    dsn = n*(n + 1)/2;
    dsn2 = dsn*(2*n + 1)/3;
    for(ulong i = 0; i < n; ++i){
        dsn -= givenArray[i];
        dsn2 -= givenArray[i]*givenArray[i];
    }
    return (dsn2 - dsn*dsn)/(2*dsn);
}

Note that this method of finding extra or missing numbers in a list that is otherwise a range can be extended simply by adding equations for higher powers (cubes and beyond).


Checking if any permutation of a string can make it palindrome

You may simply use Counter method of collections module to get the frequency of each character in the given word and then simply create a list of the frequency of a given character modulo 2, and then get the sum of the generated list, So the list will have only 2 values, either 0 or 1, So we calculate the sum of the list, and evaluate the condition of <=1 is True

from collections import Counter

s = "summs"

print sum([i%2 for i in Counter(s).values()]) <= 1