PHP Factory Method Pattern Implementation

$militaryJet = JetFactory::create( 'FighterJet' );
$privateJet = JetFactory::create( 'PrivateJet' );
$commercialJet = JetFactory::create( 'JumboJet' );

This is a Factory pattern.  I'm not sure that I'd call it the Factory method pattern.  Look at the Wikipedia example for C# -- this looks like the before version.  If you were doing the same thing as the after version here, you'd have

$militaryJet = FighterJetFactory::create();
$privateJet = PrivateJetFactory::create();
$commercialJet = JumboJetFactory::create();

Where FighterJetFactory, PrivateJetFactory, and JumboJetFactory would all extend or implement JetFactory.

The question here is why not just say

$militaryJet = new FighterJet();
$privateJet = new PrivateJet();
$commercialJet = new JumboJet();

Given this example, you don't need any variation of the Factory pattern.  You could just create the objects directly.  As a general rule, you shouldn't look to use design patterns.  You should meet problems that can be solved by the design pattern.  You don't have a problem that needs a design pattern to solve.

Example of a problem that needs a Factory pattern solution:  given a passenger count and a cargo weight, return an object representing a plane that is capable of carrying those passengers with that cargo.

Example of a problem that needs a factory method solution:  define an interface for a plane and another that will allow you to create a plane object.  Give the interfaces to two partners.  Have one write a BoeingFactory that implements your factory interface and the other an AirbusFactory.  Both should return plane objects that implement your plane interface.


You can remove the let, as you only reference f once.

I'd also make it a named function; this makes it easier for you to update the definition, or to bind it to additional keys:

(defun start-mpv--file-at-point ()
  (interactive)
  (start-process "test" "output" "mpv" (ffap-file-at-point)))

(global-set-key [f3] 'start-mpv--file-at-point)

You might also want to look at the implementation of shell-command for inspiration.  Some things it does that might interest you:

killing any process that's already writing to the output buffer
erasing the current contents of that buffer
setting the comint output filter to handle carriage motion
making the output buffer visible


Every piece of code should have a clear purpose. If you need to conduct some maintenance on a piece of code, you obtain its description first. You consult users, manuals, previous developers as needed.

I assume this code is bug-free and it's doing some calculation on some hailstone numbers.

First of all, you extracting the implicit sequence is an improvement on the original, provided we know we are dealing with a sequence.

Further improvements

That only even numbers are included in the sum is not part of the Collatz Problem. By moving the condition we can rename the unnamed sequence as hailstones. Also f is not a good name for a sequence, as f and g usually denote parameters which are functions.

foo' :: Integer -> Integer
foo' = sum . filter even . hailstones -- removed unnecessary parentheses

hailstones :: Integer -> [Integer]
hailstones x
 | x == 1    = []
 | even x    = x : hailstones (x `div` 2)
 | otherwise = x : hailstones (3 * x + 1) -- space around *

Stopping condition is not part of the original Collatz problem, either. Hailstone sequences do not stop at 1, but rather go  \$ \cdots, 1, 4, 2, 1, 4, 2, \cdots \$ forever.

foo' :: Integer -> Integer
foo' = sum . filter even . takeWhile (/= 1) . hailstones

hailstones :: Integer -> [Integer]
hailstones x
 | even x    = x : hailstones (x `div` 2)
 | otherwise = x : hailstones (3 * x + 1)

Make the recursive nature of these sequences explicit:

collatzStep n
 | even n    = n `div` 2
 | otherwise = 3 * n + 1

hailstones x = x : collatzStep x

Last line can be written as hailstones = iterate collatzStep.

Altogether:

collatzStep n
 | even n    = n `div` 2
 | otherwise = 3 * n + 1

hailstones = iterate collatzStep

foo' = sum . filter even . takeWhile (/= 1) . hailstones

Now, of course if you were to hand this in as a homework, TAs or the professor would have asked you to add a lot of comments. First of all you do not tell them that "Comments are a code smell." Or describe what you did as KISS, DRY, readability etc.

Since this probably is a Programming Languages homework, you should add a comment mentioning that collatzStep is "lambda lifted", not "factored out"; that hailstones is an anamorphism and this, of course, makes foo an hylomorphism (correct the greek, and add more of it as necessary desired).


Minor tweak

    public static int pennies(int total)
    {
        return total - (quarters(total)*25) - (dimes(total)*10) - (nickels(total)*5);
    }

A shorter version of this would be

    public static int pennies(int total)
    {
        return total % 5;
    }

Of course, it would be reasonable to argue that the consistency of the original outweighs the terseness of this version.

Don't forget and repeat work

I would also consider making this an object rather than a static class.  Then you wouldn't have to recalculate these every time that you wanted one.

And this may be a little too much single responsibility principle.  Consider

    public void initialize(int total) {
        quartersCount = total / QUARTER_VALUE;
        total %= QUARTER_VALUE;

        dimesCount = total / DIME_VALUE;
        total %= DIME_VALUE;

        nickelsCount = total / NICKEL_VALUE;
        total %= NICKEL_VALUE;

        penniesCount = total;
    }

This is DRYer, as it puts the change breakdown in just one place rather than doing total - (quarters(total)*25) in three different methods.

A good compiler should generally be able to find the quotient and remainder in one operation, so this should simplify to three calculations even though there are seven assignments.  Your original version takes nineteen just to count pennies.  Thirty-three to calculate all four.  Even if subtractions and multiplications are lower weight than divisions, seven of those were divisions.

I added the constants, as they make it less likely that you will divide by one value and take the remainder of a different value.

I won't write out the getters or the object field declarations.

Just-in-time declarations

        String total;
        int intTotal;
        System.out.println("Hi, this application will take your number and will display the minimum amount of"
                + "coins necessary to represent the dollar amount");
        System.out.println("Please enter in the total amount of dollars and cents:");
        total = keyboard.next();

        total = total.replace(".","");
        intTotal = Integer.parseInt(total);

In Java, it's more customary to do variable declarations just in time to be used.  So

        System.out.println("Hi, this application will take your number and will display the minimum amount of"
                + "coins necessary to represent the dollar amount");
        System.out.println("Please enter in the total amount of dollars and cents:");
        String total = keyboard.next();

        total = total.replace(".","");
        int intTotal = Integer.parseInt(total);


var l1 = [...];
var l2 = [...];
if (l1.length > l2.length){
    actOnDuplicateOfFirstElementIfPresent(l1, l2, action_a);
} else if (l1.length < l2.length){
    actOnDuplicateOfFirstElementIfPresent(l2, l1, action_b);
} else {
    action_c();
}

function actOnDuplicateOfFirstElementIfPresent(la, lb, action) {
    var i = lb.indexOf(la[0]);
    if (i !== -1){
        action(i);
    }else{
        action_c();
    }
}

This Extract Method refactoring eliminates the duplication found in the first two branches.  Eliminating duplication is both an excellent motivation, and an excellent technique, for refactoring.


If you use getopt or getopts to parse the options, you can use multiple options together, and it would simplify your code quite a bit. Example.
When you create arrays explicitly (name=(values)) you don't need to declare it first.
arrayContains should take one needle and then the contents of the array in question. This is how it works in other languages, and is easier to program and more explicit than using an array reference and concatenated needles. Also, when expanding needle the values will be concatenated with a space between them, which is rather arbitrary.
If needle is empty, arrayContains should return 0 regardless of the array contents.
You can merge the if statements in arrayContains by separating them with -o:

if [ $a -eq 0 -o $b -eq 0 -o $c -eq $a ]

ls works with globs rather than regular expressions by default. The find* functions will not return the same filenames as ls with the same input. For example, run touch example && mkdir eclectic and compare

ls [e]*

with

find . -maxdepth 1 -depth -type f -regextype gnu-awk -regex "[e]*"

You should be able to get the current working directory with $PWD rather than pwd to save a fork. This makes the code a tiny bit faster, without losing clarity, and fixes a very common but little known bug: The `command` construct (identical to the preferred $(command) when using Bash) removes newlines from the end of the command output. That means if you mkdir $'foo\n' && cd $'foo\n' , ORIGIN_DIR="`pwd`" will give the wrong result, but ORIGIN_DIR="$PWD" will give the right one.
Use More Quotes, for example do ARG="$1" to enable working with whitespace in filenames. This is a very tricky subject.
If you want to get this working with all filenames, you'll need to use an array to store the find results before sending them to ls


Why are you using __double_underscore_prefixes for your member variable names?

Double-underscores get name-mangled by Python for the purpose of 'class-local references'. They're for when your class's implementation relies on something that you don't want subclasses to customise. This is a very rare situation, and typically happens quite late in a library's lifetime.

What double-underscore names are not for is access control. This is one of the biggest pieces of mis-information given to Python beginners.
Python doesn't have a concept of 'public' and 'private', and you shouldn't try to hack one together out of a language feature designed for something else. All your member variables should just be public by default; if you need to change an implementation detail, you can maintain your contract using properties.

If you really insist on declaring something as private, the conventional way to do that in Python is using a _single_leading_underscore. It's still not actually private, it's just a clear signal to your consumers that they shouldn't mess around with that stuff because it might change.

I also don't really like the way you're using __str__. __str__ is designed to return a meaningful description of the object, generally for the purposes of debugging (or when you wish to emulate string-like behaviour). You're using __str__ as part of the behaviour of your class (returning a formatted string in plain English).

I'd put the body of __str__ inside the talk method, and either delete __str__ altogether, or use it for something more meaningful to a person working with the code - something like this:

def __str__(self):
    return "Critter named {} with hunger {} and boredom {}".format(self.__name, self.__hunger, self.__boredom)

def talk(self):
    print("Hi, I'm " + self.__name + " and I feel " + self.mood + ".")
    self.__passTime()


Validation for DTO using DataAnnotations

What do you think about non static validators? While making validators smarter, we will sooner or later need to wire up their dependencies (like repositories)... Validators can easily do much more while being instantiated by IoC container.

I would suggest to define this interface and class:

interface IModelValidator<in T>
{
    IEnumerable<string> Validate(T subject);
}

class ModelValidator<T> : IModelValidator<T>
{
    public ModelValidator(IEnumerable<IModelValidator<T>> validators)
    {
        Validators = validators;
    }

    public IEnumerable<string> Validate(T subject) =>
        Validators.SelectMany(v => v.Validate(subject));

    IEnumerable<IModelValidator<T>> Validators { get; }
}

Now some demo code; models:

class Order { }
class MailOrder : Order { }

Validators:

class OrderValidator : IModelValidator<Order>
{
    public IEnumerable<string> Validate(Order subject)
    {
        yield return "Bad order.";
    }
}

class MailOrderValidator : IModelValidator<MailOrder>
{
    public IEnumerable<string> Validate(MailOrder subject)
    {
        yield return "Bad mail order.";
    }
}

Something to check validity of the order:

class Controller
{
    public Controller(ModelValidator<MailOrder> validator)
    {
        var order = new MailOrder();
        foreach (var message in validator.Validate(order))
            Console.WriteLine(message);
    }
}

So now it is just about proper registering them in IoC container (here Autofac):

class Program
{
    static void Main(string[] args)
    {
        var builder = new ContainerBuilder();
        builder.RegisterSource(new ContravariantRegistrationSource());
        builder.RegisterGeneric(typeof(ModelValidator<>))
            .AsSelf();
        builder.RegisterType<OrderValidator>()
            .AsImplementedInterfaces();
        builder.RegisterType<MailOrderValidator>()
            .AsImplementedInterfaces();
        builder.RegisterType<Controller>()
            .AsSelf();

        IContainer container = builder.Build();
        var controller = container.Resolve<Controller>();
    }
}

You could play with it to discover how perfectly contravarians works here. You just declare what to validate - compatible validators will show up. No need to change client code - just register more validators if necessary. One of them might be IModelValidator<DtoBase> with attribute checking.


The main problem I have with your code is with these templates:

template<int N> RelType compare(double, double) { static_assert(false, "Not implemented."); }
template<> RelType compare<5>(double v1, double v2) { return _compare(v1, v2, 100000); }

They are misleading. The 5 in the second function should be supposed to denote the number of decimal places to be compared, however, it is not implemented to do so, being only used as name decoration. E.g.:

// Comparing 5 decimal places:
cout << (compare<5>(v1, v2) == RelType::Equal) << endl;

// Also comparing 5 decimal places:
// (In actuality, a shady compile error due
// to the static_assert. But we can do better...)
cout << (compare<8>(v1, v2) == RelType::Equal) << endl;

I see no point in having a parameter if it always has to have the same value, so one improvement to the interface would be just getting rid of the templates and having a single function that always compares with 5 decimal places and no other option.

Another possibility, if you need to have the ability to configure the number of decimal palaces at compile time, would be actually using the N parameter to compute the multiplier, instead of hardcoding a value. You can do so with a compile-time power function:

template<int N> RelType compare(double v1, double v1)
{
    constexpr auto multiplier = compile_time_pow(10, N);
    // ... the rest ...
}

Note that in the above link C++11 is utilized, though it is probably possible to achieve the same without constexpr.


Branching to change behavior is a code smell.  A cleaner design would be to use the State pattern, and let the state toggle each time you descend to the next layer of the tree.

Also, I think you've made things less clear by tangling your traversal logic, with your output logic.  Which is to say, instead of doing something with the child, and something with the child values, instead of working with the parent value and adding the children to the traversal tree.

In pseudo code, I would expect the logic to look like

currentNodes = [ root ]
while( currentNodes.notEmpty ) {
    state = state.switch
    valueList = report.nextValues

    nextNodes = []

    for ( node : currentNodes ) {
        valueList.add(node.value)

        nextNodes.add( state.order(node.left, node.right) )
    }
    currentNodes = nextNodes.reverse;
}

return report


What is better for the code segment, sockets or multiple processes?

If you want to use this function you should have buffering:

function failOut($http, $text) {
    header('HTTP/1.x ' . $http);
    die(htmlspecialchars($text));
}

Otherwise it's possible that the script sends out some output (including error messages) and you can't send out any header later. (How do headers work with output buffering in PHP?) Anyway, I don't see any call to this function, so you might be able to remove it.

$con = mysql_connect('localhost',$user,$password) or die('Could Not Connect..');

As others already suggested you should use mysqli or PDO. Another note is that you might want to set the HTTP response code to 503 here to save your search engine ranking when the database is down.

$params = $_GET;
...
$count = mysql_query("select * from info where ID='".$params['id']."'")or die('Error In Query'.mysql_error());

As others already mentioned in comments it's not safe against SQL injections attacks. mysql_error() should not be the output of the script. Show only a generic error message and log the details to a server-side log file, don't help attackers. It would also be more user-friendly, most of the users doesn't care nor understand MySQL errors (or at least can't fix them). (How to log errors and warnings into a file?)

