Factory / Builder Design Pattern in Python

IScreens is a callable
Actually, your IScreens class (interface) contains only one abstract method (the main method), so this class is a kind of callable.
Instead of creating a specific class, you can use collections.Callable:
import collections

IScreens = collections.Callable

To use that class, you can do:
class Screen1(IScreens):
    def __init__(self, data, config):
          ...

    def __call__(self, *args, **kwargs):  # instead of `main`
        return ...

s1 = Screen1(data=..., config=...)
result = s1()  # call the callable s1

IScreens can contain common data
I see that the data and config variables are common to Screen1 and Screen2.
It's a good practice to factorize this in the base class:
class IScreens(collections.Callable):
    def __init__(self, data, config):
        self.data = data
        self.batch = config["cfg1"]

NOTE: Here, I don't understand why you pass a config dictionary, but only get the batch (config["cfg1"]).

Avoid extra complexity
Private methods with double underscores, like __get_letter, are more difficult to debug,
because their names are disguised into _{className}__{attr_name}.
For instance:
class C:
    def __init__(self):
        self.__secret = "foo"

obj = C()
print(obj._C__secret)
# 'foo'

Very short functions like __get_letter should be avoided, unless reused several times.
Here, you add complexity (and extra computation time) with them.
Getters should not mutate the instance
A getter should not change the class instance state.
Here, in your __get_letter method, you are extracting a value (self.data[self.batch].str[:1])
and modifying the internal state (self.data["campaign"]). Is it intentional?
It is better to initialize everything in your constructor:
class Screen1(IScreens):
    def __init__(self, data, config):
        self.data = data
        self.batch = config["cfg1"]
        self.data["campaign"] = self.data[self.batch].str[:1]
        self.data["num"] = self.data[self.batch].str[1:]
        self.data["other_stuff"] = self.data["num"].astype(int) * 100 / 2

Factory registration
There are two different ways to implement factories:

The factory (or the main function) knows all its classes and is responsible for the class registration,
Each class knows the factory and it can auto-register itself, like a plugin.

It seems that you choose the first case. You may also need to add a method to unregister.
In the second case, registration is usually final: its more difficult to unregister…
Both are good, so.
To register a class in a factory, we used to use the class name (or a class instance) instead of an arbitrary name.
Example using the class name:
class ScreenFactory:
    def __init__(self):
        self._screens = {}

    def register_screen(self, screen_class):
        self._screens[screen_class.__name__] = screen_class

    def get_screen_class(self, class_name: str):
        return self._screens[class_name]

Example using the class attribute:
class IScreens:
    kind = "unknown"

class Screen1(IScreens):
    kind = "s1"

class ScreenFactory:
    def __init__(self):
        self._screens = {}

    def register_screen(self, screen_class):
        self._screens[screen_class.kind] = screen_class

    def get_screen_class(self, kind: str) -> IScreens:
        return self._screens[kind]

The second method is interesting if you want to select an implementation (a IScreens class)
according to a tag/label extracted from textual data…

NOTE: you may have noticed that I added a get_screen_class method.

Factory access

This is the difficult part

In your get_screen method, you are checking if a specific configuration is valid (existence of "screen_indicator")
and if there is a suitable class which satisfy a second condition (config["screen_indicator"] is a kind of IScreens).
I am OK with that, but it can be simplified. Here is a solution with error handling:
class ScreenNotImplementedError(Exception):
    fmt = "Screen not implemented for this configuration: {config}"

    def __init__(self, *, config):
        msg = self.fmt.format(config=config)
        super(ScreenNotImplementedError, self).__init__(msg)

class ScreenFactory:
    ...

    def get_screen(self, data, config):
        try:
            kind = config["screen_indicator"]  # may raise KeyError
            cls = self.get_screen_class(kind)  # may raise KeyError
        except KeyError:
            raise ScreenNotImplementedError(config=config)
        else:
            screen = cls(data=data, config=config)
            return screen


Breaking file paths into file names and file extensions is unneeded when properties exist to access these elements directly, in this case the name extension property.

set newExt to the text returned of (display dialog "Enter extension:" default answer "Do not include first point")

tell application "Finder"
    set selFiles to selection
    repeat with eachFile in selFiles
        set name extension of eachFile to newExt
    end repeat
end tell


Variable parser for the Hack programming language

A few observations...

General

It would be great if you could include a syntax snippets of how a line in your programming language would look so we can test our solutions against the expected output. I had to go to your Google Code project and search for an actual syntax example in your source files
Your parsing functionality is still very rudimentary. (I didn't change that.) It can't yet handle function arguments and it doesn't work if there are no spaces in between words. Also, if there are spaces in front of the variable declaration, the function will not get translated at all  (this I fixed)
It's usually advisable to stick with library functions and not to reinvent the wheel, especially since you have stated that readability trumps efficiency in your scenario. .NET's string functions are mostly fine
There's no need to explicitly specify the default constructor as it (along with it's call to the argument-less constructor of Parser) will be automatically generated by the compiler. Leaving it out means one less thing for your readers and contributors to worry about

Naming issues

According to the comment just above the class definition, VarParser handles all the variable declarations. Although this makes sense, I'd suggest you ponder on finding a more descriptive name, such as VariableDeclarationParser or at least VariableParser
The function name CheckVariable is lacking at best, or misinformation at worst. It tells us it is "checking a variable" but in reality it isn't - it's checking if the current line contains a variable and, if it does, it will process the line - otherwise it will do nothing. An adequate name for that would be ParseLineIfItContainsAVariableDeclaration. Of course we don't use that, but rather we realize that the function needs to be split up to separate the check from the processing, so we choose two names for our new functions:

ContainsVariableDeclaration(string line) will return a bool indicating if we should process the line
ParseLine(string line) will return a string containing the parsed line

FuncTable is a very vague name for your Singleton containing the (also vague) NormSet - consider something like HackToCSharpMapper (or just LanguageMapper) and FunctionMappings or something along those lines instead of NormSet
CheckFunctions doesn't check anything, rather it seems to parse functions. Therefore, name it ParseFunctionsIn(string line)
I'm not saying you should choose the exact names I recommended, just try to think of the name that captures what the function does best and don't imply a function is doing something it doesn't do
Naming is important because it forces us to define what a given function, variable or class should do. When we end up with long names (see example above), we know that our code isn't well-structured and needs to be changed so that we follow the principles of OOP.

  A function should do one thing. It should do it well. It should do it only.
              — Robert C. Martin in Clean Code: A Handbook of Agile Software Craftsmanship

  Comments

Almost all of your comments can be made obsolete by choosing proper names and generally making the code as expressive as possible. IMHO, we should avoid comments that tell us what a particular statement does, rather we should use them only to clarify why we have made an unusal decision.
Or, to put it like Uncle Bob, I view every comment I write as a failure to express myself in code.
So I deleted most of your comments from the refactored version below because the names now stand for themselves, without the need for further clarification.

Dangerous and unusual things

Are you sure there won't be any whitespace before the var keyword? I've added a call to String.TrimStart() to make sure we don't stumble over this edge case
In your class, I see absolutely no reason to pass the line parameter by reference. This should be avoided because it makes your code more unpredictable - one can no longer be sure whether the function has a side effect on the input parameter

CheckFunctions returns a string, but the return value is never used because you rely on the ref parameter - be consistent!

Why are CheckVariable and CheckFunctions public? Too me, it looks like they should only ever be accessed from within that class
What if someone passes in a line that doesn't contain a variable declaration? At the moment, there will be no warning at all, the result will just be the same as the input - I suggest changing your program to throw an ArgumentException if it is not passed a valid declaration

Loops

Your nested foreach loop is unnecessary and bad for performance because it loops over all possibilities. As further investigation of the rest of your source code on Google Code shows, FuncTable.Instance.NormSet is a Dictionary<string,string> and therefore suitable for fast access by key.
Note that in your original code, you kept going through further possible function matches even after you have already replaced the current word with it's C# function!

After quite a bit of refactoring, we arrive at the below solution. If anything needs to be clarified, go ahead and ask.

Refactored example

All methods could have been made static, however I suspect you will change the base class - to which VariableDeclarationParser has no dependency at the moment - to a more useful one that provides a virtual Parse() method that can be overridden.

public class VariableDeclarationParser : Parser
{
    public string Parse(string line)
    {
        if (ContainsVariableDeclaration(line))
        {
            return ParseLine(line);
        }
        throw new ArgumentException("Invalid declaration: " + line);
    }

    private bool ContainsVariableDeclaration(string line)
    {
        return line.TrimStart().StartsWith("var");
    }

    private string ParseLine(string line)
    {
        string parsedLine = string.Empty;
        foreach (string word in line.Split(' '))
        {
            parsedLine += GetFunctionOrVariable(word);
        }
        return parsedLine.TrimEnd() + ";";
    }

    private string GetFunctionOrVariable(string candidate)
    {
        string key = candidate.Trim();
        var mappings = HackToCSharpMapper.Instance.FunctionMappings;
        if (mappings.ContainsKey(key)) return mappings[key] + "() ";
        return candidate + " ";
    }
}

If you're into LINQ, consider this alternative ParseLine function. It's more concise, but it sacrifices some readability - I think the above foreach is the better solution.

private string ParseLine(string line)
{
    string parsedLine = line.Split(' ').Aggregate(
        string.Empty, (parsed, word) => parsed + GetFunctionOrVariable(word));
    return parsedLine.TrimEnd() + ";";
}


Max Sum of Nodes in Each Path in Binary Tree

It seems like you are doing a little too much work.

The maximum sum of a node that is None will be 0.

The maximum sum of a node that is not None will be the value of the node, plus the max of the sums of the two children.

That recursion alone should be enough to avoid using intermediate data structures. Something like:

def find_max_sum_of_binary_tree_path(root):
    if root is None:
        return 0

    left_sum = find_max_sum_of_binary_tree_path(root.left)
    right_sum = find_max_sum_of_binary_tree_path(root.right)

    return root.value + max((left_sum, right_sum))


Improving the flexibility of my library/what can be improved?

A few observations/thoughts from a quick look at the code and accompanying description. Feel free to explain/correct as appropriate:

For starters, the Game class seems to delegate everything to the GameLoop class, why? It seems more logical that GameLoop would drive the Game which would make use of GameEngine do to input/output and GameStateStack (or stacks) to keep track of game-related states. As it stands, I need to think in terms of frame changes/deltas in more than one section of the code.
When would I want to use the GameLoop as-is as opposed to using isRunning()/update() or deriving from GameLoop? Why not place the call to initialize() in the constructor?
Why does GameStateStackListener need to know about the GameStateStack? Does it consume events or produce events? Or both? How do you avoid infinite recursion if both?
Why only one type of GameStateStack per listener? We might want to keep track and be informed of several state types (for instance, a character would want to be notified of changes in gravity and wind).

I think you should make and publish a simple game using this library to illustrate the purpose of each class


Defining a finite set of instances of a class to check against

First of all, as "being special" is obviously an attribute of your Type class, the check should go into the Type class, as you did, therefore always choose:
public class Type {
    ...
    public boolean isSpecial() {...}
}

over
aType.equals(new Type("specialType1")) || aType.equals(new Type("specialType2")) ||...

