Converting Arabic numerals to Roman numerals

I wouldn't do an ArabicNumeral, too, as this is the default numeric system of java.

From a design view, I would see an object RomanNumeral, which is an aggregation of RomanLiteralobjects, this RomanLiteral, are the constant roman string->decimal value pairs, which can't be computed.

Both classes can extend java.lang.Number

Class RomanLiteral represents one base value of the roman numeral system, it is a String - Integer relation, e.g. "V" -> 5. toString() is overriden to return the String value.

Class RomanNumeral
Represents a fully roman numeral, it is an aggregate of RomanLiterals, which are basic String - Integer relation, e.g. "V" -> 5, and so on.

Attributes

defaultRomanLiteralSet this Set containts the basic constant RomanLiterals
literals this is the List which contains all RomanLiterals that aggregate this RomanNumeral

Methods

RomanNumeral parseRomanNumeral(Integer) is an analogy to Integer#parseInt(String) this method may be static, and returns the RomanNumeral of the Integer param.
add(RomanNumeral) adds an RomanNumeral to the current value of the object and returns it.
add(RomanLiteral) adds the RomanLiteral to the current value of the object and returns it.
toString() is overriden to return the right String representation of the roman numeral - there happens some calculations with the matching values in the default-set. Here actually gets the roman String calculated out of the integer value of the aggregate.

I think that would be a good useable design. I would stay quite near to the Number style of java, and would do my implementation and design in this direction. (analgous methods and so on..)


It seems that the above caching works much faster than the Ascending Minima algorithm.
the code below contains both algos with benchmarks (this version is for finding the lowest).

static class Program
{
    static Random r = new Random();
    static int Window = 1000; //(small to facilitate visual functional test). eventually could be 100 1000, but not more than 5000.
    const int FullDataSize =100000;//000;
    static double[] InputArr = new double[FullDataSize]; //array prefilled with the random input data.

    //====================== Caching algo variables
    static double Low = 0;
    static int LowLocation = 0;
    static int CurrentLocation = 0;
    static double[] Result1 = new double[FullDataSize]; //contains the caching mimimum result
    static int i1; //incrementor, just to store the result back to the array. In real life, the result is not even stored back to array.

    //====================== Ascending Minima algo variables
    static double[] Result2 = new double[FullDataSize]; //contains ascending miminum result.
    static double[] RollWinArray = new double[Window]; //array for the caching algo
    static Deque<MinimaValue> RollWinDeque = new Deque<MinimaValue>(); //Niro.Deque nuget.
    static int i2; //used by the struct of the Deque (not just for result storage)

    //====================================== my initialy proposed caching algo
    static void CalcCachingMin(double currentNum)
    {
        RollWinArray[CurrentLocation] = currentNum;
        if (currentNum <= Low)
        {
            LowLocation = CurrentLocation;
            Low = currentNum;
        }
        else if (CurrentLocation == LowLocation)
            ReFindHighest();

        CurrentLocation++;
        if (CurrentLocation == Window) CurrentLocation = 0; //this is faster
        //CurrentLocation = CurrentLocation % Window; //this is slower, still over 10 fold faster than ascending minima

        Result1[i1++] = Low;
    }

    //full iteration run each time lowest is overwritten.
    static void ReFindHighest()
    {
        Low = RollWinArray[0];
        LowLocation = 0; //bug fix. missing from initial version.
        for (int i = 1; i < Window; i++)
            if (RollWinArray[i] < Low)
            {
                Low = RollWinArray[i];
                LowLocation = i;
            }
    }

    //======================================= Ascending Minima algo based on http://stackoverflow.com/a/14823809/2381899
    private struct MinimaValue
    {
        public int RemoveIndex { get; set; }
        public double Value { get; set; }
    }

    public static void CalcAscendingMinima (double newNum)
    { //same algo as the extension method below, but used on external arrays, and fed with 1 data point at a time like in the projected real time app.
            while (RollWinDeque.Count > 0 && i2 >= RollWinDeque[0].RemoveIndex)
                RollWinDeque.RemoveFromFront();
            while (RollWinDeque.Count > 0 && RollWinDeque[RollWinDeque.Count - 1].Value >= newNum)
                RollWinDeque.RemoveFromBack();
            RollWinDeque.AddToBack(new MinimaValue { RemoveIndex = i2 + Window, Value = newNum });
            Result2[i2++] = RollWinDeque[0].Value;
    }

    public static double[] GetMin(this double[] input, int window)
    {   //this is the initial method extesion for ascending mimima
        //taken from http://stackoverflow.com/a/14823809/2381899
        var queue = new Deque<MinimaValue>();
        var result = new double[input.Length];

        for (int i = 0; i < input.Length; i++)
        {
            var val = input[i];

            // Note: in Nito.Deque, queue[0] is the front
            while (queue.Count > 0 && i >= queue[0].RemoveIndex)
                queue.RemoveFromFront();

            while (queue.Count > 0 && queue[queue.Count - 1].Value >= val)
                queue.RemoveFromBack();

            queue.AddToBack(new MinimaValue { RemoveIndex = i + window, Value = val });

            result[i] = queue[0].Value;
        }

        return result;
    }

    //============================================ Test program.
    static void Main(string[] args)
    { //this it the test program.
        //it runs several attempts of both algos on the same data.
        for (int j = 0; j < 10; j++)
        {
            Low = 12000;
            for (int i = 0; i < Window; i++)
                RollWinArray[i] = 10000000;
            //Fill the data + functional test - generate 100 numbers and check them in as you go:
            InputArr[0] = 12000;
            for (int i = 1; i < FullDataSize; i++) //fill the Input array with random data.
                //InputArr[i] = r.Next(100) + 11000;//simple data.
                InputArr[i] = InputArr[i - 1] + r.NextDouble() - 0.5; //brownian motion data.

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i = 0; i < FullDataSize; i++) //run the Caching algo.
                CalcCachingMin(InputArr[i]);

            stopwatch.Stop();
            Console.WriteLine("Caching  : " + stopwatch.ElapsedTicks + " mS: " + stopwatch.ElapsedMilliseconds);
            stopwatch.Reset();

            stopwatch.Start();
            for (int i = 0; i < FullDataSize; i++) //run the Ascending Minima algo
                CalcAscendingMinima(InputArr[i]);

            stopwatch.Stop();
            Console.WriteLine("AscMimima: " + stopwatch.ElapsedTicks + " mS: " + stopwatch.ElapsedMilliseconds);
            stopwatch.Reset();

            i1 = 0; i2 = 0; RollWinDeque.Clear();
        }

        for (int i = 0; i < FullDataSize; i++) //test the results.
            if (Result2[i] != Result1[i]) //this is a test that algos are valid. Errors (mismatches) are printed.
                Console.WriteLine("Current:" + InputArr[i].ToString("#.00") + "\tLowest of " + Window + "last is " + Result1[i].ToString("#.00") + " " + Result2[i].ToString("#.00") + "\t" + (Result1[i] == Result2[i])); //for validation purposes only.

        Console.ReadLine();
    }

}


Following suggestions from Landei above, and this article on recursive type declarations in Scala, I've come up with a slightly different solution where states are directly modelled as state transitions.

trait StateFunc [ T ] extends PartialFunction [ T, StateFunc [ T ] ]

sealed abstract class Event

case object E0 extends Event
case object E1 extends Event
case object E2 extends Event

class FSA {
  private type State = StateFunc [ Event ]

  private def transitions [ T ] ( pf : PartialFunction [ T, StateFunc [ T ] ] ) = new StateFunc [ T ] {
    def apply( event : T ) = pf ( event )
    def isDefinedAt ( event : T ) = pf.isDefinedAt ( event ) }

  private val ( s0 : State ) = transitions { case E0 => s1; case E1 => s2; case E2 => s0 }
  private val ( s1 : State ) = transitions { case E0 => s3; case E1 => s0; case E2 => s1 }
  private val ( s2 : State ) = transitions { case E0 => s2; case E1 => s1; case E2 => s0 }
  private val ( s3 : State ) = transitions { case E0 => s3; case E1 => s3; case E2 => s1 }

  private var state = s0

  def handle ( e : Event ) { state = state ( e ) } }

I'm not saying that this is better than the other solutions proposed, but I wonder about memory usage. Clearly, as this is a highly recursive construct, if the compiler doesn't do tail-call optimisation, this solution will run out of memory eventually. I have no understanding of the Scala compiler, but I would imagine that in this simple case the tail calls are optimised to ensure constant stack space usage. But what if the transition functions do something more complicated (e.g. possibly throwing exceptions)? Can constant space usage still be guaranteed?

As an aside, is it really necessary to go through so many hoops to define a recursive type? Why can I not simply write e.g. type T = Map [ Int, T ]?

Edit 9.9.2011: I added @tailrec annotations to the program above with the following results: The compiler accepts @tailrec on s0, ..., s3 just fine. But it balks when I annotate the private definition of transitions, which is not surprising. What that means in practise for stack-space usage of this form of implementing FSAs I don't know.


Create a directed graph and compute in degrees in Python

In make_complete_graph, the inner loop could be written with a list comprehension:

result[i] = set([num for num in range(num_nodes) if num != i])

In compute_in_degrees, instead of iterating over all nodes for all nodes x to find links going to x, you could build a dictionary of counts easier:

counts = dict([(x, 0) for x in digraph])
for targets in digraph.values():
    for target in targets:
        counts[target] += 1


The trouble with using a pseudo-random number generator to produce your shortened URLs is, what do you do if there is a collision? That is, what happens if there are values v and w such that v != w but genkey(v) == genkey(w)? Would this be a problem for your application, or would it be entirely fine?

Anyway, if I didn't need to solve the collision problem, I would use Python's built-in pseudo-random number generator for this instead of writing my own. Also, I would add a docstring and some doctests.

import random
import string

def genkey(value, length = 5, chars = string.ascii_letters + string.digits):
    """
    Return a string of `length` characters chosen pseudo-randomly from
    `chars` using `value` as the seed.

    >>> ' '.join(genkey(i) for i in  range(5))
    '0UAqF i0VpE 76dfZ oHwLM ogyje'
    """
    random.seed(value)
    return ''.join(random.choice(chars) for _ in xrange(length))

Update: you clarified in comments that you do need to avoid collisions, and moreover you know that value is a number between 1 and domain inclusive. In that case, you're right that your transformation is an injection, since prime is coprime to domain, so your method is fine, but there are several things that can be done to simplify it:

As far as I can see, there's no need to subtract 1 from value.
There's no need to use the value seed at all. You're using this to ensure that you have at least length digits in num, but it's easier just to generate exactly length digits. (This gives you a bigger domain in any case.)
There's no need to call reversed: the reverse of a pseudo-random string is also a pseudo-random string.

