Using Custom Attributes to Populate Members from IDataReader

public class DatabaseField: Attribute

According to the naming guidelines, the names of attribute classes should end with Attribute, so this class should be called DatabaseFieldAttribute.

public string Name { get; set; }

I don't see any reason why the setter should be public, so I would make it private.

public Employee( IDataReader reader )

I don't think all this code should be here. Instead, it should be in a library that's not specific to your types.

Have you considered adding the knowledge of your naming conventions to your code, so that not all properties need the attribute?

Also, I would go the other way around: for each column in the reader, find the appropriate property to set. That way, if your type is missing a property, you can learn about it.

foreach( object attr in prop.GetCustomAttributes(true) )

I would use the generic extension method GetCustomAttribute<T>() here, to simplify your code:

var attr = prop.GetCustomAttribute<DatabaseFieldAttribute>(true);

if( null != field )

There is not reason to use Yoda conditions in C#. The issue they're addressing is that buggy code like if (field = null) is valid C and C++. But it's not valid C#.


There are three things wrong with the while loop.

You are looping over a fixed number of times. The only other way to leave the loop is a return statement. This is exactly what a for loop is for. A while loop is used when the number of times the loop needs to execute is not known ahead of time. You should use the right tool for the job.
Don't use the truth value of a value when you can very easily explicitly state what you want the break condition to be. There are two advantages to using i > 0 is better than what you have. First, it is much easier for the reader. What you have forces the reader to think about what i is, how it might be equivalent to False, and how the loop has to manipulate i to reach that condition. Secondly, you can accidentally cause an infinite loop if you are not properly manipulating i. If you accidentally double decrement i when it is equal to 1, then while clause will evaluate to True when it checks -1. This will not happen when you are explicit about when you want the looping to continue.
In the first example, the last line of the loop is continue. This serves no purpose. There is no code that would be executed otherwise if the continue was omitted. Since it is the last line, the next thing that would happen would be to evaluate the while clause. That is the same thing a continue will trigger.

Edit:

With respect to the actual question, I think returning is fine. The seconds example is an attempt to follow the single return pattern. However, the first implementation still only has one return statement. The only other way to exit the method is by having an exception raised. The try block is the main body of the method. Everything else is the retry functionality.


Clojure: Find specific element in HTML tree

It's not bad, but we can make it a bit more idiomatic. Let's look at this function first:

(defn- matches-attributes [current-attributes required-attributes]
    (reduce #(and %1 (= (second %2) ((first %2) current-attributes)))
            true
            required-attributes))

The use of reduce is a bit odd, instead let's use every? Secondly, if current-attributes is a hash map or a set, then we can actually use it as a function. Since every? takes a predicate, we can rewrite the entire function as:

(defn- matches-attributes [current-attributes required-attributes]
  (every? (fn [tv tg]
              (= (current-attributes tg) tv))
          required-attributes))

On the last function, when-let will help you clean it up a bit more:

(defn- find-rss-feed [page-result]
    (let [document (tagsoup/parse-string (:body page-result))
          rss-links (when-let [head (first (find-tag :head document nil))]
                        (find-tag :link head {:type "application/rss+xml"}))]
    ... do something with rss-links...))

Hopefully this helps a bit. Your code doesn't really support this, but the cool thing to remember is that Clojure collections are functions that return nil if the item doesn't exist. So for example:

=> (remove #{1 2 3} [1 2 3 4 5 6 7])
(4 5 6 7)


There are a few things wrong security wise before we even get to the parameters.

private char[] password;

Storing the plain text password in an instance field makes it discoverable from memory dumps for a considerably long time. There is no need for the field to be an instance field since it is only used in the hash method.

public void hash(String rawPassword) {

Passing plain text password as a String parameter makes it impossible to be securely disposed of. When being passed around, passwords need to be char arrays and they need to be cleared immediately when they are no longer needed.

public void destroy() {

You have the right idea that the class needs to be cleared from sensitive data, but here you have made the clearing the responsibility of the caller while the data needing to be cleared is completely irrelevant to the caller. You should avoid having to rely on other people when dealing with sensitive data. Someone will forget to call destroy() because it is not something that needs to be done in a garbage collected environment. At least you could make it Closeable so there is some common contractual indication about the class needing cleanup. Because the method also clears the actual payload it is guaranteed that the sensitive data will be in memory as long as the payload is needed, which is much longer than the sensitive data needs to exist. But it's better to write the class so that it doesn't need external cleanup at all.

private int ammountOfBytes = 64;
private int keyLength = 512;
private int iterations = 100000;

These should be static and final constants, since you don't have any means to change them.

private String saltHex;
private String hashHex;

These are the only fields that have a information that needs to be kept for a longer period. Instead of wrapping all the fields into a same PasswordHasher class, you should put these two fields into a dedicated data class called HashedPassword, have all the other code be static utilities and have the hash method return the data class.

If we look at the naming, PasswordHasher implies that the class is an actor that implements an algorithm. Your implementation uses it as both a data container and the algorithm. It is better to separate the responsibilities to two different classes (single responsibility principle)


Because Paddle and Ball have a lot in common, I think it would make sense if they were to inherit from a common class (PhysicalObject for instance) with size, position, velocity, color, etc...

self.ball.vy = -self.ball.vy can be written self.ball.vy *= -1.

You could try to handle collision in a slightly more generic way by creating 4 walls inheriting from PhysicalObject around the area and then handle the collisions between 2 PhysicalObject. Also, it would be nice to have some fancy behavior like the speed of the paddle having an impact on the speed of the ball when they interact.


After reading @user1777136 s answer, I came up with this

module Awesome
  # Has methods that are similar to but extended versions
  # of core ruby methods
  module Extensions
    # Get multipe inputs from user
    # Masks passwords if detected
    # Bypasses prompt when ENV variables present
    def self.mgets(names)
      names.map do |name|
        sgets(name)
      end
    end

    # single gets
    def self.sgets(name)
      print "#{name.to_s.capitalize}: "
      return env_sgets(name) if ENV['AWESOME_' + name.to_s.upcase]
      return secure_sgets if name.match?(/password/)
      STDIN.gets.chomp
    end

    # get from env variable
    def self.env_sgets(name)
      ENV['AWESOME_' + name.to_s.upcase]
    end

    # secure gets from stdin
    def self.secure_sgets
      STDIN.noecho(&:gets).chomp
    end
  end
end


remove duplicates in a sorted array if duplicates are allowed at most twice

Opps one bug:
 if(A[pos]==A[pos-1])

If pos == 0 (if there is only one first element) it will fail (undefined behavior).
Two Recommendation:
This:
 int i=0;
 while(i<n)
 {
     // Stuff
     i = pos+1;
 }

Seems like a classic for(;;) loop.
 for(int i = 0; i < n; i = pos +1)
 {
 }

Don't use single letter variable names.
If your function is only slightly larger then looking through the code and finding all the uses of i can be hard. Give it a longer more unique name.

So the rest is just some personal preferences. Nothing I could complain about in a code review.
int rightMost_of_curElem(int A[], int curElem, int ind, int n)
This returns the righmost element. Which means the user has basically has the index to beginning an end of a range. Most C/C++ like functions use a concept of beginning to one past the end. So I would have made this return the index of the first element that did not match (and re-named slightly).
Slight improvement is that you pass the index of the current index which you already know equals the value. You should pass current index + 1 (avoids one compare).
int remove_duplicates(int A[], int n)
You hard code the number of elements to retain. In an interview (and in real life) I would have parametrized this.
Using if(A[pos]==A[pos-1]) as a test seems a bit hard to read when testing one or two elements. I would just use the distance between pos and i to find the number.
I would have written like this:
int getNextElement(int* data, int size, int index, int curElem)
{
    for( ; ((index < size) && (data[index] == curElem)) ; ++index)
    { /* No Body */ }

    return index;
}

int removeDuplicates(int* data, int size, int maxElements)
{
    int count = 0;
    int pos   = 0;
    for(int loop = 0; loop < size; loop = pos)
    {
        int pos = getNextElement(data, size, loop + 1, data[loop]);

        int lastElement = min(loop + maxElement, pos);
        memcpy(data + count, data + loop, (lastElement - loop) * sizeof(int));
        count += (lastElement - loop)
        /*
        for(int copy = loop; copy < lastElements; ++copy, ++count)
        {
            data[count] = data[copy];
        }
        */
    }

    return count;
}

int removeDuplicates2(int* data, int size) {return removeDuplicates(data, size, 2);}


Python code for serving k customers with bounded time window

Time complexity is unnecessarily large.
First, it is linear in the timespan of the arrivals. A list [[1,2], [100,101]] would require 100 iterations; a list [1,2], [1000,1001]] would require 1000 iterations, etc. Don't bruteforce every minute.
Second, del intervals[0] has a linear time complexity in number of intervals, which results in an overall quadratic time complexity. A cheap way out is to sort in a descending order, and work right to left. This way you would remove intervals from the tail of the list, which is O(1).

DRY. A presence of two semantically identical breaks (the loop is broken when it runs out of the intervals) suggests refactoring. Do not test for if not intervals explicitly. Consider
  try:
      while i < end:
          for j in range(k):
              if intervals[0][0] <=i <= intervals[0][1]:
                  del intervals[0]
          i += 1
  except:
      pass

Of course, never except blindly. Catch only exceptions you expect and know how to handle, in this case except IndexError:.


Finding a max element in an array in Java

Yes, this is O(n), because you visit every element once.  You can't possibly do better than O(n), because there is no way to be sure that you have found the maximum value without inspecting every element.  (There are two exceptions.  If the array is known to be sorted in some way, then you can skip straight to the maximum.  Also, if you ever encounter Integer.MAX_VALUE, you could return early.  The latter optimization is probably not worthwhile.)  Recursion would not be faster than iteration, and, in general, iteration should be favoured over recursion in Java for performance.

Since Java 8, you can implement this as a one-liner using IntStream.max():

java.util.Arrays.stream(array).max()

Notice that IntStream.max() returns an OptionalInt.  Why OptionalInt instead of int?  Because the array might be empty.  Your code would return Integer.MIN_VALUE in that case.  If that is what you consider to be the "correct" behaviour, then you should document it in the JavaDoc.


A few things, bad messages first…

Double and Int

return Math.sqrt(level);

Math.sqrt returns a double. That is a floating point number, probably something like: \$2.352561\$. If you now "cast" that to an int (because your method says, "I only return integers"), you just cut everything behind the dot.

This can sometimes lead to funny behavior:

  \$2.7371 \mapsto 2\$
  \$2.0125 \mapsto 2\$

That's not nice…

Braces:

It's usually a very good idea to place braces, even when you could leave them out:

for (Equipment e : equipments) {
    attack += e.getAttack();
}

This is because if you want to do something else, too you need to add braces either way, and If you forget it, the results become "unpredictable"

Copy/Paste:

You should never do that, because as soon as you do, you usually can extract a method for it. But if you do it either way then at least take the bother to change the names…

public int getDefense() {
     int attack = 1 + level;

'nuff said on the bad stuff ;)

Attributes

You might want to consider changing your attribute structure to be more "generic". Consider the following code:

for (Equipment e : equipments) {
    defense += e.getAttribute(Attribute.DEFENSE);
}

or similarly for attack:

for (Equipment e : equipments) {
    attack += e.getAttribute(Attribute.ATTACK);
}

now we already can see, that if you do that twice, this wants to be a single method:

public int getPlayerAttribute(Attribute attribute) {
    int attribute = 1 + level;
    for (Equipment e : equipments) {
        attribute += e.getAttribute(attribute);
    }
    return attribute * Math.sqrt(level);
}

This would of course need a relatively large change in your code. You'd then need to change your Equipment from (wild conjecture):

public class Equipment {
    private int attack;
    private int defense;
    //getters and setters
}

to:

public class Equipment {
    private Map<Attribute, Integer> stats = new HashMap<>();
    // or a different Map implementation of your choice, like
    // EnumMap, as suggested by @ratchet freak in a comment:
    private Map<Attribute, Integer> stats = new EnumMap<>(Attribute.class);

    public int getAttribute(Attribute attribute) {
        return stats.get(attribute);
    }
}

And create a new enum to hold all the different kinds of attributes you have:

public enum Attribute {
    ATTACK, DEFENSE, HITPOINTS, WHATEVER
}


Get height for tallest possible stack of boxes

The code implements a greedy approach (to be exact, n greedy attempts): as soon as a box can be placed, it is placed. It does not necessarily give an optimal solution. For example, with the set of boxes ((height, width)):

    5, 5
    4, 1
    3, 4
    2, 3

the algorithm will only consider towers

    (5,5) (4,1)
    (4,1)
    (3,4) (2,3)
    (2,3)

but not an optimal tower

    (5,5), (3,4), (2,3)

You are right about the complexity of the algorithm, but I am afraid it is not relevant if the algorithm itself is not correct.


Unit (Integration) Test for code that interacts with a database

I don't claim to be an expert, but here's my experience.

Apart from that i see you are using a constant string "MyProviderName" in your code and you would do well to move that to a const string for easy refactoring and future changes.

Also i suggest you use the more common "ArgumentNullException" vs creating your own custom "UndeclaredDBProviderException" as you want to capture that a null parameter was passed to the function.

I would also suggest you run the code through FxCop and fix any errors.


Loading items into array from SQL Server

Main issues

Access

DOM operations take time. You're selecting the element N^2 + 1 times. This can be reduced to 1: document.getElementById('itemSelect')
You're constantly getting arrayValues[i], which only needs to be done once.

Style

You should put spaces after commas: arg, arg2
You should put spaces before and after operations, for readability: var name = value
Spaces after semicolons: i < length; i++

Rewrite

function loadItem(arrayValues, arrayNames) {
    var itemSelect = document.getElementById('itemSelect'),
        j = itemSelect.options.length;
    for(var i = 0, length = arrayValues.length; i < length; i++) {
        let val = arrayValues[i];
        if(!existsElement(itemSelect, val)) {
            itemSelect.options[j] = new Option(val + " - " + arrayNames[i], val, null);
            j++;
        }
    }
}


Given an unsorted integer array, find the first missing positive integer

PEP8

Python uses underscore as naming separator in function and variable names, see PEP8

Naming

for i,v in enumerate(nums)

It's better to use some obvious names so instead of i,v you should use index, value

Improvements

You've got a right idea on how to solve this, but there are some minor things in your implementation that can be improved.

for i,v in enumerate(nums):
    if v > len(nums):
        nums[i]=-1
    elif v <= 0:
        nums[i]=-1
    else:

this part can be simplified to

if  0 >= value > len(nums):
    continue

Now your while loop can make infinite number of cycles on such list [3,4,3,-1] so you need to handle this, also you don't have to replace items that are <= 0 or items that are >= len(nums) with -1 you can just skip them.

So in the end your code should look like this:

def first_missing_positive(nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    if not nums:
        return 1
    for index, value in enumerate(nums):
        if len(nums) < value <= 0:
            continue
        while index + 1 != nums[index] and 0 < nums[index] <= len(nums):
            v = nums[index]
            nums[index], nums[v-1] = nums[v-1], nums[index]
            nums[v-1] = v

            # Don't create infinite loops
            if nums[index] == nums[v-1]:
                break

    for index, value in enumerate(nums, 1):
        if value != index:
            return index
    return len(nums) + 1


One thing I noticed, the sorting routine is modifying the array and returning the array.  I would suggest either make the functions void or create a new array to do the merge in.  A sort function with a void return type automatically tells the user that the sort is in place.  Where as, a return type of an array, tells the user that a new array is created, but that the original array isn't touched.


Clone a linked list with a random pointer (part 2)

Cloning

I would expect from a cloning process to not modify the original instance, even if the modifications are transient and the original state is restored.
Your implementation adds nodes in the original list during the process.
After the clone is ready,
you clean up and restore the original list,
but this approach is surprising,
and a mistake could destroy the integrity of the original list.

I suggest to stick with more conventional approaches that produce a clone without modifying the original instance, for example by using an intermediary map to store the mapping of old nodes to new nodes, so that the random links can be correctly recreated.

Usability

How would you use this linked list in a program?
I see several usability issues:

The concept of a list and a node are not separated. This is confusing.
Common methods of a list are missing. How to add a node? The implementation doesn't offer an easy way to do that, users have to do that manually. They can only do that if they know the implementation, especially the linking between the nodes.

In other words, there's a total lack of encapsulation,
leading to serious usability consequences.

Conventions

Some Python conventions (PEP8) are violated, for example:

Function and variable names should use snake_case
There should be a blank line between functions of a class

There are others too. I suggest to go over PEP8 and follow the recommendations.


Disclaimer: I did not get any noticeable performance improvements but here are a few ideas nonetheless. Also, your code looks really good to me and there is not much to improve.
In calculate_hash, you compute a power in the body of the loop. Based on the way the exponents is computed, we can tell that the different values will be: BASE ** (length - 1), BASE ** (length - 2), etc. A different option could be to compute the initial value with the '**' and then update the power using division by BASE.
We could get something like:
def calculate_hash(s: str, length: Optional[int] = None) -> int:
    if length is not None:
        s = islice(s, 0, length)
    else:
        length = len(s)
    power = BASE ** (length - 1)
    ret_hash = 0
    for c in s:
        ret_hash += char_to_int(c) * power
        power /= BASE
    return ret_hash % MOD

In roll_hash, the computation is split across different lines as the first line is getting too big. In order to keep the expressions easier to read, it may be useful to define additional local variables such as: prev_int, next_int = char_to_int(prev_char), char_to_int(next_char).
Then, a few things can be spotted:

we compute m = (val1 % MOD) and then (m + val2) % MOD: we could perform the modulo operation just once
the ((prev_hash - char_to_int(prev_char) * BASE ** (length - 1)) * BASE) expression can be slightly simplified by expanding it, we get: prev_hash * BASE - char_to_int(prev_char) * BASE ** length. It is much easier to read and should be just as efficient (if not more).

At the end, the whole function becomes:
def roll_hash(prev_hash: int, prev_char: int, next_char: str, length: int) -> int:
    prev_int, next_int = char_to_int(prev_char), char_to_int(next_char)
    return (next_int + prev_hash * BASE - prev_int * BASE ** length) % MOD

As mentionned in the comment, the power operation is quite expensive. Maybe we could try to compute it just once and provide it to the roll_hash function.
Also, we could try to take this chance to use an unknown part of the pow builtin: the mod parameter. Here, we may as well compute BASE ** length % MOD so that we get to handle smaller values later on (this is an improvements when the length of the pattern is bigger than 4).
At this stage, we get:
def roll_hash(prev_hash: int, prev_char: int, next_char: str, base_pow_length: int) -> int:
    prev_int, next_int = char_to_int(prev_char), char_to_int(next_char)
    return (next_int + prev_hash * BASE - prev_int * base_pow_length) % MOD

def rabin_karp(text: str, pattern: str) -> List[int]:
    """
    Returns a list of indices where each entry corresponds to the starting index of a
    substring of `text` that exactly matches `pattern`
    """
    p_hash = calculate_hash(pattern)
    n = len(pattern)
    curr_hash = calculate_hash(text, n)
    indices = []
    if p_hash == curr_hash:
        indices.append(0)
    base_pow_length = pow(BASE, n, MOD)
    for i in range(1, len(text) - n + 1):
        curr_hash = roll_hash(
            curr_hash, text[i - 1], text[i + n - 1], base_pow_length
        )
        if p_hash == curr_hash:
            indices.append(i)
    return indices


Implementing a Simple "MoneyAccount" in CoffeeScript

This seems closely tied to your other question. I posted an answer for that one, which I'll incorporate/reference here.

Calling it MoneyAccount (in "UpperCamelCase") implies that it's a constructor. But it's not quite; it's just a function. But I assume that's done on purpose in order to have "private" variables (i.e. the closed-over balance argument) while still allowing one to invoke it with or without the new keyword.

Still, there are a couple of things you could do:

You're diligent in checking the input for deposit and withdraw... but not the initial balance. So account = MoneyAccount("foo") would spell trouble right away.
But even if you check the type of the initial balance, it'd still allow someone input a negative initial balance. But the way withdraw works seems to imply that a negative balance is impossible.
Incidentally, I could also say account = MoneyAccount(1/0) and have Infinity money! Sounds nice, but perhaps not what you want.
Similar to the above, there's nothing stopping you from withdrawing or depositing a negative or infinite amount.
As mentioned in the answer I linked to, you don't need if...else branches if you throw an an exception; the function will exit if it throws.
There's no way to just get the balance, which would seem problematic for an account. You can print it, sure, but you can't just get it. If you add a method to do that, you can skip the console.log stuff (which incidentally, you're only doing for withdraw but not for deposit). Logging stuff isn't really the responsibility of an account object anyway; leave that to external code.
x should probably be named amount instead, just to be descriptive.
You might want to throw a RangeError in withdraw to be a bit more precise.
Return values are a little haphazard. deposit returns the new balance while withdraw returns the amount withdrawn.
The obj var is unnecessary; you can just leave it out entirely. And you can even leave out the curly brackets (which I personally like to do in a case like this, but it's a matter to taste, really).

In the end, I get this:

MoneyAccount = (balance = 0) ->
  # Adapted from the linked answer
  assertValidAmount = (amount) ->
    number = Number amount
    if isNaN(number)
      throw new TypeError("Expected a numeric amount")
    if not isFinite(number) or number < 0
      throw new RangeError("Expected a positive, finite amount")

  assertValidAmount balance

  # everything below will be interpreted as an object
  # and returned, even without the curly braces

  balance: -> balance

  withdraw: (amount) ->
    assertValidAmount amount
    throw new RangeError("Insufficient funds") if amount > balance
    balance -= amount

  deposit: (amount) ->
    assertValidAmount amount
    balance += amount

That should be pretty safe.


sorting a map by converting it to vector

The code is correct. However, I still have some recommendations:

Sort the includes, so you can easily spot recurring/missed ones

#include <algorithm>
#include <iostream>
#include <map>
#include <utility>
#include <vector>

You do not need to run the loop, you can simply pass the map to the std::vector constructor. As you use structured bindings and therewith at least C++17, I suggest Template Argument Deduction to omit the type of the vector

std::vector items(freq.begin(), freq.end());

The comparison function takes the arguments by copy, which is not optimal. Rather use const auto&:

[] (const auto& a, const auto& b) { return a.second > b.second;})

Note that std::sort may change the ordering of elements with equal value. If you want those elements with equal frequency to appear in the same order than in the map you would need std::stable_sort. However, keep in mind that this requires additional resources in memory and compute time.
You are using a std::map, which is an ordered container. If you are only interested in the frequencies then a std::unordered_map will generally offer better performance. Although for a simple alphabet this will most likely be negligible.


Path validation helper in a 'path input box'

Start a Timer.

Whenever the text box changes, the user presses a key, the TextChanged event occurs, etc, start the timer. If it changes again, reset it. Create some timeout that, after which, the file validation would occur. (200ms would be plenty)

This has the obvious benefit of reducing the number of IO requests you do, and it helps keep responsiveness up. You can also make it asynchronous, and only hold the UI when doing actual updating.

As far as your code goes...

I would add braces in your else condition. I used to omit braces whenever possible, but I encountered more than one bug as a result, and it's just as easy to add them.

There's really not much else to comment on; there's not a lot going on here and it's quite clean to begin with.


Another approach I can think of could be this. Get rid of myMemory altogether. Once you receive data in thread B, allocate memory and copy that data (as you're doing now). Send thread C a message that data is received. Once thread C copies the data into its internal buffer, thread C can send message back to thread B that the data has been copied. Thread B then deallocate the buffer.

Your design seems fine to me. Yet another approach could be avoiding the data copy in thread C.

int index2 = 0;
char* dataToProcess;
if (event Fires) // if event in Thread B is set
 dataToProcess = &myMemory[index2*30*1024*1024];
 processData(dataToProcess)
// Rest of the code


The MAX_OUTPUT_SIZE constant does not correctly account for how many characters might be generated, and it does not agree with the calculation made within to_string().  In particular, note that sizeof (int) and sizeof (float) indicate how much memory is required to store values of those types; that's not at all related to how many characters are required to print them.

The correct calculation is hard to get right: you need to add the longest int value (formatted as a decimal), the longest float value (as a float) and the longest display_name, as well as all your fixed text and the terminating NUL.

It's hard to do that portably.

It should also be noted that a function parameter of char[MAX_OUTPUT_SIZE] decays to a pointer, and you have no guarantee that it points to an array of the declared size.

The right way to output into a char array is to pass the length as a separate parameter, and for your output function to indicate the required length if it fails (either by the return value, or via an output parameter).  Consider a function interface similar to snprintf() - but be aware of the common ways of mis-calling snprintf() and make sure you avoid them.

Other comments:

Avoid passing your player by value - it's much cheaper to pass a pointer to a readonly struct.
With the code below, we can check the worst-case output by constructing a struct player with id of INT_MIN, points of -FLT_MAX and a maximum-length display_name, and a debug version will tell us how big a buffer is required.  You can then modify the constant to the value indicated.
If you later internationalize the program, the fixed portion of the strings are no longer fixed.  You might even have to resort to the technique of calling snprintf(NULL, 0, format, args...) to measure the size, then allocating sufficient memory with malloc().  That adds to your work, as you then need to ensure that the allocated memory is correctly freed.

#include <stdio.h>
#include <string.h>

typedef struct player {
  int id;
  float points;
  char display_name[256];
} player_t;

/* Will write no more than length characters, including the terminating NUL.
   The return value indicates the number of characters to be written, excluding the NUL.
   A return value of length or more indicates a truncated write */
size_t to_string(char *output, size_t length, const player_t *player)
{
    size_t required_len =
        snprintf(output, length,
                 "\n\tid: %d\n\tpoints: %f\n\tdisplay_name: %s",
                 player->id, player->points, player->display_name);
#ifndef NDEBUG
    if (required_len >= length)
        fprintf(stderr,
                "Buffer too small: needs %zd but %zd was supplied\n",
                required_len+1, length);
#endif
    return required_len;
}

static const size_t MAX_OUTPUT_SIZE = 5;

#include <limits.h>
#include <float.h>
int main()
{
  char stringified[MAX_OUTPUT_SIZE];

  player_t p1 = {.id = 1, .points = 17.4, .display_name = "Tester"};

  if (to_string(stringified, sizeof stringified, &p1) >= sizeof stringified) {
      fprintf(stderr, "Buffer too small!\n");
      return 1;
  }

  printf("player: %s\n", stringified);
  return 0;
}


2-opt algorithm for the Traveling Salesman and/or SRO

You repeatedly evaluate

cost(cost_mat, best)

There is an opportunity to memoize this, or at least store it in a temp var.

You should decide if you want "optimal" TSP, or "good enough" TSP
that is k-competitive with an optimal solution.

You suggest you're taking 15ms per city.
You didn't post profile / timing data, but
I have to believe that much of the time is taken up by roll + sum,
rather than by, say, creating route copies.
Could we pre-compute distances between points, and
then consider just next hops within some threshold distance?
Or order by distance, and consider only a fixed number of next hops,
adjusted upward each time a better route is found?

Could the cost() function be broken into "near" and "far" components,
with the advantage that "far" would be substantially constant?
Usually we do not find a better cost.
If we do find one, we could then fall back to "carefully"
computing the detailed "far" cost.


Here is an example of your carousel written in Angular 1.6 style with ES2015

(function(){
    class componentController {

        constructor($interval) {

            Object.assign(this, { $interval })

            this.currentCar = 0;

            this.carData = [
                {
                    class:'A4',
                    name: "Audi A4",
                    tagline: "The time is now.",
                    img: "img/big/car1.jpg"
                },
                {
                    class:'A5',
                    name: "Audi A5",
                    tagline: "Do you like power?",
                    img: "img/big/car2.jpg"
                }
            ];

            this.$interval(changeCar, 4000);
        }

        changeCar(){
            // this way you can have collection of any size
            this.currentCar = this.currentCar++ % this.carData.length;
        }
    }

    const componentOptions = {

        templateUrl: 'partials/car-slide.html',
        controller: componentController

    };

    angular.module('myApp').component('carSlide', componentOptions);

}());

ConrollerAs is $ctrl by default.


C dynamic array implementation using preprocessor

Here are some things that may help you improve your code.

Use the appropriate #includes

This program requires two headers, both of which should be included:

#include <stdio.h>
#include <stdlib.h>

Check the return value of malloc

If the program runs out of memory, a call to malloc (or realloc) can fail.  The indication for this is that the call will return a NULL pointer.  You should check for this and avoid dereferencing a NULL pointer (which typically causes a program crash).

Don't leak memory

This code leaks memory.  To begin with, the code calls malloc but there is no corresponding call to free.  For a usable general list, there should be something akin to list_destroy().

Be careful with multiline macros

Multiline macros can have odd effects if you're not careful. For instance, if we do this:

for (int i=10; i < 70; ++i)
    list_append(arr, i);

The effect is that the if part of list_append is only executed once rather than once per iteration.  This can be fixed by wrapping all multiline macros in their own block by enclosing them in curly braces.  This will, however, have the side effect of no longer requiring a terminating semicolon if that matters to you.


Optimizing jQuery functions for mobile menu

you can add some data attribute to the HTML like this

Préface

Maison Ilan

History

Vineyard

Cuverie

Chai

Wines

Contacts

so instead of .on('click') for each link you can do something like this

//all the links in #menuMain
$('#menuMain a').on('click', function(e){
    e.preventDefault();
    $('#menuMain').css('display', 'none');
//$(this).data("menu") have the id of the element to display
    $($(this).data("menu")).css('display', 'block');
    $('button').html('MAIN MENU');
});

http://jsfiddle.net/zXe7C/4/
for the example i only add the data attribute to the last two links but if you dont have something on the attribute or some element with that id then it will only hide "menuMain" but you can check first if the element $($(this).data("menu")) exists


This code looks complicated for me. Not because I don't know how to use AES encrypter but it contains a lot of redundancy. From setting CipherMode.CBC which is default to GetNewIv() which is random by default.
Is a lot of code is targeting the a security improvement? If it is, you have a breach storing key in a string. I can easily get the key from App's memory even if it currently not in use because string is immutable and can be stored in memory for undefined period of time. Storing key in byte[] array allows to cleanup the array at any moment.
If security on DB side is enough then you may simplify the code as following two methods.
I use streams because it more friendly for me. As a bonus the code can be easily ported to streams use.
private static string Encrypt(string text, byte[] key)
{
    using AesManaged aes = new AesManaged() { Key = key };
    using MemoryStream ms = new MemoryStream();
    ms.Write(aes.IV);
    using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write, true))
    {
        cs.Write(Encoding.UTF8.GetBytes(text));
    }
    return Convert.ToBase64String(ms.ToArray());
}

private static string Decrypt(string base64, byte[] key)
{
    using MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64));
    byte[] iv = new byte[16];
    ms.Read(iv);
    using AesManaged aes = new AesManaged() { Key = key, IV = iv };
    using CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read, true);
    using MemoryStream output = new MemoryStream();
    cs.CopyTo(output);
    return Encoding.UTF8.GetString(output.ToArray());
}

Demo
string text = "Hello world";
byte[] key = Enumerable.Range(0, 32).Select(x => (byte)x).ToArray(); // just for example :)
string base64 = Encrypt(text, key);
Console.WriteLine(base64);
Console.WriteLine(Decrypt(base64, key));

Output
Qh+XfnIuIdgllOiKFgzCpTURW+bUuj91S91zA1przRQ=
Hello world

I think that's enough to keep it secure on DB side. Btw, you may keep the Key generator methods if you need it.
P.S. old Rijndael solution - Rijndael was superseded by Aes in .NET, i don't remember the exact reason but something like Rijndael has a padding issue and Aes fixed it.

One more tip. If you're on Windows and the encrypted data is allowed to be lost (in case of emergency), you can use DPAPI to protect the key (MS NuGet package exists, Current User/Local Machine protecting modes available) and store protected key in DB in the same sequence as IV. Then you can use totally random key for each Encrypt() call and store it with data. The data may be lost on Windows reinstall or moving the ASP.NET server to other machine, because DPAPI uses key associated with Current User credentials or Local Machine ID. But protected data can't be restored if DB was stolen or in any other way on other PC. Anyway learn how DPAPI works, it may be useful if the server runs under Windows.


Creating a EventHandler class for buttons with different actions

Assuming that you have Java 8 available:

this.saveNewButton.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent actionEvent) {
        savePatientData(actionEvent);
    }
});