Regarding the implementation: I'm not too fond of creating a static collection to compare to. First of all, you search every time, then you use a relatively heavyweight equals method, which seems somewhat exaggerated to me, if the only distinction is a string passed in the constructor.
Personally, I'd use the underlying strings as a constant and determint the special flag in the constructor:
public class Type {
    private static final List<String> SPECIAL_CODES = Arrays.asList("this", "that", "whatever");
    private final String code;
    private final boolean special;

    public Type(String code) {
        this.code = code;
        this.special = SPECIAL_CODES.contains(code);
    }

    public boolean isSpecial() {
        return special;
    }
}

(Note that this change will not make a difference in runtime in real life, unless you check isSpecial() in a tight loop. It is more of a gut-feeling of being somewhat clearer.)


There are many code smells:

You create a single Student class, and differentiate students by an explicit type. This is a bit sad in an object-oriented language, where one should rather attempt to use interfaces and classes to represent types, leveraging the power of abstraction and polymorphism. Typically, your design would not scale well if you were to add new student types, or specific student behaviors (SRP / OCP from SOLID are at risk).
You create a property which should not be set not read (documents). This code is therefore a bit dubious (not useful, prone to misinterpretation).

Back to your domain: a student necessarily originates from somewhere (domestic), and may study abroad (international). In other words, I think you should simply have InternationalStudent inherit DomesticStudent, extending the class with the documents.

As for immutability, you don't have many options. The members must be final, and thus must be initialized during construction, with arguments passed to the constructor (either separately, or grouped inside a value object). Collections returned through getters must be wrapped by unmodifiable. You are already aware of this.

As for the creation method, you don't provide enough of your requirements to elicit a particular solution. Constructor calls or factories both seem fine to me.

Static methods may or may not be good, depending on the context. They do incite to consider a class as a namespace rather than a class (an object-orientation failure), and complicate testing (difficulty to mock dependencies).


In Java, the convention wants that methods are written in camelCase. Which means PrintArray should be printArray and so on.

The indentation is a little off with the declaration of the int[]. Instead of this :

int []fArrayDuplicate

It should be like this

int[] fArrayDuplicate

It might look like nitpicking (and it might be!) but it improves readability by a ton.

Talking about nitpicking, I think your for loop could use some spacing :

for(int x=0;x<len;x++)

could be

for (int x = 0; x < len; x++)

When you comment your code, you should explain why you wrote what you did write, not what you wrote. I mean,

int len = finalArray.length; //First, I took the length of the array.

is pretty obvious, so the comment isn't neccessary. I think it is the same for all your comments, except the third. But what I need to understand, as a developper who reads your code, isn't that you used a formula to get the total, but to understand how your formula works so you can get the total.

Both your methods use the same int[], which makes me think it should be a parameter of both your methods, this way you can be sure they will never be different.

public static void main(String[] args){

    int[] fArrayDuplicate = {1,2,3,4,5,7,8,9,10};
    PrintArray(fArrayDuplicate);
    FindMissing(fArrayDuplicate);
}

I also think you should pull out the main method of this class and put it in a class that is used only to start the application with the good parameters. Doing so, you could use your MissingInteger class to only find missing integer. This way, if you ever want to reuse it, you will be able to without bringing the main method with it.

Also, you could make your MissingInteger class respect the OOP more. You could input the int[] in the constructor like so :

public class MissingInteger {

    private int[] fArrayDuplicate;

    public MissingInteger(int[] fArrayDuplicate){

        this.fArrayDuplicate = fArrayDuplicate;
    }

    public void PrintArray(){

        System.out.println("\nGiven the incomplete array:");
        System.out.print("[");
        for(int a = 0 ; a<fArrayDuplicate.length ; a++)
            System.out.print(" " + fArrayDuplicate[a] + " ");
        System.out.print("]");
    }

    public void FindMissing(){

        int len = fArrayDuplicate.length; //First, I took the length of the array.
        int sum = 0;
        for(int x=0;x<len;x++)
            sum+=fArrayDuplicate[x]; //Second, I took the sum of the given array.
        int totalNumber = ((len + 1) * (len + 2)) / 2; //Third, I used this formula to get the total number.
        int missingInt = totalNumber - sum; // Fourth, I subtract the sum to total number to get missing integer.
        System.out.println("\nTherefore, the missing integer is " + missingInt + ".");
    }
}

I think you might want to rename your class to MissingIntegerFinder since well, the class itself isn't about a missing integer, but about finding a missing integer. And the name fArrayDuplicate doesn't mean much to me. There's nothing talking about duplicates in your code, why is it prefixed with a f? I have a hard time to find a better name, someone might find one. But for now I'd name it integersWithOneMissing or... something like that.


For all it's worth, and this is pretty old but for the sake of clearing unanswered reviews, here is my take:

id INT AUTO_INCREMENT PRIMARY KEY,

I find that being more specific in column names makes the code easier to work with, especially when you are using JOIN and table aliases. Suppose the following:

SELECT l.*, c.*
FROM location AS l
LEFT JOIN country AS c
ON l.loc = c.loc

The result set would have column headers as l.id and c.id unless you took the time to make column aliases for everything. If your columns were instead named location_id and country_id the result set would be much easier to read to someone who is not a database programmer.
name VARCHAR(20)

I think 20 may be a bit short for country name. For instance:

SELECT CHAR_LENGTH('United States of America');

Result: 24

Other than that I think it looks fine.


Should I return true or false if both of the IP address strings are empty?

From the IP validation point of view null or empty IP addresses are exceptional actions so you can not say that two null or empty strings are the same IP addresses becouse they aren't IP addresses and sometimes not even strings.

And you don't have to sorrund the logic with try-catch block becouse it will eat usefull information when things will get ugly. If you don't want to deal with parsing exception then use IPAddress.TryParse it will be faster becouse throwing an exception is always a heavy weight stuff (check it with profiler).

public static bool IsIPAddressMatching(string ipAddressA, string ipAddressB)
{
    if (ipAddressA == null)
    {
        throw new ArgumentNullException("ipAddressA");
    }
    if (ipAddressB == null)
    {
        throw new ArgumentNullException("ipAddressB");
    }

    if (string.IsNullOrEmpty(ipAddressA))
    {
        throw new ArgumentException("ipAddressA cannot be an empty string", "ipAddressA");
    }
    if (string.IsNullOrEmpty(ipAddressB))
    {
        throw new ArgumentException("ipAddressB cannot be an empty string", "ipAddressB");
    }

    var address1 = IPAddress.Parse(ipAddressA);
    var address2 = IPAddress.Parse(ipAddressB);

    if (address1.AddressFamily == address2.AddressFamily)
    {
        return (address1.Equals(address2));
    }

   // some code here to check mapped IP addresses

   return ...
}


I would go with a third approach so you don't have to manually update your User model:

class Notification(TimeStampedModel):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'),
                             related_name='notifications')
    viewed = models.BooleanField(verbose_name=_('has viewed'), default=False)

from django.contrib.auth.models import User as DjangoUser

class User(DjangoUser):
     @property
     def not_viewed_notifications(self):
         return self.notifications.filter(viewed=False).count()

This is twofold:

You don't need special logic in Notification and handle it in your view very simply (you can also have your users "unsee" some notifications);
You can never be out-of-sync between the number of not seen notifications for a user and the state of the notifications for said user.

This approach also have the advantage of not requiring anything from the selected User model (settings.AUTH_USER_MODEL). If using the proposed one, you will have access to the "not viewed" count from the property, if using the base User model from Django (or any other, for that matter), nothing will break and you'll still have access to the reverse relationship. Whereas, in your current implementation, you'll get into troubles when trying to access a non-existent not_viewed_notifications.


Python pattern searching using re standard lib, str.find()

If you name your function getSomething(), I expect it to return a value with no side effects.  I do not expect it to print anything.  Therefore, your function should either return the found string, or None if it is not not found.

Your original and revised code look for different things: the former wants as many digits as possible, and the latter wants 15 characters.  Combining the two requirements, I take it that you want 15 digits.

re.search() lets the regular expression match any part of the string, rather than the entire string.  Therefore, you can omit .* from the beginning of your regular expression.

Here's how I would write it:

import re
STR = "0001x10x11716506872xdc23654&xd01371600031832xx10xID=000110011001010\n"

def getID(string):
    result = re.search('ID=(\d{15})', string)
    return result and result.group(1)

print getID(STR) or "No Results"


JavaScript on page load and on scroll functions

I can't really see much to refactor in your code except a few things, so I'll go through those.

if (trigger_height == false)

could be if (!(trigger_height))

$this = $(this);
if (isScrolledIntoView($this, false)) {
    $this.removeClass("hidden");
}

I don't really see why you need to initialise $this, you could just use $(this) later on instead.


Summing all keys in the leaves of a tree

return sum(my_list)

You don't need to calculate the sum every time.  Do it just when count is 1:

if count == 1:
    return sum(my_list)

You have a recursive function, but your function doesn't care what itself returns.  All it cares about is the side-effect: mylist.append(K).  Just changing that (without any other changes) made the second example take less than a second.  It would be best to return my_list and let whatever is calling the function decide if it wants the sum.

In two places you say:

A, B, M, L1, L2, L3, D, R = list(map(int, inputs))

You don't need to convert to a list just to iterate.  That is what A, B, M, ... = ... does.  Just use A, B, M, ... = map(int, inputs).  That prevents the unnecessary storage of the numbers in memory.

Enough about efficiency.  Let's talk about other things.

Your naming is not ideal.  How does someone looking at your program know what A, B, M, etc. are?  They are just letters.  To tell you the truth, I have no idea what this program is doing.  If you had more descriptive names, it would be easier for future readers (possibly including you) to read the code.  PEP 8, the Python style guide, recommends snake_case for normal variables.

It is better not to use global variables.  I would suggest passing my_list as an argument to sum_keys() instead of relying on the existence of a global variable.


Is this a good example of Reactive Extensions? How can I make this better?

possible improvements :

make CallStackOverflow asynchronous
use Observavle.Timer instead of thread.sleep

Here is what it would look like

class Program
{
   static void Main(string[] args)
   {

        Observable
        .Timer(TimeSpan.Zero,TimeSpan.FromSeconds(10))
        .Take(10)
        .Select(() => CallStackOverFlow().ToObservable())
        .Select(d => {
             //send the result for checking to a delegate
               foreach (var q in d.questions)
                   {
                       var list = (q.tags as JArray).Values().Select(v => v.ToString()).ToList();
                       var result = FindByTag(list);
                       if(result)
                           Console.WriteLine("Quesion title :{0}",q.title);
                   }
         })
         .Wait();

       Console.WriteLine("Subscribing"); // Make visible when we subscribe
       start.Subscribe(Console.WriteLine);
       Console.ReadKey();
   }

   private static readonly Func<List<String>,bool> FindByTag =(x => x.Contains("c#"));

   private static async  Task<dynamic> CallStackOverFlow()
   {
       var client = new RestClient("http://api.stackoverflow.com/1.1");
       var request = new RestRequest("/questions/no-answers", Method.POST);
       // -- async invocation
       var response = await client.ExecuteAsync(request);
       // or  var response = await Task.Factory.FromAsync<TResponse>(client.BeginExecute, client.EndExecute, null);
       var content = response.Content; // raw content as string
       dynamic deserialised = JsonConvert.DeserializeObject(content);
       return deserialised;
   }
}