$dom->getElementsByTagName('BITRATE')->item(0)->textContent

This is in the code at least five times (with different tagname). You could create a function (whose parameter is the tagname) to remove the duplication.


WebApi action that updates entity using stored procedure

You don't have a people, you have a person.
Saying if (person.IsMain == true) is exactly equivalent to if (person.IsMain)

Updated code below.

public HttpResponseMessage SetAsMain(int id)
{
    People person = repository.GetById(id);

    if (people == null)
    {
        return ErrorMsg(HttpStatusCode.NotFound, string.Format("No people with ID = {1}", id));
    }

    if (person.IsMain)
    {
        return ErrorMsg(HttpStatusCode.OK, string.Format("{0} is already set as main", person.Houses.ToString()));
    }

    try
    {
        var parameters = new Dictionary<string, string>();
        parameters.Add("PeopleID", id.ToString());

        repository.ExecProcedure("usp_PeopleSetMain", parameters);
        return Request.CreateResponse(HttpStatusCode.OK, repository.GetById(id));
    }
    catch (Exception ex)
    {
        return ErrorMsg(HttpStatusCode.InternalServerError, ex.Message);
    }
}

I would also recommend changing the name of the repository method that returns a person from GetById to GetPersonById. As it is currently, the method name gives us no clue what's going on. I had to figure it out from context.


Can this parser (concerning about infinite hierarchy of operators) be implemented purely in ReadPrec?

A simple rule of thumb is that you should never use readS_to_Prec and readS_to_P. Consider that once you've converted a parser to a ReadS to run it, there is no way back. (One handwavy explanation is that those functions are really dirty hacks, which is also why gather is undefined when they are used.)
Under those constraints, the only place where you can find out the maximal level opn of hyperoperators is at the very top level where you actually apply your parser to a string; that is the one location where you can scan the string to compute opn. That means that all your parsers need to be parameterized by opn in order to pass it down to parseHyperOp.
parseOp :: Int -> P.ReadP Integer
parseOp opn = readPrec_to_P (parseHyperOp opn) 0

-- Top-level runner for parsers parameterized by opn
runP :: (Int -> P.ReadP a) -> ReadS a
runP parser str =
  let opn = highestOp str in
  P.readP_to_S (parser opn) str

example = runP parseOp "(1 + 2) ^ 3 + 2 ^ 2"

Having an infinite number of precedence levels makes top-down parsing (the popular approach using parser combinators) rather problematic, since there isn't really a "top" to start from. Consider giving up that feature (by making all operators beyond a certain level non-associative at the same level), or switching to a bottom-up parsing strategy.


Optimizing code that needs to run through a lot of different numbers for Project Euler

Iterating [1...num] is too slow
Only [1...sqrt(num)] needed

Instead of

for (j=1; j<=num; j++) {
  if (num % j == 0) {
    divisors += 1;
  }
}

Go to the root of num (when j*j <= num) and get 2 or 1 divisors.

for (j=1; j*j <= num; j++) {
  if (num % j == 0) {
    divisors += 1;
    if (j*j < num) divisors += 1;
  }
}

Re-formulate to avoid j*j overflow

for (j=1; j < num/j; j++) {
  if (num % j == 0) {
    divisors += 2;
  }
}
if (j == num/j) {
  divisors += 1;
}

Note: Many compilers with recognize the nearby num/j and num % j and perform the operation for the time cost one of one.

Example

Consider num == 36.  Original code tries 36 numbers with the starred ones having an exact division.

1*,2*,3*,4*,5,6*,7,8,9*,10,11,12*,13,14,15,16,17,18*,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36*.

Notice that when num%j == 0, both j and num/j are divisors.  Except when j == num/j, that discovers two unique divisors at once.  Code only needs to  iterate to 6.

j=1, divisors: 1 & 36
j=2, divisors: 2 & 18
j=3, divisors: 3 & 12
j=4, divisors: 4 & 9
j=5, divisors: none
j=6, divisor: 6

6 iterations faster than 36.

With a num = 1,000,000, new code will iterate to 1000 rather than 1,000,000 - a thousand times faster.

Detail on overflow possibility.

Consider num is at or near INT_MAX:

With for (j=1; j<=INT_MAX; j++) {, j will attempt to increment beyond INT_MAX resulting in undefined behavior.

With for (j=1; j*j < near_INT_MAX; j++) {, Unless near_INT_MAX is a perfect square, j*j will overflow.  Again undefined behavior.

With for (j=1; j < num/j; j++) {, j never overflow for all num.

====

There are many more advance techniques for faster code.


Creating bootstrap modals that can run JavaScript in MVC5

Simply put, you are using AJAX to return markup when you should be using AJAX to fetch data. If you are doing a per-item fetch using AJAX, you should be fetching more package detail information and returning it in an object, not as a munged HTML string. If you already have all the data you need when the page is loaded, then you should not be making additional AJAX calls, you should be doing all the work in Javascript.

I think Vsevolod Goloviznin made a good suggestion, to render the modal on the page once. That's good because it does not make the server have to generate a bunch of crap, but if you use straight-up jQuery you end up writing a bunch of messy procedural code to update the markup and event handlers (destroy and reassign) during the selection callback of your packages table.

Client-side templating is your friend. Here's an article that seems to be right up your alley:

http://www.smashingmagazine.com/2012/12/05/client-side-templating/


Most idiomatic way of declaring a deck in Rust

You’ve made a fairly classic mistake when it comes to modeling cards in software. Cards have different values depending on the game. In some games, an Ace == 1, others 11, sometimes it could be either in the same game (Blackjack for example). Non-face cards aren’t always their value either. In some games, they’re all “5 points”, regardless of the number on the card.

In short, the value of a particular card depends on the game, not the card. How might you redesign to account for that?


Entity Framework - updating two different arrays of child associations

Use design patterns to simplfiy your Data Access Layer and the Separation of concerns.

This method UpdateExercise(Exercise exercise) is very complicated and is not SRP.

Your problem in the model architecture more than in code. Of course you can use some tricks to simplify the code syntax like LINQ queries but the core problem will still there!

I recommeded you to apply Repository pattern and UnitOfwork pattern then you will see how it easy can you do all wished changes in one Transaction.
Use eager loading to inclued the wished entities(Tools,Muscles, etc.)  and load all load all everywhere
Use Linq to simplify the queries
Use attached entities, if possible!! slower but better!


Calculate total cost of items, based on bulk discount

Avoid using namespace std

This can cause name collisions because it adds every name in the std namespace to the global namespace. For a small program like this one it's unlikely that you'll run into any problems (then again, maybe not) but it's best to get into the habit of using the std:: prefix on names in the std namespace.

Alternatively, you can introduce using declarations like using std::cout; to add specific names to the global namespace.

Avoid duplicated code like gesamt=stk*ep;

That statement appears three times in your code. If that logic ever changes you'll need to make sure you change it everywhere, and you might miss one or more instances. Put that duplicated code in a function if necessary, or just write it once if possible.

Indent for readability

None of the code in main() is indented, for example. It's easier to read your program if it's indented like this:

int main() {
  int stk, ep, gesamt;
  //...
}

Use more whitespace for readability

E.g. use gesamt = stk * ep; instead of gesamt=stk*ep;

Use descriptive variable names

The variable names seem to be in a different language (German?) but stk and ep in particular look like they are abbreviations or acronyms. I would prefer pieces for stk and unit_price for ep.

Avoid std::endl in favor of \n

std::endl flushes the stream, which can cause a loss in performance. In some cases you can also reduce calls to operator<< (e.g. cout << "Pieces?" << endl; becomes cout << "Pieces?\n";).

Check the problem statement logic

The problem statement says to apply a 5% discount if pieces > 10 but you use >=. Your code applies a discount if pieces = 10 but the problem statement implies that the discount should not be applied in that case (only starting with pieces = 11).

Use the appropriate type for variables

In this case, you probably need to use float or double for ep and gesamt. The price isn't necessarily an integer and neither is the total price if the discount is applied.

Check your inputs for error conditions

For example, neither the number of pieces nor the unit price should be negative. Check for these error conditions and handle them appropriately (output an error message, throw an exception, ask for a new input, etc.).

Avoid unnecessary goto statements

goto is generally not needed, and that is the case in your program. Your program will reach the stop statement after entering the various if/else clauses.

Result

Here's the end result of your program with the above suggestions (I've also made the code more concise in some cases, e.g. by the use of the *= operator to multiply a number by itself):

#include <iostream>

int main() {
    int pieces;
    double unit_price;
    double gesamt;

    std::cout << "Pieces?\n";
    std::cin >> pieces;

    if (pieces < 0)
    {
        std::cout << "Cannot have negative pieces!\n";
        return -1;
    }

    std::cout << "Price per Piece?\n";
    std::cin >> unit_price;

    if (unit_price < 0)
    {
        std::cout << "Cannot have negative unit price!\n";
        return -1;
    }

    // Calculate total price
    gesamt = pieces * unit_price;

    // Apply discount, if applicable
    if (pieces > 10)
    {
        if (pieces > 50)
        //10% discount
        {
        gesamt *= 0.9;
        }
        else   //5% discount
        {
        gesamt *= 0.95;
        }
    }

    std::cout << gesamt << '\n';

    return 0;
}


Making loop in CSS Stylus more efficient

Based on what I can tell of these three loops is that they are not nested, which means that you are running one loop for the whole range of 1-19 another loop for the range of 1-9 (which you already went over once) and another loop for the range of 10-19 which you have already looped over as well.  and the first loop that goes over the entire range already divides the top half from the bottom half to change other things, I may be looking at this all wrong, but I put the last two loops inside the first loops if-then statements and came up with this

for i in (1..19)
  .l:nth-child({i})
  n = (20 - i)
  height 0
  if i >= 10
    margin-left ((n * n) * (1.25/n)) + 17 px
    box-shadow 0px 0px (n+4)px 0 rgba(40,70,200, 0.5),0px 0px (i+8)px 0 rgba(80,100,235, 0.45),0px 0px 14px 0 rgba(115,215,235, 0.35),0px 0px 23px 0 rgba(110,130,215, 0.5)
    width (n * 1.05) + 0px
    animation (heights- + i) 0.75s (n/80)s linear forwards

    $keyframe-name = (heights- + i)
    @keyframes {$keyframe-name}
      0%
        height 0
      91%
        height ((n + 4) * 1.4) px
      98%
        height ((i + 38) * 5.4) px
      100%
        height ((n + 38) * 4.4) px
        opacity (n/6)
        if i == 10
          height ((i + 43) * 4.4) px
          opacity (i/6)

  else
    margin-left ((i * i) * (1.25/i)) + 17 px
    box-shadow 0px 0px (i+4)px 0 rgba(40,70,200, 0.5),0px 0px (i+8)px 0 rgba(80,100,235, 0.45),0px 0px 14px 0 rgba(115,215,235, 0.35),0px 0px 23px 0 rgba(110,130,215, 0.5)
    width (i * 1.05) + 0px
    animation (heightsx- + i) 0.75s (i/80)s linear forwards

    $keyframe-namex = (heightsx- + i)
    @keyframes {$keyframe-namex}
      0%
        height 0
      91%
        height ((i + 4) * 1.4) px
      98%
        height ((i + 38) * 5.4) px
      100%
        height ((i + 38) * 4.4) px
        opacity (i/16)

I agree with @Cimmanon in that you would get more answers to this question if we had somewhere that we could run the code and tinker with it a little bit.  I assume that you would have done it this way to begin with unless there was another reason for doing it this way.

I also moved some variables around to merge them and use them in other expressions.

like

    animation (heights- + i) 0.75s (n/80)s linear forwards

    $keyframe-name = (heights- + i)
    @keyframes {$keyframe-name}
      0%
        height 0
      91%
        height ((n + 4) * 1.4) px
      98%
        height ((i + 38) * 5.4) px
      100%
        height ((n + 38) * 4.4) px
        opacity (n/6)
        if i == 10
          height ((i + 43) * 4.4) px
          opacity (i/6)

you create $keyframe-name to hold the value heights- + i when you could have just put that expression into @keyframes{heights- + i}, but since we merged the two for loops into one we can use $keyframe-name like this

$keyframe-name = (heights- + i)
animation ($keyframe-name) 0.75s (n/80)s linear forwards
@keyframes {$keyframe-name}
  0%
    height 0
  91%
    height ((n + 4) * 1.4) px
  98%
    height ((i + 38) * 5.4) px
  100%
    height ((n + 38) * 4.4) px
    opacity (n/6)
    if i == 10
      height ((i + 43) * 4.4) px
      opacity (i/6)

and do the same thing inside the else statement

$keyframe-namex = (heightsx- + i)
animation ($keyframe-namex) 0.75s (i/80)s linear forwards
@keyframes {$keyframe-namex}
  0%
    height 0
  91%
    height ((i + 4) * 1.4) px
  98%
    height ((i + 38) * 5.4) px
  100%
    height ((i + 38) * 4.4) px
    opacity (i/16)


Your printTree function is unnecessarily long.

Also, I really don't like the output of your serialize. I was not able to parse (as a human) this back into the structure of the tree. For me it would be much better if the structure was apparent from the serialization.

Therefore I rewrote your code in the following way:

class Node:

    def __init__(self, value='#', children=None):
        self.value = value
        self.children = children if children else []

    def __nonzero__(self):
        return self.value != '#'

    def __eq__(self, other):
        return self.value == other.value and self.children == other.children

    def __str__(self):
        buf, out = [self], []
        while buf:
            # current level
            out.append(", ".join(str(node.value) for node in buf))
            if any(node for node in buf):
                # add children
                buf = [subnode if subnode else Node()
                       for node in buf
                       for subnode in node.children]
            else:
                break
        return "\n".join(out)

    def __repr__(self):
        if not self:
            return "Node()"
        children_repr = ",".join(repr(child) for child in self.children)
        return "Node({.value},[{}])".format(self, children_repr)

    def serialize(self):
        return repr(self).replace("Node", "").replace("()", "#")

    @staticmethod
    def deserialize(source):
        return eval(source.replace("#", "()").replace("(", "Node("))

if __name__ == "__main__":
    root = Node(1, [Node(2, [Node(4)]), Node(3, [Node(5), Node(6)])])
    print repr(root)
    print root
    source = root.serialize()
    root2 = Node.deserialize(source)
    print repr(root2)
    print root2
    assert root == root2

This class has the nice feature, that eval(repr(root)) is a copy of root, so repr(root) is a serialization of root.

The output of repr(root) is a bit verbose, though:

Node(1,[Node(2,[Node(4,[])]),Node(3,[Node(5,[]),Node(6,[])])])

Therefore I defined a serialize function, which just gets rid of all the Nodes. The deserialize function just puts them back in and does an eval.

Note that I used a different tree here than you. Here would be your structure:

root = Node(0, [Node(1, [Node(3, [Node(), Node(), Node()]),
                         Node(4, [Node(), Node(), Node()]),
                         Node(5, [Node(), Node(), Node()])]),
                Node(2, [Node(6, [Node(), Node(), Node()]),
                         Node(7, [Node(), Node(), Node()]),
                         Node(8, [Node(), Node(), Node()])]),
                Node()])

Or, even better to visualize:

root = Node(0, [Node(1, [Node(3, [Node(),
                                  Node(),
                                  Node()]),
                         Node(4, [Node(),
                                  Node(),
                                  Node()]),
                         Node(5, [Node(),
                                  Node(),
                                  Node()])]),
                Node(2, [Node(6, [Node(),
                                  Node(),
                                  Node()]),
                         Node(7, [Node(),
                                  Node(),
                                  Node()]),
                         Node(8, [Node(),
                                  Node(),
                                  Node()])]),
                Node()])

Example:

>>> root.serialize()
'(0,[(1,[(3,[#,#,#]),(4,[#,#,#]),(5,[#,#,#])]),(2,[(6,[#,#,#]),(7,[#,#,#]),(8,[#,#,#])]),#])'

This could be cut down even further, but at this point it becomes a balance between the processing time needed to make this string smaller and the gain in memory from that.

With this function it could become:

def serialize2(self):
    replacements = [("Node", ""), ("()", "#"),
                    ("(", ""), (")", ""), (",[", "["), (",", "")]
    out = repr(self)
    for replacement in replacements:
        out = out.replace(*replacement)
    return out

>>> root.serialize2()
'0[1[3[###]4[###]5[###]]2[6[###]7[###]8[###]]#]'

But this becomes hard to parse back into the tree and would break the setup of using __repr__ and eval. It would be possible using some fancy regular expressions, though.


jQuery plugin to highlight text spans in various colors

The example you posted makes no use of inherited behaviour as far as I can tell, and can be implemented as the example below.

I think however that you are preparing for something that this example does not showcase, since you're asking about delegated implementations.
It's hard to tell what exactly you are aiming for though, so for now I'll just supply the simplification of your example.

;(function($, window, document, undefined) {
  "use strict";

  function show(elem, settings) {
    $(elem).css("color", settings.color);
  }

  function hide(elem, settings){
    $(elem).css("color", settings.normal);
  }

  var defaultSettings = {
      color: 'blue',
      normal: 'black'
  };

  function setHoverHandlers(elem, settings) {
    $(elem).hover(function() {
      show(elem, settings);
    }, function() {
      hide(elem, settings);
    });
  }

  $.fn.myPlugin = function(opts) {
    var elemSettings = $.extend({}, defaultSettings, opts);

    return this.each(function(id, elem) {
      $(elem).children('span').each(function(_, elem){
        setHoverHandlers(elem, elemSettings);
      });
    });
  };
}(jQuery, window, document));

As a side note, I generally discourage the use of Object.create, in favour of using plain data structures and functions working on them, or encapsulating state using closures. Crockford elaborates on it in this talk.

As another side note, it's funny that Crockford holds this talk, when he is in fact the single reason thatObject.create is in JavaScript in the first place. It was literally added to the standard after him nagging about it long enough.


Your code here is hard to follow because your code style and format are inconvenient.

Structures like this:

currentMap = mapByHashedId[hashedId];
if (currentMap) do {
    if (mapId[currentMap] == id)
        return mapPtr[currentMap];
    #ifdef __DEBUG__
    ++colls;
    #endif
} while ((currentMap = mapNext[currentMap]));

are .... irregular. a better format would be:

currentMap = mapByHashedId[hashedId];
while (currentMap)
{
    if (mapId[currentMap] == id)
        return mapPtr[currentMap];

    #ifdef __DEBUG__
    ++colls;
    #endif

    currentMap = mapNext[currentMap]
}

Additionally, this is the only loop in your method. All the other code are simple array and pointer manipulations. This method can only be slow because of three reasons:

it is called many, many times
the while loop iterates many many times
there's something else you're not showing.

Assuming the number of calls are appropriate, and you're not missing anything, the only alternative is that the while loop loops often. This indicates there are many collisions. Collisions happen for two reasons:

your MAP_HASH_SIZE is too small
your hashing function is irregular

I am going to go with both of those. In fact, I am going to guess that MAP_HASH_SIZE is something like 8192, or some other power of 2. The reason this is my (educated) guess, is that your hash function is vulnerable to inconsistencies.

Consider how you build your function, using two 32-bit values with the x value shifted and or'd with the y value. Let's also use some test data:

  x      y
---    ---
0x1    0x1
0x2    0x1
0x3    0x1
0x4    0x1

Now, in your function you would produce the ID by shifting the X, and the hash, by the modulo of the table size. Let's assume the table size is 32768 (a nice big value that should eliminate collisions, right)?

  x      y          id   hashedId
---    ---  ----------   --------
0x1    0x1  0x10000001        0x1
0x2    0x1  0x20000001        0x1
0x3    0x1  0x30000001        0x1
0x4    0x1  0x40000001        0x1

Because your MAP_HASH_SIZE is likely a power-of-2, the % MAP_HASH_SIZE is essentially the same as a bitmask of the low-order bits (or 0x7fff for size 32768)

If all your y values are similar, you will end up with many collisions in just a few buckets in the hash table.

For the hash function I would consider guaranteeing a minimum size (say 16 bits, or 64K), and then having a function which at least shifts some of the x value in to the range, and does an Xor....

hashedId = ((x << 7) ^ (y * 31)) % MAP_HASH_SIZE;

The above function will give you better distribution (perhaps not perfect) even if the hash size is a power of 2 > about 16 bits.


Python path-breaking script for use in R

Always throw things in main:

def main():
    # code

main()

It might seem pointless but it does help with preventing global pollution, which is good if you ever decide to add a function somewhere.

Using

x = sys.argv[1]

is acceptable for a trivial script, but it's not much harder to use docopt and implement a proper command-line parser:

"""
Name Of Program.

Usage: prog.py <pathname>
"""

import docopt

def main():
    args = docopt.docopt(__doc__)

    x = args["<pathname>"]

Trivial, but it gives you --help, error reporting and sane handling of bad input, nearly for free.

This can be simplified a little with pathlib:

parts = pathlib.PurePosixPath(args["<pathname>"]).parts

if len(parts) >= 2 and parts[0] == "/":
    parts = ("/" + parts[1],) + parts[2:]

You can actually use just pathlib.Path but it may assume a Windows format on Windows machines.

Your quoting:

parts = ["'" + i + "'" for i in parts]

should be done with repr:

parts = map(repr, parts)

and the formatting should use .format:

res = "file.path({})".format(",\n    ".join(parts))

This gives

#!/usr/bin/env python3

"""
Name Of Program.

Usage: prog.py <pathname>
"""

import docopt
import pathlib

def main():
    args = docopt.docopt(__doc__)
    parts = pathlib.PurePosixPath(args["<pathname>"]).parts

    if len(parts) >= 2 and parts[0] == "/":
        parts = ("/" + parts[1],) + parts[2:]

    args = ",\n    ".join(map(repr, parts))
    print("file.path({})".format(args))

main()

Technically PEP 8 says docopt should be separated from pathlib, the second being in the stdlib, but it looks nicer this way for now.


Is there better way of writing these IF checks?

Maybe a switch?  Although whether it's shorter or more efficient or even easier to read up for debate.

string actionString = GetStatusMessage(auditAction);

// ...
function GetStatusMessage(DSRHelper.SaveStatusEnum status)
{
   switch(status)
   {
      case DSRHelper.SaveStatusEnum.Save:
           return Properties.Resources.SAVE_ACTION_MESSAGE;
      case DSRHelper.SaveStatusEnum.Complete:
           return model.Dirty ? "Save'NComplete" : "OnlyComplete.";
      default:
           return string.Empty;
   }
}


Why don't you use the classes provided in java.util.concurrent that can handle these requirements? Or is this written for practice?

There is still problem if you don't synchronize, because the ArrayList.add() method is not thread-safe thus it can happen that two threads trying to add a new job into the queue nearly the same instant (to the same slot in the array), then it is possible that the one adding later will overwrite the job added by the first thread.

Using normal boolean does not guarantee, that if one thread writes the value, and another accesses immediately after that then it will see the new value. You can use volatile with boolean as well, as in mentioned in the answer you linked. See an explanation for volatile

Or refer to Java Concurrency in Practice, pretty good book.


Is there a more semantic way to markup Price Lists? Example as Table and as Description List

I'd say stick with the table.

Yes, tables are frowned upon - if you use them for purely visual purposes. But this isn't "just" layout; it's information structure. And these are tabular data sets so semantically speaking tables are the right choice. There's nothing hacky about it; the table element was made for this sort of thing.

Meanwhile, dls are for terms and their definition(s). Semantically speaking, is an item defined by its cost? Eh, not quite. Of course this is a rather pedantic interpretation I'm applying, and a dl solution wouldn't be completely crazy, but still.

Flexibility is another issue: If an item only has name and cost, sure, a list will work. But what if that's not all? What if you need to add a column for the number of units ordered/in stock/shipped/whatever. Or an SKU column? Or anything else, really?

Yes, you can have multiple dd elements following a dt but you'll have to do all the layout yourself for n "pseudo-columns" of unknown content, whereas a table just works it out for you including resizing itself, wrapping text where necessary and all that. Again: It's made for this.

Think of it this way: If it wasn't a web page, and you just had to make a document, wouldn't you use a spreadsheet, or at least use table in a word processor? If yes, use a table in on the webpage too.

Other stuff:

I'd add a thead element with th elements for column headers, and wrap the rest in a tbody
I'd probably use a span for the total cost instead of strong. Give the span a class like cost or amount or total for styling purposes. I'm assuming you just want the price to stand out visually, but using a strong is a bit, well, strong. A span, meanwhile, doesn't imply much at all about its content. Even a good ol' b tag could be used here. b simply says "this text is bold" without implying why it's bold - which is why you don't often see the b tag anymore: no semantic purpose. But that's kinda what you want here; just some bold text for visual purposes.


Splitting the coordinates of the world into equal blocks

Here are three ways your code could be made more pythonic (which I consider to be more readable):

Use python keyword expansion:

Python allows the expansion of a dict object when calling a function.  This means we can change:

def getCoordinate(Country, interval):
    ne_lng = Country['ne_lng']
    ne_lat = Country['ne_lat']
    sw_lng = Country['sw_lng']
    sw_lat = Country['sw_lat']

To this:

def get_coordinate(ne_lng, ne_lat, sw_lng, sw_lat, interval):

if we call it like:

get_coordinate(interval=100, **Country)

Use list comprehension to remove loop boilerplate:

This:

i = 0
temp = ne_lng
lngList = []
n = int((ne_lng - sw_lng)/interval)+1
for _ in range(n):
    i += 1
    lngList.append(temp)
    temp -= (ne_lng - sw_lng) / n
i = 0
temp = ne_lat
latList = []
n = int((ne_lng - sw_lng)/interval)+1
for _ in range(n):
    i += 1
    latList.append(temp)
    temp -= (ne_lat - sw_lat) / n

becomes:

n = 1 + int((ne_lng - sw_lng) / interval)
lng_list = [
    ne_lng - (ne_lng - sw_lng) * i / n for i in range(n)]

n = 1 + int((ne_lng - sw_lng) / interval)
lat_list = [
    ne_lat - (ne_lat - sw_lat) * i / n for i in range(n)]

Build the output format while iterating:

This code takes the product of two lists and builds a list of lists of the results.  It then iterates through that list to generate a list of dicts.

for ki, vi in enumerate(lngList):
    for kj, vj in enumerate(latList):
        if ki == n-1 or kj == n-1:
            pass
        else:
            coordinate.append([vi, vj, lngList[ki+1], latList[kj+1]])
newList = []
for host in coordinate:
    newDict = {
        'ne_lng': host[0],
        'ne_lat': host[1],
        'sw_lng': host[2],
        'sw_lat': host[3],
        "interval": interval
    }
    # print posts.insert(newDict)
    newList.append(newDict)
return newList

But it is easy to build the dict during the first loop, which will elimnate one entire loop. In addition, the result list can be produced with a list comprehension, which gives:

return [
    {
        'ne_lng': vi,
        'ne_lat': vj,
        'sw_lng': lng_list[ki + 1],
        'sw_lat': lat_list[kj + 1],
        "interval": interval,
    }
    for ki, vi in enumerate(lng_list[:-1])
    for kj, vj in enumerate(lat_list[:-1])
]

Note:

I imagine the second line of:

n = 1 + int((ne_lng - sw_lng) / interval)

is a bug since at that point a lat is going to be calculated.

Code:

For completeness here is the entire code I ended up with:

def get_coordinate(ne_lng, ne_lat, sw_lng, sw_lat, interval):
    interval = float(interval)

    n = 1 + int((ne_lng - sw_lng) / interval)
    lng_list = [
        ne_lng - (ne_lng - sw_lng) * i / n for i in range(n)]

    n = 1 + int((ne_lng - sw_lng) / interval)
    lat_list = [
        ne_lat - (ne_lat - sw_lat) * i / n for i in range(n)]

    return [
        {
            'ne_lng': vi,
            'ne_lat': vj,
            'sw_lng': lng_list[ki + 1],
            'sw_lat': lat_list[kj + 1],
            "interval": interval,
        }
        for ki, vi in enumerate(lng_list[:-1])
        for kj, vj in enumerate(lat_list[:-1])
    ]

Country = {
    'ne_lat': 89.000000,
    'ne_lng': 179.000000,
    'sw_lat': -89.000000,
    'sw_lng': -179.000000
}

new_data = get_coordinate(interval=100, **Country)
old_data = getCoordinateOrig(Country, 100)
assert new_data == old_data


Monte-Carlo method to check triangle inequality

The problem of your code is the way you generate triangles. You just create three independent random numbers. In theory, you could always end up rolling numbers that don't end up in a valid triangle and thus your code would not even terminate. That is, because triangle side lengths are dependent.

To always create a valid triangle, you can instead roll two angles and one side and then use the law of sines to calculate the remaining sides.

The sum of angles in a triangle is 180 degrees (or pi radians). So the first angle alpha is randomly selected between (0, pi), the second angle beta is then between (0, pi-alpha) and the third angle gamma is gained by simple arithmetics: gamma = pi - alpha - beta

Or in code:

alpha = random.uniform(0, math.pi)
beta  = random.uniform(0, math.pi - alpha)
gamma = math.pi - alpha - beta

If we know two sides and the angle in between, we can easily calculate the area. Since your inequality uses twice the area, we can drop the factor of 0.5.

double_area = side_b * side_c * sin_alpha

Some micro-optimisations: math.sin is an expensive function (time-wise), so we save the result in a variable. Same goes for floating point division. Multiplication is faster, so once again, we save the result to use multiplication later on.

Lastly: Since you already know how often you want to execute the loop, you can use a for-loop instead of a while-loop although frankly, I don't know how well this goes in terms of memory consumption.

import math
import random
import time

max_side_length = 100000000
n_max_tries     = 10000000
n_successes     = 0

time_start      = time.time()

for k in range(n_max_tries):
    alpha                   = random.uniform(0, math.pi)
    beta                    = random.uniform(0, math.pi - alpha)
    gamma                   = math.pi - alpha - beta

    side_a                  = random.randint(1, max_side_length)
    sin_alpha               = math.sin(alpha)
    side_a_over_sin_alpha   = side_a / sin_alpha

    side_b                  = side_a_over_sin_alpha * math.sin(beta)
    side_c                  = side_a_over_sin_alpha * math.sin(gamma)

    double_area             = side_b * side_c * sin_alpha

    if side_a * side_b * side_c > double_area:
        n_successes += 1

time_end = time.time()

print("successes: ", n_successes, " / ", n_max_tries, " (", n_successes/n_max_tries, ")")
print("time: ", time_end-time_start)

I didn't do excessive timings because I couldn't be bothered, but this code runs on my machine in about 37.8s, while three runs of your code averaged on 109.8s, resulting in an optimistic speed-up factor of around 3.

Disclaimer: I can somewhat write in python but I'm probably violating this famous pep-8. Yet, I strongly encourage you to give reasonable names to your variables as it makes the code more easy to understand. Not only for others, but also for yourself, when you look at it 2 weeks later.


The general idea is to use library code, particularly to eliminate explicit recursion, and inline things used only once.

MaybeT abstracts computations that can fail and abort at some point, and allows you to bind into pattern matches that fail the computation if they don't match.

desperately abstracts retrying them until they work, using MaybeTs Alternative instance.

StateT abstracts computations that carry around a piece of state to read and write to.

forever defeats the need for loop to manually loop.

Contrary to that comment, abstraction is kinda Haskell's thing.

import System.Exit (exitSuccess)
import Control.Monad.State
import Control.Monad.Trans.Maybe
import Safe (fromJustNote)

type TodoList = [String]

main :: IO ()
main = do
    putStrLn "TODO-LIST\n"
    (`evalStateT` []) $ forever $ do
        say "----------------------------"
        say "You have to do these things:"
        say ∘ unlines ∘ zipWith (\i e -> show i ++ ": " ++ show e) ([0..] :: [Integer]) =<< get
        input <- desperately $ do
            say "Select an action"
            say ∘ unlines $ map (\(char, desc, _) -> char : ") " ++ desc) options
            [c] <- hear
            return c
        case find (\(c, _, _) -> c == input) options of
            Just (_, _, action) -> action
            _ -> say "action not found"

desperately :: Monad m => MaybeT m a -> m a
desperately = fmap (fromJustNote "desperately") . runMaybeT . asum . repeat

say = liftIO . putStrLn
hear = liftIO getLine

To bring main's last lines closer in method with the rest of your code, you could do Just (_, _, action) <- find (\(c, _, _) -> c == input) options and put another desperately to the right of forever. (Or runMaybeT, because the forever repeats everything anyway, but that's kinda incidental.)

When you implement a transformation of a simple partial algorithm into a safe one, chances are safe's already got something, here splitAtExactMay.

(,,) in its prefix form allows me to not close each option with a multi-line closing bracket, and shuddup indentation blocks split code into units just as well as names do, and then you don't need to choose names for everything. Each option even already lists a description of what it does!

import Safe.Exact (splitAtExactMay) -- goes at the top of the file, but relevant here

options :: [(Char, String, StateT TodoList IO ())]
options =
    [ (,,) 'c' "create new item" $ do
        say "enter a description of the new item:"
        hear >>= modify . (:)
    , (,,) 'd' "delete item" $ desperately $ do
        say "enter the number of the item you want to delete"
        Just n <- readMaybe <$> hear
        Just (before, _ : after) <- gets $ splitAtExactMay n
        put $ before ++ after
    , (,,) 'x' "delete everything" $ put []
    , (,,) 'l' "load file" $ desperately $ do
        say "enter the file you want to load"
        line <- hear
        Right file <- liftIO $ tryIOError $ openFile line ReadMode
        liftIO $ hSetEncoding file utf8
        Right content <- liftIO $ tryIOError $ hGetContents file
        modify (++ lines content)
    , (,,) 's' "save to file" $ desperately $ do
        say "enter the filename to save your todolist. The file will be overwritten."
        line <- hear
        Right file <- liftIO $ tryIOError $ openFile line WriteMode
        liftIO $ hSetEncoding file utf8
        result <- liftIO . tryIOError . hPutStr file . unlines =<< get
        case result of
            Left _  -> say "couldn't write to file"
            Right _ -> liftIO $ hClose file
    , (,,) 'q' "quit" exitSuccess
    ]


Just based on the code, and in no particular order:

Bikeshedding: as Dice represents a single die, I would call it such.
You're passing Dice by reference to const everywhere.  In your current design it is just an int, and I don't see anything happening that would increase the cost of passing it significantly, or cause it to become non-copyable.  As per Optimizing Emergent Structures in C++ you should prefer to pass by value here.
Your rd, gen, and dis should all be in an anonymous namespace to prevent linker errors when people define things of the same name in other files.
Does equality and inequality really make sense here?  It bothers me that x == y is not preserved after x.roll(); y.roll();.  I think I'd stick to accessing value explicitly, and not allow equality on Dice.

As for design: the implicit sharing of state between dice bothers me.  It isn't detectable as-is, but it means that there is no way of specifying that a particular die will return particular results (for debugging).  If this is used in a multithread application, the results of roll may be surprising; I'm fairly sure uniform_int_distribution<>::operator() should not be called from multiple threads at once.

I think I'd go for the more explicit approach of having an updateRandom and getRandom pair, or ensure thread-safety of roll.

You could also make this more generic:

// die.hpp
extern std::random_device rd;
extern std::mt19937 gen;

template<typename T>
struct Die {
    T value() const {
        return topValue;
    }

    void roll() {
        topValue = dis(gen);
    }

private:
    T topValue;
    static std::uniform_int_distribution<T> dis;
};

template<typename T>
std::uniform_int_distribution<T> Die<T>::dis(1, 6);

// die.cpp
std::random_device rd;
std::mt19937 gen(rd());

However, this would have the obvious drawback of the implementation being exposed.


Naming

First of, what you have created is not an iterator so naming it as such is misleading. I would recommend a name but I actually think that you should redesign your class and the name I would recommend wouldn't be fit for the redesigned class so I'll wait with that until the end.

Design

In C++ as opposed to Java, when you assign an object you get a copy of the object which can be slow and it occupies extra memory for the copy.

I believe that there are two ways that you can improve this design:

Design a proper iterator that fulfills the contract of being an Iterator. It takes some doing but when you're done you it will not copy the contents and will be generally usable. One pitfall is how to define the end of the iterator.
Design a "view" over an existing container. This may or may not be more convenient depending on the use case.

The two ideas are kind of related but different concepts. You can store a view as a member and it makes sense but storing an iterator as a member is kind of dubious. Depending on your use case either a view or iterator is better, for this particular case I have a feeling that an iterator is better.

Implementation sketch as an iterator

Here I'll outline a start of an implementation of a random iterator and add a utility function in_random_order which provides nice syntactic sugar for use in range based for loops. I guess you could think of in_random_order as a poor-man's temporary view. Anyway here we go:

template<typename It>
class random_iterator{
    using it_traits = std::iterator_traits<It>;
public:
    // You must always provide these for all iterators
    // or explicitly specialise std::iterator_traits
    // for your iterator. It's easier to just provide them here.
    using iterator_category = it_traits::iterator_category;
    using value_type = it_traits::value_type;
    using difference_type = it_traits::difference_type;
    using pointer = it_traits::pointer;
    using reference = it_traits::reference;

    // This stores one iterator to each iterator position in the original
    // container. Any modification of the original container invalidates
    // this iterator. We could use an LCG to avoid the linear memory.
    random_iterator(It first, It last){
        while(first != last){
            its.emplace_back(first);
            ++first;
        }
        // Shuffle the its vector.
    }

    random_iterator& operator ++(){
        ++it;
        return *this;
    }

    // Depending on if you want an input iterator, forward iterator,
    // bidirectional or random access iterator you need to implement
    // various methods here. Check the concepts page linked earlier
    // for what you must provide.

    reference operator *(){
        return *(*it); // First de-ref gets original iterator
    }

private:
    std::vector<It> its;
    std::vector<It>::iterator it;
};

template<typename Iterator>
class random_order{
public:
    in_random_order(Iterator f, Iterator l){
        first = f;
        last = l;
    }

    random_iterator<Iterator> begin(){
        return random_iterator(first, last);
    }

    random_iterator<Iterator> end(){
        return random_iterator(); // Figure out how to properly make end
    }

private:
    Iterator first;
    Iterator last;
};

// These functions are necessary because template argument deduction is not
// done for class templates. This is the final piece of the puzzle
// that enables the syntax below.
template<typename Container>
random_order in_random_order(Container& c){
    return random_order<Container::iterator>(c.begin(), c.end());
}

template<typename Iterator>
random_order in_random_order(Iterator first, Iterator last){
    return random_order<Container::iterator>(first, last);
}

When the above is properly implemented you should be able to do:

std::vector<X> data;

for(auto& value : in_random_order(data)){
    // stuff
}

// Or just a range:
for(auto& value : in_random_order(data.begin() + 10, data.begin() + 20)){
    // stuff
}

Note that for range based for to work, the object to be iterated over must provide member methods begin and end; or there must exist specialisations of std::begin and std::end for the object that is being iterated over.

This is why we invent the random_order class, it basically just provides the necessary boilerplate to make the fancy syntax possible in the for loop.

In fact, if you implement different types of iterators like for example filtering iterators and suitable iterables like filter which provide the requisite begin/end methods, you can do all manners of fun stuff by nesting iterators types like for example:

for(auto& : in_random_order(filter(data,
                [](const X& x) { return x.isHappy();})) {

Although you can do the same with views I'd think the syntax is a bit more cumbersome.

Note: The above code uses a vector of indexes which is undesirable for an iterator. Iterators should ideally be a lightweight objects and are often assumed to be, for example they are often passed by value. This makes code that uses the random iterator slightly inefficient. This is worth keeping in mind or looking for a solution that doesn't need a lot of memory like this implementation does.


A better way to convert an SQLObject instance into a dict

def sqlobject_to_dict(obj):
    obj_dict = {}
    cls_name = type(obj)

That's not a name, its a class object

    has_props = False
    for attr in vars(cls_name):
        attr_parent = type(getattr(obj, attr)).__bases__[0]

You have getattr(obj, attr) over and over and over. Do it once, and store it in a local variable

        if isinstance(getattr(cls_name, attr), property):
            has_props = True
            if isinstance(getattr(obj, attr), Decimal):
                obj_dict[attr] = float(getattr(obj, attr))
            elif isinstance(getattr(obj, attr), list):
                dict_list = []
                for list_item in getattr(obj, attr):
                    dict_list.append(sqlobject_to_dict(list_item))
                obj_dict[attr] = dict_list

I recommend doing obj_dict[attr] = map(sql_object_dict, getattr(obj, attr))

            elif isinstance(getattr(obj, attr), dict):
                dict_dict = {}
                for key, val in getattr(obj, attr):

Don't you need .items()?
                        dict_dict[key] = sqlobject_to_dict(val)
                    obj_dict[attr] = dict_dict

I'd do obj_dict[attr] = dict( (key, sql_object_to_dict(value)) for key, value in getattr(obj, attr) )
                elif attr_parent == SQLObject:

Why did you fetch attr_parent instead of using isinstance?

                obj_dict[attr] = sqlobject_to_dict(getattr(obj, attr))
            else:
                obj_dict[attr] = getattr(obj, attr)

Is a default really a good idea? There may some sort of attribute with isn't valid JSON that makes it through.

        elif not has_props and attr_parent != SQLObject:

            if "_get_" in attr:
                attr_name = '_'.join(attr.split('_', 3)[3:])

Thats a confusing way to do that. I'm sure what exactly the form you are trying to match here is,  but I think this is a use case for regular expressions.

                if hasattr(obj, attr_name):
                    obj_dict[attr_name] = getattr(obj, attr_name)

So I'm guessing you've got various _get_foo() functions which are invoked by some sort of __getattr__ magic. You stop checking for this once you find a property. (Probably newer objects use properties instead.) I would consider not doing the has_props thing. It makes your code less clear, and probably doesn't make much difference performance wise.

    return obj_dict


Simple mathematical operations (add, sub, mul, div) in C++11 template

When passing around move references, the recommended is to forward the parameters to ensure that the move reference is preserved:

template <typename T, typename ... Types>
auto add(T&& first, Types&& ... rest)
    -> decltype(first + add(std::forward<Types>(rest)...))
{
    return first + add(std::forward<Types>(rest)...);
}

Note that you have to explicitly provide the template type to std::forward(). It would deduce the wrong type otherwise.


Alternative to starting enum values with a number

public enum Hertz{
    none = 0,
    Hz= 1,
    KHz = 1000,
    MHz = 1000000,
    GHz = 1000000000
}

public static class Frequency{
    public static int Hz(this int frequency){
        return frequency;
    }

    public static int KHz(this int frequency) {
        return  frequency * (int)Hertz.KHz;
    }

}

client code:

int freq = 10.Hz();
int faster = 10.KHz();
int thousandsOfGigahertz = 234.KHz().GHz();


Deleting object properties if they are not found in another object. (javascript)

Bugs and Problems

There are a few problems with your code

Crash when o1 references null.

Reason typeof null === "object" is true.

null is an object when inspected with typeof however Object.keys(null) will throw the error "Can not convert null to Object" so if you have any properties that are null your code will throw an error.
Crash when both objects have similar cyclic references.

Many objects have references to themselves (are cyclic). Your code does not check if there is a cyclic reference and will continue to recurse until the call stack overflows (which is a thrown error)

General

Always aim to keep the code complexity as low as possible.

The variable goDeeper is not needed. You can return true where you set it to false
I do not see why you would need the keys sorted. Sorts are expensive operations, you should always ask yourself "Do I need to sort?" before using it.
The function deepSameKeys will always return true so why return a value at all?
It is unclear if you want to remove undefined properties, or all properties that evaluate to undefined. As you have it you remove all that evaluate to undefined.

I.E. the object {a: undefined} contains a property named a while {} does not contain the property a yet both will evaluate a as undefined.

You can use the in operator which will eval to true for the first object and false for the second. Note this also checks the prototype chain so you may want to use Object.hasOwnProperty if this will be an issue
The naming is very poor, not indecipherable but could be a lot better.
When using recursive functions you should try to avoid using iterators that use anonymous functions EG Array.every

Most recursive functions are just an alternative way to implement a stack to hold the current item's state as you search deeper.

This state is held in the function context (variables scoped to the function)
and stored on the JS heap.

Defining a function inside that context means that a second copy of the state is created as a closure, and also another context for the anonymous function.

The additional state per item is a lot of unneeded overhead (and halves the max depth of recursion).

If you use a for, while, or do loop you avoid the overhead .

Solutions

Bug 1 the solution is to change the lines...

 const t1 = typeof v1;
 return t1 === "object" && goDeeper ? deepSameKeys(v1, v2) : true;

...to include a check for null and have the variable store a bool.

 const isObject = v1 !== null && typeof v1 === "object";
 return isObject ? deepSameKeys(v1, v2) : true;

Note I have removed goDeeper

Bug 2 There are a few options here.

If the objects are parsed directly from JSON files then they can not be cyclic and the is no danger of error. This can also be an unenforced condition of the call (no cyclic object) and let the caller deal with the error is the breach the condition.
Limit the recursion depth. JavaScript's Array.map function uses this method to protect against cyclic references and simply counts the depth down per call and the up on exit. It will not go deeper is this count is <= 0
Track objects recursed using a Set. On each call check if the current object is in the Set, if it is return, if not then put it into the set and process the object.

Rewrite

I am assuming you only want to delete missing properties not properties referencing undefined and the return is not needed.

There are a few versions. After the first I have reduced the variable name lengths to keep the code compact for CR snippet container.

Delete undefined properties in reference from dirty. DOES not remove if property references undefined.
Function returns undefined
Using Object.entries to get at the key and value at the same time.

Keeping the same (almost) behavior and cyclic bug.

const removeMissingProps = (dirty, reference) => {
    Object.entries(dirty).forEach(([key, val]) => {
        if (key in reference) {
            val !== null && typeof val === "object" && removeMissingProps(val, reference[key]);
        } else { delete dirty[key] }
        return true;
    });
};

To provide a deeper call stack and avoid double state capture.  Using for loop.

function remProps(dirty, ref) {
    for (const [key, val] of Object.entries(dirty)) {
        if (key in ref) {
            val !== null && typeof val === "object" && remProps(val, ref[key]);
        } else { delete dirty[key] }
    }
};

To protect against call stack overflow by depth count

function remProps(dirty, ref, depth = 10) {
    if (depth > 0) {
        for (const [k, v] of Object.entries(dirty)) {
            if (k in ref) {
                v !== null && typeof v === "object" && remProps(v, ref[k], depth - 1);
            } else { delete dirty[k] }
        }
    }
};

Uses a WeakSet to check for repeated references.

function remProps(dirty, ref) {
    const checked = new WeakSet();
    remProps(dirty, ref);
    function remProps(dirty, ref) {
        if (!checked.has(dirty)) {
            checked.add(dirty);
            for (const [k, v] of Object.entries(dirty)) {
                if (k in ref) {
                    v !== null && typeof v === "object" && remProps(v, ref[k]);
                } else { delete dirty[k] }
            }
        }
    };
};

Update I forgot to add the last one.

Almost all the recursion functions I see are just implementations of stacks. Recursion has two drawbacks, small stack size (limited to the size of the call stack) and the needless capture of unrelated state.

The following example uses an array rather than the call stack. Its behavior is slightly different (more intuitive) from the function above if you have cyclic references.

There can be significant performance gains using stacks.

function remProps(dirty, ref) {
    const push = (v, ref) => !chk.has(v) && (chk.add(v), stack.push([v, ref]));
    const stack = [[dirty, ref]], chk = new WeakSet([dirty]);
    while (stack.length) {
        [dirty, ref] = stack.pop();
        for (const [k, v] of Object.entries(dirty)) {
            k in ref ?
                v !== null && typeof v === "object" && push(v, ref[k]):
                delete dirty[k];
        }
    }
}


Sorting strings in a one dimensional array

How about the simple process of converting the chars to separate strings, sorting the Strings, then copying the results back to an array?

It would look something like:

String source = new String(input);
String[] values = new String[input.length / blocksize];
for (int i = 0; i < values.length; i++) {
    values[i] = source.substring(i * blocksize, (i + 1) * blocksize);
}
Arrays.sort(values);
char[] result = new char[values.length * blocksize];
for (int i = 0; i < values.length; i++) {
    System.arraycopy(values[i].toCharArray(), 0, result, i* blocksize, blocksize);
}
return result;


I noticed that you have a spot for controllers, but then in your directive you declare a function for the Controller Attribute instead of using a controller that you have already at your disposal from the controller's section.

I would think that you would want to be able to reuse that function that controls tab selection, you should create a controller for that so that you can reuse it on several pages, rather than write from scratch every time you create a page with Panel tabs.


Make PdfPTable a property of the class and set it in the constructor.


As a long-term Java programmer, I know that most of my time will be spent in maintenance.
On that basis I prefer simple code that expresses its purpose clearly to clever, concise, unclear code.
With that context in place here's some basic comments.
 String a="a", b="b", c="c", d="d";

It's not the Java way to do multiple declarations together - I'd
split these.

They are constants not variables, so they should be "static final" (and UPPERCASE).

Three of them are not used, so delete them.
System.out.println(shc.isGapLessHierarchy("a", b, "", "") );

Why do you mix use of a constant and a literal? As a maintenance
programmer looking at your code I'm now wondering whether this has
some significance.

Now to your "isGapLessHierarchy()" method:

The method has no dependency on an object, so it should be "static"
Never call anything "args" (other than perhaps the arguments to a main method). Give your method parameters meaningful names. How about "hierarchyElements" in this case?
(Almost) Never use 'i' and 'j' as indexes. Use something meaningful.
Going forwards through a list is (IMHO) clearer than going backwards. Your condition can be expressed as "a gap should never be followed by a non-gap", which allows us to go forwards.

Here's my code using your pattern, with some cleanup and adding a more extensive set of tests (I couldn't be bothered with Junit in this case, but you probably should).
  public class HierarchyCheck {

  public static void main(String[] args) {
    String[][] testCases = new String[][]{
      new String[]{"Name", "Street", "City", "County", "State", "Country"},
      new String[]{"Name", "Street", "City", "County", "State", ""},
      new String[]{"Name", "Street", "City", "County", "", "Country"},
      new String[]{"Name", "Street", "", "County", "State", "Country"},
      new String[]{"Name", "", "City", "", "State", "Country"},
      new String[]{"Name", "", "", "", "", ""}
    };

    for (String[] testCase : testCases) {
      System.out.format("%s %s gapLess%n",
                        Arrays.toString(testCase),
                        isGapLessHierarchy(testCase) ? "is" : "is not");
    }
  }

  private static boolean isGapLessHierarchy(String... hierarchyElements) {

    // Find the first gap
    int firstGap = 0;
    for (firstGap = 0; firstGap < hierarchyElements.length; firstGap++) {
      if (isBlank(hierarchyElements[firstGap])) {
        break;
      }
    }

    // Is there a non-gap after the first gap?
    for (int nonGap = firstGap + 1; nonGap < hierarchyElements.length; nonGap++) {
      if (!isBlank(hierarchyElements[nonGap])) {
        // There is, so it's not gapless
        return false;
      }
    }

    // Definitely gapless
    return true;
  }

  // We don't have Java 11 for the String.isBlank() method, so fake it!
  private static boolean isBlank(String string) {
    return (string == null) || (string.trim().length() == 0);
  }
}

However, I'd probably have gone for a simpler, arguably cruder approach.
  private static boolean isGapLessHierarchy(String... hierarchyElements) {

    boolean seenGap = false;

    for (String hierarchyElement : hierarchyElements) {
      if (isBlank(hierarchyElement)) {
        seenGap = true;
      }
      else {
        if (seenGap) { // gap followed by non-gap
          return false;
        }
      }
    }

    // Definitely gapless
    return true;
  }


It would be more intuitive if your validate_all method was just called validate.

In quite a few places you are doing something like this in validate_length:

def validate_length(self):  # Check the length, gotta be over 8
    if len(self.password) > 8:
        return True
    else:
        return False

Just return the right value right away:

def validate_length(self):  # Check the length, gotta be over 8
    return len(self.password) > 8

It would also make more sense if the Validator.validate method just returned True or False instead of setting a class variable and returning a string detailing the status:

def validate(self, password):
    return all(validator(password) for validator in [self.validate_length, self.validate_upper_case, ...])

I would also make failing a testcase raise an exception and catch it in validate:

class ValidatorError(Exception):
    pass
...

class PasswordValidator(object):
    def __init__(self):
        self.validators = [self.validate_length, self.validate_upper_case, ...]

    ...

    def validate_length(self, password):
        """Check the length, gotta be over 8"""
        if len(password) > 8:
            return True
        raise ValidatorError("Failed length validation. Allowed length: (> 8)")

    def validate(self, password):
        try:
            return all(validator(password) for validator in self.validators)
        except ValidatorError as e:
            print e
            return False

...
if __name__ == '__main__':
    pass_verify = obtain_password()
    val = PasswordValidator()
    if not val.validate(pass_verify):
        print "Password not validated."
    else:
        print second_authentication(pass_verify)

Also your encrypt function seems to be one-way. There is no way to validate an entered password in the future (to see whether the entered password is equal to the password set by this program).


Measuring the distance between NumPy matrixes

(This is already implemented as
scipy.spatial.distance.cdist.
I'm going to assume that it's more optimised too.)

Why initialise MatrixDistances to zero if you're only going to
delete the first column regardless?  A matrix can also have zero for
any dimension.

Some more general observations:

As always, take a look at
PEP8 for Python
conventions, in particular naming of functions and variables, but also
missing whitespace.
The imports could be more consistent; the import spatial isn't being
used.
A zero matrix should probably be allocated with numpy.matlib.zeros
since it's shorter.
In Python 2 use xrange if you don't need the full list; also use the
function form of print for compatibility with Python 3 (it's also
more consistent to use it this way).
The repeated vstack may not be the most efficient option, but you
should consult a profiler for that.

When keeping the naming it should still rather look like this maybe.

import random
import numpy as np
import numpy.matlib
import scipy
import scipy.spatial

P, V = 5, 5

def CalculateMatrixDistances(MatRows, MatColums):
    numberRows = MatRows.shape[0]
    numberColumns = MatColums.shape[0]
    MatrixDistances = np.matlib.zeros((0, 5))
    for r in xrange(numberRows):
        d = [scipy.spatial.distance.euclidean(MatRows[r], MatColums[c]) for c in xrange(numberColumns)]
        MatrixDistances = np.vstack([MatrixDistances, d])
    return MatrixDistances

PositionP = np.random.rand(P, 2)
PositionV = np.random.rand(V, 2)

MatrixDistancesVP = CalculateMatrixDistances(PositionV, PositionP)

print(PositionP)
print(PositionV)
print(MatrixDistancesVP)
print(scipy.spatial.distance.cdist(PositionV, PositionP))


Ensuring HttpClient can be used safely as a singleton

Just a few things:

You have already named the variable _oneMinuteInSeconds - I'd say you don't gain much by initializing it via a TimeSpan the way you do it. Just saying _oneMinuteInSeconds = 60 would be good enough since it's quite clear what the 60 stands for.
Actually, according to MSDN the ConnectionLeaseTimeout is set in milliseconds as such your code is of by a factor of 1000 regarding the timeout (why the framework designers have not consistently used TimeSpan everywhere is a bit of a mystery to me).


As Kid Diamond stated in a comment, your HTML has errors - 5 of them.  You can validate it by running it through the W3C validator.

First off, you need a DOCTYPE so browsers know which version of HTML you are using - the latest is simply <!DOCTYPE html>

Second, img elements need alt attributes so screen readers, search engines, and other computer programs can make sense of them:

<img src= "http://static.jsbin.com/images/jsbin_static.png" alt="image description">

Finally, you forgot to close one of your divs - the div around the img element.

Your CSS has no errors at the W3C CSS validator.


Two-dimensional array, modified one field at a time

A few things:

Someone's getting a head-start on Battleship, eh? :)
Don't modify native objects/prototypes. Array is the native JavaScript array constructor (a.k.a. "class"), and you're adding initialize and shoot methods to it. Don't.
Well, ok, you can extend native objects, but it's more hygienic to leave it alone. And in this case the methods you're adding are super-specific to your task, and not generic functionality, so that's a double "don't".
I'm pretty sure you have a bug: cInit isn't used for anything, but instead you have an previously undeclared (and therefor undefined) variable called initial. I'm guessing they were supposed to be one and the same.

Now, in terms of memory efficiency: Don't worry about it. JavaScript has automatic memory management and garbage collection, but it's buried deep in the runtime, so it's not something you can fiddle with. It also has dynamic typing, so it's kinda hard to even guess at memory consumption at times. For instance, the number 32 is 8 bytes long, since all numbers are 64-bit IEEE floating point values, yet 32 == "32" happens to be true due to dynamic typing/type-coercion. So the string "32" is for some purposes it's the same number, but it's probably only 2-3 bytes long. Maybe? I don't know. Because behind the scenes, all JS runtimes do a ton of voodoo, so in the end it's really hard to tell what's going on. Besides the runtime's own memory consumption is probably way beyond whatever data you're handling. The runtime might well trade memory for speed somewhere. And another runtime might do the opposite, but they'll both run your code the same.

Point is, memory just isn't a thing you really can worry about in JavaScript the same way you can worry about it in other languages. At least not on the same low level. Of course you can still run out of memory and things like that, but you'd have to try pretty hard. Especially with a simple little 2D array.

Aside: Don't bother with Hungarian notation either. Well, again, you can, but it's a lot of busywork when there's dynamic typing and type-coercion. You have parameters like iRows, which, yeah, should be an integer, but as mentioned all integers are just the Number type - which is really a float. And you could also pass in a numeric string and have it work. So it just gets confusing in a hurry.

Of course, you still want efficient data structures, but since the idea here is to construct a 2D array, well, you're probably best off using... a 2D array. So again, don't worry too much.

As for the code, you have the basics well in hand. As mentioned, you shouldn't be appending functions to the native Array constructor, but otherwise it's fine. Fixing that little thing you get:

function createArray(rows, columns, initialValue) {
  var array = [];
  for (var i = 0; i < rows; ++i) {
    var columns = [];
    for (var j = 0; j < columns; ++j) {
      columns[j] = initialValue;
    }
    array[i] = columns;
  }
  return array;
}

function shoot(row, column, array) {
  array[row][column] = "H";
  return array;
}

Still, I'd use push to append stuff to an array, rather than assigning things to an index.

But you said you might want a more OO-style implementation. However, sub-classing Array would be tricky. Especially as there are no "classes" in JavaScript, per se. It's easier to go with object composition; make your own constructor, and have your array be a property (aka member, aka instance variable) on the instances that constructor creates.

So let's make a Grid constructor and let's give it a shoot method:

function Grid(rows, columns) {
  var r, c, row;
  this.cells = []; // instance variable
  for(r = 0 ; r < rows ; r++) {
    row = [];
    for(c = 0 ; c < columns ; c++) {
      row.push("U");
    }
    this.cells.push(row);
  }
}

Grid.prototype.shoot = function (row, column) {
  this.cells[row][column] = "H";
};

Now, much like before, you can say:

var grid = new Grid(12, 12);
grid.shoot(5, 5);
grid.shoot(0, 4);

console.log(grid.cells); // notice you still have access to the "raw" array

Of course, you may want to do some bounds-checking in shoot to make sure the coordinates make sense, but otherwise... yeah, that's pretty much it.


nodeJS, fs, path - creating new directorties

There are util libraries for this:fs-extra.

From its doc:

  mkdirs(dir, callback) Creates a directory. If the parent hierarchy
  doesn't exist, it's created. Like mkdir -p.

  Alias: mkdirp()

  Sync: mkdirsSync() / mkdirpSync()

  Examples:

var fs = require('fs-extra')

fs.mkdirs('/tmp/some/long/path/that/prob/doesnt/exist', function (err) {
  if (err) return console.error(err)
  console.log("success!")
})

fs.mkdirsSync('/tmp/another/path')

If you write function as a promise it would enable other code to run between each step of your function (eg. between each subdir being created) so it will not block other code like sending some request after calling this function.


An idiomatic approach

  to implement this instead of basic arrays and raw pointers

is to use iterators.
Returning bool is dubious. The situation where I only want to know if the element is present or not is very rare. Typically I want to know where exactly the element is (or, if absent, where it should be inserted to keep the collection sorted). Your function does compute this information, but immediately throws it away. Return an iterator.
All that said, consider the signature

template<typename It, typename T>
It binary_search(It first, It last, const T& target)

It is now suspiciously similar to the standard library's std::lower_bound. Follow the link for further insight and inspiration.


A much simpler solution would be to use a lookup table.  A mapping implemented using a lookup table would be easier to understand, with no magic numbers.

Furthermore, phone numbers are more numeric strings than numbers, so I'd make it a char-to-char lookup.

Repeated string concatenation is bad for performance.  To compose a string, use a StringBuilder.

public class Keypad {
    private static final char[] DIGITS = (
                 // ABC     DEF
                   "222" + "333" +
        // GHI      JKL     MNO
          "444"  + "555" + "666" +
        // PQRS     TUV     WXYZ
          "7777" + "888" + "9999").toCharArray();

    public static String getNumbers(CharSequence s) {
        StringBuilder result = new StringBuilder(s.length());
        for (int i = 0; i < s.length(); i++) {
            char c = Character.toUpperCase(s.charAt(i));
            if ('A' <= c && c <= 'Z') {
                result.append(DIGITS[c - 'A']);
            }
        }
        return result.toString();
    }
}


As you figured out, moving a line requires two passes:

one to determine what  to move and where to move it to,
and another to re-write the file with the lines moved.

With some meta-programming you can add a method to the InputStream class that would allow you to move a line ahead of another using concise code like this:

def source = /line to move/
def dest = /line to recognize/

input.moveLine(source, dest).writeTo(writer)

The meta-programming

You can start with a Groovy Category that adds the method Writable moveLine(Object, Object) to a class, such as an InputStream.

@groovy.lang.Category(InputStream)
class MoveLineCategory {

    Writable moveLine(Object sourceMatcher, Object destinationMatcher) {
        def (sourceLine, lines) = this.readLines().inject([null, []]) {output, line ->
            switch(line) {
                case ~sourceMatcher:
                    if(!output[0]) output[0] = line
                    break
                case ~destinationMatcher:
                    output[1] << null
                    output[1] << line
                    break;
                default:
                    output[1] << line
            }

            return output
        }

        {Writer writer ->
            lines.each {line ->
                if(line == null) writer << "$sourceLine\n"
                else writer << "$line\n"
            }
        }.asWritable()
    }
}

The first pass is similar to your File.eachLine() loop except it's done with Collection.inject(). The inject() method Closure returns a List containing two items: the line which matched the sourceMatcher regular expression, and a List of the entire file with a null inserted as a place holder for the destination of the matched line.

The second pass is actually not executed right way. Instead, a Closure coerced into a Writable is returned for later use. The returned Writable contains the code needed to write out the changed file.

Using InputStream.moveLine()

With the Writable on hand, it's now possible to write the file with the line moved. But to even use the InputStream.moveLine() method the Category in which it's defined needs to be made available. the Object.use(Class) method does this.

def source = /line to move/
def dest = /line to recognize/

use(MoveLineCategory) {
    input.moveLine(source, dest).writeTo(writer)
}

Complete (self-contained) example

Here's the entire thing in action:

@groovy.lang.Category(InputStream)
class MoveLineCategory {

    Writable moveLine(Object sourceMatcher, Object destinationMatcher) {
        def (sourceLine, lines) = this.readLines().inject([null, []]) {output, line ->
            switch(line) {
                case ~sourceMatcher:
                    if(!output[0]) output[0] = line
                    break
                case ~destinationMatcher:
                    output[1] << null
                    output[1] << line
                    break;
                default:
                    output[1] << line
            }

            return output
        }

        {Writer writer ->
            lines.each {line ->
                if(line == null) writer << "$sourceLine\n"
                else writer << "$line\n"
            }
        }.asWritable()
    }
}

def input = ['''This is a line.
And this is another line.
And this is yet another line.
You guessed it, another line.'''] as StringBufferInputStream

def writer = new StringWriter()

use(MoveLineCategory) {
    input
        .moveLine(/And this is another line\./, /You guessed it, another line\./)
        .writeTo(writer)
}

assert writer.toString().split(/\n/) == [
    'This is a line.',
    'And this is yet another line.',
    'And this is another line.',
    'You guessed it, another line.'
]

Disclaimer

These examples were written with Groovy 2.4.4.


I would not refactor this substantially, except maybe to avoid the reuse of the matched1 and matched2 variables:

{
    boolean matched1 = false;
    boolean matched2 = false;
    for (...) {
        ...
    }
}

// and here again

Your intuition is correct that this could be done much cleaner using functional programming, but FP is a pain with Java 1–7. So we have the following options:

use Java 8
use functional language like Scala
ignore the pain, and do it anyway

The last solution does not involve java.util.concurrent.Callable, but an interface of our own:

interface TuningDataTest {
    boolean test(Product product, AlgoTuningData datum);
}

We can then write a function scoreTuningData:

private static class Score {
    final public int score1;
    final public int score2;

    public Score(int s1, int s2) {
        score1 = s1;
        score2 = s2;
    }

    public Score add(Score that) {
        return new Score(this.score1 + that.score1, this.score2 + that.score2);
    }
}

private Score scoreTuningData(Product p1, Product p2, Iterable<AlgoTuningData> data, TuningDataTest test) {
    boolean matched1 = false;
    boolean matched2 = false;
    int score1 = 0;
    int score2 = 0;

    for (AlgoTuningData datum : data) {
        if (!matched1 && test.test(p1, datum)) {
            matched1 = true;
            score1 += datum.getRank();
        }
        if (!matched2 && test.test(p2, datum)) {
            matched2 = true;
            score2 += datum.getRank();
        }
        if (matched1 && matched2) {
            break;
        }
    }

    return new Score(score1, score2);
}

Note that “data” is the plural form of “datum”, the word “datas” does not exist. One “datum” is a “record”, “data” are a set of records.

And your main code would then look like:

List<AlgoTuningData> topRatedData = ...;
List<AlgoTuningData> feedbackScoreData = ...;
Score score = scoreTuningData(p1, p2, topRatedData, new TuningDataTest() {
    @Override
    public boolean test(Product product, AlgoTuningData datum) {
        return product.getIsTopRated().equals(datum.getValue());
    }
}).add(scoreTuningData(p1, p2, feedbackScoreData, new TuningDataTest() {
    @Override
    public boolean test(Product product, AlgoTuningData datum) {
        return product.getPrice() <= datum.getMaxProductPrice();
    }
}));

int score1 = score.score1;
int score2 = score.score2;


Using the Return Value of a Function to Select an Element in a Struct Array

I think this comes pretty close. The use of arrayfun() or other *fun()-Operations is very often better than for loops.

Your code was not working out of the box. Thus, I created code, which is directly executable:

function minimalExample()
    target.x = 10;
    target.y = 5;

    source(1) = struct('x', 1, 'y', 3);
    source(2) = struct('x', 5, 'y', 15);

    [~, minIndex] = min(arrayfun(@(x) (myDistance(x, target)), source));

    minSource = source(minIndex);
    disp(minSource);

    function d = myDistance(source, target)
        d = (source.x - target.x)^2 + (source.y - target.y)^2;
        d = sqrt(d);
    end
end


Template to determine most frequent entries within a collection

Well, nice to see you follow stdlib conventions for your algorithm and accept an iterator-range.
But you really should use std::iterator_traits<It> to query the iterators associated types, as-is you cannot handle pointers.

Let's hope the elements are efficiently copied, or the algorithm is staggeringly inefficient.

Next, the count of unique symbols is often much smaller than k, making first inserting all elements, then sorting and finally removing most quite inefficient.
Consider limiting the result-vector to never grow beyond k elements using a heap.
(The standard provides std::make_heap (and for sorted output alsostd::sort_heap), but not down_heap (a vastly more efficient combination of std::pop_heap and std::push_heap, building-block of make_heap).)


String puzzle - operations with numbers inside of strings

The structure of your code looks quite good so far but you could improve readability:

Naming Conventions

As with almost every other programming language java has a schema of how to name identifiers that's common consensus You can read the details here:
 http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html

The main line is: classes start with an uppercase letter, method and variable names start with lower case letter. And if the name consists of multiple words use CamelCase.

variable declarations

You declared 2 variables ab the end of your class file. The  common consensus in Java is to write class (or object) scope variables at the top of the class file.

less comments ##

there should be 2 types of comments in your code:

Description of the contract of an interface method
this type  of comment should guide the implementer of that method and tell what the caller of the method expects, especially what the properties of the parameters and the result are like.
Explanations why the code is like it is
this should tell the reader why you chose a certain approach.

There should not be any other comment in your code.

Whenever you feel the need to write a comment try to find better identifier names first.

Especially comments like this are not needed instead they clutter the code:

 /**Get smallest perimeter to use in ribbon length calculation
     *
     * @param l length of present
     * @param w width of present
     * @param h heigth of present
     * @return smallest perimeter
     */
    private static int smallestPerimeter(int l,int w,int h){

Instead the code could be like this:

private static int getSmallestPerimeterToUseInRibbonLengthCalculation(int length, int width, int heigth){

You may argue that the name is to long and you're right: the method should only tell what it does and not restrict the possible callers, so it should better be:

private static int getSmallestPerimeter(int length, int width, int heigth){

And get is not correct since this method is not a getter in the sense that the content of an object (or class) variable is returned, it calculates the returned value and the name should reflect that:

private static int calculateSmallestPerimeter(int length, int width, int heigth){

You use comments to structure a method:

  //Definition of the three dimensions of the present.
        int l = Integer.parseInt(presentText[0]), w = Integer.parseInt(presentText[1]), h = Integer.parseInt(presentText[2]);

  //Definition of the area of the sides in the present.

In such cases you should better extract that code between the comments into separate methods or objects with names derived from the comments:

PresentDimensions.java

  class PresentDimensions{
    final int length, height, width;
    PresentDimensions(int length, int width, int height){
       this.length  =  length;
       this.width  =  width;
       this.height  =  height;
    }
    public int[] calculateSurfaceAreas(){
       return new int[]{length*width,width*height,height*length}
    }

in calcEachPresent

 PresentDimensions presentDimensions = new PresentDimensions(presentText[0], presentText[1], presentText[2]);
 int[] d = presentDimensions.calculateSurfaceAreas();