Applying all those simplifications yields the following:

def genkey(value, length=5, chars=string.ascii_letters + string.digits, prime=694847539):
    """
    Return a string of `length` characters chosen pseudo-randomly from
    `chars` using `value` as the seed and `prime` as the multiplier.
    `value` must be a number between 1 and `len(chars) ** length`
    inclusive.

    >>> ' '.join(genkey(i) for i in range(1, 6))
    'xKFbV UkbdG hVGer Evcgc 15HhX'
    """
    base = len(chars)
    domain = base ** length
    assert(1 <= value <= domain)
    n = value * prime % domain
    digits = []
    for _ in xrange(length):
        n, c = divmod(n, base)
        digits.append(chars[c])
    return ''.join(digits)

A couple of things you might want to beware of:

This pseudo-random scheme is not cryptographically strong: that is, it's fairly easy to go back from the URL to the value that produced it. This can be a problem in some applications.
The random strings produced by this scheme may include real words or names in human languages. This could be unfortunate in some applications, if the resulting words were offensive or otherwise inappropriate.


Splitting and printing comma-separated values

sizeof(char) by definition is 1. tmp += l + 1; would be as good.
I don't see a need to special case l == 0.
You don't have to initialize l in a loop header: it is immediately reassigned.
gcc complains about precision specifier in printf("\"%.*s\"\n", l, tmp) being size_t; unfortunately, cast is unavoidable.
I don't see a need for 2 separate loops. A single

char * tmp = (char *)str;
do {
    int l = strcspn (tmp, tok);
    printf("\"%.*s\"\n", l, tmp);
    tmp += l + 1;
} while (tmp[-1]);
return 0;

works equally well.


A couple points:

Encapsulate the resource bundle in an instance of the class instead of using static methods.
If the key doesn't exist, don't return the empty string. If this situation is acceptable, return null or change the return type to Optional<String> and return Optional.none(). If this situation indicates an error, throw an exception.
Don't declare MalformedURLException. That is an implementation detail. Catch and throw a more appropriate exception.


Downloading the oldest available version of some data files

Why don't you read the index from http://www.rbsp-ect.lanl.gov/data_pub/rbspa/MagEphem/def/ and use that to decide which files you want to download?

Also, try to give multiple files (eg. 20) to each curl call: this will enable curl to reuse the same connection for those files.

Please also note that Matlab is not the right tool for this job. For example, this would be easier in Python which has many libraries to perform HTTP requests.


As you are dealing with whole numbers and remainders do not use floating point numbers. It's inaccurate and furthermore confusing because others may think that the result may be not a whole number.
As the solutions will get very high very fast consider to use BigInteger
During calculation make sure your divisions will always be without rest
Avoid return statements within the loop. Programmers have to search for breaking conditions through the code if you do not provide them in the loop header. Beside readability unexpected return, break or continue statements cause serious problems when extending the code or applying refactorings like "extract method".
Use lazy evaluation of boolean operators (&& instead of &). In complex evaluations you give other developers the chance to count on the evaluation and produce side effects.
Separate responsibilities. Currently two algorithms are fighting against each other. One is providing a factor and the other is using the factor to try a calculation. But maybe the second algorithm is not satisfied by the factor what is evaluated during calculation. This should be modelled explicitly.

I am not a mathematician. Maybe there is a more efficient way (a shortcut) to calculate it. But I won't cover that.

So here is a refactored version. It's more verbose but it has less accuracy problems and shows the responsibilites of the two algorithms. They communicate through a result object that contains the calculated base value so far and the information if the method was satisfied by the factor given so the base value is a valid result.

    public static BigInteger calculateCoconuts(final long sailors) {

        long factor = 1;

        CalculationResult calculationResult = null;

        do {

            calculationResult = tryCoconutCalculation(sailors, factor);
            factor++;

        } while (!calculationResult.isSatisfied());

        return calculationResult.getBaseValue();

    }

    private static CalculationResult tryCoconutCalculation(final long sailors, long factor) {

        BigInteger factorBI = BigInteger.valueOf(factor);
        BigInteger sailorsBI = BigInteger.valueOf(sailors);
        BigInteger baseValueBI = factorBI.multiply(sailorsBI);

        long counter = 0;

        boolean satisfied = baseValueBI.remainder(sailorsBI.subtract(BigInteger.ONE)).equals(BigInteger.ZERO);

        while (satisfied && (counter < sailors)) {
            baseValueBI = baseValueBI.divide(sailorsBI.subtract(BigInteger.ONE)).multiply(sailorsBI).add(BigInteger.ONE);
            counter++;
            if (counter < sailors) {
                satisfied = baseValueBI.remainder(sailorsBI.subtract(BigInteger.ONE)).equals(BigInteger.ZERO);
            }
        }

        return new CalculationResult(baseValueBI, satisfied);
    }

    public static class CalculationResult {

        private BigInteger baseValue;
        private boolean satisfied;

        public CalculationResult(BigInteger baseValue, boolean satisfied) {
            super();
            this.baseValue = baseValue;
            this.satisfied = satisfied;
        }

        public BigInteger getBaseValue() {
            return baseValue;
        }

        public boolean isSatisfied() {
            return satisfied;
        }

    }


Polymorphic event notification model in Rails

Here's a really basic refactor of notification_redirection_path:

def notification_redirection_path(notifiable_type:, notifiable_id:, notification_action:, **)
  case notification_action
  when "commented"
    case notifiable_type
    when "Post"
      posts_path(anchor: "post_#{notifiable_id}")
    when "Product"
      product_path(notifiable_id, anchor: "comment-panel")
    when "ProductLead"
      product_lead = ProductLead.find(notifiable_id)
      product_product_lead_path(product_lead.product_id, notifiable_id, anchor: "comment-panel")
    when "ProductCustomer"
      product_customer = ProductCustomer.find(notifiable_id)
      product_product_customer_path(product_customer.product_id, notifiable_id, anchor: "comment-panel")
    end
  when "invited"
    product_path(notifiable_id, anchor: "product-invitation-well")
  when "accepted"
    product_product_users_path(notifiable_id)
  end
end

A few things to notice:

I changed the method arguments to keyword arguments. This way instead of doing this:

redirect_to notification_redirection_path(
  params[:notifiable_type],
  params[:notifiable_id],
  params[:notification_action]
)

...we can do this:

redirect_to notification_redirection_path(params)

I turned the outer if expression into a case expression. I also changed the indentation so the whens line up with their case. Usually I prefer the other style (like you wrote it) but I find with nested cases this is a bit easier to read.
I removed your initial if notifier_type == ... expression and moved that logic into the when "ProductLead" and when "ProductCustomer" blocks below. No need to have those in two separate places.

This is still pretty messy, though. A quick win for readability, maintainability, and testability would be to split it into separate methods:

def notification_redirection_path(notifiable_type:, notifiable_id:, notification_action: nil, **)
  case notifiable_type
  when "commented"
    commented_notification_redirection_path(notifiable_type, notifiable_id)
  when "invited"
    product_path(notifiable_id, anchor: "product-invitation-well")
  when "accepted"
    product_product_users_path(notifiable_id)
  end
end

private
def commented_notification_redirection_path(type, id)
  case type
  when "Post"
    posts_path(anchor: "post_#{id}")
  when "Product"
    product_path(id, anchor: "comment-panel")
  when "ProductLead"
    product_lead = ProductLead.find(id)
    product_product_lead_path(product_lead.product_id, id, anchor: "comment-panel")
  when "ProductCustomer"
    product_customer = ProductCustomer.find(id)
    product_product_customer_path(product_customer.product_id, id, anchor: "comment-panel")
  end
end

You could employ polymorphic_path to take this to its extreme conclusion, which might look something like this:

ACTION_ANCHORS = {
  "commented" => "comment-panel",
  "invited" => "product-invitation-well"
}

def notification_redirection_path(notifiable_type:, notifiable_id:, notification_action:, **)
  if notification_action == "commented" && notifiable_type == "Product"
    return posts_path(anchor: "post_#{notifiable_id}")
  end

  notifiable = notifiable_type.constantize.find(notifiable_id)

  path =
    if notification_action == "commented" &&
        (ProductLead === notifiable || ProductCustomer === notifiable)
      [ notifiable.product, notifiable ]
    elsif notification_action == "accepted"
      [ notifiable, :product_user ]
    else
      [ notifiable ]
    end

  polymorphic_path(path,
    anchor: ACTION_ANCHORS[notification_action])
end

...but it's probably not worth it, since you lose a lot in readability and maintainability.


Function to find a certificate in either the user or the machine store

I agree with @JanDotNet that by using a separate method you will gain readability but that's just my subective view.

As you are asking about C#7 stuff I assume that you will use .NET >= 4.6. Starting with .NET 4.6 the X509Store implements IDisposable hence you should enclose the using of the X509Store inside a using block.

Instead of using a concrete type you could use the var type  to declare your variables.

This would result in

public X509Certificate FindClientCertificate(string serialNumber)
{
    return Find(serialNumber, StoreLocation.CurrentUser) ?? Find(serialNumber, StoreLocation.LocalMachine);
}
private static X509Certificate Find(string serialNumber, StoreLocation location)
{
    using (var store = new X509Store(location))
    {
        store.Open(OpenFlags.OpenExistingOnly);
        var certs = store.Certificates.Find(X509FindType.FindBySerialNumber, serialNumber, true);
        return certs.OfType<X509Certificate>().FirstOrDefault();
    }
}


Security. xor is an associative operation.

    nth ^= pieces[0];
    nth ^= pieces[1];
    ...
    nth ^= pieces[n-2]