Reduce function on custom data structure using Cats Semigroup

Yes, using a Monoid can simplify what you want:

def foldMonoidal[A : Monoid](f: Element => A): A =
      Monoid.combine(f(this), Monoid.combineAll(els.map(f)))
...

e1.foldMonoidal(_.value)

One issue with that though is that you lose the information of the nested structure: You may as well have just a list of (name, value).

Any nested data structure can have a fold operation defined for it, in a way that keeps knowledge of its structure. In your case, this would be:

def fold[A](f: (Element, List[A]) => A): A =
  f(this, els.map(_.fold(f)))
...
e1.fold[Int]((el, list) => el.value + list.sum)

You can see this allows more freedom, e.g. you may want to sum the value with the average of the nested elements, which you couldn't do with the monoidal solution above.

e1.fold[Double]((el, list) => el.value + list.sum / list.size)

Or for pretty-printing:

e1.fold[String]((el, strEls) => s"(${el.name} -> ${el.value}, ${strEls.mkString("[", ",", "]")}")
// (Zero -> 0, [(One -> 1, [(Two -> 2, [(Three -> 3, [],(Four -> 4, []]],(Five -> 5, [(Six -> 6, [],(Seven -> 7, [],(Eight -> 8, [(Nine -> 9, [],(Ten -> 10, []]]]


Capture Min() And Max() Of Numbers Input

not going to be much better than what you have
only parse once and only compare once

int min = Convert.ToInt32(txtStart.Text);
int max = Convert.ToInt32(txtEnd.Text);
if(max < min)
{
   int temp = min;
   min = max;
   max = temp;
}


Styling and activating radio buttons on condition

Firstly, you could shorten the names of the variables e.g from $nav_color_i_active to $i_active and so on.
Secondly, there is a problem in your logic. You see else part will run if $navcolorhas any value other than 1. You should use elseif instead of else in both parts of code.


Yes, you could just write:

public Point GetSprite(int x, int y)
{
    if (x <= xCount && y <= xCount)
    {
        return new Point(x * spriteHeight, y * spriteWidth);
    }

    return null;
}

And write in the documentation it could return null if if (x <= xCount && y <= xCount)

So who use your code could just write

Point point = GetSprite(x, y);
if (point == null) { /* something went wrong, check variables! */ }
else { /* ok! go ahead! */ }

I found this syntax very useful, and could not lead to bugs if the programmer is alerted about the null.

And, anyway you don't need the else block since the return call will stop the function (except if there are any finally blocks, but it's not the case.).


Bugs

I found a couple of bugs in your program.

Your end-of-string handling is off for input strings smaller than 3 bytes.  This is because your end-of-string check is too late to stop the first byte from being processed.  So for the input "a", your function returns "YA==" instead of "YQ==".  See below for a solution for this problem.
If the input string contains characters with the high bit set, such as what could happen with UTF-8 input, then your function handles that incorrectly.  The culprit is that you use signed chars, and do bit shifting with those signed chars.  Imagine that input[n] is 0x80 here:

        i = (uint8_t)(input[n] >> 2);

What you would like to be calculated for i is 0x20.  But what you will actually calculate for i is 0xe0.  Later you will use 0xe0 as an index into your string and it will overflow the bounds.  You can fix this by moving your cast to the right place:

        i = ((uint8_t)input[n] >> 2);

One pass instead of two

Right now you are building up an array x of indices and then you use a second pass to convert the x array into the base64 string.  It would be quicker and simpler to just build up returnString directly and get rid of the intermediary x array.  For example, instead of:

        case 0:
            i = (uint8_t)(input[n] >> 2);
            x[xlen++] = i;
            break;

You could write:

        case 0:
            i = (uint8_t)(input[n] >> 2);
            returnString[xlen++] = index[i];
            break;

Simplifying the loop termination check

Right now, you have a complicated check that looks like this:

    if ((len - n) == ((padding==2)?2:3) && padding > 0) {
        n++;
        break;
    }

As mentioned earlier, this check was also insufficient for strings smaller than 3 bytes.  A simpler way of doing this is just to modify len to round down to the nearest multiple of 3 before starting the loop.  This does exactly what you wanted and also handles smaller than 3 byte strings:

    len -= (len % 3);
    for (n = 0; n < len; n++) {
        switch (n % 3) {
            ...
        }
        // Complicated check removed.
    }

Getting rid of the switch

Once you have made len a multiple of three (above), you can actually get rid of the switch statement.  Instead of iterating over every byte of the input, you can now iterate by three bytes at a time and do all three switch cases one after the other.

Confusing bitmask constants

Your code is correct, but I had a hard time trying to figure out what some of your constants meant.  For example:

            o = (uint8_t)((input[n] & 240) >> 4);

would make a lot more sense if you used the hex value like this:

            o = (uint8_t)((input[n] & 0xf0) >> 4);

Now I know you are taking the top 4 bits and shifting them down.

Reusing common code

After the main loop when you handle the two possible padding cases, most of the code for the padding == 2 case is also done in the padding == 1 case.  You can combine some of the common code together so that you don't repeat the code twice.  This is a matter of preference though, so what you have is fine if you find it more readable.

Other things

You should check the return value of malloc.
Your input argument is unmodified so you can make it a const argument.
You don't really need both i and o although if you like them to be separate variables you can.

Putting it all together

Here's what your code would look like after all my suggested changes (and a lot of other tweaks that are stylistic/optional):

char *base64encode(const char *input)
{
    int      len      = strlen(input);
    int      leftover = len % 3;
    char    *ret      = malloc(((len/3) * 4) + ((leftover)?4:0) + 1);
    int      n        = 0;
    int      outlen   = 0;
    uint8_t  i        = 0;
    uint8_t *inp      = (uint8_t *) input;
    const char *index = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                        "abcdefghijklmnopqrstuvwxyz"
                        "0123456789+/";

    if (ret == NULL)
        return NULL;

    // Convert each 3 bytes of input to 4 bytes of output.
    len -= leftover;
    for (n = 0; n < len; n+=3) {
        i = inp[n] >> 2;
        ret[outlen++] = index[i];

        i  = (inp[n]   & 0x03) << 4;
        i |= (inp[n+1] & 0xf0) >> 4;
        ret[outlen++] = index[i];

        i  = ((inp[n+1] & 0x0f) << 2);
        i |= ((inp[n+2] & 0xc0) >> 6);
        ret[outlen++] = index[i];

        i  = (inp[n+2] & 0x3f);
        ret[outlen++] = index[i];
    }

    // Handle leftover 1 or 2 bytes.
    if (leftover) {
        i = (inp[n] >> 2);
        ret[outlen++] = index[i];

        i = (inp[n]   & 0x03) << 4;
        if (leftover == 2) {
            i |= (inp[n+1] & 0xf0) >> 4;
            ret[outlen++] = index[i];

            i  = ((inp[n+1] & 0x0f) << 2);
        }
        ret[outlen++] = index[i];
        ret[outlen++] = '=';
        if (leftover == 1)
            ret[outlen++] = '=';
    }
    ret[outlen] = '\0';
    return ret;
}


Using reflection in a test to check if a private variable is really null after a function, is this okay?

Personally I wouldn't do this.

The reason why is when your field change name, your test fails because the field is hardcoded there and with refactoring this isn't persisted to the test.

What should I do?

Normally your AuthorizationBeanTest is in the same package as your AuthorizationBean.
When this is correct you could use a protected method.

Example :

protected boolean isUserNull () {
    return user==null;
}

This is completely safe in your pojo, nobody could even acces the User object.
And outside the package no one will ever see this method.

The advantage is when you refactor user or the method name, your test is automatically updated.


C++ makefile for CPLEX with environment loading

Instead of providing your own %.o: %.cpp rule, you can let Make use its built-in one.  You need to pass your extra include directory, and the standard way to do that is to add to CXXFLAGS:
CXXFLAGS += -I$(CPX_INCDIR)

Or perhaps
CPLEX_DIR = /opt/ibm/ILOG/CPLEX_Studio126/cplex
CXXFLAGS += -I$(CPLEX_DIR)/include

Similarly, take advantage of the built-in link command; this is especially easy, as there's a built-in rule that will create main from main.o.  You need to tell Make to use the C++ linker rather than the plain (C) linker:
LINK.o = $(LINK.cc)
LDFLAGS += -L$(CPLEX_DIR)/lib/x86-64_linux/static_pic
LDLIBS += -lcplex -lm -pthread

To declare the dependency on the header file, note that main.o needs to be rebuilt whenever the header changes:
main.o: cpxmacro.h

That's all!
Header file dependencies can be hard to manage by hand in larger projects; for these, search for "automatic dependency generation", or read Paul D. Smith's excellent article.

Modified makfile
With my changes:
CPLEX_DIR = /opt/ibm/ILOG/CPLEX_Studio126/cplex

CXX = g++
CXXFLAGS = -g -Wall -O
CXXFLAGS += -I$(CPLEX_DIR)/include

LINK.o = $(LINK.cc)
LDFLAGS += -L$(CPLEX_DIR)/lib/x86-64_linux/static_pic
LDLIBS += -lcplex -lm -pthread

all: main

main.o: cpxmacro.h

clean:
    $(RM) *~ *.o main

.PHONY: all clean


Your demo throws errors in console, something about uniqueId in ui.selectmenu.

Anyway:

You can expose $.ajax deferred so someone may use all features of jQuery.Deferred which is already there.
Call success callback with data as argument.

settings.success.call(this, n);

If you do not want to do anything special in case of failure, and just want to provide this to error callback, you do not have to create closure there.

.fail( settings.error );

..., unless you want to hide other rejection arguments.
Do not use each if for do the same (for performance reason):

for( var index = 0; index < n.length; index ++){
  list += '<option value=' + n[index].Id + '>' + n[index].Nazwa + '</option>';
}

Personally I don't like single char variable names, as they are really painful for future development