Can become, using a lambda:

this.saveNewButton.setOnAction(actionEvent -> savePatientData(actionEvent));

Or, for that particular event handler:

this.saveNewButton.setOnAction(this::savePatientData);

Example of another EventHandler

this.deletePatientButton.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent actionEvent) {
        deleteExistingPatient();
    }
});

Can become:

this.deletePatientButton.setOnAction(event -> deleteExistingPatient());

If you do not have Java 8 available:

Sorry, you're pretty much screwed. :(

Essentially, there is not that much code duplication as you might think, as each EventHandler is different.

The only way possible to solve it in this case would be to have all the buttons use the same EventHandler and perform a whole lot of checks such as:

if (event.getSource() == this.deletePatientButton) {
    ...
}

Side note:

If you are using JavaFX 8, you have the possibility to define an onAction in your FXML for your buttons, this will be associated with a method of that name in your controller.

See also http://code.makery.ch/blog/javafx-8-event-handling-examples/


Making a list of customers who buy the top N items from a supplier

As said in a comment this may be done better and faster with an SQL script depending on how the involved data sets are created, but below are some optimization suggestions.

You should maybe consider some input check:

private void CustomersBuyingRange(string supplier, int topN)
{
  if (string.IsNullOrWhiteSpace(supplier)) return;
  if (topN <= 0) throw new ArgumentOutOfRangeException(nameof(topN));

Optimizations:

1)

  // Get a list of products from a supplier.
  string[] products = productDetails
                      .Where(x => x.SupplierID == supplier.ToUpper())
                      .Select(x => x.ProductCode).ToArray();