like your code does is as good as

    nth ^= (pieces[0] ^ pieces[1] ^ ... ^ pieces[n-2]

doXOR is way too verbose to my taste.
toBinary doesn't belong here (and is never called indeed, unless I am missing something).
Obviously all the keys you have generated collapse into a single one. The bad guy doesn't have to recover all the keys - he only needs their accumulated xor. There is no additional security.


The function get_sums_freqs returns an int, but when I call it, I do not assign the result to anything: get_sums_freqs (root, sum_freqs);. Is it ok to do it this way?

Your uneasiness here probably arises from the difference between a Tree and a TreeNode.  A TreeNode is an internal tree detail, which should be hidden from the user of the Tree.  I should be able to pass an Tree object to some function, and have it add some number of nodes to the Tree.  If I pass an nullptr as the TreeNode * root, the caller can't modify my tree.  Similarly, if two entities are supposed to share access to a Tree, that is fine as long as the TreeNode *root contains at least one node.  But you can't share a common empty Tree; instead you have two nullptr ... which are not "shareable".

class Tree {
    TreeNode *root;
    int num_nodes;
    int max_depth;
}

Now we have a Tree object, which can be shared ... even if it is an empty tree.  As a bonus, our Tree can hold meta-information about the tree, such as the number of nodes in the tree, the maximum depth of the tree, and so on.

The LeetCode challenge is promoting a broken tree model, by using a TreeNode * to represent a tree.  It works, but it has issues; I wouldn't want to see it used in a professional "Project".

I prefer not to walk into nullptr nodes.  Imagine:

void TreeNode::get_sums_freqs(unordered_map<int, int>& sum_freqs) { ... }

Now, you would be calling TreeNode::get_sums_freqs() with a nullptr for this, which is bad.

Instead:

int get_sums_freqs(TreeNode* node, unordered_map<int, int>& sum_freqs) {

    int curr_sum = root->val;

    if (node->left)
       curr_sum += get_sums_freqs(node->left, sum_freqs);
    if (node->right)
       curr_sum += get_sums_freqs(node->right, sum_freqs);

    sum_freqs[curr_sum]++;

    return curr_sum;
}

Note we are calling the current node node, instead of root.  We need to start off the search at the root of the tree, which is a little different:

void tree_get_sums_freqs(Tree* tree, unordered_map<int, int> &sum_freqs) {
    if (tree->root) {
       root_sum = get_sums_freqs(tree->root, sum_freqs);
       sum_freqs[root_sum]++;
    }
}

No root_sum needs to be returned from this top-level.

Of course, since LeetCode doesn't define their trees this way, you have your odd, unused return value.

  For some reason, it feels like a bad style to me to initialize the hash map unordered_map<int, int> sum_freqs; in one function and then pass it to another function to fill it out. Is there a better way to do it? Or is this a correct way?

This is fine.  It is a visitor pattern.  You create an accumulator object, and visit every node of your structure with it, to accumulate the results.


Prefix- and z-functions in C++ (string algorithms)

This will be a somewhat strange answer but the thing is that I can't find anything wrong with your code: it is not that easy to understand what it is doing, but it is only because the algorithms are not the most straightforward in the world; if we compare your code and the algorithms pseudo-code, it's easy to see that they are performing the same computations. Everything seems well-written, the language is used as it should be used... In the end, I only have a few almost-irrelevant remarks left:

The only obvious thing you could do is to templatize your algorithm so that it works for any std::basic_string specialization and not only for std::string.
If you strive for speed and can overcome a little less readability (generally, you don't), you could try to change this piece of code:

if (str[i] == str[pref]) {
    ++pref;
}

into this one:

pref += str[i] == str[pref];

But even then, time it, time it again, and I'm pretty sure that the compiler is somehow smart enough to get rid of that branch for you and that it won't impact the overall speed of the algorithm in any significant way.
You are slightly inconsistent in the way you call the functions: you wrote std::min (/* ... */) but also std::max(/* ... */). You should either put a space everywhere or remove it everywhere, but be consistent.

Well, as you see, there is little to say about what you wrote. It's some pretty good code. Great job writing it! :)


Array multiple assignment
You pass arrays around, and you find yourself calling for x[1] and x.last - this is very unreadable, and brittle.
Ruby allows you to implicitely assign elements of the array to parameters in your block according to its location, so you could write the same "maps" like this:

  .map do|numerator, denominator|
     [numerator.to_f / denominator.to_f, numerator.chars, denominator.chars,
      numerator.chars & denominator.chars]
  end.map do |result, numerator_digits, denominator_digits, mutual_digit|
    [result, numerator_digits - mutual_digit, denominator_digits - mutual_digit,
     numerator_digits, denominator_digits]
  end.select do|result, new_numerator_digits, new_denominator_digits|
    result == new_numerator_digits.join.to_f/new_denominator_digits.join.to_f
  end.map do |_, _, _, numerator_digits, denominator_digits|
    Rational(numerator_digits.join.to_i, denominator_digits.join.to_i)
  end.reduce(:*)

Note that unneeded array elements at the end of the array are truncated, so you don't have to write them. For the unneeded elements at the beginning of the array I've used the _ idiom which tells the method that I expect these parameters, but I won't need them.

If it deserves a comment - it deserves a method
Instead of commenting your code, consider refactoring it into methods. Each method will do one thing, and, given the proper name, will be descriptive when used, and easily read in itself:

def trivial?(pair)
  pair.any? {|y| y.chars.include? '0'}
end

def identical?(numerator, denominator)
  numerator == denominator
end

def larger_than_one?(numerator, denominator)
  numerator.to_i > numerator.to_i
end

def has_common_digits?(numerator, denominator)
  (numerator.chars & numerator.chars).size > 0
end

a = 10.upto(99).to_a.map(&:to_s)
puts a.product(a)
      .reject(&method(:trivial?))
      .reject(&method(:identical?))
      .reject(&method(:larger_than_one?))
      .select(&method(:has_common_digits?))

Make your steps logical
The last few steps you take look like they are held out with gum, and that you made some acrobatics to stay one-line and "idiomatic". It is better to make your methods do something you can explain, than simply adding and removing temp-variables:

def reduced_fraction(numerator, denominator)
  mutual_digit = numerator.chars & denominator.chars
  (numerator.chars - mutual_digit).join.to_f / (denominator.chars - mutual_digit).join.to_f
end

a = 10.upto(99).to_a.map(&:to_s)
puts a.product(a)
      .reject(&method(:trivial?))
      .reject(&method(:identical?))
      .reject(&method(:larger_than_one?))
      .select(&method(:has_common_digits?))
      .select do |numerator, denominator|
        numerator.to_f / denominator.to_f == reduced_fraction(numerator, denominator)
      end.map { |fraction| Rational(*fraction) }
      .reduce(:*)

Update
Yes, it seems that using &method(:something) in map and multiple assignment are mutually exclusive... :(

I can suggest a few strategies where you don't have to fall back to using pair.first, pair.last:

Use multiple assignment in the first line of your method:

def identical?(pair)
  numerator, denominator = pair
  ...
end

Use a hash to hold your values, and use keyword arguments in your method

def identical?(numerator: nil, denominator: nil)
  numerator == denominator
end

a = 10.upto(99).to_a.map(&:to_s)
puts a.product(a)
      .reject(&method(:trivial?))
      .map { |numerator, denominator| {numerator: numerator, denominator: denominator } }
      .reject(&method(:identical?))


To search files you're using Directory.GetFiles(), nothing wrong with that but, especially in conjunction with SearchOptions.AllDirectories, it may take some time to search for them all. You should switch to Directory.EnumerateFiles() because you can consume enumeration immediately and search will progress on-the-fly (in this case you do not give any progress feedback then you do not need to know the total number of files to process in advance).

It has few advantages:

You can start processing immediately, reducing the total perceived execution time.
You use less memory than reading the whole list (not such an issue nowadays).
It's easy to be parallelized.

And we then arrive to the second point: parallelization. It's always tricky to make I/O bound code parallel but in this case you have two main tasks:

Read file content.
Calculate hash.

Even a very simple parallel approach will benefit from overlapping next read operation with previous hash calculation. Roughly something like this:

var allFiles = Directory.EnumerateFiles(directoryPath, "*.*", SearchOption.AllDirectories);

var hashedFiles = allFiles.AsParallel()
    .Select(x => new { Path = x, Hash = CalculateHash(x) });

You may want to play with options to limit the maximum number of concurrent reads. Also note that I moved the hash calculation in its own separate function. I'd do the same also for the other tasks, it's true that this method is pretty small but you will gain in clarity, proof of concept:

public static void DeleteDuplicateFiles(string searchPath)
{
    foreach (var file in FindDuplicateFiles(searchPath))
        TryDeleteFile(file);
}

private static IEnumerable<string> FindDuplicateFiles(string searchPath)
{
    var hashedFiles = FindAllFiles(searchPath)
        .AsParallel()
        .Select(x => new { Path = x, Hash = CalculateHash(x) });

    return FindDuplicates(hashedFiles);
}

And so on, I think you get what I mean. Some of those functions may also be reused and to understand overall algorithm you just need to read few lines of code, no need to dig into implementation details.

I hope you noted I used a TryDeleteFile() function instead of directly calling File.Delete(). This is because I/O operations may fail and error may be transitory (for example another program or Windows Shell may keep temporarily keep the file open (without sharing for deletion) but it may be deleted few seconds later. In this function you simply try to delete the file and if you get an IOException with HRESULT for file in use then you simply wait and retry few times.

One last thing: do not mix your logic with presentation. This code can be easily reused outside a console application. You may also want to provide a different output (for example coloring messages) but if you mix them together then any change will be a pain. Introduce an interface IProgressWriter for example like this:

public interface IProgressWriter
{
    void Trace(string message);
    void Error(string messsage);
}

In this case I wrote a somehow generic one but you might want a specialized one (for example to later switch to a GUI application without touching a single line of code in your logic). Note that you can do it both with an interface and with events, like this:

public sealed class DuplicatedFilesSleuth
{
    public string SearchPath { get; set; }

    public void FindDuplicates() { ... }

    public void DeleteDuplicates() { ... }

    public event EventHandler<DuplicatedFilesSleuthEventArgs> Hashing;

    public event EventHandler<DuplicatedFilesSleuthEventArgs> Deleting;
}

Note that, as t3chb0t pointed out in a comment, if you do not expose callable methods but data then you should use IProgress<T>/Progress<T> instead of another custom interface.


Avoiding instanceOf when finding index of an interface within a list

I totally agree with Uri and have some further comments:

  the class has no idea what the set will contain, it does however know there maybe a IDescriptor that is meant for video..

I'm sorry, but I have to ask: If you're not sure about exactly what the Set contains, why are you storing it in a set in the first place?

Consider instead something like Map<KEY_TYPE, List<? extends IDescriptor>> descriptors; where KEY_TYPE can be a Class<? extends IDescriptor>, a String, or something else that can tell you what type it is.

When adding items to this map you could use:

List<? extends IDescriptor> list = descriptors.get(descriptor.getClass());
if (list == null) {
    list = new ArrayList<>();
    descriptors.put(descriptor.getClass(), list);
}
list.add(descriptor);

And then all you would need to do is to use descriptors.get(VideoDescriptor.class) (assuming VideoDescriptor is not subclassed, otherwise you could loop through the supertypes as well when adding to the list).

Another thought is that you can use a enum to describe what kind of IDescriptor it is, and the IDescriptor type can have a getDescriptorType method. Then you could check if (fragmentDescriptor.getDescriptorType() == DescriptorType.VIDEO)

As I only see a portion of your code and not the big picture, I can't really tell what would be best for you.


Small program to download wikipedia articles to pdf

Here are some stylistic and code style points:

fix the variable naming - in Python, there is a lower_case_with_underscores variable naming style (PEP8 reference)
organize your imports as per PEP8 guidelines - first, the system-level imports, then third-parties, then your "local" imports. Also, remove unused from gtts import gTTS import:

import os

import pdfkit
import wikipedia

docstrings should start with a capital letter and end with a dot
I think you should define pdfOptions as a module-level (or configuration-layer-level) constant instead of having them defined as an instance variable
if self.includeLinks == False: can be simplified to if not self.includeLinks:
you should have spaces around the operators inside expressions (reference)
I think you can handle both cases in your download() method in a unified way:

def download(self):
    links = self.page.links if self.includeLinks else [self.page]
    for link in links:
        page = wikipedia.page(link)
        print("Downloading " + page.url)
        filename = self.targetDir + "/" + page.title + '.pdf'
        pdfkit.from_url(page.url, filename, options=self.pdfOptions)

I would also use os.path.join() instead of string-concatenating filename paths


List files and folders in current dir with special handling for tty

OsStr conversion

According to the path source, s.as_os_str().to_str() is the same as s.to_str():

pub fn as_os_str(&self) -> &OsStr {
    &self.inner
}

pub fn to_str(&self) -> Option<&str> {
    self.inner.to_str()
}

Moreover, using unwrap() here is not safe at all as invalid Unicode is pretty common (e.g. when mounting file system with alien character encoding). There is Path::to_string_lossy that converts path to a printable string.

Using crossterm

crossterm provides helper macros to output strings. It is more idiomatic to use them instead of println!("{}{}", ...): execute and queue.

Using queue may be beneficial in case of outputting to the pipe instead of stdout.

Reporting errors

It is common practice to report errors to stderr. It also may be more helpful to show error reason when fs::read_dir() fails. You can also use crossterm to make it more colorful:

match fs::read_dir(dir) {
    Err(err) =>
        execute!(
            stdout(),
            Colored::Fg(Color::Red),
            Output(format!("Failed to list {}: {}", dir.to_string_lossy(), err)),
            Reset),
    Ok(entries) => ..
}

Callbacks

Using callbacks to print colorful vs. normal is a nice idea, but is not future-proof. It will be hard to add other output options like short/long view, hidden files, etc.


How can this swift, firebase image fetching, function be made more concise?

I would start by investigating the cases where you are performing if lets and basic unwrapping. Cases like if snapshot.value as? [String: AnyObject] != nil can be turned into guard statements and provide routes for early termination. This reduces the pyramid by one level for each early termination.

After that, I see some redundant code in the try section on the innermost level that can be brought together.

Other minor changes I'd make would be regarding variable names, some of the names are not entirely that descriptive and make for some less than ideal reading. More descriptive names with less abbreviation would help understand the code better. Things like usersPostRef2 don't make a lot of sense since we don't see a usersPostRef.

Also lastly, make sure you update the UI on main threads, which you appear to be doing at the end, but not necessarily within the second snapshot closure.

This would give us the following:

func fetchAllUserFristImage() {
    Database.database().reference().child(“Posts”).observe(.childAdded, with: {(snapshot) in
        guard snapshot.value as? [String: AnyObject] != nil else {
            return
        }

        let user = snapshot.key
        self.databaseReference = Database.database().reference()
        let usersPostReference = self.databaseRef.child(“Posts”).child(user)
        usersPostReference.observe(.value, with: {(postXSnapshots) in
            guard let postDictionary = postXSnapshots.value as? [String:AnyObject] else {
                return
            }

            for anyPosts in postDictionary {
                guard let posts = anyPosts.value as? [String:AnyObject] else {
                    return
                }

                //to get back to where i was delete the below for i
                for anyImage in posts {
                    guard let imageUrlString = anyImage.value as? [String:AnyObject], let postUrl = imageUrlString[“image1”] as? String else {
                        return
                    }

                    self.feedArray.append(Post(fetchedImageURL: postUrl))
                    let imageUrl = URL(string: “\(postUrl)“)
                    do {
                        let imageData = try Data(contentsOf: imageUrl!))
                        let image = UIImage(data: imageData)
                        self.tableData.append(UserImage(image: image!, postNum: p.key, userID: user))
                        DispatchQueue.main.async {
                            self.tableView.reloadData()
                        }
                    } catch {
                        print(error)
                    }
                }
            }
        })
        //below shud stay same
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    })
}


I know that you subsequently posted c++ code for this and that post has answers, one of which is accepted.

I did notice that the code above references the global variable colours. This may be seen as bad programming style because it can cause side effects that may be challenging to detect. Alternatively, function parameters could be used, or else a  class with a class/data/instance member.


Idiomatic way of handling optional values in Swift

A better way to handle optional values is "optional binding":

if let path = NSBundle.mainBundle().pathForResource("NavigationMenu", ofType: "plist") {
    // do something with `path`
} else {
    NSLog("Unable to locate file : NavigationMenu.plist")
}

which tests and unwraps the optional result as a single action.
Inside the if-block, path is the unwrapped String.

You can do the same with the items:

if let path = NSBundle.mainBundle().pathForResource("NavigationMenu", ofType: "plist") {
    if let items = NSArray(contentsOfFile: path) {
        // do something with `items` ...
    } else {
        NSLog("Navigation menu items could not be read from plist.")
    }
} else {
    NSLog("Unable to locate file : NavigationMenu.plist")
}

As of Swift 1.2, multiple optional bindings can be combined in
a single if-statement, which reduces the number of nested if-levels:

if
    let path = NSBundle.mainBundle().pathForResource("NavigationMenu", ofType: "plist"),
    let items = NSArray(contentsOfFile: path) {
        // do something with `items` ...
} else {
    NSLog("Unable to load NavigationMenu")
}

The downside is that you have only a common else-block for the
error condition and cannot distinguish which of the optional bindings
failed.

Instead of objectAtIndex() and objectForKey() you can use
subscripting for NSArray and NSDictionary:

for var i = 0 ; i < items!.count ; i++ {
    let item = items![i] as! NSDictionary
    let navItem = NavigationItem(name: item["name"] as! String,
        andSegueIdentifier: item["segueIdentifier"] as! String)
    navigationItems.append(navItem)
}

But a better way is to cast the NSArray to a Swift array of Swift dictionaries in the first step.
Then you can use array enumeration and don't need any casts later:

if
    let path = NSBundle.mainBundle().pathForResource("NavigationMenu", ofType: "plist"),
    let items = NSArray(contentsOfFile: path) as? [[String : String]] {

        for item in items {
            let navItem = NavigationItem(name: item["name"]!, andSegueIdentifier: item["segueIdentifier"]!)
            navigationItems.append(navItem)
        }
} else {
    NSLog("Unable to load NavigationMenu")
}

This assumes that values for the "name" and "segueIdentifier" are
present (and will crash at runtime otherwise). Alternatively, use
optional binding again:

for item in items {
    if let name = item["name"], ident = item["segueIdentifier"] {
        let navItem = NavigationItem(name: name, andSegueIdentifier: ident)
        navigationItems.append(navItem)
    } else {
        NSLog("Invalid navigation item")
    }
}

Finally, you could replace the inner loop by a map() operation:

if
    let path = NSBundle.mainBundle().pathForResource("NavigationMenu", ofType: "plist"),
    let items = NSArray(contentsOfFile: path) as? [[String : String]] {
        navitationItems = map(items) {
            NavigationItem(name: $0["name"]!, andSegueIdentifier: $0["segueIdentifier"]!)
        }
} else {
    NSLog("Unable to load NavigationMenu")
}


Java Date class- switches and ifs in the constructor

Getting your class compiling and working is an achievement in itself. So don't let my comments discourage you, but see them as hints for the next learning steps.

Processing time

Don't worry about that until you really experience performance problems. Even expert programmers often fail when trying to predict the performance of their code. If you run into performance issues, then learn to use analysis tools like "profilers". But most probably, you won't need them for the next few years.

Code in constructor

It's good to do validity checks in constructors. But you're right, the constructor's readability suffers from its length. The key to readability is introducing good abstractions instead of writing lengthy code, as you already did with the leap() method. Writing a monthLength(int year, int month) method and using that in the constructor, you can get rid of most switch/if statements.

Invalid dates

You chose to create a 01.01.2000 date in case of invalid date elements. Professionals will instead throw an IllegalArgumentException.

As a Java beginner, it's quite likely that you haven't learnt about the concept of exceptions yet, but it's an important thing, an elegant way to tell someone who wants to construct e.g. a 31.2.2010 date that you can't give him that date as it doesn't exist. As a caller of a constructor or method, I always want to be informed about success or failure, and exceptions are a good way to do that.


x86-64 Assembly - Sum of multiples of 3 or 5

if01 and if0 are not the greatest names.

Instead of reloading r9, use two registers. Let r9 always contain 3, and r10 always contain 5.

Increment r8 in one place.

Running the loop downwards (1000 to 0), rather than upwards, spares an instruction (cmp).

mov rdx, 0 is encoded in 7  bytes. xor rdx, rdx is way shorter.

All that said, consider
main:
    mov r8, 0
    mov r9, 3
    mov r10, 5

    ; for i in (1000, 0]
    mov rcx, 999

for0:
    mov rax, rcx
    xor rdx, rdx
    div r9
    test rdx, rdx
    jeq accumulate

    mov rax, rcx
    xor rdx, rdx
    div r10
    test rdx, rdx
    jne next

accumulate:
    add r8, rcx
next:
    dec rcx
    jne  for0

PS: I hope you know that this problem has a very straightforward arithmetical solution.


Look through a string and return the most frequent character (Ruby)

You can get the most common separator in header with a one-liner like this:

most_common = SEPARATORS.sort_by{|separator| header.count(separator)}.last

But as you have noticed CSV.foreach attempts to split up the rows, assuming by default that the separator is a comma.

You probably need to determine the separator in a preprocessing step before actually doing the CSV processing.

You could just do something like

contents = File.read(@file)
@config[:col_sep] = %w(; ,).sort_by{|separator| contents.count(separator)}.last

CSV.parse(contents, @config) do |row|
   ...
end

# or use the returned array of arrays
rows = CSV.parse(contents, @config)

This might be quite slow if your file is large because you have to read the whole thing into memory. In that case you might want to just look at the first line of the file, and guess the separator from that. To do this, assuming \n is your line separator:

first_line = File.open(@file) do |file|
  file.first
end

Note that you should use the block form to ensure that the file gets closed.

If you need to be line-separator agnostic, I don't think there's a built-in way to do so (although you can change the line separator, that assumes you know it in advance). You might try something like

first_line = ""
File.open(@file) do |file|
  file.each_char do |char|
    break if "\r\n".include?(char)
    first_line << char
  end
end


Django: Database efficiency - currently accessed twice

Your step 2 can be done entirely in DB by filtering and limiting your order_items. And then updating it to contain the desired value. Note that the F objects documentation already mention that use of a queryset update method. So we could imagine something like:

order.order_items.filter(social_discount__isnull=False)[:1].update(social_discount__redeemed_amount=F('social_discount__redeemed_amount') + 1)

Except this doesn't work:

we cannot use update after slicing a queryset;
we cannot update fields of related models anyway.

Instead we must use the relationship backwards and filter/update on the SocialDiscount model, the filter being the subset of OrderItems we are interested in:

order_item = order.order_items.filter(social_discount__isnull=False)[:1]
# Note that order_item is still a queryset and has not hit the database yet
SocialDiscount.objects.filter(order_items__in=order_item).update(redeemed_amount=F('redeemed_amount') + 1)

Even though this only hit the database once, this will update all SocialDiscount objects that are related to the one order_item specified by the queryset above. If it ever can mean that more than one object is updated and you don't want that, you can still remove the for loop using this two-queries code:

social_discount = order.order_items.filter(social_discount__isnull=False).select_related('social_discount').first().social_discount
social_discount.redeemed_amount = F('redeemed_amount') + 1
social_discount.save()


You shouldn't inherit from builtin data types - there's a UserList type that's more appropriate.

On top of that, you probably shouldn't inherit from UserList either: your code is not a list and doesn't fill its contractual obligations. This is a time to favour composition over inheritance.

Before I look at implementing this, here are a few quick things I noticed. One is

if isinstance(item, tuple):
    ...

in __getitem__, which doesn't seem to work since _adj_index is packing any tuples it gets into another tuple.

Another thing was the use of for i in xrange(len(self)):, which would be much simpler if you could just do for i in self._items - another advantage of composition. You can actually manage this with super(Ring, self).__iter__(), though.

Your __getslice__ returns another ring; this seems strange - a slice of a ring is rarely itself also a ring. If you have a ring of paper and cut a section out, that section has ends!

Finally, your __str__ and __repr__ are the default ones for list, which is entirely misleading and very bad practice.

Back to the point, looking at the abstract base classes in collections (later moved to collections.abc), the only interfaces it makes sense to support are Container and Iterable, since the class doesn't have a __len__. Adding __{get,set,del}item__ and __repr__ on top of that would give something like

def _adj_index(method):
    def _dec(instance, *args):
        if isinstance(args[0], int):
            index = args[0] % len(instance._items)
            return method(instance._items, index, *args[1:])
        return method(instance._items, args)
    return _dec

class Ring:
    """
    Ring datatype.
    """

    def __init__(self, items):
        self._items = list(items)

    def __iter__(self):
        while True:
            for i in xrange(len(self._items)):
                yield self._items[i]

    __getitem__ = _adj_index(list.__getitem__)
    __setitem__ = _adj_index(list.__setitem__)
    __delitem__ = _adj_index(list.__delitem__)

    def __getslice__(self, i, j):
        return [self[x] for x in range(i, j)]

    def __repr__(self):
        return "Ring({})".format(self._items)

This discards __getitem__ since it's no longer needed but keeps it similar to your code.

__iter__ could just delegate to itertools.cycle.

__getslice__ is deprecated and has been for ages. Let's consider doing this properly:

def __getitem__(self, idx):
    if isinstance(idx, slice):
        return ???

    return self._items[idx % len(self._items)]

What should ??? be? Well, we'd like something akin to

[self[i] for i in xrange(idx.start, idx.stop, idx.step)]

but start, stop or step might be None. We can say that start and stop should not be None (since both directions extend infinitely), but step can reasonably be asked to default to 1. Unfortunately, slice.indices isn't appropriate here, as with other tricks you can normally use.

Thus:

step = 1 if idx.step is None else idx.step
return [self[i] for i in xrange(idx.start, idx.stop, step)]

Now, __setitem__ probably has no good semantics for slice assignment because:

If a slice is larger than len(self._items), there is no obvious cannonical mapping on how to handle the assignment.
If a slice crosses through the start index (has idx % len(self._items) == 0) and assigns to a slice of a different size, there is no obvious way to decide where the new start is moved to.

You could restrict slice assignments to slices of the same size, and on slices no more than len(self._items) in size - but then you're not giving much bang for the buck. For this reason, I think __setitem__ and __delitem__ should remain as they are, operating only on integers.

However, _adj_index is not worth its cost. You could just implement them as

def __setitem__(self, idx, value):
    if not isinstance(idx, int):
        raise TypeError("Ring indices must be integers, not {}".format(type(idx)))

    self._items[idx % len(self._items)] = value

def __delitem__(self, idx):
    if not isinstance(idx, int):
        raise TypeError("Ring indices must be integers, not {}".format(type(idx)))

    del self._items[idx % len(self._items)]

(the error mirrors that of indexing lists).

In the scheme of things, this code is simpler, faster and contains not too much logical duplication. However, deduplication is nice, so one could merely add a _from_integer_index method:

def _from_integer_index(self, idx):
    if not isinstance(idx, int):
        raise TypeError("Ring indices must be integers, not {}".format(type(idx)))

    return idx % len(self._items)

def __getitem__(self, idx):
    if isinstance(idx, slice):
        step = 1 if idx.step is None else idx.step
        return [self[i] for i in xrange(idx.start, idx.stop, step)]

    return self._items[self._from_integer_index(idx)]

def __setitem__(self, idx, value):
    self._items[self._from_integer_index(idx)] = value

def __delitem__(self, idx):
    del self._items[self._from_integer_index(idx)]

In this case, wrapper methods do not seem to be the most appropriate solution to the problem.

This also allows checking for indexing 0-length rings.

All together:

import itertools

class Ring:
    """
    Ring datatype.
    """

    def __init__(self, items):
        self._items = list(items)

    def __iter__(self):
        return itertools.cycle(self._items)

    def _from_integer_index(self, idx):
        if not isinstance(idx, int):
            raise TypeError("Ring indices must be integers, not {}".format(type(idx)))

        if not len(self._items):
            raise IndexError("Indexing empty ring")

        return idx % len(self._items)

    def __getitem__(self, idx):
        if isinstance(idx, slice):
            step = 1 if idx.step is None else idx.step
            return [self[i] for i in xrange(idx.start, idx.stop, step)]

        return self._items[self._from_integer_index(idx)]

    def __setitem__(self, idx, value):
        self._items[self._from_integer_index(idx)] = value

    def __delitem__(self, idx):
        del self._items[self._from_integer_index(idx)]

    def __repr__(self):
        return "Ring({})".format(self._items)


Simple object oriented design for a patient system

Bracing style

You started off with Allman-style bracing approach, but switched to the Java convention for HelloWorld and its main() method. Regardless of the styles you choose, please be consistent on this front. :)

Medical condition dates

Your medical conditions carry a start date, but should they also have an end date? Or are we only talking about incurable medical conditions here? While we're at it, Java 8 has new 'Time' APIs with a different (and better) approach to modeling chronology, so you may want to use the newer LocalDate class.

OK, now I get it... you delete medical conditions when they are cured. If you need to preserve medical history, you now know what you can do too...

Throwing Exceptions

public static void main(String args[]) throws ParseException

I understand HelloWorld is something like a test class to see your implementation in action, but still try to avoid doing something like this, especially when it's your main() method. One wrong input will simply cause your test class to quit with a stacktrace. It will be better if you have a method to handle the parsing and any possible errors. For example, if you want to default to the current date in case of parsing errors:

private static LocalDate parse(String date) {
    // using the new time APIs
    try {
        return DateTimeFormatter.ISO_LOCAL_DATE.parse(date, LocalDate::from);
    } catch (DateTimeParseException e) {
        return LocalDate.now();
    }
}

equals() implementation

  Do I need to implement an equals method in the MedicalCondition class?

Your call. :) The longer answer is, what does it mean when a medical condition is-equal to another? Same condition and date? How helpful will such an equivalence be? To 'group' patients by the same medical conditions? If you don't have a strong case for this, you probably wouldn't want to implement it first.

Adding medical conditions

In this regard, I will recommend your existing approach over @Amr Ayman's answer. This is mainly because your Patient class should know what it means to add a medical condition, instead of letting callers of your Patient instances 'figure that out'. A better refinement is to wrap the instance returned by getMedicalConditions() with a Collections.unmodifiableList(): this will prevent callers of the method to modify the list's contents directly, such as wiping them outright.

Actually, on this note, you can also consider making your MedicalCondition class immutable, and I shall leave that as an exercise for the healthy reader...


Creating a fast Android dictionary (word counts)

Just some ideas.

Maybe you could use batching?

You may be also able to save some time by iterating over sent.entrySet() instead of looking up the count separately.

Split on [^a-zA-Z] as you later throw non-letter away anyway.

Can't you use JDK5 loops like

for (String in : send) {...}

? I guess, clearBindings is unnecessary as you always overwrite everything.

Make all fields private. Always (unless you have a very good reason not to). AT least I hope that pat_rep etc. are fields.

Split your method. Shorter methods are easier to read and to optimize.


Increase performance in sub-line detection

Yes it can be done faster. Your algorithm has a \$O(n^2)\$ time.

Idea: store the indexes of the points of the line in a dictionary and use the points as key (I assume that two distinct points never have the same coordinates. If this is not the case, then an index list would have to be stored for each point).

var lineIndexes = new Dictionary<Point, int>();

//TODO: add the points of the line to the dictionary

foreach (int i = 0; i < subline.Length - 1; i++) {
    Point sublinePoint1 = subline[i];
    Point sublinePoint2 = subline[i + 1];

    int k; // Index in line.
    If (lineIndexes.TryGetValue(sublinePoint1, out k) &&         // We found one matching point AND
        ( k > 0 && sublinePoint2.Equals(line[k - 1]) ||              // (previous one matches OR
          k < line.Lengh - 1 && sublinePoint2.Equals(line[k + 1]))) {//  next one matches)

        return true;
    }
}
return false;

This is \$O(n)\$, since the dictionaries have a constant access time.

Equal vs. Equals

Every object (other than System.Object) inherits Equals and GetHashCode from System.Object. Do not introduce your own Equal method but override Equals and GetHashCode in your own objects. This is necessary for right functioning of the dictionary and other .NET data structures.

If you cannot do that, there are overloads of the dictionary's constructor accepting an IEqualityComparer<TKey>. Provide your own implementation of IEqualityComparer<Point>.


In this code, at first I didn't see the "danger" until I scrolled to the right by accident:

def menu(parent_id=0, menutree=None):
    menutree = menutree or []
    cur = g.db.execute('select id, parent, alias, title, ord from static where parent="'+ str(parent_id) +'" and ord>0 order by ord')
    fetch = cur.fetchall()

    if not fetch:
        return None

    return [{'id':raw[0], 'parent':raw[1], 'alias':raw[2], 'title':raw[3], 'sub':menu(raw[0])} for raw in fetch]

In the g.db.execute statement you're embedding a parameter and we cannot know where the parameter comes from and if it was properly validated to prevent SQL injection. Two things to do here:

Make the line shorter, especially when it contains potentially dangerous stuff in the far right
Use prepared statements with ? placeholder

It's not clear what kind of database you're using, so you might need to edit, but it should be something like this, shorter and without embedded parameters:

cur = g.db.execute('select id, parent, alias, title, ord '
                   'from static where parent = ? and ord > 0 '
                   'order by ord', parent_id)

Another small tip here, if you reverse the checking logic of if not fetch to if fetch at the end, you don't need to return None, as that's the default anyway, and the method will be a bit shorter:

def menu(parent_id=0, menutree=None):
    menutree = menutree or []
    cur = g.db.execute('select id, parent, alias, title, ord '
                       'from static where parent = ? and ord > 0 '
                       'order by ord', parent_id)
    fetch = cur.fetchall()

    if fetch:
        return [{'id': raw[0], 'parent': raw[1], 'alias': raw[2],
                 'title': raw[3], 'sub': menu(raw[0])} for raw in fetch]

And a tiny thing, PEP8 dictates to put a space after the : in a key:value pair, like so: key: value.

In this code:

@app.route('/')
def index():
    menu_list = menu()
    [...]
    return render_template('index.tpl', **locals())

I recommend to NOT include all **locals(), but use the list of variables you want to pass explicitly. We're all humans, one day you might accidentally expose something.


Three ways to read a number for a BitInputStream

If you are so concerned about performance, then you should run a benchmark.  I would bet that there is no appreciable difference in performance, as the task is going to be IO-bound rather than CPU-bound.  A much bigger impact on performance would be, for example, whether the input stream is buffered.  Therefore, you should just pick the code that looks the best.  I personally prefer a variant of variant 3.

It seems that you are interested in the values of value and aNumberOfBits after the loop.  Since i is unimportant, let's just ditch it.  Also, iBuffer seems to be a temporary variable, so its scope should be limited to the loop.

Finally, let's get rid of the Hungarian notation!

for (; bitCount >= 8; bitCount -= 8) {
    int b = input.read();
    if (b == -1) {
        throw new EOFException();
    }
    value = (value << 8) | b;
}

What might make a performance impact is reading a byte[] array at once instead of a byte at a time.  Handling possible buffer underruns correctly would be a pain, though, so I don't recommend it here.


Performance

The getSum function calculates the sum of the values in the given array up to the specified index. As you calculate the result to multiple queries, each using the same array as the parameter, the same calculation is repeated multiple times, which is certainly the cause of the slowness. The time complexity of  getSum is \$O(n)\$, and of the entire solution it's \$O(n^2)\$.

You could improve the performance greatly by pre-computing an array of so-called prefix sums: the sums of elements up to each index. For example if the input array contains 7 3 1 5 5 then the array of prefix sums will contain 0 7 10 11 16 21. This can be done in a single pass, in \$O(n)\$ time.

With this change, the time complexity of  getSum would become \$O(1)\$, and of the entire solution  \$O(n)\$, significantly faster than the original solution.

Style issues

Try to organize your program into multiple functions with a single responsibility. Like getSum, that was well done, but the rest of the program should be split up to smaller logical units.

In C++ you don't need to declare variables at the top of functions, like you did for q. It's better to declare right before you need it.

Lastly, note that using namespace std is generally not recommended.


Test for the easy cases

    private static boolean similar(int []arr, int a, int b, int c, int d) {

This misses several quick and easy to check possibilities.

          if (a == c && b == d) {
              // each segment is similar to itself
              return true;
          }

Check if it's the same segment.  If so, done.

          if (b - a != d - c) {
              // if different sizes, not similar
              return false;
          }

The segments have to be the same size to be similar.

          if (a < c) {
              if (b >= c) {
                  int temp = b + 1;
                  b = c - 1;
                  c = temp;
              }
          } else {
              if (d >= a) {
                  int temp = d + 1;
                  d = a - 1;
                  a = temp;
              }
          }

If either segment overlaps the other, then we can remove the overlap.  We don't have to check those elements, as we already know that they are the same.  This eliminates all the work of checking the overlap.  In particular, we don't have to copy or sort those elements.

The two cases are a < c < b < d and c < a < d < b.  We test for the order of the first three, and the final one must be in that order to keep the sizes equal.  I.e. b = a + size - 1, so d = c + size - 1.  Therefore if a < c, then b < d.

Consider the worst case for your code.  That's when a and c both equal 0, while b and d equal arr.length - 1.  Your code copies the entire array twice, then sorts the entire array twice, and finally iterates over both arrays to compare each element.  This code would simply return true in constant time.

There's a method for that.

        int [] arr1 = new int[b-a+1];
        int [] arr2 = new int[d-c+1];

        for(int j = a-1, k = c-1, l = 0; j < b; j++, k++) {
            arr1[l] = arr[j];
            arr2[l] = arr[k];
            l++;
        }

We could use Arrays.copyOfRange, as such:

        int[] arr1 = Arrays.copyOfRange(arr, a, b + 1);
        int[] arr2 = Arrays.copyOfRange(arr, c, d + 1);

Then we don't have to write out the logic.

Don't do extra checks

        for(int j = 0; j < arr1.length; j++) {
            if( arr1[j] != arr2[j])
                diff++;
            if( diff > 1 )
                break;
        }
        if( diff < 2 )
            return true;
        else
            return false;

You could rewrite this as

        for (int j = 0; j < arr1.length && diff <= 1; j++) {
            if ( arr1[j] != arr2[j]) {
                diff++;
            }
        }

        return diff <= 1;

That's shorter but takes no less time.

The simpler return is a common pattern.  In Java, you can simply return the result.  You don't need to process it with an if/else.

I prefer to compare to 1 rather than 2, as 1 is what appears in the problem statement.  I prefer to keep the code as close to the problem statement as possible to make it easier to read later.

Even better might be

        for (int j = 0; j < arr1.length; j++) {
            if ( arr1[j] != arr2[j]) {
                diff++;
                if ( diff > 1 ) {
                    return false;
                }
            }
        }

        return true;

We only need to check diff if we increment it.  The rest of the time, it stays the same as it was.

Binary search

I haven't tried to write up a solution, but you don't have to copy and sort both array segments.  If you copy and sort one, you can just iterate over the other and binary search the first.  If there is a match, you go to the next one.  If no match, you mark off the value as if matched and increase the difference count.

This won't give any asymptotic improvement, but it may make the program a little faster.

Dynamic programming

Again, I haven't tried to write up a solution, but realize that two segments are similar if their first elements are the same and the remainder of the segments are similar.  So it might be worthwhile saving the work that we've done in sorting and comparing previous segments.  Then we can reduce new queries to previous queries with some added entries.

This would likely be memory intensive.

New data structure

Consider the possibility of a data structure that kept track of the original order and the sorted order and could map between them.  At the simplest level, a sorted order that remembered the original placement.  But at a more complex level, possibly a trie-like structure.

Again, this would likely be memory intensive.


Parsing indented text and inserting its data into a tree

You should be able to accomplish this task by making one linear pass through the lines, instead of making one pass to build indents and a second pass to build entries.

It's good practice to package your code into functions, and to write docstrings for them.  In particular, if you have code that follows the pattern

outputs = []
for item in inputs:
    outputs.append(…)

… then consider writing a generator instead.

When you detect indentation that is not a multiple of 4 spaces, you print a message and stop building indents, but other than that, you still allow the program to proceed normally.  The program should probably abort at that point, and I suggest doing so by raising an exception.  Furthermore, I consider indentation that is suddenly excessively deep (e.g. going from 1 level to 3 levels of indentation) to be another kind of error that should be detected.

I don't like the way you handle the special case of the root node.  In particular, having a non-uniform tuple length is asking for trouble — it is basically data that is not of the same type.  I would avoid making the root node part of the data structure altogether, so that you don't have to write an exclusion for this special case:

for a in entries:
    if len (a) == 3: continue

Analyzing the text one character at a time (using while a[indent] == ' ': indent+=1) feels tedious.  I suggest using regular expressions to describe what kind of text you are expecting.  For example,

re.compile(r'^(?P<indent>(?: {4})*)(?P<name>\S.*)')

… says that you are looking for indentation at the beginning of the line that is a multiple of four spaces, followed by a name that starts with a non-space character.

Suggested solution

import re

def parse_tree(lines):
    """
    Parse an indented outline into (level, name, parent) tuples.  Each level
    of indentation is 4 spaces.
    """
    regex = re.compile(r'^(?P<indent>(?: {4})*)(?P<name>\S.*)')
    stack = []
    for line in lines:
        match = regex.match(line)
        if not match:
            raise ValueError(
                'Indentation not a multiple of 4 spaces: "{0}"'.format(line)
            )
        level = len(match.group('indent')) // 4
        if level > len(stack):
            raise ValueError('Indentation too deep: "{0}"'.format(line))
        stack[level:] = [match.group('name')]
        yield level, match.group('name'), (stack[level - 1] if level else None)

raw = """…"""
for level, name, parent in parse_tree(raw.split('\n')):
    print('{0}{1} ( {2} )'.format(' ' * (4 * level), name, parent or 'root'))


Python's style guide (PEP0008) says that lines should aim to be 79 characters long. This prevents people having to scroll across as they read a line. You've broken that multiple times. I'd suggest using ways of breaking lines to avoid it. Like this:

parser = argparse.ArgumentParser(description="""A tool to help memorize some text!
When provided with a file, this program will remove random words from each line
of text and ask you to provide the words that were removed.""")
parser.add_argument('--no-color', action='store_true',
                    help='hide colorful underlining')
parser.add_argument('--a', dest='attempts', default=3,
                    help=('number of attempts to allow per word '
                          '(0 for unlimited attempts, default: 3)') )

To explain that last one. You can spread what would be one line over multiple lines by putting brackets around it. You can then break strings up without even using + because they'll be implicitly concatenated together, turning it back into one long string.

You can assign the result of a boolean to a variable in Python, so you could turn these three lines:

show_word = True
if random.randrange(10) < 5:
    show_word = False

Into just one:

show_word = random.randrange(10) > 4

You don't need to use a for loop and refer to the character by index, you can directly get Python to loop over the individual elements of a list. So instead of

for char_idx in range(0,len(word)):
    if (word[char_idx].isalpha() and show_word) or not word[char_idx].isalpha():

you can use

for char in word:
    if (char.isalpha() and show_word) or not char.isalpha():

Much cleaner and easier to read.

What is this part doing? It's quite unclear and I had to read back up and down to understand it. A comment would give very useful context here.

# If there was a word added, append a new empty string to missing words.
if len(missing_words[idx]):
    missing_words.append(u'')
    idx += 1

That comment could be improved, but I think even better would be a refactoring of this code. You should make a temporary empty string, then at the end check if it contains anything and append that. Performing operations on the list item only to append a new item one is kind of backwards. Also, for the record, you could eliminate idx anyway because with Python you can use -1 as an index value to get the last item in the list. So you could just do missing_words[-1] and get the same result.

I assume you have this bare try except so that people don't get errors spat at them for using Ctrl+C to exit the program. But in that case you should still use a specific error like KeyboardInterrupt otherwise you're just hiding your errors and making debugging harder. Also it's important not to put too many lines inside a try except when it can be avoided. If my presumption is right and this is to catch KeyboardInterrupts nicely, then it only needs to be around the raw_input line.

try:
    attempt = raw_input('Enter the next missing word: ')
except KeyboardInterrupt:
    sys.exit(0)

If you have other errors you want to catch, you can catch multiple ones. Just make sure they're in a comma separated list and then any of those exceptions will run your exit.

except (KeyboardInterrupt, SystemExit):

Don't have an integer called attempts and a string called attempt. Either switch the int to being tries or switch the string to being guess. It's just confusing the other way and liable to cause typos. Also it could be a good idea to start the loop with next_word = missing_words[0]. It would save you some typing throughout and is more clear about what the variable is.

''.join('_' for char in missing_words[0]) is long and confusing. You can actually just use the multiplication operators on a string, so '_' * len(missing_words[0]) would work fine.

Python has a concept called truthiness where many types of data can be evaluated as a boolean easily. So if you just go elif args.attempts, that will return True for integers that aren't 0, and False for 0 itself.

elif args.attempts and attempts == args.attempts:

Also you have duplicate code here. It could be avoided with a little rearranging.

if unicode(attempt,'utf-8') == missing_words[0]:
    print("Correct! The word was '" + missing_words[0] + "'.")
elif args.attempts > 0 and attempts == args.attempts:
    print("Too many attempts. The word was '" + missing_words[0] + "'.")
else:
    print("Incorrect. Please try again.")
    attempts += 1
    continue

if args.no_color:
    current_line = current_line.replace('_' * len(nextWord), nextWord, 1)
else:
    current_line = current_line.replace('\033[91m_\033[0m' * len(nextWord),
                                        nextWord, 1)
missing_words.pop(0)
attempts = 0

The main thing that might look confusing to you here is the continue keyword. It's used in loops to tell Python to ignore the rest of the code in the loop and go to the next iteration. This way, if the answer is incorrect but the user has attempts left, Python will continue onto the next iteration.

This is a good error message, but you should use str.format to make nicer looking string formatting.

print("File not found: '{}'".format(args.filename))

It's helpful both for coercing variables into strings but also for making the string one coherent string of characters you can read rather than breaking it up.


Excessive use of let a problem in Clojure?

First of all, you could use abstract structural binding (a.k.a. destructuring) to reduce the number of let bindings:

(defn- create-counts_org [[_ & present :as coll]]
  "Computes how many times did each 'next state' come from a 'previous state'.
   The result type is {previous_state {next_state count}}."
  (let [zipped  (map vector coll present)
        sorted  (sort zipped)
        grouped (group-by first sorted)
        seconds (map (fn [[key pairs]] [key (map second pairs)]) (seq grouped))
        freqs   (map (fn [[key secs]]  [key (frequencies secs)]) seconds)]
    (into {} freqs)))

I think there's nothing wrong in using let bindings that are technically not necessary to improve readability and comprehensibility.

But in your function, I think it is pretty clear what every step does:

sorted -> the first thing I see is the sort function
grouped ->  the first thing I see is the group-by function
seconds / freqs -> I think these are also pretty clear, using second and frequencies

And because each let binding just uses the previous binding once, I would probably use the thread-last (->>) macro:

(defn- create-counts [[_ & rest :as coll]]
  "Computes how many times did each 'next state' come from a 'previous state'.
   The result type is {previous_state {next_state count}}."
  (->>  (map vector coll rest)
        (sort)
        (group-by first)
        (map (fn [[key pairs]] [key (map second pairs)]))
        (map (fn [[key secs]]  [key (frequencies secs)]))
        (into {})))

I think this also answers your better to just put it all inside one expression question. Also, even if there where a performance penalty in using let bindings, it would probably be negligible.


Sorting dates in this format (DD-MM-YYYY)

UPDATE: You can run performance tests I prepared based on various code samples from the answers to this question: https://jsperf.com/cr-se-date-array-sorting/1. When I ran them, I see that my code is second best performing. The best is the one by @Kevin Cline (up voted!).

Here's my take on it. The following code uses the same idea about the string representation of date that is directly comparable for sorting.

It is not possible to tell in advance how performant will this solution be compared to one you presented above. It all depends a lot on how many dates are being sorted. If you deal with tons of dates, there will be many more invocations to the arrow function we're passing to sort(...). Therefore, it's not good to keep translating the date via split() every time our arrow function is being used.

Instead, I recommend three steps:

Translate dates into a sortable representation (one time). Use .map().
Do the sorting with .sort().
The values will be put in a lexicographical order.
Translate the sorted dates back into original representation.

This will guarantee that each date is translated at most twice, which makes the entire solution more performant for large Ns.

Also, Notice that steps #1 and #3 can use same exact implementation, which I extracted.

const reverseDateRepresentation = date => {
  let parts = date.split('-');
  return `${parts[2]}-${parts[1]}-${parts[0]}`;
};

const sortedDates = ['01-02-2018', '02-01-2018', '01-01-2018', '31-12-2017']
  .map(reverseDateRepresentation)
  .sort()
  .map(reverseDateRepresentation);

console.log(sortedDates);

Produces result:

["31-12-2017", "01-01-2018", "02-01-2018", "01-02-2018"]

Little note. I think, that from the "big O" point of view we haven't improve the algorithm. Since .map(reverseDateRepresentation) is \$O(n)\$, the performance of the entire solution is limited by the .sort() (which is probably \$O(n * {\log n})\$). The way we're potentially improving solution is by making sure that the constants in our "big O" cost are as small as we can achieve.

Nevertheless, if we'd put the performance as top criteria of the solution, I'd learn as much as I can about the real data being processed; as well as conducted a thorough performance test.

In real life scenario, however, I personally never put performance above readability, because I believe that lack of readability is eventually the same thing as lack of correctness ...and correctness is almost always more important than performance (few exceptions are known though).


Project Euler 18/67 : Maximum Path using Memoization

Storage

A Map is most useful when the key values are not in a sequence,
but sparse, with smaller and bigger gaps between key values.

In this example, the key corresponds to a row of the triangle,
taking on values from 0 to size, and using all values in the range.
An array would be a more natural choice for storage,
in this example an int[][].

Note that a hash map has some storage overhead.
Also, accessing array elements is simpler to write than .get(...) and .put(...) calls.

Encapsulation

This is a bit unfortunate:

TriangularArray theArray = new TriangularArray(size);
theArray.acceptArray(in);
theArray.displayArray();
theArray.findMaximum();

Since findMaximum will modify the underlying storage,
if you call theArray.findMaximum() one more time,
it will produce different output,
which is unexpected.

It's best when you can call a method multiple times and get the same result consistently.
Unless of course it is by design that the call manipulates state,
for example in an iterator.
The name "findMaximum" doesn't hint at manipulating state,
which is misleading.

In fact, findMaximum is designed for one-time use.
It would be better to rewrite this in a way that the state manipulation becomes obvious.
Or throw an exception if the method is called a second time.
Or encapsulate the logic in a way that calling findMaximum repeatedly would produce the same result consistently.

I would also recommend to make findMaximum return the maximum instead of printing text.

Pointless statements

This variable is unused (and poorly named):

int someInt;

The map.put(i, currArray) statement at the end is unnecessary:

int[] currArray = map.get(i);
for(int j=0; j<currArray.length; j++){
    currArray[j] = in.nextInt();
}
map.put(i, currArray);

Because currArray comes from map.get(i), and it is not reassigned.

Other redundancies

TriangleArray.size is redundant.
The same information is available through the underlying storage,
whether using a map or an array.

Instead of initializing the arrays in the constructor,
you could do it at the same time as parsing from Scanner,
to iterate over the lines only once.

Most of the comments are completely redundant, noise, for example:

// Display the array
public void displayArray() {

This helps nobody, omit such redundant comments.

Naming

acceptArray is a strange name for a method that parses numbers from a Scanner. How about parseFromScanner ?

displayArray is a strange name for method that prints the content of the triangle. How about simply print ? As the method is on the TriangleArray class, it's implied that it will print the triangle itself.

Alternative implementation

Consider this alternative implementation:

static class TriangularArray {
    private final int[][] rows;

    public TriangularArray(int size) {
        rows = new int[size][];
    }

    public void parseFromScanner(Scanner scanner) {
        for (int i = 0; i < rows.length; i++) {
            rows[i] = new int[i + 1];
            for (int j = 0; j < rows[i].length; j++) {
                rows[i][j] = scanner.nextInt();
            }
        }
    }

    // Finds the maximum using Memoization.
    public int findMaximum() {
        int[] below = rows[rows.length - 1];
        for (int i = rows.length - 2; i >= 0; i--) {
            int[] current = rows[i].clone();
            for (int j = 0; j < current.length; j++) {
                current[j] = Math.max(below[j], below[j + 1]) + current[j];
            }
            below = current;
        }
        return below[0];
    }
}


Is this node replacement code reasonable?

From a once over;

i and f, even for forEach are not very good names, pick something more meaningful.
if data-id is the action id, perhaps you could have gotten/set it with $().data('actionId') ?
The way your replacement function uses OldDiv and RepDiv smells like global variable abuse
Consider using smallCamelCase, actionid -> actionId, OldDiv -> oldDiv
Consider caching $(f), since you access it several times ( var $f = $(f); and then only access $f )
This : $(f).css('cursor', 'pointer'); really belongs in .css file

Other than that, your code looks okay to me.


PEP8

The official Python style guide will suggest that:

there be two newlines between functions at the global scope, and only one newline between functions in the class scope (i.e. check_if_should_die)
functions be named in lower_snake_case, i.e. listen_to_quit

Hard exit

Currently, you have a forever-loop that only exits on sys.exit. Instead, simply return a boolean from listenToQuit (which can be called should_quit), and if the return value is true, break out of the loop.

Abbreviated imports

pygame.sprite.Sprite can just be Sprite if you from pygame.sprite import Sprite.

Typo

assests -> assets

Generator

    self. animation = iter([
        pygame.image.load('assests/splatter_1.png'),
        pygame.image.load('assests/splatter_2.png'),
        pygame.image.load('assests/splatter_3.png'),
        pygame.image.load('assests/splatter_4.png')
    ])

can be

self.animation = iter(
   pygame.image.load(f'assets/splatter_{i}.png')
   for i in range(1, 5)
)

Generally I don't think your iter/StopIteration approach is that bad. That said, you can rework it by changing your outer while True into a for drop in drops, where drops is an iterable through four instances of a drop object tied to a specific asset.


No, it's not thread-safe. Between the call to Interlocked.Increment() and the if check, another thread could call Interlocked.Increment(). That means both of them could see that _counter is 101, which means a call to _methodToCall would be skipped.

But this is exactly why Interlocked.Increment() returns the incremented value. So the thread-safe version would be:

public void PerformCall()
{
    if (Interlocked.Increment(ref _counter) % _cycleValue == 0)
        _methodToCall();
}

This is exactly why writing code like this is hard (although this is a simple situation, so it's not that hard here). It's much easier to write correct multi-threaded code, if you lock all shared values.

Also, if you do something like this, you need to be sure that inserting a row in your code is also thread-safe. And the same applies to SaveChanges(). For example, if you used something like ConcurrentQueue in a straightforward way, it would be possible for SaveChanges() to save more than 100 items at a time, because new items could have been inserted between the call to Interlocked.Increment() and the final dequeue from the queue. This may not be a problem for you, but you should think about that.


You could get rid of the service methods, initialise the values in the initialize method.  And then in a subclass set a service that doesn't actually do anything with the enrollment.

class Enrolments::Suspend
  ...
  def initialize
    @responses = []
    # get rid of the methods and set the services in the intitialiser
    @event_service ||= Events::Outgoing::Enrolments::SuspendedEnrolment.new
    @suspend_enrolment_presentation_service ||= Enrolments::EnrolmentPresentations::Suspend.new
  end
  ...
end

class EnrollmentWithoutEvent < Enrolments::Suspend
  ...
  def initialize
    super
    # do default config here
    @event_service ||= Events::DoNothing.new
  end
  ...
end

Or, you could create a subclass that overrides the raise_suspended_enrolment_event method:

class Enrolments::SuspendWithoutErrors < Enrolments::Suspend
  def raise_suspended_enrolment_event
    # change the implementation here
  end
end

Another options would be to use class_attribute for your service objects/procs:

class Enrolments::Suspend
  ...
  class_attribute :event_service, :suspend_enrolment_presentation_service
  ...
end

Then, when you subclass, you get set your services per class or instance and can  change/add the services on any sub-classes or instances of sub-classes.  Have a look at here for how it works.  This method means that you can create classes with specific services, and when you instantiate the class, the instances also use the same services.

For example:

class Enrolments::Suspend
  ...
  class_attribute :event_service, :suspend_enrolment_presentation_service

  # create the services used for this class
  self.event_service = proc {|enrollment| ... }
  self.suspend_enrolment_presentation_service = proc {|e| ... }
end

class SuspendWithoutError < Enrolments::Suspend
  # override one of the services but keep the rest
  self.suspend_enrolment_presentation_service = proc {|e| ... }
end

The final option is to use actual methods:

class Enrolments::Suspend
  ...

  def event_service(enrollment)
    ...
  end

  def suspend_enrolment_presentation_service(enrollment)
    ...
  end
end

This allows any sub-classes to override the methods.


This is a pretty straightforward program. Overall, very easy to read, and makes sense. Here are a few things I'd do differently:

Use Types

You have several places where you use an unstructured vector of floats. While that's the formate you need to send to the GPU, you don't have to make it so hard on yourself (and anyone who's going to read your code in the future). You should make a 2D point structure, an RGB color structure, and a matrix class to handle those very different types of data. You might look into glm which has several data types that mimic those used in vertex and fragment shaders.

Or create your own:

struct Point2D {
    float x;
    float y;
};

struct RGBColor {
    float red;
    float green;
    float blue;
};

etc.

Use Functions

You code for creating and uploading the texture is really tangential to the rest of the code. You should put those into either a single other function, or 2 other functions (one to create the data and one to upload it). If it were me, I'd do 2, as I know that I upload a lot of textures when working with OpenGL and the code is going to mostly be the same.

Speaking of creating the texture, your code is difficult to understand. It would be simpler to do something like this:

// Create texture: simple chess board 8x8
const unsigned char kBlack = 0;
const unsigned char kWhite = 0;
auto numRows = 8u;
auto numCols = 8u;
std::vector<unsigned char> texture(numCols * numRows);
for (auto row = 0u; row < numRows; ++row)
{
    for (auto col = 0u; col < numCols; ++col)
    {
        bool evenRow = (row % 2) == 0;
        bool evenCol = (col % 2) == 0;
        if (evenRow == evenCol)
        {
            texture [ row * numCols + col ] = kWhite;
        }
        else
        {
            texture [ row * numCols + col ] = kBlack;
        }
    }
}

If You Set State, Use It

I notice that you're using a color array, but then you upload a texture, and you don't specify GL_MODULATE for the texture parameters. What is the point of setting the vertex colors if you aren't going to use them? (I don't see any shaders, so presumably you aren't using them there, either.) If you aren't going to use the vertex colors, don't waste time uploading them to the card.

Also, when you've completed drawing the arrays, you should disable the client state you set above, as when you inevitably expand this code in the future, those values will need to change for each object you draw. Your draw loop should look something like this:

while (window.isOpen())
{
    sf::Event windowEvent;
    while (window.pollEvent(windowEvent))
    {
        if (windowEvent.type == sf::Event::Closed)
            window.close();
    }

    // render
    glClear(GL_COLOR_BUFFER_BIT);

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glVertexPointer(2, GL_FLOAT, 0, vertices.data());
    glColorPointer(3, GL_FLOAT, 0, colors.data());
    glTexCoordPointer(2, GL_FLOAT, 0, texCoord.data());

    glDrawArrays(GL_QUADS, 0, 4);

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);

    window.display();
}

And really all the drawing stuff should be in some sort of drawObjects() function.


You'd definitely need to name your function something more descriptive than build_tuple for it to be a good idea (and same with t1 and t2 in the multi-liner!).

I'd use a function if it's something you do more than once or twice, otherwise I'd probably stick with the list comprehension - I find it easier to read than the multi-liner version.

If I was doing a function, I'd probably make it generate the whole list - is there any reason not to do that?

def make_users_to_sent(user_ids, my_database, group):
    return [(my_database.get_user_by_id(x), group['num_sent'][x]) for x in user_ids]

users_to_sent = make_users_to_sent(user_ids, my_database, group)


Parsing a CSV file in node.js and express.js

Your code is fine and the approach will work. However, I do have the following comments based on my own experience.

In the case of error response, why not use the error object to capture the error details and pass return next(err), something to the effect of:

//handling errors in your code woud look like
if(somethingisntright()){

    err.message = 'Something is wrong';
   next(err);
}

//error handler presumably in your app.js
app.use(function(err, req, res){
//if you have multiple errors you could articulate based on assigning err.status
    res.json({
        status: 'error'
        message: err.message,
    });
});

This will reduce the amount of error handling code in the current module and centralize error handling thus reducing maintenance effort in the future.
I'm not sure if it is worth it but you may want to consider short circuiting your logic so that the code handling line numbers >= 3 are handled first. It saves some cycles having to evaluate the first two scenarios for every other line regardless.


RPN-Stack-Based Recursive Calculator Needs Tuneup

Instead of returning an error-String, I would pass in a nil'ed-NSError object by reference, and write an error to it, in case it occurred. the returned object would be nil

+ (NSNumber *)popOperandOffProgramStack:(NSMutableArray *)stack error:(NSError **)error
{
    //…
    error = [[NSError alloc] int…] ;
}

Usage:

NSError *error = nil;
if ([Calculator popOperandOffProgramStack:parameters error:&error])
{
    //returned object not nil -> success
} else {
    //nil-object -> let's check the error
}

this avoids type checking.


VBA Data Conversion (random printout -> CSV file)

Your code does not look bad overall. Here are my 2 cents:

To improve readability, I would split your procedure in sub procedures / functions (does not make a difference if this is the only function in the module, but makes a difference in larger projects). The main procedure could look like this for example (simplified):

Sub main()
  openPlFile
  readPlFile
  writeCsvFile
  saveCsvFile
End Sub

You could add some error handling logic:

Right after your declarations:

On Error GoTo error_handler

And at the end of the code:

Exit Sub
error_handler:
  'code to handle the error for example:
  MsgBox "There was an error: " & Err.Description
End Sub

If performance is an issue there are a few steps to improve the code:

a. You can turn off ScreenUpdating and turn Calculation to manual (don't forget to turn them back on before exiting AND in the error_handler block if there is one).

b. If you want to improve performance further, you could use arrays instead of reading from / writing to the spreadsheet directly in a loop (see http://www.avdf.com/apr98/art_ot003.html)

c. If you want to improve performance even more, you could read and write the files directly without opening / creating workbooks.

d. I generally avoid using Integer as they use the same memory space as Longs anyway (on 32 or 64 bit systems) - VBA simply applies different overflow rules. Declaring Longs instead of Integers can result in a slight performance gain (not so much in your case, but can be useful when declared in a loop for example)


Consider the real world scenario a little bit. Does a car know what the speed limit is? Does it issue itself a fine if it's speeding? Or do the police do this?  Assuming we're talking about the current state of things and not some near future world where cars do these things, police do.

A more proper OOP approach would be to create a Policeman class with a IsSpeeding method that takes a Car in as an argument. The Policeman would then be responsible for determining whether or not the car was speeding and issuing tickets when necessary.