Instead of $(this).empty();$(this).append(list); you can simply use $(this).html(list);
You can expose jQuery.Deffered, for example as this.promise = $.ajax(..., example in here http://jsfiddle.net/dhRRN/5/
I would suggest also applying received options to ajax call, so your plugin's user could also alter request itself.


Replacing "no-js" with “js” class in the body element properly

It's a decent and pretty bullet-proof solution. Modern browsers also support the classList API, so you can do:

document.body.classList.remove('no-js');

It's a slightly safer solution, as the original could technically replace parts of a word (like abcno-jsfoo). Not really a concern here, but still.

To avoid that, and still use the original solution, you could use a regular expression to match word boundaries too:

document.body.className = document.body.className.replace(/\bno-js\b/, '');


You could use the composite pattern to create a tree of Validator instances. Each node would validate its with its own Validator before delegating to children (if any). This way children don't need to check again what was already validated in parent nodes

public class ValidatorTree<T> implements Validator<T> {

    private Validator<? super T> node;
    private List<Validator<? super T>> children;

    // constructor etc. snipped for brevity

    @Override
    public void validate(T t) {
        node.validate(t);
        for (Validator<? super T> child : children) {
            child.validate(t);
        }
    }
}

This way you can bundle several validators into one (so only one root validator needs to be referenced). And validation order is guaranteed, so no need to perform duplicate checks.

Edit (in response to comment)

A Validator for Model1 may very well be different from a Validator for Model2. If Validators are to be reused for different models you can define interfaces that define the common parts to be validated.

e.g.

public interface Named {

    String getName();
}

and a matching NameNotNullValidator :

public class NameNotNullValidator implements Validator<Named> {
    @Override
    public void validate(Named named) {
        if (named.getName() == null) {
            throw new ValidationException(/* appropriate message here */);
        }
    }
}

And this Validator can be reused in validator trees for all models that implement Named. Note that I adapted the generics in ValidatorTree for this.


It's been a while since I've used lisp, so I can't really critique your code for style or any common lisp gotchas.

That said, the biggest thing I notice here is that the code for generating the 3 numbers, sorting them, and printing the result are all tightly coupled with each other.  I would suggest defining a separate function that takes three numbers and returns them in sorted order, which can then be combined with your existing functions for generating three numbers and printing three numbers to give the desired output.  The added benefit, of course, is that this sort function can later be used to sort any three numbers, not just the three in this bit of code.


You can use into, for example:

(defn extract-headers [message]
  (let [headers (enumeration-seq (.getAllHeaders message))]
       (into {} (map #(vector (.getName %1) (.getValue %1)) headers))))

first, with map you build sequence of 2-element vectors, that later is converted into map


My only concern would be the hard coding of 15, 20, and 25, and the redundant code used to handle these 3 values:

Private Function GetTip() As Double
    If (Tip15.Checked) Then
        Return PriceBox.Text * 0.15
    ElseIf (Tip20.Checked) Then
        Return PriceBox.Text * 0.2
    ElseIf (Tip25.Checked) Then
        Return PriceBox.Text * 0.25
    End If
End Function

[...]

Private Sub Tip15_CheckedChanged(sender As Object, e As EventArgs) Handles Tip15.CheckedChanged
    If TotalBox.Text <> "" Then
        TotalBox.Text = Format(CalcTotal(), "currency")
    End If
End Sub
Private Sub Tip20_CheckedChanged(sender As Object, e As EventArgs) Handles Tip20.CheckedChanged
    If TotalBox.Text <> "" Then
        TotalBox.Text = Format(CalcTotal(), "currency")
    End If
End Sub
Private Sub Tip25_CheckedChanged(sender As Object, e As EventArgs) Handles Tip25.CheckedChanged
    If TotalBox.Text <> "" Then
        TotalBox.Text = Format(CalcTotal(), "currency")
    End If
End Sub

You might want to add more values later (18% seems to be a new popular tip value for some reason) or edit the existing values, so hardcoding isn't a great idea, design/style wise.


Use parameter to filter results in a database without directly allowing users to access database

It's completely unnecessary to execute the request SELECT slug FROM countries only to verify the user input before running SELECT countryid, name FROM countries WHERE slug = :slug LIMIT 1.
You can safely use the user input in the second query directly.
This is thanks to using prepared statements.
Even if the user input is malicious, PDO prevents SQL injection.

In other words, the first part of your snippet could be simply this:

if (isset($_GET['l'])) {
    $location = strip_tags($_GET['l']);
    $sql = "SELECT countryid, name FROM countries WHERE slug = :slug LIMIT 1";
    $matchCountry = $db->prepare($sql);
    $matchCountry->execute(array(':slug' => $location));
    $countryDetails = $matchCountry->fetch(PDO::FETCH_ASSOC);
}

If your main goal is to do SELECT * FROM items,
then if items.countryid is indexed, and countries.countryid is indexed,
then it would be best to write a single JOIN:

SELECT items.* FROM items JOIN countries USING (countryid)
WHERE items.suspend = 0 AND countries.slug = :slug GROUP BY items.id

This optimizes performance with the fewest necessary queries, without compromising safety.

However, it's recommended to avoid SELECT * queries, and always specify the fields you want to fetch explicitly.


Resize the hash table and rehash every element

Advice 1

for (int i = 0; i < newSize; i++) {
    if (T[i] != empty) {

Did you intend to iterate only over size entries from T? If so, you need:

for (int i = 0; i < size; i++) {
    if (T[i] != empty) {

Advice 2

T = newTable;
delete newTable;

You deallocate the actual new table array. Also, since you don't delete the table pointed to by T, you leak memory. I think your intention was to write:

delete[] T;
T = newTable;

Advice 3

T is not a good name for a hash table, since people can confuse it with a type parameter. Consider using something like storage_array, storage_table, table, or similar.


If you only need the entries once, you could simply keep using shift until there are no more entries:

var exercises = [
    {
        "desc":       "Pushup/Pullup",
        "countdown":  30
    }, {
        "desc":       "Squat punch",
        "countdown":  45
    }, {
        "desc":       "Jumping jacks",
        "countdown":  60
    }
];

function exerciseTimer(exercises) {
    // do stuff
    var exercise = exercises.shift(),
        tt = setInterval(function() {
            // write html to the page
            exercise.countdown = exercise.countdown - 1;
            //Does it work ?
            console.log( exercise );
            if (exercise.countdown <= 0) {
                exercise = exercises.shift();
                if(!exercise) {
                    clearInterval(tt);
                }
            }
        }, 100);
    };

exerciseTimer( exercises );

I would also suggest to not make the type of the variable part of the variable name. exercise and exercises are much easier to read than exerciseArray and exerciseObject.


Counting all words from text and ordering it

All in all this is not bad.

Split into functions

I would split this into more functions.

to generate a stream of words
to do the count
for the presentation

splitting the text

This is a simple generator

def text_split(text):
    text = text.lower().replace(",", "").replace(".", "")
    for word in text.split():
        yield unidecode.unidecode(word)

You can generalize this a bit using re and string.punctuation:

import re
import string

PUNCTUATION = re.compile(rf'[{string.punctuation}]')
def text_split_re(text):
    text = PUNCTUATION.sub('', text.lower())
    for word in text.split():
        yield unidecode.unidecode(word)

This removes all punctuation in 1 go.

Counter

you use dict.setdefault, so you read the documentation. If you had looked a tiny bit further, in the collections module, you'd have found Counter, which is exactly what you need, especially with it's most_common method. This is so handy, you don't really need the second method. You just need to feed it to the Counter.

presentation

def print_result(word_count: Counter):
    for word, count in word_count.most_common():
        print(f'{word} = {count}')

as simple as:

putting it together

from collections import Counter
if __name__ == '__main__':
    words = text_split_re('''text here''')
    word_count = Counter(words)
    print_result(word_count)

tests

splitting this in parts also allows you to unit-test each of the parts

assert list(text_split_re('text here')) == ['text', 'here']
assert list(text_split_re('Text here')) == ['text', 'here']
assert list(text_split_re('Text he.re')) == ['text', 'here']
assert list(text_split_re('''Text
    here''')) == ['text', 'here']


A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++

Don't try to deduce the predicate's parameter type
As Quuxplusone mentioned in the comments of the predecessor question, you should not try to determine the type of the predicate function's parameter, this is bound to fail. And indeed the problem immediately starts when you look at your predicate:
auto size5 = [](std::string s) { return s.size() == 5; };

And think: hey, that's making a copy of s, I should pass that by const reference instead:
auto size5 = [](const std::string &s) { return s.size() == 5; };

Now it fails the requires clauses of your functions. You might be able to add some more tricks to cast away cv-qualifiers and references before comparing the types with std::same_as, but that does not cover all possible situations either. For example, I could write a lambda which allows any type of std::basic_string to be checked:
auto size5 = []<typename T>(std::basic_string<T> s) { return s.size() == 5; };

As I suggested in the comments, you just want to write a concept that checks if the predicate can be applied to the argument it is fed, you don't need to check the types themselves. Here is a possible implementation:
template<typename Pred, typename T>
concept is_applicable_to_elements = requires(Pred predicate, const T &container)
{
    predicate(*container.begin());
};

template<class T1, class T2> requires is_applicable_to_elements<T2, T1>
auto recursive_count_if(const T1& input, const T2 predicate)
{
    return std::count_if(input.begin(), input.end(), predicate);
}

template<class T1, class T2>
auto recursive_count_if(const T1& input, const T2 predicate)
{
    return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto& element) {
        return recursive_count_if(element, predicate);
    });
}

Note that since all the templates used is_iterable(), you can remove that requirement, although if you keep it you get nicer error messages if you accidentily try to apply recursive_count_if() on something that does not support iterating over.


You want to avoid as much work inside drawRect: as possible. Instead of recalculating the attributed string for each line here do it whenever self.screen changes. That way it's done once instead of every time the some portion of the view is redrawn (which will happen a lot).

Maybe keep a self.lines array with the attributed string for each line in it. Or maybe it's a dictionary with the key being the line number and you just keep adding lines and drawRect just draws the last displayHeight lines.

Basically do everything you can to remove unnecessary work from drawRect.


I have found some things that might help you improve your code:

Strive for portable code

Several of the features of this code are either platform-specific or compiler-specific or both.  Specifically, #include <conio.h>, clrscr(), and getch() are all non-standard.  Instead consider portable replacements.  For instance you could use this instead of clrscr():

putchar('\f');

Or possibly this:

for (int lines=40; lines; --lines)
    putchar('\n');

Alternatively, one could eliminate it entirely, which is what I've done in my modified version of your code.

Follow standard declaration of main

Your compiler may allow you to declare void main() but that construction is technically only valid for what are called "non-hosted" environments, e.g. one in which you are not running Windows.  For that reason, you should use the standard int main() instead.  Note that you don't need to explicitly provide a return 0; at the end of main -- it's created implicitly by the compiler.

Whitespace improves readability

Allofyourwordsarecrammedtogether.  Inserting some spaces in your lines will make them much easier to read.  For example, instead of this:

while((n>0)&&(i<=sqrt(n)))

try this:

while((n > 0) && (i <= sqrt(n)))

Avoid scanf if you can

There are so many well known problems with scanf that you're usually better off avoiding it.  The usual approach is to read in user input into a string and then parse from there, in this case using something like atoi().

Eliminate redundant code

In this case, the line n=n1; is redundant since the initializer of the for loop does that again just two lines later.

Consider reducing the scope of variables

The variable n is only used within the for loop, so you could declare it within the initializer:

for(int n=n1; n <= n2; n1++, n=n1)

Use a for loop instead of while

Because the i variable is used only within the while loop, consider again reducing scope and turning that into a for loop:

for (int i=2;(n>0) && (i <= sqrt(n)); )

Even better, in that loop, the only use of n is for testing primes, so within it you can instead use a variable local to that loop.  I've used t (for testing):

for (int i=2, t=n; (t>0) && (i <= sqrt(t)); )
{
    printf("\t%d\n",c++);//printing the comparision number
    if(t%i==0)
    {
        count++;
        t/=i;
    }
    else i++;
}

This change also allows you to remove n1 entirely and to simply use n everywhere that n1 had been used.

Improve your algorithm

Except for 2, all prime numbers are odd.  You can take advantage of that to reduce the number of comparisons:

for (int i=2, t=n; (t>0) && (i <= sqrt(t)); )
{
    printf("\t%d\n",c++);//printing the comparision number
    if(t%i==0)
    {
        count++;
        t/=i;     // better:  break;
    }
    else if (i==2)
    {
        ++i;
    } else
    {
        i += 2;
    }
}

However, once we discover that a number is not prime, why continue factoring it?  You can eliminate even more comparisons by replacing the line t/=i with break to break out of the enclosing for loop.

You can do a similar optimization on the outer loop, incrementing it by 2 each loop iteration once you assure that it is odd coming into the loop.

Print newlines after rather than before

The code currently has printf("\n%d", n1); but the effect is that the last line printed doesn't actually end with \n.  Instead, re-arrange the two printf statements to that they both end rather than begin with \n.

Results:

When I applied all of these to your code, I found that when I compute the primes from 500 to 1000, the original code made 6766 comparisons, while the optimized version made 1444.


Responsive / CSS fixed and variable widths

To have a responsive web design, you need to do more than have no horizontal scrolling when viewed with a desktop browser.  You have to adapt to the viewport of any device, from the really small (phone) to the really big (desktop).  This code does not, sorry.

Responsive web design is typically achieved by using media queries (there are other ways, but they're unavailable in IE versions older than 10), which are completely absent from your code.  I suggest you take the time to learn about what responsive web design is:

http://bradfrostweb.com/blog/post/7-habits-of-highly-effective-media-queries/
http://www.smashingmagazine.com/responsive-web-design-guidelines-tutorials/
http://www.html5rocks.com/en/mobile/responsivedesign/
http://thesiteslinger.com/blog/responsive-design-why-youre-doing-it-wrong/
http://blog.cloudfour.com/the-ems-have-it-proportional-media-queries-ftw/

That said, there are other things that are not good here:

Absolute positioning of the "left menu".  In general, absolute positioning should be avoided unless it is absolutely necessary (eg. drop menus, etc.).  Absolutely positioned elements can become cut off if there's not enough surrounding content to prevent it from overflowing its ancestor elements.  Multi-column layouts can easily be done using floats or the table display properties (eg. display: table-cell) and the content won't get cut off.
Using px to restrict the width of text containing elements.  If the user needs to increase their font-size for accessibility reasons, 100-125px is no longer an appropriate sized container for that text.  You should be using ems or other relative units instead.
No semantic markup.  With HTML5 (see: http://html5doctor.com/), a whole slew of new semantic container elements have been added (eg. article, nav, aside, section) which may or may not be more appropriate than the general purpose div (I can't tell because there's no real content here).  Markup should be chosen to describe the content first, then you can worry about how to make it pretty.


This is horribly inefficient both in terms of storage and runtime:

As already mentioned in comments (though not spelled out) recursion has a memory overhead directly proportional to the number of iterations - which in you case is input size.

Remember - every function call takes up stack space, and a recursive call is the same as regular call!

You create extra temporaries by rejoining the string you just split for the recursive call and having a string concatenation on each iteration.

That's two new strings create in every step in addition to the split array!

Everything mentioned in step 2 takes processing time as well as memory.

You will not notice this overhead with any string you might type in a console for testing, but try reading and reversing a sizable text file, and the problem will become apparent.


Password checker containing many conditional statements

Enter password to test: premaintenance disdainful hayloft seer
too long
your password strength is medium

Enter password to test: NXJCWGGDVQZO
your password strength is weak

Enter password to test: Password1
strong

Your knowledge of password strength is: weak.

Explanation

Password strength is normally measured in "bits of entropy" — the idea being that if a password has been picked randomly from a pool of similar passwords of size N, then its entropy is log2N bits.

The first password I tried above was picked using a method suggested by Randall Munroe, like this:

>>> words = list(open('/usr/share/dict/words'))
>>> import random
>>> random.SystemRandom().shuffle(words)
>>> print(' '.join(w.strip() for w in words[:4]))
premaintenance disdainful hayloft seer

Its entropy can be calculated like this:

>>> from math import log
>>> l = len(words)
>>> log(l * (l - 1) * (l - 2) * (l - 3), 2)
71.39088438576361

This is a strong password—a cracker that tried a billion such passwords a second would take on average about 50,000 years to find it.

The second password is also strong, but not as good as the first. I generated it like this:

$ </dev/random base64 | tr -cd A-Z | head -c 12
NXJCWGGDVQZO

Its entropy is 12 × log226 = 56.4 bits.

The third password is, of course, the weakest. password1 is about the 600th most common password (according to Mark Burnett, here) and the initial capital letter is a common substitution that password cracking programs know all about.


I strongly recommend refactoring your HTML. At the moment it works, and I have based a solution around your HTML, however I strongly recommend changing it into nested ul tags to make it easier to manipulate with jquery e.g.

Item a

Sub item

Another sub-item

That said:

I have removed display: none from your UL and am using JS to hide the nav divs on page load (this can be moved to the css, but this is just proof of concept).

The javascript has paired the class of the a tag to the class of the nav div in the path variable.

When the user clicks on the nav link, all nav divs are hidden and the corresponding nav div for the clicked link is animated open.

var path = {
  'socialNav':'social_icons_list',
  'dogzNav':'dogz_list',
  'Nav':'navigation_list',
};

var navDivs = $('.social_icons_list,.dogz_list,.navigation_list');

$(document).on('ready', function(){
  navDivs.hide();
  $('a.socialNav, a.dogzNav, a.Nav').on('click', function(){
    navDivs.hide();
    navDivs.filter('.' + path[$(this).attr('class')]).slideDown(500);
  });
});
body {
  background: #ccc;
  font-family: 'proxima_nova_rgregular';
  color: #524a45;
}
.header {
  height: 129px;
  border-bottom: 1px solid #666;
}
.header .container {
  padding: 0;
}
/*social_icons desktop version*/
.social_icons {
  float: left;
  margin-top: 25px;
  width: 90%;
}
.social_icons .twitter {
  float: left;
  width: 24px;
  height: 50px;
  display: block;
  margin: 0 32px 0 0;
  background: url(../img/logos_icons/twitter.svg) no-repeat 0 center;
}
.social_icons .twitter:hover {
  background: url(../img/logos_icons/twitter_hover.svg) no-repeat 0 center;
  cursor: pointer;
}
.social_icons .facebook {
  float: left;
  width: 24px;
  height: 50px;
  display: block;
  margin: 0 32px 0 0;
  background: url(../img/logos_icons/fb.svg) no-repeat 0 center;
}
.social_icons .facebook:hover {
  background: url(../img/logos_icons/fb_hover.svg) no-repeat 0 center;
  cursor: pointer;
}
.social_icons .pinterest {
  float: left;
  width: 24px;
  height: 50px;
  display: block;
  margin: 0 32px 0 0;
  background: url(../img/logos_icons/pin.svg) no-repeat 0 center;
}
.social_icons .pinterest:hover {
  background: url(../img/logos_icons/pin_hover.svg) no-repeat 0 center;
  cursor: pointer;
}
.social_icons .instagram {
  float: left;
  width: 24px;
  height: 50px;
  display: block;
  margin: 0 32px 0 0;
  background: url(../img/logos_icons/insta.svg) no-repeat 0 center;
}
.social_icons .instagram:hover {
  background: url(../img/logos_icons/insta_hover.svg) no-repeat 0 center;
  cursor: pointer;
}
.logo {
  position: absolute;
  float: left;
  background: url(../img/logos_icons/logo_mobile.svg) no-repeat center center;
  width: 100%;
  height: 115px;
  display: block;
  margin-top: 10px;
}
.hold {
  float: left;
  width: 100%;
  margin-top: 25px;
  display: none;
}
.bag {
  float: right;
  width: 47px;
  height: 36px;
  background: #fff url(../img/logos_icons/bag.svg) no-repeat 7px center;
  border-radius: 5px;
  border: 1px solid #c6c6c5;
  padding: 7px;
  text-align: right;
}
.nav {
  margin: 0;
  float: left;
  width: 100%;
}
.navbar-nav > li {
  float: none;
  margin: 0;
}
.navbar-inverse .navbar-nav > li > a {
  color: #524a45;
  text-transform: uppercase;
  font-family: 'proxima_nova_rgregular';
  letter-spacing: 1.5px;
  padding: 15px 15px;
}
.dropdown-menu > li > a {
  color: #524a45;
  text-transform: uppercase;
  font-family: 'proxima_nova_rgregular';
  letter-spacing: 1.5px;
  clear: both;
  color: #333;
  display: block;
  font-weight: normal;
  line-height: 1.42857;
  padding: 20px 20px;
  white-space: nowrap;
}
.navbar-inverse .navbar-nav > .active > a,
.navbar-inverse .navbar-nav > .active > a:hover,
.navbar-inverse .navbar-nav > .active > a:focus {
  color: #524a45;
  background-color: #fff;
}
.navbar-inverse .navbar-nav > li > a:hover,
.navbar-inverse .navbar-nav > li > a:focus {
  color: #524a45;
  /*border-bottom:1px solid #524a45;*/
  background: #524a45;
  color: #fff;
}
.dropdown-menu {
  padding: 0;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
  background-color: #efefee;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {
  background-color: transparent;
  color: #524a45;
}
.navbar {
  background: #fff;
  min-height: 178px;
}
.navbar-header {
  float: none;
  background: #fff;
}
.navbar-collapse.collapse {} .navbar.shrink {
  min-height: 135px;
}
.navbar.shrink * {
  transition: 1s;
}
.navbar.shrink .header {
  height: 85px;
}
.navbar.shrink .logo {
  background: url(../img/logos_icons/logo_small.svg) no-repeat top 10px center;
  margin: 0
}
.navbar.shrink .navbar-brand {
  font-size: 25px;
}
.navbar-toggle {
  display: block;
}
.nav > li {
  display: block;
  position: relative;
}
.navbar-inverse .navbar-collapse,
.navbar-inverse .navbar-form {
  border: none;
}
.navbar-collapse {
  padding: 0;
}
.navbar-inverse .navbar-toggle {
  border-color: #c6c6c5;
  border-radius: 5px;
}
.navbar-inverse .navbar-toggle:hover,
.navbar-inverse .navbar-toggle:focus {
  background-color: #524a45;
}
.navbar-inverse .navbar-toggle:hover .icon-bar {
  background-color: #fff;
}
/* button mobile social_icons */
.navbar-header > .social_icons {
  display: block;
  margin: 10px;
  width: 20%;
}
.navbar > .social_icons_list ul {
  padding: 0;
  margin-top: 10px;
  width: 100%;
  background: #eee;
  float: left;
}
.navbar > .social_icons_list ul li {
  display: block;
  float: none;
  height: 50px;
  width: 100%;
}
.navbar-header > .social_icons a.socialNav {
  display: block;
  background: url(../img/logos_icons/mobile_social_icon.svg) no-repeat center center;
  width: 47px;
  height: 36px;
  border-radius: 5px;
  border: 1px solid #c6c6c5;
}
.navbar-header > .social_icons a.socialNav:hover {
  background: #524a45 url(../img/logos_icons/mobile_social_icon_hover.svg) no-repeat center center;
  width: 47px;
  height: 36px;
  border-radius: 5px;
  border: 1px solid #c6c6c5;
}
.social_icons_list ul li a {
  padding-left: 50px;
  display: block;
  height: 50px;
  padding-left: 50px;
  line-height: 50px;
  color: #524a45;
  text-transform: uppercase;
  letter-spacing: 1.5px;
}
.social_icons_list .twitter {
  background: url(../img/logos_icons/twitter.svg) no-repeat 10px center;
}
.social_icons_list .twitter:hover {
  color: #fff;
  background: #524a45 url(../img/logos_icons/twitter_hover.svg) no-repeat 10px center;
  cursor: pointer;
}
.social_icons_list .facebook {
  background: url(../img/logos_icons/fb.svg) no-repeat 10px center;
}
.social_icons_list .facebook:hover {
  color: #fff;
  background: #524a45 url(../img/logos_icons/fb_hover.svg) no-repeat 10px center;
  cursor: pointer;
}
.social_icons_list .pinterest {
  background: url(../img/logos_icons/pin.svg) no-repeat 10px center;
}
.social_icons_list .pinterest:hover {
  color: #fff;
  background: #524a45 url(../img/logos_icons/pin_hover.svg) no-repeat 10px center;
  cursor: pointer;
}
.social_icons_list .instagram {
  background: url(../img/logos_icons/insta.svg) no-repeat 10px center;
}
.social_icons_list .instagram:hover {
  color: #fff;
  background: #524a45 url(../img/logos_icons/insta_hover.svg) no-repeat 10px center;
  cursor: pointer;
  float: left;
}
/* button mobile dogz */
.navbar-header > .dogz {
  display: block;
  margin: 10px;
  width: 20%;
  float: left;
}
.navbar > .dogz_list {
  display: block;
  width: 100%;
  float: left;
}
.navbar > .dogz_list ul {
  padding: 0;
  margin-top: 10px;
  width: 100%;
  background: #eee;
}
.navbar > .dogz_list ul ul {
  padding: 0 0 0 20px;
  margin: 0;
}
.navbar > .dogz_list ul li {
  display: block;
  float: none;
  width: 100%;
}
.navbar > .dogz_list ul li > a {
  color: #524a45;
  text-transform: uppercase;
  font-family: 'proxima_nova_rgregular';
  letter-spacing: 1.5px;
  clear: both;
  color: #333;
  display: block;
  font-weight: normal;
  line-height: 1.42857;
  padding: 15px;
  white-space: nowrap;
}
.navbar > .dogz_list ul li > a:hover {
  color: #fff;
  background: #524a45;
}
.navbar-header > .dogz a.dogzNav {
  display: block;
  background: url(../img/logos_icons/paw.svg) no-repeat center center;
  width: 47px;
  height: 36px;
  border-radius: 5px;
  border: 1px solid #c6c6c5;
}
.navbar-header > .dogz a.dogzNav:hover {
  background: #524a45 url(../img/logos_icons/paw_hover.svg) no-repeat center center;
  width: 47px;
  height: 36px;
  border-radius: 5px;
  border: 1px solid #c6c6c5;
}
.navbar-header > .hold {
  float: left;
  margin-top: 10px;
  width: 20%;
  display: block;
}
.navbar-header > .dogz a.Nav {
  display: block;
  background: url(../img/logos_icons/paw.svg) no-repeat center center;
  width: 47px;
  height: 36px;
  border-radius: 5px;
  border: 1px solid #c6c6c5;
}
.navbar-header > .dogz a.Nav:hover {
  background: #524a45 url(../img/logos_icons/paw_hover.svg) no-repeat center center;
  width: 47px;
  height: 36px;
  border-radius: 5px;
  border: 1px solid #c6c6c5;
}
.navbar > .navigation_list {
  display: block;
  width: 100%;
  float: left;
}
.navbar > .navigation_list ul {
  padding: 0;
  margin-top: 10px;
  width: 100%;
  background: #eee;
}
.navbar > .navigation_list ul li ul {
  display: none;
}
.navbar > .navigation_list ul li ul li a {
  color: #ccc;
}
.navbar > .navigation_list ul ul {
  padding: 0;
  margin: 0;
}
.navbar > .navigation_list ul li {
  display: block;
  float: none;
  width: 100%;
}
.navbar > .navigation_list ul li > a {
  color: #524a45;
  text-transform: uppercase;
  font-family: 'proxima_nova_rgregular';
  letter-spacing: 1.5px;
  clear: both;
  color: #333;
  display: block;
  font-weight: normal;
  line-height: 1.42857;
  padding: 15px;
  white-space: nowrap;
}
.navbar > .navigation_list ul li > a:hover {
  color: #fff;
  background: #524a45;
}

0

      social

      dognav

      nav

About

FAQ's

Gifting

Her

Product 1

Product 2

Product 3

His

Product 1

Product 2

Product 3

Our Craft

Blog

Contact

Tweet

Like

Pin

Share

Her

His


Best Algorithm for solving USACO: Photoshoot - Python

Mathematical approach
Let us assume the following notation:
$$ \mathbb{B} = \sum_{i = 1}^{n - 1} b_i = b_1 + b_2 + \cdots + b_{n-1} $$
As mentioned earlier in comments, you have set of interdependent equations as follows:
$$
\begin{align}
b_1 &= a_1 + a_2 \\
b_2 &= a_2 + a_3 \\
b_3 &= a_3 + a_4 \\
\vdots \\
b_{n - 1} &= a_{n - 1} + a_n \\
\end{align}
$$
The above is \$ n - 1 \$ sets of equations, and the last equation you can derive from those is:
$$
\begin{align}
\sum_{i = 1}^{n - 1} b_i &= \sum_{i = 1}^{n} a_i + \sum_{j = 2}^{n - 1} a_j \\
\implies \mathbb{B} + (a_1 + a_n) &= 2 \times \left( \sum_{i = 1}^{n} a_i
\right) \\
\implies a_1 + a_n &= 2 \times \left( \dfrac{n (n + 1)}{2} \right) - \mathbb{B} \\
&= \left( n \cdot (n + 1) \right) - \mathbb{B} \tag{1}
\end{align}
$$

Now, let's see what happens if we try the summation with a slight variation:
$$
\begin{align}
\sum_{i = 1}^{n - 1} \left[ (-1)^{i + 1} \cdot b_i \right] &= b_1 - b_2 + b_3 - \cdots \cdots (-1)^{n - 2} b_{n - 1} \\
&= (a_1 + a_2) - (a_2 + a_3) + (a_3 + a_4) - \cdots \cdots + (-1)^n (a_{n - 1} + a_n) \\
&= a_1 + (-1)^{n} a_n \tag{2}
\end{align}
$$
Now, there would be 2 cases; 1 is fairly straight to solve:
Case 1: \$ n \$ is odd
The equation 2 becomes: $$ a_1 - a_n = \sum_{i = 1}^{n - 1} \left[ (-1)^{i + 1} \cdot b_i \right] $$
giving you the direct result (adding equation to above):
$$
a_1 = \dfrac{1}{2} \left( \sum_{i = 1}^{n - 1} \left[ (-1)^{i + 1} \cdot b_i \right] + n^2 + n - \mathbb{B} \right)
$$
Case 2: \$ n \$ is even
This gives you the same result as equation 1, therefore the replacement operation from SylvainD's answer comes into play. I'll leave this for the programming specific solution.

Program/code review

Use the names of variables which are closer to words used in problem statement. This makes it easier to go through code and question at the same time.

The photo.in serves no purpose once it has been read, use a contextual open for this:
with open("photo.in", "r") as file_in:
    num_cows = int(file_in.readline())
    summations = map(int, file_in.readline().split(" "))

Same as above, the photo.out serves no purpose until you want to write:
with open("photo.out", "w+") as file_out:
    file_out.write(" ".join(output_string))


This computation is wrong:

let primeInner n =
 let numbers = seq {for i in 2..(int (sqrt (float n))) -> i}
 numbers |> Seq.forall (fun n1 -> n % n1 = 0)

You need to invert the condition to n % n1 <> 0. Then you find a noticeable speed improvement of roughly 10x to the overall algorithm.

You should think of better names. isPrime instead of primeInner; findNth instead of nthPrimeInner.

A much prettier way is to filter an infinite sequence with isPrime and take the nth.

let nthPrime n =
  let isPrime n =
    seq {2..(int (sqrt (float n)))}
    |> Seq.forall (fun n1 -> n % n1 <> 0)

  let rec potentialPrimesFrom n =
    seq { yield n; yield! potentialPrimesFrom (n + 1) }

  potentialPrimesFrom 2
  |> Seq.filter isPrime
  |> Seq.nth n

This adds a little overhead, but you can get some of that back by applying nicer filters upfront to potentialPrimes

  let potentialPrimes =
    let rec oddFrom n = seq { yield n; yield! oddFrom (n+2) }
    seq { yield 2; yield! oddFrom 3 }

  potentialPrimes
  |> Seq.filter isPrime
  |> Seq.nth n

Rather than pushing performance further here, I would suggest rewriting to a more optimal algorithm like a Sieve of Eratosthenes.


Eliminate copy/paste and Factor logic out of foreach loop

I'd start by writing another method, containing what's common in both blocks; then I'd extract another method for processing a single file, and in that method I'd decide if I want to archive or just delete the file... and then I'd get annoyed with having a method that does two things and I'd extract some MoveOrCopyToArchive method, and try to delete the file in all cases.

But that's just easy moving stuff around and reducing redundancies.

This is more worrying:

try
{
    IOUtility.MoveFile(pagePath, newArchivePath);
}
catch
{
    try
    {
        IOUtility.CopyFile(pagePath,newArchivePath, true);
    }
    catch (Exception ex)
    {
        throw new IOException("Failed to move or copy file: " + pagePath + " to archive: " + newArchivePath, ex);
    }
}
File.Delete(pagePath);

Nested try/catch blocks have a funky smell, but the worrying line is the last one: what makes you think pagePath can be safely deleted? If something went wrong moving or copying it, my bet is on File.Delete throwing an exception as well - and that one will bubble up your stack, meaning Directory.Delete would never get called... and the entire application might just die a horrible death.

Now back to that nested try/catch - first you attempt to move the file, and if that fails, you try to copy it. There are several reasons for failing to move a file, several of which will also fail to copy it. I think that's a good case for cherry-picking which exceptions will warrant trying to copy, and which ones aren't worth it:

ArgumentNullException is almost certainly ruled out, you're checking if pageName is null already. But I don't know what IOUtility.PathCombine does, and I have no garantee that GenerateArchiveDirectory returns a valid path either. Better safe than sorry; catching this exception means attempting to copy the same file/path is 100% certain to fail as well.
ArgumentException or NotSupportedException would be thrown for a path containing characters invalid in a path, or for a path in an invalid format. No need to try copying that file, it's garanteed to fail anyway.
DirectoryNotFoundException and PathTooLongException would also fail copying.
IOException would be thrown if the destination file already exists, or if the source filename wouldn't be found. Clearly not worth trying to copy.
UnauthorizedAccessException - ok, moving can't work, but maybe the file can be copied.

https://msdn.microsoft.com/library/system.io.file.move(v=vs.110).aspx

The catch block that doesn't specify any exception not only enters on any exception, without a handle on the exception object you have lost the original exception that tells you how the first operation - moving the file - failed.

Catching System.Exception would be over-the-top here; as shown above, you'd only really want to try a copy when an UnauthorizedAccessException is thrown - every other exception you can possibly catch there, would be caused by something that would also make the copy fail.

But then if any of these exceptions is caught, my bet is on File.Delete throwing the same exception.

I'll add that throwing your own IOException is confusing here, because the System.IO methods you're using can throw that same exception type, with a different meaning. If you really want to wrap the exception with one of your own, then you have a case for a custom exception type here - a FileArchiveException or something similar.

Why is there no try/catch block in the ImportedFileDispositionActions.Delete case?

I'd do it something like this:

if (fileDisposition == ImportedFileDispositionActions.Archive)
{
    SendToArchive(pagePath, documentMetadataFile, batch);
}

if (File.Exists(pagePath))
{
    File.Delete(pagePath);
}

//Assert.IsFalse(File.Exists(pagePath));

Understanding at a glance what's going on is easier if each idea reads like a sentence.

The nested try/catch can be avoided by extracting a method out of the try block:

private readonly ILogger _logger; // do something about exceptions!

private void SendToArchive(string path, string metadata, FooBar batch)
{
    try
    {
        var archivePath = GenerateArchiveDirectory(path, metadata, batch);
        MoveOrCopyToArchive(archivePath);
    }
    catch(IOException exception)
    {
        _logger.Info(exception);
    }
    catch(Exception exception)
    {
        _logger.Debug(exception);
    }
}

private void MoveOrCopyToArchive(string path)
{
    try
    {
        File.Move(path, ArchivePath);
    }
    catch(UnauthorizedAccessException exception)
    {
        _logger.Warn(exception);
        File.Copy(path, ArchivePath, true);
    }
}

The stack trace will contain enough information to determine if the exception was thrown moving, copy, or deleting the file; there's not enough information in your post to recommend whether exceptions should be handled, rethrown or simply bubbled up - I've made a few assumptions here.


Turns out I needed to normalize the normal first:

n.normalize();

full code for reference:

PVector[] face = new PVector[3];
float ai = TWO_PI/3;//angle increment
float r  = 300;//overall radius
float ro = 150;//random offset

PVector n;//normal
Ray r1;

void setup() {
  size(500, 500, P3D);
  for (int i = 0 ; i < 3; i++) face[i] = new PVector(cos(ai * i) * r + random(ro), random(-50, 50), sin(ai * i) * r + random(ro));
  r1 = new Ray(new PVector(-100, -200, -300), new PVector(100, 200, 300));
}
void draw() {
  background(255);
  lights();
  translate(width/2, height/2, -500);
  rotateX(map(mouseY, 0, height, -PI, PI));
  rotateY(map(mouseX, 0, width, -PI, PI));
  //draw plane
  beginShape(TRIANGLES);
  for (PVector p : face) vertex(p.x, p.y, p.z);
  endShape();
  //normals
  PVector c = new PVector();//centroid
  for (PVector p : face) c.add(p);
  c.div(3.0);
  PVector cb = PVector.sub(face[2], face[1]);
  PVector ab = PVector.sub(face[0], face[1]);
  n = cb.cross(ab);//compute normal
  n.normalize();
  line(c.x, c.y, c.z, n.x, n.y, n.z);//draw normal

  pushStyle();
  //http://paulbourke.net/geometry/planeline/
  //line to plane intersection u = N dot ( P3 - P1 ) / N dot (P2 - P1), P = P1 + u (P2-P1), where P1,P2 are on the line and P3 is a point on the plane
  PVector P2SubP1 = PVector.sub(r1.end, r1.start);
  PVector P3SubP1 = PVector.sub(face[0], r1.start);
  float u = n.dot(P3SubP1) / n.dot(P2SubP1);
  PVector P = PVector.add(r1.start, PVector.mult(P2SubP1, u));
  strokeWeight(5);
  point(P.x, P.y, P.z);//point of ray-plane intersection

  //vector reflecting http://www.3dkingdoms.com/weekly/weekly.php?a=2
  //R = 2*(V dot N)*N - V
  //Vnew = -2*(V dot N)*N + V
  //PVector V = PVector.sub(r1.start,r1.end);
  PVector V = PVector.sub(r1.start, P);
  PVector R = PVector.sub(PVector.mult(n, 2 * (V.dot(n))), V);
  strokeWeight(1);
  stroke(0, 192, 0);
  line(P.x, P.y, P.z, R.x, R.y, R.z);
  stroke(192, 0, 0);
  line(r1.start.x, r1.start.y, r1.start.z, P.x, P.y, P.z);
  stroke(0, 0, 192);
  line(P.x, P.y, P.z, r1.end.x, r1.end.y, r1.end.z);
  popStyle();
}
void keyPressed() {
  setup();
}//reset
class Ray {
  PVector start = new PVector(), end = new PVector();
  Ray(PVector s, PVector e) {
    start = s ;
    end = e;
  }
}


Instead of create the whole list and modify it subsequently, you could calculate the value directly.

The code could like that:

static void Main()
{
    GettingInput gi = new GettingInput();
    var input = gi.GetInput();
    Console.WriteLine("Your input:\n{0}", input);

    var first = (int)'a';
    var last = (int)'z';
    var length = last - first;

    var query = Enumerable
        .Range(0, length)
        .Select(i => (char)(first + ((input + i) % length)));

    foreach (var number in query)
        Console.WriteLine(number);

    Console.ReadLine();
}

You could use int.TryParse(Console.ReadLine(), out input) instead of catching the exception


io::stdin().read_line(&mut num);

Here you are ignoring the Result from read_line; you should have seen a compiler warning about this. Add .unwrap() or .expect() to check the error and panic if there is a problem reading:
io::stdin().read_line(&mut num).expect("Read error");

(Below I'll be talking about handling errors instead of panicking. This case is different because an IO error during reading shouldn't occur in normal usage and there isn't really any way to recover from it.)

        if num.trim().parse::<i32>().unwrap() == 0 {break;}
        vec.push(num.trim().parse::<i32>().unwrap());

In these two lines you are parsing the number twice. Put the parse result in a variable instead.
        let num = num.trim().parse::<i32>().unwrap();
        if num == 0 {break;}
        vec.push(num);

If the user makes a typo and enters something that does not parse as i32 (e.g. a letter) then the program will panic since you are .unwrap()ing the parse result. It probably makes sense to tell the user and let them reenter instead. We can combine that with the handling of 0 inputs:
        match num.trim().parse::<i32>() {
            Err(_) => {
                println!("{:?} wasn't an integer. Try again.", num);
            }
            Ok(0) => {
                break;
            }
            Ok(x) => {
                vec.push(x);
            }
        }

Finally, you used .unwrap() for the min and max, which means that it will panic if the user doesn't enter any numbers. It's generally better for a program to not panic on any input. We can eliminate the unwrap from a single print like this:
    if let Some(min) = vec.iter().min() {
        println!("Min: {}", min);
    }

But, since three of the four outputs don't make sense for zero items, I think it makes more sense to put them inside a single condition, even if that means keeping the unwraps:
    println!("Sum: {}", sum);
    if !vec.is_empty() {
        println!("Min: {}", vec.iter().min().unwrap());
        println!("Max: {}", vec.iter().max().unwrap());
        println!("Mean: {}", sum as f32 / vec.len() as f32);
    }

One more thing. If the input to the program reaches end-of-file without containing 0, it will loop infinitely, reading no characters and producing error messages. (Well, your initial version didn't, because it panicked on a parse error instead). The right thing to do is to check whether read_line met end of file; this is reported in the return value but also detectable by the fact that num will be the empty string (without any newline).
        io::stdin().read_line(&mut num).unwrap();
        if num == "" {
            break;
        }

Putting together all my suggested changes:
use std::io;

fn main() {
    let mut vec: Vec<i32> = Vec::new();
    loop {
        println!("Enter any number, 0 to terminate");
        let mut num = String::new();
        io::stdin().read_line(&mut num).unwrap();
        if num == "" {
            break;
        }
        match num.trim().parse::<i32>() {
            Err(_) => {
                println!("{:?} wasn't an integer. Try again.", num);
            }
            Ok(0) => {
                break;
            }
            Ok(x) => {
                vec.push(x);
            }
        }
    }
    let sum: i32 = vec.iter().sum();
    println!("Sum: {}", sum);
    if !vec.is_empty() {
        println!("Min: {}", vec.iter().min().unwrap());
        println!("Max: {}", vec.iter().max().unwrap());
        println!("Mean: {}", sum as f32 / vec.len() as f32);
    }
}


HackerRank, Cracking the Coding Interview: Arrays - Left Rotation

Don't use:

using namespace std;

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

Only include the headers you need. Also organizing them by length of name does not seem to have any benefits. Personally I group them by function others sort them alphabetically. Pick something logical.

Pass large objects by const reference rather than value.

vector<int> array_left_rotation(vector<int> const& a, int n, int k) {
                                      ///   ^^^^^^

If you pass by value as in the code above. The compiler needs to add code to copy the object from the main function into array_left_rotation().

Prefer pre-increment:

for(int i = 0, len = a.size(); i < len; i++)
                                     // ^^^ prefer ++i

When using integers it makes no difference. But for other types it can potentially make a difference. So by using the pre-increment version you guarantee that you always use the most efficient version no matter what the type.

Not sure why we add len here:

int swapValue = (i + len - k) % len;

This is exactly the same as:

int swapValue = (i - k) % len;

Prefer to always use braces: '{' and '}' when you have a sub statements.

for(int i = 0; i < n;i++)
    cout << output[i] << " ";

I would have used this:

for(int i = 0; i < n;i++) {
    cout << output[i] << " ";
}

Prefer \n over std::endl. THe only difference between the two is that std::endl will flush the stream. Since the code will automatically flush the stream at appropriate points (doing it manually usually results in efficiencies).


How to make Project Euler 32 in Python faster?

Since you know that all of the non-zero digits must be present in the answer, you can skip most of the numbers in the range.  That is, it's pointless to do a test multiplication of 22*3333 because those both repeat digits.

So what is needed is an efficient way to run through all of the permutations of digits quickly, and fortunately, Python's itertools provides exactly that.

import itertools
start = timer()
products = set()
def makeint(n):
    return int(''.join(map(str,n)))

target = range(1,10)
d = itertools.permutations(target, 5)
for a in d:
    product = makeint(a[:2])*makeint(a[2:])
    if sorted(list(a)+map(int,str(product))) == target:
        products.add(product)
    product = makeint(a[:1])*makeint(a[1:])
    if sorted(list(a)+map(int,str(product))) == target:
        products.add(product)

ans = sum(list(products))

The way this works is to pick off permutations 5 digits at a time and then group as 2 and 3 or as 1, 4 as you have done.  There are other refinements one can make, such as skipping every number which ends in a 5 (because 5*n will always end in either 0, which is not in the range, or 5 which would be a duplicate digit), but I'll leave such refinements to you.

As it stands, this code runs almost 8x faster than the original.


A little detail; in Run:

// Run application
func (a App) Run(ctx context.Context) error {
    spew.Dump(a.v.AllSettings())

    return nil
}

error will be always null.
And according go-spew/spew#Dump;

  func Dump(a ...interface{})

Dump doesn't return a thing.
So seems like you should be able to a.- remove errorfrom your signature, or b.- do some sanity check on a.v to see, for example, that those elements are not nil/etc.


I'm no expert on security, but I believe this is not current best practice. I'll copy from an another answer of mine.

Cryptographic Right Answers (2009, Colin Percival, author of scrypt)

  Password handling: As soon as you receive a password, hash it using
  scrypt or PBKDF2 and erase the plaintext password from memory.

  Do NOT
  store users' passwords. Do NOT hash them with MD5. Use a real key
  derivation algorithm. PBKDF2 is the most official standard; but scrypt
  is stronger.  Please keep in mind that even if YOUR application isn't
  particularly sensitive, your users are probably re-using passwords
  which they have used on other, more sensitive, websites -- so if you
  screw up how you store your users' passwords, you might end up doing
  them a lot of harm.

How To Safely Store A Password (2010)

  Use bcrypt

  Use bcrypt. Use bcrypt. Use bcrypt. Use bcrypt. Use bcrypt.
  Use bcrypt. Use bcrypt. Use bcrypt. Use bcrypt.

  ...

  Why Not {MD5, SHA1, SHA256, SHA512, SHA-3, etc}?

  These are all general purpose hash functions, designed to calculate a digest of huge amounts of data in as short a time as possible. This means that they are fantastic for ensuring the integrity of data and utterly rubbish for storing passwords.

  ...

  Salts Will Not Help You

  It’s important to note that salts are useless for preventing dictionary attacks or brute force attacks. You can use huge salts or many salts or hand-harvested, shade-grown, organic Himalayan pink salt. It doesn’t affect how fast an attacker can try a candidate password, given the hash and the salt from your database.

  Salt or no, if you’re using a general-purpose hash function designed for speed you’re well and truly effed.

How to securely hash passwords? (2013)

  Conclusion

  Use bcrypt. PBKDF2 is not bad either. If you use scrypt you will be a
  "slightly early adopter" with the risks that are implied by this
  expression; but it would be a good move for scientific progress
  ("crash dummy" is a very honourable profession).


Recursively convert a list of lists into a dict of dicts

You could simplify your function:

def nested_pairs2dict(pairs):
    d = {}
    for k, v in pairs:
        if isinstance(v, list): # assumes v is also list of pairs
           v = nested_pairs2dict(v)
        d[k] = v
    return d

It seems to work.


Piano, output all the keys and give a scale

Since you tagged this question with typescript, I would say you could benefit greatly from making your keyboard and scale representations into classes.

Since there are different keyboard layouts, I wonder if it makes sense to generalize the functionality on creating a keyboard based on standard keyboard configurations?

Your current logic to build keys seems basically hard-coded for standard 88 key keyboard. There is an odd mix of work that is happening before the main loop where keys are populated (setting the octave 0 keys) and after that main loop (setting the octave 8 key). I would strive to set all key values within the loop so this logic isn't disjointed like it currently is.

In both pieces of logic, you might consider "rotating" the array of 12 notes to get to an appropriate starting position for working with the array based on the values input.  This could make your array interaction logic much cleaner, by avoiding the need to look for boundary conditions on the array (i.e. when you need to go back to index 0);

You also have some fragility in your code around data input.  You really don't have anything here that validates or handles edge cases in input data (for example what if values like a, ABm, are passed to getScale()?).

Code like this:

if(scaleName.indexOf("m") > -1){

might be better to be made more specific like this:

if(scaleName.indexOf("m") === 1) {

as there is only one index value where m should ever be encountered.

Alternately, I would consider a regex like /^([A-G]b?)(m?)$/ to be able to validate the input string and capture the components of the string in one pass.

I don't understand the need for both KEYS and KEYS_NORMALIZED in the scale code.  This is just the same array rotated, and considering you will have to rotate or transform the array given the specific input scale, why have two arrays that hold the same values?

Some variable names seem confusing. For example:

In the "piano" code, your KEYS constant might better be called notes or keyNotes or similar since this array is not the representation of the physical "keys" on the keyboard.
In getScale(), keys array is not dealing with the key of the scale or keys on a keyboard, but rather the notes in the scale, so perhaps notes might be a better name.
In getScale() the major/minorSemiTones variables might better be named major/minroSemiToneIntervals.

Putting it all together might yield something like:

class Keyboard {
     static readonly standardKeyboardConfig = {
         49: {
             startKey: 'C',
             startOctave: 0,
             octaveBoundary: 'C'
         }
         61: {
             startKey: 'C',
             startOctave: 0,
             octaveBoundary: 'C'
         },
         76: {
             startKey: 'E',
             startOctave: 0,
             octaveBoundary: 'C'
         },
         88: {
             startKey: 'A',
             startOctave: 0,
             octaveBoundary: 'C'
         }
     }
     static readonly defaultKeyCount = 88;
     static readonly keyNotes = ["C", "Db", "D", "Eb", "E", "F",
         "Gb", "G", "Ab", "A", "Bb", "B"];
     readonly keys: string[];

     constructor(keyCount: number) {
         keyCount = keyCount || Keyboard.defaultKeyCount;
         if (keyCount in Keyboard.standardKeyboardConfig === false) {
             throw new RangeError('Invalid keyboard specified');
         }

         let config = Keyboard.standardKeyboardConfig[keyCount];
         let startKey = config.startKey;

         // first rotate the array of notes if needed
         let keyNotes = Keyboard.keyNotes;
         if(startKey !== keyNotes[0]) {
             let index = keyNotes.indexOf(startKey);
             keyNotes = keyNotes.slice(index, keyNotes.length)
                              .concat(keyNotes.slice(0, index));
         }

         // now build out keys with octave values
         let octave = config.startOctave;
         let octaveLength = keyNotes.length;
         let octaveBoundary = config.octaveBoundary;
         for (i = 0; i < keyCount; i++) {
             let noteIndex = i % octaveLength;
             let note = keyNotes[noteIndex];
             if (i > 0 && note === octaveBoundary) {
                 octave++;
             }
             this.keys.push(note + octave);
         }
     }
}

// usage for default keyboard (a piano)
let piano = new Keyboard();
let keys = piano.keys;

class Scale {
    static readonly majorSemiToneIntervals = [2,2,1,2,2,2];
    static readonly minorSemiToneIntervals = [2,1,2,2,1,2];
    static readonly regex = /^([A-G]b?)(m?)$/;
    static readonly allNotes = ["A", "Bb", "B", "C", "Db", "D", "Eb",
        "E", "F", "Gb", "G", "Ab"];
    readonly name: string;
    readonly tonic: string;
    readonly isMinor: boolean = false;
    readonly notes: string[];

    constructor (scaleName: string) {
        // validate scale name and capture components
        let match = Scale.regex.match(scaleName);
        if(match === null) {
            throw new RangeError('Invalid scale name.')
        };
        this.name = match[0];
        this.tonic = match[1];
        let intervals = Scale.majorSemiToneIntervals;
        if(match[2].length === 1) {
            this.isMinor = true;
            intervals = Scale.minorSemiToneIntervals;
        }

        // rotate the allNotes array
        let notes = Scale.allNotes;
        let index = notes.indexOf(this.tonic);
        if (index !== 0) {
            let notes = notes.slice(index, notes.length)
                             .concat(notes.slice(0, index));
        }

        // build notes for scale based on intervals;
        this.notes.push(notes[0]);
        noteIndex = 0;
        intervalIndex = 0;
        while (intervalIndex < intervals.length) {
            this.notes.push(notes[noteIndex]);
            noteIndex = noteIndex + intervals[intervalIndex];
            intervalIndex++;
        }
    }
}

// usage
let scale = new Scale('C');
let notesInScale = scale.notes;

Is this more code?  Yes.  But, this code is more reusable, less fragile, and does not pollute the global namespace as your current code examples do.  All logic is encapsulated within the classes.


The formula for calculating entropy is:

$$ \sum_i p_i \log\frac{1}{p_i} $$

or \$-\sum p_i \log p_i\$. It would be nice if the code could express that.

probabilities = [f / 10 for f in frequencies.values() if f > 0]
column_entropy = -sum(p * log(p, 2) for p in probabilities)

The second line is the goal — it's a direct translation of the formula.  The first line is the setup that makes it possible to write the second line nicely.


Identifying an object pointer by generating and using a unique ID

While your solution works, it can be made even more understandable.

Instead of using a vector of tuples, consider using an std::map:

std::map<unsigned, std::tuple<image *, table *>> imageTablePairs;

This is the most natural expression of the problem statement: mapping an ID to an image-table pair. It will also simplify the logic of your getId function. Here's an algorithm for what you need to do:

  Cycle through the map and check if the image exists. If it does, delete its record from the map (using std::map::erase).

Then, simply do:

imageTablePairs[++m_iCurrentId] = std::make_tuple(img, tbl);

This covers both the case when the image exists (in which case its old record gets deleted per the algorithm above) and the case when the image does not exist (in which case we simply make a new record).

For the other two getter functions, we obviously can't assume that the ID being passed in exists in the map, so we can create a private helper function that takes an ID and returns true if it exists and false otherwise. Then, the logic becomes:

getImage: if the ID exists, return std::get<0>(imageTablePairs[uId]).
getTable: if the ID exists, return std::get<1>(imageTablePairs[uId]).

If I misunderstood the problem statement and this solution is not possible, please let me know.

Edit: Here's the code I'd use. Tested in Visual Studio 2017 and confirmed that it compiles and runs as expected (I used empty image and table structs for testing).

browserInfo.h

#pragma once
#include <map>
#include <tuple>

class BrowserInfo
{
public:
    // Returns a unique ID for the <image, table> pair
    /*
        @param  img The image file pointer
        @param  tbl     The table view pointer
        @return         A unique ID for the input pair
    */
    unsigned getId(image *img, table *tbl) const;

    /// Returns a image pointer for the given ID
    /*
        @param  uId The ID of <image, table> pair
        @return     A pointer to image file if ID exists, otherwise nullptr
    */
    image *getImage(unsigned uId) const;

    /// Returns a table pointer for the given ID
    /*
        @param  uId The ID of <image, table> pair
        @return     A pointer to table if ID exists, otherwise nullptr
    */
    table *getTable(unsigned uId) const;

private:

    bool idExists(unsigned uId) const;

    mutable std::map<unsigned, std::tuple<image *, table *>> imageTablePairs;

    // The current ID
    mutable unsigned m_iCurrentId = 0;

}; // class BrowserInfo

browserInfo.cpp

#include "browserInfo.h"

unsigned BrowserInfo::getId(image * img, table * tbl) const
{
    for (auto &record : imageTablePairs)
    {
        if (std::get<0>(record.second) == img)
        {
            imageTablePairs.erase(record.first);
            break;
        }
    }

    imageTablePairs[++m_iCurrentId] = std::make_tuple(img, tbl);
    return m_iCurrentId;
}

image * BrowserInfo::getImage(unsigned uId) const
{
    if (idExists(uId))
    {
        return std::get<0>(imageTablePairs[uId]);
    }

    return nullptr;
}

table * BrowserInfo::getTable(unsigned uId) const
{
    if (idExists(uId))
    {
        return std::get<1>(imageTablePairs[uId]);
    }

    return nullptr;
}

bool BrowserInfo::idExists(unsigned uId) const
{
    std::map<unsigned, std::tuple<image*, table*>>::iterator it = imageTablePairs.find(uId);
    return it != imageTablePairs.end();
}