supplier.ToUpper() is called repeatedly for every element in the vector. Consider to do it once:

  supplier = supplier.ToUpper();

  // Get a list of products from a supplier.
  var products = productDetails
                      .Where(x => x.SupplierID == supplier)
                      .Select(x => x.ProductCode);

As shown, there is also no need to populate an array with the result here.

2)

  var customers = customerDetails
      .Where(x => x.LastInvoiceDate > DateTime.Now.AddMonths(-3).Date)
      .OrderBy(x => x.CustomerName)
      .ToList();

Again you create a new DateTime object for each customer you evaluate in the Where() call. Consider to create that date once:

    DateTime minDate = DateTime.Now.AddMonths(-3).Date;
    // We only want customers that have had an order in the last 3 months.
    var customers = customerDetails
        .Where(x => x.LastInvoiceDate > minDate)
        .OrderBy(x => x.CustomerName);

You can then reuse it in the last loop too.

3)

    for (int i = 0; i < topN; i++)
    {
      row[topSellers[i]] = detailedOrderLines
          .Any(x => x.CustomerID == customer.CustomerID &&
               x.ProductCode == topSellers[i] &&
               x.InvoiceDate > DateTime.Now.AddMonths(-3).Date
               ) ? "Yes" : "No";
    }

Here you should be able to run a foreach loop instead:

      foreach (var topSeller in topSellers)
      {
        row[topSeller] = detailedOrderLines
            .Any(x => x.CustomerID == customer.CustomerID &&
                 x.ProductCode == topSeller &&
                 x.InvoiceDate > minDate) ? "Yes" : "No";
      }

4)

foreach (var customer in customers)
  {
    DataRow row = table.NewRow();
    row["CustomerID"] = customer.CustomerID;
    row["Customer"] = customer.CustomerName;
    row["AccountManager"] = customer.AccountManager;
    for (int i = 0; i < topN; i++)
    {
      row[topSellers[i]] = detailedOrderLines
          .Any(x => x.CustomerID == customer.CustomerID &&
               x.ProductCode == topSellers[i] &&
               x.InvoiceDate > DateTime.Now.AddMonths(-3).Date
               ) ? "Yes" : "No";
    }
    table.Rows.Add(row);
  }

Here you keep require the entire detailedOrderLines although you previously when creating the topSellers actually grouped those by ProductCode. So if you instead of selecting topSellers as strings select them as anonymous objects like:

  // Rank the products by distribution and then by sales,
  // then add the required amount to an array.
  var topProducts = detailedOrderLines
                          .Where(x => products.Contains(x.ProductCode))
                          .GroupBy(x => x.ProductCode)
                          .Select(x => new
                          {
                            ProductCode = x.FirstOrDefault().ProductCode,
                            DeliveredQty = x.Sum(p => p.DeliveredQty),
                            Distribution = x.Select(c => c.CustomerID).Distinct().Count(),
                            OrderLines = x.ToList()
                          })
                          .OrderByDescending(x => x.Distribution)
                          .ThenByDescending(x => x.DeliveredQty)
                          .Take(topN).ToList();

you only have to query the subset of orderLines that belongs to the current ProductCode:

    foreach (var customer in customers)
    {
      DataRow row = table.NewRow();
      row["CustomerID"] = customer.CustomerID;
      row["Customer"] = customer.CustomerName;
      row["AccountManager"] = customer.AccountManager;

      foreach (var topProduct in topProducts)
      {
        row[topProduct.ProductCode] = topProduct.OrderLines.Any(x => x.CustomerID == customer.CustomerID && x.InvoiceDate < minDate) ? "Yes" : "No";
      }

      table.Rows.Add(row);
    }

All in all the method could then be something like:

private void CustomersBuyingRange(string supplier, int topN)
{
  if (string.IsNullOrWhiteSpace(supplier)) return;
  if (topN <= 0) throw new ArgumentOutOfRangeException(nameof(topN));

  supplier = supplier.ToUpper();

  // Get a list of products from a supplier.
  var products = productDetails
                      .Where(x => x.SupplierID == supplier)
                      .Select(x => x.ProductCode);

  // Rank the products by distribution and then by sales,
  // then add the required amount to an array.
  var topProducts = detailedOrderLines
                          .Where(x => products.Contains(x.ProductCode))
                          .GroupBy(x => x.ProductCode)
                          .Select(x => new
                          {
                            ProductCode = x.FirstOrDefault().ProductCode,
                            DeliveredQty = x.Sum(p => p.DeliveredQty),
                            Distribution = x.Select(c => c.CustomerID).Distinct().Count(),
                            OrderLines = x.ToList()
                          })
                          .OrderByDescending(x => x.Distribution)
                          .ThenByDescending(x => x.DeliveredQty)
                          .Take(topN).ToList();

  using (DataTable table = new DataTable("Customers"))
  {
    table.Columns.Add("CustomerID", typeof(string));
    table.Columns.Add("Customer", typeof(string));
    table.Columns.Add("AccountManager", typeof(string));
    // Add the columns with the products.
    foreach (var topProduct in topProducts)
    {
      table.Columns.Add(topProduct.ProductCode, typeof(string));
    }

    DateTime minDate = DateTime.Now.AddMonths(-3).Date;
    // We only want customers that have had an order in the last 3 months.
    var customers = customerDetails
        .Where(x => x.LastInvoiceDate > minDate)
        .OrderBy(x => x.CustomerName);

    foreach (var customer in customers)
    {
      DataRow row = table.NewRow();
      row["CustomerID"] = customer.CustomerID;
      row["Customer"] = customer.CustomerName;
      row["AccountManager"] = customer.AccountManager;

      foreach (var topProduct in topProducts)
      {
        row[topProduct.ProductCode] = topProduct.OrderLines.Any(x => x.CustomerID == customer.CustomerID && x.InvoiceDate < minDate) ? "Yes" : "No";
      }

      table.Rows.Add(row);
    }

    Export.ExportToExcel(table, true);
  }
}

Disclaimer: I haven't had the opportunity to test the above, so don't hang me if it doesn't improve anything or if I have misunderstood something.


General solution to sum multiples of multiple numbers below a limit

After I provided a quick-glance alternative implementation yesterday, here comes a full review now. It's so different in approach I chose to add another answer for it. That said, let's get started:

I see in the comments to a now deleted answer that you don't want comments on the code you provided as main. I'll do it anyways, because you're doing some things that make me shiver:

System.out.println( sumMultiples(below, base) );

This is definitely nitpickish, but I personally prefer to not add additional spaces inside the braces of a method-call:

System.out.println(sumMultiples(below, base));

// Making names shorter to help readability
int b0 = base[0];
int b1 = base[1];

Don't do that. Shorter names are not readable. A readable name can be easily read out loud. That makes your comment a blatant lie in my eyes. Usually this would be the point where you'd have lost my respect as fellow programmer... I understand that you may sometimes want variable names shorter, and they are nice in the rest of your code. But the resoning is something ...

Oh and... Don't number your variables! This makes it difficult to process them in their mental context, and makes the code harder to understand.

// Hand tuned to number and values. Something I'd like to avoid
System.out.println( sumSkip(b0, below) + sumSkip(b1, below) - sumSkip(b0*b1, below) );
System.out.println( b0*sumIdentity(below/b0) +
                    b1*sumIdentity(below/b1-1) -
                    b0*b1*sumIdentity( below/ (b0*b1) )  );

Why are you doing this? There is some relatively complicated problematic and it's slammed into the reader's face in the main-method.

The main-method is supposed to be a place of high-level abstraction. I think reading a main-method should be just like reading English. A simple English sentence. Consider the following (as example):

public static void main(String[] args) {
    new Program().start();
}

Extract the complexity into methods. I figure it's fine to have this hand-tuned and doubt there is a way to avoid this when not working with an already generalized formula.

// General solution - any sited base with any values - uses brute force approach

This wants to be javadoc:

/**
 * General solution. Calculates the result using a brute-force approach
 *
 * @parameter below
 *     An integer representing the non-inclusive upper border of the problem.
 * @parameter base
 *     At least one integer representing the divisors for leftover-free division of numbers that are to be summed.
 */

For the sumMultiples, see my other answer. There's not really much else to say about that. Nice naming, simple and straightforward approach... Actually this goes for the rest of your code (aside from the non-javadoc javadocs) with one small exception:

How the **** does sumIdentity work? //Sum using math doesn't help me all that much ;)

Alas, that's it for now.


if(dimension == 0) {
    return 0;
}

Mathematically, that is not correct. The determinant of an empty (i.e. zero-dimensional) matrix is one, see for example What is the determinant of []? on Mathematics Stack Exchange.

With respect to efficiency: Your program computes the determinant recursively using the Laplace formula, which requires \$ O(n!) \$ arithmetic operations, and the creation of many temporary “submatrices”.

A better method (at least for larger matrices) is Gaussian elimination which requires \$ O(n^3) \$ arithmetic operations, and can operate on a single copy of the original matrix.


Object scope

You should introduce object scope. Your source code gains flexibility through the possibility to to apply abstraction, polymorphy, inheritance (Open Closed Principle). Your code will be testable much more easy. Furthermore in JAVA 8 you can make use of functional interfaces. That would not be possible in a static context.

Constants

As "bracketMap" is a constant you should declare it "static final". Then you will get rid of instantiating the HashMap every time you call "validateBracketPairs".

break, multiple return (and continue)

Avoid those statements. Using them you hinder yourself to make use of applying refactorings like "extract method".

Within a loop you spread your breaking conditions all over the place. That makes the code less readable an maintainable. All breaking conditions for a loop should be at one place, the loop header/footer.

For methods that have to have a return value try to have only ONE return statement at the end.

for-loop

The for-each-loop is not the appropriate loop for this case. Consider a loop type that allows breaking conditions to have a proper place to put your go-on (breaking) conditions: As long as there are characters to process OR you not found a validation error.

switch-case

The switch case statement can be simplified through the standard if-then-else. Use the keys() and values()-method of the bracketMap to check if they contain a character. Now you are able to extends bracket pairs through putting them into the bracketMap without touching the if statement anymore. (Single Responsibility Principle).

Naming

Because bracketStack only contains open brackets it should be mentioned in the name: openBracketStack.

Code

So I would end up with something like this:

public class BracketPairsValidator implements Function<String, Boolean> {

    public static void main(String[] args) {
        System.out.println(new BracketPairsValidator().apply(""));
    }

    public static final char OPEN_SQUARE_BRACKET = '[';
    public static final char CLOSED_SQUARE_BRACKET = ']';

    public static final char OPEN_CURLY_BRACKET = '{';
    public static final char CLOSED_CURLY_BRACKET = '}';

    public static final char OPEN_PARENTHESIS = '(';
    public static final char CLOSED_PARENTHESIS = ')';

    private final static Map<Character, Character> BRACKET_MAP = createBracketMap();

    private static Map<Character, Character> createBracketMap() {
        HashMap<Character, Character> map = new HashMap<>();
        map.put(OPEN_SQUARE_BRACKET, CLOSED_SQUARE_BRACKET);
        map.put(OPEN_CURLY_BRACKET, CLOSED_CURLY_BRACKET);
        map.put(OPEN_PARENTHESIS, CLOSED_PARENTHESIS);
        return map;
    }

    @Override
    public Boolean apply(final String candidate) {

        StringCharacterIterator iterator = new StringCharacterIterator(candidate);

        final Stack<Character> openBracketStack = new Stack<>();

        boolean hasMatchingBracket = true;

        for (char ch = iterator.current(); ch != StringCharacterIterator.DONE && hasMatchingBracket; ch = iterator.next()) {

            if (isOpenBracket(ch)) {
                openBracketStack.add(ch);
            } else if (isClosedBracket(ch)) {
                hasMatchingBracket = !openBracketStack.isEmpty() && ch == BRACKET_MAP.get(openBracketStack.pop());
            }

        }

        return hasMatchingBracket && openBracketStack.isEmpty();
    }

    private boolean isClosedBracket(final char ch) {
        return BRACKET_MAP.values().contains(ch);
    }

    private boolean isOpenBracket(final char ch) {
        return BRACKET_MAP.keySet().contains(ch);
    }

}


Bug
Your program computes the distance between "kittenede" and "s" as 1.  For some reason you switched your two array indices when you initialized them:

for (i = 0; i <= m; i++) {
    d[i][0] = i;
}
for (j = 0; j <= n; j++) {
    d[0][j] = j;
}

should be:
for (i = 0; i <= m; i++) {
    d[0][i] = i;
}
for (j = 0; j <= n; j++) {
    d[j][0] = j;
}

With this change, the program correctly computes the distance between "kittenede" and "s" as 9.
Fixed length array
There's no need for this:
int[][] d = new int[100][100];

when you already know the lengths of your two strings.  You should just move that line lower and use the n and m you compute:
int[][] d = new int[n+1][m+1];


The code leaves a bad first impression because of how it is formatted. In particular, the extra whitespace between the return type and the function name, and that between the variable's type and its name, looks odd.
Unless you are writing code that needs to be compatible with pre-C99 compilers, you should break the habit of declaring variables at the top of the block and initializing them later. Instead, postpone the declaration of variables until the point when they can be initialized (to the extent possible). This helps to minimize bugs caused by uninitialized variables.
I recommend always using curly braces to create block scope after if statements, even if you currently only have one statement there. This minimizes the potential for serious bugs when you later go back and add some additional logic.
The return value of malloc must be checked immediately after the call to malloc! If malloc fails, it will return a null pointer, and any attempt to use a null pointer results in undefined behavior. Therefore, you need to move the call to memset to after you check the result of malloc, otherwise you risk undefined behavior.
In fact, you do not need to call memset at all. If you check the C language specification for information on the realloc function, you will see that it does not initialize the additional memory in the case where the new size is larger than the old size.
You are breaking the realloc specification in several other ways, too. If your goal is to simulate/reinvent realloc, then you absolutely must ensure that your implementation behaves in exactly the same way as realloc.

In fact, realloc is really a complete memory management subsystem wrapped in a single function—it does everything that malloc and free do—and more—making its semantics very complicated and confusing. Here's a summary of the relevant requirements for realloc from the standard:

If the requested block size is smaller than the original size of the block, realloc either frees the unwanted memory at the end of the block and returns the input pointer unchanged, or allocates a new block of the appropriate size, frees the original block, and returns a pointer to this newly-allocated block.
If the requested block size is larger than the original size of the block, realloc may allocate an expanded block at a new address and copy the contents of the original block into the new location. In this case, a pointer to the expanded block is returned, and the extended portion of the block is left uninitialized. Or, if possible, it may expand the original block in-place and return the input pointer unchanged.
If realloc cannot satisfy a request to expand a block, it returns a null pointer and does not free the original block. (realloc will always succeed when you request to shrink a block.)
If the input pointer is null, then realloc behaves exactly as if you had called malloc(size), returning a pointer to the newly-allocated block of the requested size, or a null pointer if the request could not be satisfied.
If the requested size is 0 and the input pointer is non-null, then realloc behaves exactly as if you had called free(ptr), and always returns a null pointer.
If the input pointer is null and the requested size is 0, then the result is undefined!

Whew! To be correct, your code needs to implement all of these conditions, precisely as documented.

Conversely, if you are not simulating realloc (and that's perfectly fine—maybe you're reinventing the wheel because you want different behavior in your program), then you need to use a different name so that other programmers are not fooled into thinking that it is identical to realloc and won't expect it to behave in the same way.
In fact, as you can see from the list of requirements above, it is actually impossible to reinvent realloc as required by the specification, since you do not have insider knowledge about how the standard library implements memory management. You need to be able to determine the original size of the memory block pointed to by ptr, and there is no portable way to do so.

Why do you need this information? Two reasons. First, you need to know whether the caller is requesting to shrink or expand the memory block so that you can follow the correct semantics. Second, you need to know how many bytes to copy when you call memcpy—right now, you are copying past the end of the original buffer, which is undefined behavior!

The first problem could be solved by altering the semantics of our function so that it only grows the size of a block, renaming it something like GrowBlock or ExpandMemory to make it clear that it is not identical to realloc. Unfortunately, there would be no reliable way to assert this requirement that len is greater than or equal to the current size of the memory block pointed to by ptr within the body of the function, so documentation alone would have to suffice, which is a very weak guarantee. Even more unfortunately, this won't solve the second problem—we still have no way to correctly call memcpy!

Therefore, our only real option is to modify the function's signature to accept the original size of ptr as a parameter (in addition to the desired new size that you already accept as a parameter).

All of that considered, here's how I'd write it:

// This function is similar to realloc() and implements the same semantics,
// except that the caller must explicitly pass the original size of the
// memory block pointed to by 'ptr', as well as the desired size.
void *my_realloc(void *ptr, size_t originalLength, size_t newLength)
{
   // Note that because we cannot rely on implementation details of the standard library,
   // we can never grow a block in place like realloc() can. However, it is semantically
   // equivalent to allocate a new block of the appropriate size, copy the original data
   // into it, and return a pointer to that new block. In fact, realloc() is allowed to
   // do this, as well. So we lose a possible performance optimization (that is rarely
   // possible in practice anyway), but correctness is still ensured, and the caller
   // never need be the wiser.
   //
   // Likewise, we cannot actually shrink a block of memory in-place, so we either
   // have to return the block unchanged (which is legal, because a block of memory
   // is always allowed to be *larger* than necessary), or allocate a new smaller
   // block, copy the portion of the original data that will fit, and return a
   // pointer to this new shrunken block. The latter would actually be slower,
   // so we'll avoid doing this extra work when possible in the current implementation.
   // (You might need to change this if memory pressure gets out of control.)

   if (newLength == 0)
   {
      free(ptr);
      return NULL;
   }
   else if (!ptr)
   {
      return malloc(newLength);
   }
   else if (newLength <= originalLength)
   {
      return ptr;
   }
   else
   {
      assert((ptr) && (newLength > originalLength));
      void *ptrNew = malloc(newLength);
      if (ptrNew)
      {
          memcpy(ptrNew, ptr, originalLength);
          free(ptr);
      }
      return ptrNew;
    }
}

Indeed, this looks quite complicated—and it it isn't even as complicated as a real implementation of realloc! It's a good lesson about why realloc is actually bad design. You should not write massive multi-purpose functions, and you certainly shouldn't implement an entire subsystem in a single function! Instead, break the important behaviors out into separate functions. In this case, you might have four separate functions that allocate a block (AllocateMemory), free a block (FreeMemory), expand a block (ExpandMemory), and shrink a block (ShrinkMemory). This division of labor makes the implementation(s) much easier to write, easier to reason about, easier to include error-checking, and therefore easier to maintain and less likely to contain bugs. I realize your assignment was to write realloc, but there is a broader (perhaps inadvertent) lesson here that you should not miss.


Converting A Map[String, Seq[String]] To A Seq[(String, String)] in Scala

I don't see how the functional code looks clumsy or difficult to read. If you have problems reading functional code, than don't write it - the imperative code is entirely fine, as long as the side effects remain local to a single function.

A lot of readability can be gained by giving your intermediate values useful names and to apply a different formatting:

headers.toSeq flatMap {
  case (parameter, values) =>
     values map (parameter -> _)
}

No need to squash everything into a single line or to use tuples ugly _X accessors.

Another way to write your code is:

for ((parameter, values) <- m.toSeq; v <- values)
  yield parameter -> v

which looks very similar to the imperative solution but is exactly the same as the code before.

Write code that belongs to your skill level. If you don't feel fine with shorter and more functional code, then let it longer and more imperative. Improve your skills during the next months and refactor the code once you come back and see the need for it.


Mounting a disk with the DiskArbitration framework

A few years later, and not being a C expert;
As far as I know (using Pascal myself), your application needs to wait for the callback to happen. By the looks of it though (again: not an expert) your application may already closed/finished before the callback actually happened.


Math.random() doesn't return cryptographically secure numbers on all browsers. If this is intended for production use, you'll want to use a library that has a secure PRNG.

If you're not going to go with Jerry's suggestion to make pronounceable passwords, I'd recommend at least getting rid of 1/l/I and O/0, which a number of password generators do by default, because people often mis-read them and then request a password reset.


You can create a KeyProcessor interface and implementation for every key (move the body of the current Processor.processStuffAboutKeyX() methods to these classes):

public interface KeyProcessor {
    void processStuff(String data);
}

Then fill a map with the available implementations:

Map<Key, KeyProcessor> processors = new HashMap<>();
processors.add(key1, new Key1Processor());
...
processors.add(key4, new Key2Processor());

And use that map in the loop:

for (Entry<Key, String> entry: map.entrySet()) {
    Key key = entry.getKey();
    KeyProcessor keyProcessor = processors.get(key);
    if (keyProcessor == null) {
        throw new IllegalStateException("Unknown processor for key " + key);
    }
    final String value = entry.getValue();
    keyProcessor.processStuff(value);
}

With the original 25+ cases the switch-case method is at least 75 lines long (25 case statement, 25 break statement, and at least 1-1 method call line for every case). The separate classes reduces the size and complexity which a developer see at once (+no need to scroll), the code is easier to maintain and test because you can test every case in isolation.

I think it's a lot more easier to have (and handle) a couple of small classes and corresponding *Test classes (with a few test methods for every class) than having a big class (25+ cases) and a lot of tests in one corresponding *Test class or a lot of *Test classes which test separate case branches of the same startProcessing method.

I admit that these arguments might be weak ones but without an actual implementation of the Processor class and the code which creates the input map is hard to say more.

Further readings:

Refactoring: Improving the Design of Existing Code by Martin Fowler: Replacing the Conditional Logic on Price Code with Polymorphism
Replace Conditional with Polymorphism


Your code is pretty good. Change num <=100 to True and remove the un-needed num out of the while loop, and it's good.
You should also expect user input to not be a number and handle it as you need.

Since comprehensions are a cleaner than map and filter, you may want to steer clear of them. Some people stick to never using them, I however use them if it makes the input clearer, such as map(str, user_input()).

You can then adjust your code slightly to get the iterative approach of:

list_ = []
while True:
    try:
        num = int(input())
    except ValueError:
        continue
    if num > 100:
        break
    if num >= 10:
        list_.append(num)

However, you may want a functional approach. This can be better as then you can pick and mix functions, but some don't like it as much.

Make an infinite generator, of user input.
itertools.takewhile the input is good.
Filter input.

def user_input():
    while True:
        yield input()

def to_int(numbers):
    for num in numbers:
        try:
            yield int(num)
        except ValueError:
            continue

nums = itertools.takewhile(lambda n: n <= 100, to_int(user_input()))
print('\n'.join(str(n) for n in nums if n >= 10))

Python is multi-paradigm, and so you can mix them. And so as-long as it works and is clear, it's fine. I personally would use:

def user_input():
    while True:
        try:
            yield int(input())
        except ValueError:
            continue

def filter_numbers(numbers):
    for num in numbers:
        if num > 100:
            break
        if num >= 10:
            yield num

print('\n'.join(str(n) for n in filter_numbers(user_input())))


Minimum number of flight segments using breadth-first search

1. Review

There's no docstring. What does this function do? What arguments does it take? What does it return?
The code uses a list to represent the queue of nodes to be visited. But if you look at the TimeComplexity page on the Python wiki, you'll see that list.pop(0) takes time proportional to the length of the list, and that means that the algorithm takes time that's quadratic in the number of nodes in the graph.

Instead of keeping the queue of nodes in a list, you need a collections.deque, which has an efficient popleft method.
Each time the code reaches a new node, it copies the path to reach that node, and puts the path on the queue. But this is wasteful of memory (because paths might become long and have to be copied out many times) and leads to quadratic runtime.

Since the code only needs to return the distance to the target (not the path), it only needs to store the distance to each node.
The variable n is not used.
Instead of:

while (len(queue) > 0):

write:

while queue:

It would be faster to check whether a node has been visited before adding it to the queue (rather than after removing it from the queue). This avoids unnecessary append and pop operations on visited nodes.
It would be faster to check whether the target has been reached before adding it to the queue (rather than after removing it from the queue). This avoids having to wait for the target to move all the way up the queue.
distance returns -1 if there was no path from source to target. But it is risky to return an exceptional value like this: it would be all too easy for the caller to forget to check the result. It is better to raise an exception for exceptional cases.

2. Revised code

from collections import deque

class Unreachable(Exception):
    """Exception raised when there is no path between nodes in a graph."""

def distance(graph, source, target):
    """Return the number of edges in the shortest path from source to
    target in a directed graph. The graph must be represented as a
    mapping from a node to a collection of its neighbours. If there is
    no path from source to target, raise Unreachable.

    >>> distance({1: [2, 3], 2: [3, 4], 3: [4, 5]}, 1, 5)
    2

    """
    if source == target:
        return 0
    queue = deque([(source, 0)]) # Queue of pairs (node, distance).
    visited = set()              # Set of visited nodes.
    while queue:
        node, dist = queue.popleft()
        visited.add(node)
        for neighbour in graph[node]:
            if neighbour in visited:
                continue
            elif neighbour == target:
                return dist + 1
            else:
                queue.append((neighbour, dist + 1))
    else:
        raise Unreachable("No path from {!r} to {!r}".format(source, target))


Duplicate the previous input if zero or not a number

It's possible to solve this problem using a functional Pythonic approach a layer at a time.

First, the original code is refactored as functions for reference. Long type and numpy were not available on my current workstation but were not necessary to process the example data.
A transpose and substituting generator are used to produce an alternative proof of concept. It is elaborated to include a "first qualified value or default to 0" rule because the original algorithm did not clean the first row and propagates unqualified values in a column until a qualified value occurs.

I've included a demo at the end that shows why a list comprehension fails since It does not alter the table in place.

#original code refactored as functions
data = [[0, -1, 2], [7, 8.1, -3], [-8, 5, -1], ['N', 7, -1]]
print("data: ", data)
def unnumeric_or_neg(z):
    return not isinstance(z, (int, float)) or z < 0

def clean1 (data,unqal):
    m, n = 4,3
    for i in range(1, m):
        for j in range(n):
            if unqal(data[i][j]) :
                data[i][j] = data[i-1][j]
clean1(data,unnumeric_or_neg)
print("result is in data", data)
#refresh data
data = [[0, -1, 2], [7, 8.1, -3], [-8, 5, -1], ['N', 7, -1]]
#help functions and another approach
def comp_transpose(t):
    "transpostion of rectangular table"
    return [[r[j] for r in t] for j,_ in enumerate(t[0])]

def sub_last_qal(lst,unqal):
    last_qual=0
    for (n,x) in enumerate(lst):
        if unqal(x):
            yield last_qual
        else:
            last_qual = x
            yield x
def clean2(data,unqal):
    data_t = comp_transpose(data)
    data_aug = [list(sub_last_qal(col,unqal)) for col in data_t]
    return [data[0],]+comp_transpose(data_aug)[1:]
print("2 step similar result",clean2(data,unnumeric_or_neg))
def first_qal(lst,unqal):
    """given a list return the first qualifying value given
    negative test unqal is set in scope"""
    for x in lst:
        if not unqal(x):
            return x
    return 0
def clean3(data,unqal):
    data_t = comp_transpose(data)
    data_aug = [list(sub_last_qal([first_qal(col,unqal),]+col,unqal)) for col in data_t]
    return comp_transpose(data_aug)[1:]
cn3 = clean3(data,unnumeric_or_neg)
print("augmented first qual rule ",cn3)

def first_qal_row(data_c,unqual):
    return [ first_qal(vlist,unqual) for vlist in comp_transpose(data_c)]

#list comprehensions do not support back references to results
def not_clean(data,unqal):
    return [data[0],]+[[(data[i-1][j] if unqal(x) else x ) \
        for (i,x) in enumerate(y)] for (j,y) in enumerate(data[1:])]
cn = not_clean(data,unnumeric_or_neg)
print("result is unclean", cn)
print("data is not changed ", data == [[0, -1, 2], [7, 8.1, -3], [-8, 5, -1], ['N', 7, -1]])

Output:

data:  [[0, -1, 2], [7, 8.1, -3], [-8, 5, -1], ['N', 7, -1]]
result is in data [[0, -1, 2], [7, 8.1, 2], [7, 5, 2], [7, 7, 2]]
2 step similar result [[0, -1, 2], [7, 8.1, 2], [7, 5, 2], [7, 7, 2]]
augmented first qual rule  [[0, 8.1, 2], [7, 8.1, 2], [7, 5, 2], [7, 7, 2]]
result is unclean [[0, -1, 2], [7, 8.1, 7], [7, 5, 8.1], [-1, 7, -3]]
data is not changed  True


fold expressions using a function recursively

Unfortunately c++ fold expression supports only binary operators: "any of the following 32 binary operators: + - * / % ^ & | = < > << >> += -= = /= %= ^= &= |= <<= >>= == != <= >= && || , . ->*." So you can't call your custom function in pack expansion without using a wrapper.
But if your function accepts a variadic number of arguments you can use std::apply
static constexpr std::array arr{ 1, 2, 3, 4, 5, 6, 7};

static constexpr auto sum = [](auto&&... items) {
  return (... + items);
};

static constexpr auto accumulate = [](auto&& fn, const auto& u) {
  return std::apply([fn = std::forward<decltype(fn)>(fn)](auto... item) { return fn(item...); }, u);
};

constexpr auto result = accumulate(sum, arr);

Example here.
Otherwise, you can take advantage of the comma operator:
static constexpr std::array arr{ 1, 2, 3, 4, 5, 6, 7};

static constexpr auto accumulate_impl = [](const auto& a, auto init, auto&& fn) {
  return std::apply([fn = std::forward<decltype(fn)>(fn), &init](auto... items) {
    ((void)(init = fn(std::move(init), items)), ...);
    return init;
  }, a);
};

template<class U, std::size_t N>
static constexpr U accumulate(const std::array<U, N>& u) {
  return accumulate_impl(u, U{},  [](auto&& a, auto&& b){return a+b;});
}

static constexpr auto result = accumulate(arr);

Example here.


List querying capabilities in Python 3.x

The _operators attribute is not specific to an instance but a common mapping table that can be shared by all instances, so it could be turned into a class attribute instead.

The case of an unsupported operator is not handled. The class happily keys the user create a condition with an unsupported operator, and the program will crash later. Always validate the received function parameters, and signal problems as early as possible.

After the condition is created, there's no need to hold on to the string representation of the operator only to lookup the real operator in the common mapping table. Better to lookup once, in the constructor, and store the real operator, not its string representation.

If a condition has two modes, non-reverse and reverse, consider using a boolean to represent that. Forcing the user to remember to pass on the right magic string is not very user friendly and prone to errors. If you use a boolean, there are 2 possible values, instead of an infinite spacer of invalid values. More intuitive api, and higher chance that users get it right.

These conditions cannot both be true at the same time:

            if compare_type.lower() == "non-reverse":
                # ...
            if compare_type.lower() == "reverse":

So the second one should be an elif. Converting the compare type variable to lower case twice is also not pretty.

I think par of the reason the current implementation feels clunky is that it is not fluent. For example, a fluent api to select a list of name-email pairs from a collection objects, matching a name, ordered by age, look something like this:

queryset.where(name="Jack").order_by("age").select("name", "email")

disclaimer: inspired by queries in Django


Few points:

Try to avoid long or nested if/else
Sub-divide tasks in smaller functions(clean and more readable code + easier unit testing)
Minimize variable scope(try to declare variables in the scope where you really need them)
Think about Exception in context of your business domain, may be using builder pattern (like HrsDocumentBuilder) can be useful to have consistent logging message for same type of exception(override toString() method).

We can refactor the method registerDocument() like this:

You may replace

final long start = System.currentTimeMillis();

with StopWatch

@Transactional
@Override
public void registerDocument(String submissionId) {
final long start = System.currentTimeMillis();
final List<HermesItem> items = submissionDAO.getSubmissionItems(submissionId);

if (!hasItems(items)) //extract else to method
    return;

final HrsDocumentBuilder builder = ...builder.setMailType(HermesMailType.INTERNAL);//stays the same
try {
      // minimized the scope of local variable, you need regSummary in try block so declare it here.
        RegistrationSummary regSummary = client.registerDocument(builder.buildDocument()); // will rename buildDocument() -> build()
        update(regSummary);

} catch (final ClientException e) {

       //To standarized log message we can refactor it like :
        ClientExceptionBuilder b = new ClientExceptionBuilder(e).submissionId(submissionId).build();// override toString()
        LOG.error(b.getMessage());
}
}//function registerDocument() end here

Since all other method can be easily extracted from else blocks, i am posting only the update(regSummary) because this function can be further subdivide into two smaller functions like this:

void update(regSummary) {

    if(!hasSummary()) //extract else to method
        return

    final String hermesDocId = regSummary.getHermesDocumentId();
    /* Update the DB with the documentID received from Hermes. */
    final int update = submissionDAO.updateSubmission(submissionId, hermesDocId, SubmissionStatus.HRS_REGISTERED.name());

    if (update < 1)
        LOG.error("update error");

}


Partition TPL Tasks in ASP.NET 4.0 for WCF Service

Specification

There are a couple of strategies available to you depending on what exactly you mean with

  "not spinning up too many concurrent tasks"

Possible Strategies

If you want a maximum allowed number of tasks to be processed concurrently on the server, regardless of this method, assuming you are using the default task scheduler, you can set the maximum number of threads of the .NET ThreadPool.
If you want a maximum allowed number of tasks to be processed concurrently for this given scenario, leaving the other task scheduling on the server alone, you can:

implement a custom TaskScheduler with its own dedicated thread pool. In .NET Framework you might also implement a custom SynchronizationContext instead. It's a lower level than the scheduler and you can always create a TaskScheduler.FromCurrentSynchronizationContext();.
use a SemaphoreSlim to limit the number of tasks that actually perform work concurrently. Note that this could still lead to more threads than your threshold to be activated, however, only the specified threshold amount of threads would actually be performing work.
Use JanDotNet's Parallel with MaxDegreeOfParallelism approach within a single Task. Note that this changes the affinity from threads to processors. Not sure whether this is what you are looking for. But at least it's a possibility, and non-blocking because wrapped inside a Task.


I started to write a detailed review, but in middle of it I realised that best advise I could give you looking at this code is to pick up some good Ruby book and work through it carefully, paying attention to how examples are formed. You seem to understand basics of how programming works, but your code lacks proper usage of many basic concepts, like arguments, returning, modules etc. Explaining them in detail here seems pointless, it's not a place for Ruby tutorials. You should focus on that basics before you move to object oriented design/conventions.

Still, I'll post what I already wrote as advices for you.

I don't really see any need to use OO structure in this code. It definately could still be written better though.

Indentation

Your way of indenting makes code very hard to read. Compare:

  $pic_names.each do |name|
  print 'ˁ˚ᴥ˚ˀ  '
  new_name = if pic_number < 10
  "#{$file_name} 0#{pic_number} .CR2"
else
  "#{$file_name} #{pic_number} .CR2"
end
require 'fileutils'
include FileUtils
cp(name, new_name)
pic_number = pic_number + 1
end

and:

$pic_names.each do |name|
  print 'ˁ˚ᴥ˚ˀ  '
  new_name =
    if pic_number < 10
      "#{$file_name} 0#{pic_number} .CR2"
    else
      "#{$file_name} #{pic_number} .CR2"
    end
  require 'fileutils'
  include FileUtils
  cp(name, new_name)
  pic_number = pic_number + 1
end

Ruby style guide contains some usefull examples on how you should indent your code to make it nice to read. Generally every block means 1 level of indentation (2 spaces).

Require

require 'fileutils'
include FileUtils

You only need to require 'fileutils' once, at top of your file. include also doesn't need to be reapated, instead generally it should be at top of a module.

Avoid globals

Instead of putting result of your methods in global variables, return from them. I.e:

def folder
  puts "Enter the folder name"
  while folder_name = gets.chomp
    if File.exist?("#{$folder_name}")
      puts "This folder already exists, choose a unique name"
    else
      require 'fileutils'
      FileUtils::mkdir_p "/home/moot/pickaxe/pics/#{$folder_name}"
      return folder_name
    end
  end
end

And than:

folder_name = folder
Dir.chdir "/home/moot/pickaxe/pics/#{folder_name}"

This is much more flexible.


Request for Comments: Singleton pattern implemented in Java

The best pattern for singleton that is guaranteed to be thread safe and minimizes lock overhead (because it has none) is this:

public class Singleton {
    private Singleton() {}

    private static class InstanceHolder {
        static Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return InstanceHolder.INSTANCE;
    }
}

This is lazy initialized but carries no locking overhead. It is guaranteed safe by the Java Memory Model: The inner static class is not loaded until the first call to getIinstance() and all static initializtion is guaranteed to be completed before the class is used, therefore INSTANCE is fully constructed when first accessed.

Note: The double checked locking pattern is BROKEN - see this article that explains exactly why.


I'm not sure if this is any better and it might depend on how many if statements or different categories you have whether it's worth it.  But an alternative could be something like:

var categoryLabelValues = new Dictionary<string, string>()
    {
        {"11", "Branche"},
        {"22", "Udviklingsstadie"}
    };

foreach(var interest in InterstList
                            .Where(p => categoryLabelValues.ContainsKey(p.categoryId)))
{
   <strong>@categoryLabelValues[interest.categoryId]:@interest.name</strong>
}


Problem in calculating prime numbers in python

There is no need to keep for loop in the while as while is doing the job of for,
assuming that your program tests whether the startnumber is prime or not.

using of break in else will terminate your loop once it checks that its not divisible by 2 [ the first divisor] . so break shouldn't be used there in else block as you want to test for numbers above 2.

We can while - else or for-else to solve your problem.
the code below shows the representation of your problem in while - else:

startnumber=int(raw_input("Enter a number: "))
start=2
while start<startnumber:

    if startnumber%start==0:
        print str(startnumber)+" is not a prime."
        break
    start=start+1
else:
    print str(startnumber)+" is a prime."

same code with for -else would be :

startnumber=int(raw_input("Enter a number: "))
start=2
for number in range(2,startnumber):

    if startnumber%start==0:
        print str(startnumber)+" is not a prime."
        break
    start=start+1
else:
    print str(startnumber)+" is a prime."


I'm not sure, but I don't think a generic approach is suitable for the abstract factory pattern, because the client has to specify the concrete class type in order to call the factory, and then the whole point of that pattern is gone?

The way you've tried to implement it works, but you have effectively two parallel factories (one for four wheels, and one for two) that have nothing or just very little to do with each other (DriveFourWheeler() vs DriveTwoWheeler()).

Below I've tried to fiddle a little bit with you code in order to show my understanding of the pattern and still with a generic touch.

using System;
namespace GenericAbstractFactory
{
  public enum Vehicles { car, bicycle, truck }

  interface IWheeler
  {
    void Drive();
  }

  interface IFourWheeler : IWheeler
  {
  }

  interface ITwoWheeler : IWheeler
  {
  }

  interface IVehicleAbstractFactory
  {
    IWheeler GetVehicle();
  }

  class FourWheelerFactory<FourWheeler> : IVehicleAbstractFactory where FourWheeler: IFourWheeler, new()
  {
    public IWheeler GetVehicle()
    {
      return new FourWheeler();
    }
  }

  class TwoWheelerFactory<TwoWheeler> : IVehicleAbstractFactory where TwoWheeler: ITwoWheeler, new()
  {
    public IWheeler GetVehicle()
    {
      return new TwoWheeler();
    }
  }

  class Car : IFourWheeler
  {
    public void Drive()
    {
      Console.WriteLine("Drive Car");
    }
  }

  class Truck : IFourWheeler
  {
    public void Drive()
    {
      Console.WriteLine("Drive Truck");
    }
  }

  class Bicycle : ITwoWheeler
  {
    public void Drive()
    {
      Console.WriteLine("Drive Bicycle");
    }
  }

  class Program
  {
    static IVehicleAbstractFactory GetFactory(Vehicles vehicle)
    {
      switch (vehicle)
      {
        case Vehicles.car:
          return new FourWheelerFactory<Car>();
        case Vehicles.truck:
          return new FourWheelerFactory<Truck>();
        case Vehicles.bicycle:
          return new TwoWheelerFactory<Bicycle>();
      }
    }

    static void Main(string[] args)
    {
      IVehicleAbstractFactory factory = GetFactory(Vehicles.bicycle);
      IWheeler vehicle = factory.GetVehicle();
      vehicle.Drive();

      Console.Read();
    }
  }
}

I'm not saying this is the right way for the factory pattern, but may be a little clearer. The client still has to know which actual class he wants to create due to the nature of generics.


Don't think it's a good approach.

Singletons are evil by themselves
Subscribers are likely to expect a specific type of message on specific channel
Magic strings that specify the channel name are also potential source of bugs
Incorrect messages or posts to wrong channels are detected at run-time only.
Logical dependency between objects still exist, but is hidden.

.NET already has a notion of in-process publish/subscribe, and (not that surprisingly) this functionality is covered by events... All you need to do is to wire up all your entities properly, and that's your actual challenge is.

I would recommend using any of available IoC frameworks for that (I use Autofac at the moment).

You will have a strictly-typed communication protocol between publisher and subscriber
It will allow you to explicitly declare dependency on a certain external functionality in your classes.
It will simplify unit-testing of your classes

Unfortunately you haven't described specific use cases for your pub/sub requirement so it's hard to show this solution on specific example


There is quite a bit of code duplication due to a few nearly identical functions being needed.

This is probably the biggest issue and the one I'll be addressing here.

The two schwitch functions have identical bodies, this is a major code smell. The only difference between the two is the generic constraints on T and the type T is wrapped up in (Array and Caze repectively). You don't actually care that Tconforms to ForwardIndexType in the schwitch function and the only way I was using both Caze and Array was by calling contains on them (with identical signatures). This clearly calls for a protocol. And I didn't even need to declare one myself. the contains function I was using is declared in SequenceType, a protocol both Array and Range conform to. So here's what the new (and only) schwitch function will look like:

func schwitch<S: SequenceType, R where S.Generator.Element: Equatable>(value: S.Generator.Element, _ cases: (S, () -> R)..., @autoclosure def: () -> R) -> R {
    for (vals, f) in cases {
        if vals.contains(value) {
            return f()
        }
    }
    return def()
}

You will notice that function is now missing a rethrows, the swift compiler hangs up on that due to a bug.

This also allowed me to get rid of the Caze enum and only have two caze functions, one that takes any amount of values and one that takes a range:

func caze<T: Equatable, R>(vals: T..., @autoclosure(escaping) ret f: () -> R) -> (AnySequence<T>, () -> R) {
    return (AnySequence(vals), f)
}

func caze<T, R where T: Equatable, T: ForwardIndexType>(range: Range<T>, @autoclosure(escaping) ret f: () -> R) -> (AnySequence<T>, () -> R) {
    return (AnySequence(range), f)
}

I've made both functions return an AnySequence<T> instead of more concrete type, I think that makes sense, considering how the results are used, but it's really up to you if you maybe want to return Array<T> and Range<T> instead.

I can still use my function exactly as I did before.


First-time F#: A simple Rock Paper Scissors

As a first attempt it looks in many ways ok.
I have three "complaints":
a) You rely too much on string literals as identifiers for input. That is considered bad practice in - I think - every programming language and should be avoided because it's error prone (typos and illegal input etc.) hence not very robust.
Instead of "r", "p" and "s" you could use a discriminated union - which is a very important part of the F#-toolbox to be familiar with:
type Weapon =
    | Rock
    | Paper
    | Scissors

This will for instance make the match-statement in ruling much more readable and type safe:
let ruling playerWeapon computerWeapon =
    match (playerWeapon, computerWeapon) with
    | (Rock, Paper)
    | (Paper, Scissors)
    | (Scissors, Rock) -> computerWin playerWeapon computerWeapon
    | (Rock, Scissors)
    | (Paper, Rock)
    | (Scissors, Paper) -> playerWin playerWeapon computerWeapon
    | (_, _) -> tie playerWeapon

b) Don't repeat yourself. In the functions where you print the results, you do the same thing, and therefore you should extract the common parts to a generalized function, so that:
let computerWin playerAction computerAction =
    printfn "The computer did win. '%s' beats '%s'." computerAction playerAction
let playerWin playerAction computerAction =
    printfn "The player did win. '%s' beats '%s'." playerAction computerAction

changes to:
let showWinner name winnerWeapon looserWeapon =
    printfn "The %s did win. '%A' beats '%A'." name winnerWeapon looserWeapon
let computerWin playerWeapon computerWeapon = showWinner "computer" computerWeapon playerWeapon
let playerWin playerWeapon computerWeapon = showWinner "player" playerWeapon computerWeapon

c) You recursively call the main function. I don't know if you actually violate any formal or informal rules but it just looks "ugly" to me. I would make a dedicated function that runs the game recursively.

FYI - I have below refactored your program while incorporating my suggestions above:
// HH: Instead of string literals you should use discriminated unions as identifiers for "weapons"
//     This is much more robust in respect to typos etc.
type Weapon =
    | Rock
    | Paper
    | Scissors
    static member Abbreviation w = (w.ToString().[0]).ToString().ToLower()
    static member ToWeapon ch =
        match ch with
        | "r" -> Rock
        | "p" -> Paper
        | "s" -> Scissors
        | _ -> failwith "Invalid Weapon char"

let weapons = [ Rock; Paper; Scissors ]

// HH: You should only instantiate a single random object - used throughout the session.
let rand = new Random()
let computerAction () = weapons.[rand.Next(weapons.Length)]

// HH: This now returns an optional value of None if the user wants to quit
//     or Some (Weapon) if a valid weapon is chosen
let rec playerAction () =
    let allowedActions = weapons |> List.map Weapon.Abbreviation
    let choices = weapons |> List.map (fun w -> sprintf "'%s' = %A" (Weapon.Abbreviation w) w)
    printfn "Enter:\n%s.\n'q' to Quit." (String.Join("\n", choices))
    let input = Console.ReadLine()

    let validWeapon w = List.contains w allowedActions
    match input with
    | "q" -> None
    | w when validWeapon w -> Some (Weapon.ToWeapon w)
    | _ -> printfn "invalid input '%s'" input; playerAction()

//HH: Never repeat yourself: extract a function to print the winner...
let showWinner name winnerWeapon looserWeapon =
    printfn "The %s did win. '%A' beats '%A'." name winnerWeapon looserWeapon
// HH: ... and call that from the dedicated winner functions
let computerWin playerWeapon computerWeapon = showWinner "computer" computerWeapon playerWeapon
let playerWin playerWeapon computerWeapon = showWinner "player" playerWeapon computerWeapon
let tie anAction = printfn "It's a tie. '%A'" anAction

let ruling playerWeapon computerWeapon =
    // HH: By using discriminated unions this match
    //     expression is much more readble and robust
    match (playerWeapon, computerWeapon) with
    | (Rock, Paper)
    | (Paper, Scissors)
    | (Scissors, Rock) -> computerWin playerWeapon computerWeapon
    | (Rock, Scissors)
    | (Paper, Rock)
    | (Scissors, Paper) -> playerWin playerWeapon computerWeapon
    | (_, _) -> tie playerWeapon

let playGame playerWeapon computerWeapon =
    printfn "You've chosen '%A'." playerWeapon
    printfn "The computer chose '%A'." computerWeapon
    ruling playerWeapon computerWeapon
    ()

let runGame () =
    let playerAction = playerAction ()
    match playerAction with
    | Some playerWeapon ->
        let computerWeapon = computerAction ()
        playGame playerWeapon computerWeapon
        true
    | None -> false

// HH: Personally I don't like,that you call main recursively.
//     You probably don't violate any formal or informal rule, but it just look wrong to me
//     So make a dedicated function to start the game by
let rec play () =
    match runGame() with
    | true -> play()
    | false -> ()

I have changed some of the names so that they matches my naming. For the example I show that you can extent a discriminated union with members (static and instance). You could chose to have these methods as normal function instead.


Your Select statement.

SELECT azon FROM $db ORDER BY azon ASC/DESC LIMIT 1

you could simplify the statement like this:

SELECT MAX(azon)/MIN(azon) AS 'azon' FROM $db

There are some discussions about the gain of performance by using MIN/MAX instead of ORDER BY + LIMIT. I personally experienced that MIN/MAX is faster, especially on tables with many rows.
You can simply copy a table structure by using

CREATE TABLE `$newdb` LIKE `$acttable`

but you'd have to set the AUTO_INCREMENT manually after this, otherwise it would be set to 1.

ALTER TABLE `$newdb` AUTO_INCREMENT=3524772

(I don't see the purpose on this, maybe it's not even nessecary?)
Your optimize.

I'm quite irritated about the way to want to query this. You're calling that statement inside the else-condition -> after your delete has failed. It should be called inside the if-condition (or I missunderstood the goal).
You should consider using InnoDB instead of MyISAM (in general), because there would be no need (and possibility) of running an OPTIMIZE.

There should be no performance issue on the php-side as long as you do not iterate through the many rows.
You may want to increase the max_execution_time-directive to prevent the script from stopping, but I consider this is not nessecary.

On MySQL-side, i really suggest changing to InnoDB (you may want to read this).

Conclusion:
Besides the little changes of the statements and the use of OPTIMIZE inside your if-condition, there are no required improvements for exactly this script in my opinion. I strongly recommend to change the database engine when you make your changes for using PDO. This of course means more effort, as there are many variables which you can or should set to the InnoDB engine, but I think it is worth it. In fact, there aren't real advantages on using MyISAM, less then ever in performance.