This looks like a good start, so the following is by no means a criticism, but there are various refactorings you can perform to make the code smaller, and more generic.

As a general comment, I'd advise against naming arrays listOfWhatever, since list is a concrete data type in F#, separate from arrays. I've renamed listOfWords to words, listOfAnagrams to anagrams, and so on.

Finding the anagrams

The first sortStringAsKey function doesn't need type annotations if you refactor it a bit:

// seq<'a> -> seq<string * seq<'a>> when 'a :> seq<char>
let sortStringAsKey words =
    words
    |> Seq.groupBy (Seq.sort >> Seq.toArray >> String)
    |> Seq.filter (fun (_, originalWords) -> Seq.length originalWords > 1)

You'll notice that I inlined the getKey function, but perhaps that's taking it too far. If you think that having a named local function makes the code more readable, I wouldn't disagree.

I've also changed from working explicitly with arrays, to using the Seq module. This makes the function more generic, but it can still handle arrays.

You could even perform an eta reduction on the function, in order to make it even shorter, but I'm not sure it becomes more readable by it:

let sortStringAsKey =
    Seq.groupBy (Seq.sort >> Seq.toArray >> String)
    >> Seq.filter (fun (_, originalWords) -> Seq.length originalWords > 1)

Just for the fun, you can make it even more cryptic:

let sortStringAsKey =
    Seq.groupBy (Seq.sort >> Seq.toArray >> String)
    >> Seq.filter (snd >> Seq.length >> ((<) 1))

Personally, I don't even find that readable myself; I'd prefer the first, most verbose option.

Printing the anagrams

Since there's at least three places where the code prints out the anagrams, it's more reasonable to turn that into a function:

// seq<string> -> unit
let prints a =
    a |> Seq.iter (printfn "%s")
    printfn ""

Once again, you'll notice that I chose to use Seq.iter instead of Array.iter. It'll still be able to handle arrays, but there's no reason to constrain the input if it isn't necessary.

Loading anagrams

Loading the anagrams from file can be simplified a bit as well, since you don't need the intermediate listOfWords value:

// In main function:
let filename = "../../words.txt"
let anagrams = System.IO.File.ReadAllLines(filename) |> sortStringAsKey

Because of the more generic version of sortStringAsKey, the type of anagrams is seq<string * seq<string>>.

Printing all the anagrams

With the prints function, you can easily print all the anagrams

anagrams |> Seq.map snd |> Seq.iter prints

Instead of performing work inside on of Seq.iter (which is possible), I often prefer to perform transformations etcetera first, because I can easily test such pure functions. Once you have data in the appropriate shape, you can always use Seq.iter to e.g. print it.

Finding the longest anagrams

The proposed solution suffers from calling Array.maxBy for every element, so it'd be quite inefficient.

You can make it more efficient by only doing it once:

let longestAnagrams =
    let longest = anagrams |> Seq.map (fst >> String.length) |> Seq.max
    anagrams |> Seq.filter (fst >> String.length >> ((=) longest))

This still requires two traversals of the array, so isn't as efficient as it could be, but is probably (but measure instead of assume, when it comes to performance) more efficient than doing Array.maxBy for every entry.

See below for an optional refactoring.

Finding the words with most anagrams

Likewise, you can find the largest collections of anagrams:

let mostAnagrams =
    let most = anagrams |> Seq.map (snd >> Seq.length) |> Seq.max
    anagrams |> Seq.filter (snd >> Seq.length >> ((=) most))

Notice how this is similar to longestAnagrams.

Printing

Both longestAnagrams and mostAnagrams can be printed using the prints function:

longestAnagrams |> Seq.map snd |> Seq.iter prints
mostAnagrams |> Seq.map snd |> Seq.iter prints

Alternative max and filter operation

The problem with even the refactored version of longestAnagrams is that it requires two traversals of the sequence in order to compute the results.

Once you realise that the operation is essentially a fold, you may want to optimise it to a single traversal:

let longestAnagrams =
    let folder l (k, v) =
        let xl = Seq.length k
        match xl, l with
        | _, []                                  -> [k, v]
        | x, (hk,  _)::_ when xl > Seq.length hk -> [k, v]
        | x, (hk, hv)::t when xl = Seq.length hk -> (k, v)::(hk, hv)::t
        | _                                      -> l
    anagrams |> Seq.fold folder []

As you can tell, it's more code (so more complicated), but at least in theory more efficient, as it only uses a single traversal. It does, however, potentially causes more memory allocations, so as always when performance is involved: measure.

On my machine, though, it seems to be more than twice as fast...

You can refactor the computation of mostAnagrams in the same way, but I will leave that as an exercise ;)


Easy to use code preparation script for CodeReview questions

An alternative to defaulting variables by self-assigning with fallback is to use ${parameter:=word} at the point of first use:
for dir in ${IGNORED_DIRS:=build .git}; do

for ext in ${EXTENSIONS:=c cc cpp h hpp}; do

Actually, since those are the only uses, we could get away with :- expansion, even there.
Also, it makes sense to allow user to specify no ignored dirs and/or no extensions (and we check for that later in the code), so perhaps remove the : from those expansions.

RULE_GLUE can also be simplified:
RULE_GLUE=${PRUNE_RULES:+-o}

Again, it's not necessary to name this, but it might aid clarity.  Personally, I'd just add it directly to the end of the PRUNE_RULES:
PRUNE_RULES="${PRUNE_RULES} ${PRUNE_RULES:+-o}

or just ensure that each prune rule contains its own -o as it should:
for dir in ${IGNORED_DIRS}; do
  PRUNE_RULES="${PRUNE_RULES} -name ${dir} -prune -o"
done

The name rules can be simplified by starting with with the -false predicate (did you ever wonder what it's useful for?):
NAME_RULES=${EXTENSIONS:+-false}
for ext in ${EXTENSIONS}; do
    NAME_RULES="${NAME_RULES} -o -name '*.${ext}'"
done

It's unspecified whether find expands {} when it's a substring of an argument; the safer POSIX way is to pass it as a positional argument and have the child shell expand it:
    -exec sh -c "printf '${FILE_HEADING}' \"\$1\" && sed 's/^/    /' \$1" -- {} ';'

It's probably a good idea to only match plain files (including symlinks to plain files), rather than everything that matches the name rules.  Especially if $NAME_RULES is empty, it's quite possible for a directory name to match.
I don't see why we need the explicit sh subshell as the final command (since we expand the "rules" predicates unquoted, so word splitting happens - though we'll need to disable globbing: set -f).  There's no good reason not to exec the final command.
Also, we need to be careful if $FILE_HEADING ever contains ': it might be safer to also pass this as a positional parameter, or to export the variable and have it expanded later:
export FILE_HEADING

exec find . ${PRUNE_RULES} ${NAME_RULES} -type f
    -exec sh -c 'printf "${FILE_HEADING}" "$1" && sed "s/^/    /" "$1"' -- {} ';'

I think that rather than -exec sh, it might be simpler to have two -exec predicates:
... -exec printf "${FILE_HEADING}" {} \; -exec sed 's/^/    /' {} \;

(and we no longer need to export $FILE_HEADING).

Modified code
#!/bin/sh

# user-modifiable parameters
FILE_HEADING='## File: %s\n\n'
DEFAULT_IGNORED_DIRS='build .git'
DEFAULT_EXTENSIONS='c cc cpp h hpp'

# end of user variables; code starts here

set -eu  # Usual safety
set -f   # Don't expand pathnames when expanding $NAME_RULES below

for dir in ${IGNORED_DIRS-$DEFAULT_IGNORED_DIRS}; do
    PRUNE_RULES="${PRUNE_RULES-} -name ${dir} -prune -o"
done

for ext in ${EXTENSIONS-$DEFAULT_EXTENSIONS}; do
    NAME_RULES="${NAME_RULES:--false} -o -name *.${ext}"
done

# We intend word splitting of rules variables
# shellcheck disable=SC2086
exec find -L . ${PRUNE_RULES-} ${NAME_RULES:+'(' $NAME_RULES ')'} -type f \
     -exec printf "${FILE_HEADING}" {} \; \
     -exec sed 's/^/    /' {} \;

Modified one-liner
find . -name \*.sh -exec printf '## File: %s\n\n' {} \; -exec sed 's/^/    /' {} \;


Errors in the code:

When you split str_x[:n_2] and str_y[:n_2] you're taking the same number of digits from the most significant part of each number. You need to instead take the same number of digits from the least significant part of each number.

For example, the cross multiplication step of karatsuba(12 + 34, 87 + 65) goes wrong:

You get x = 46 and y = 152 so n_2 = 1 and str_x[:n_2] = '4' and str_y[:n_2] = '1'. These are not offset by the same amount!

Instead you could set

#higher bits of each number
x_h = int(str_x[:-n_2])
y_h = int(str_y[:-n_2])

#lower bits for each number here
x_l = int(str_x[-n_2:])
y_l = int(str_y[-n_2:])

Negative indices count from the end, and this is just what you want so that you pull out the same number of powers of ten from each. Then str_x[:-n_2] = str_x[:-1] = all but the last n_2 = 1 digit of x which is 4, and str_y[:-n_2] = str_x[:-1] = all but the last n_2 = 1 digit of x which is 15. This works the way it should

With or without the above fix, your code will crash when both numbers > 10 and one of them is twice (or more) as many digits as the other. Then one of the slices will be the empty string, and int('') throws an error as opposed to (as you would want) returning 0.

A quick fix to this would be to make the higher part and lower part each a function, and check for the empty string. Alternatively, you could have a special case in karatsuba when n_2 >= min(...)

Finally, there's a bug in the return computation. Instead of len(str_x) you want 2 * n_2 and instead of len(str_x) // 2 you want n_2.

Some quick comments on issues other than the errors

Using str(x) is not very efficient, and does a lot of extra work in what is supposed to be an implementation of an efficient way to multiply. For getting the basic ideas of the algorithm down, though, it's fine for a start and I won't complain too much.

But you should at least be aware that a better way would be to split the number into two pieces in base 2 and use bit string operations. This would be a good follow-up exercise. Specifically x >> n is the same as x // 2**n and x << n is the same as x * 2**n and these are much more efficient than base 10 operations.


Checking for existence of object by id, name, display name, or web id

To me such a method

public final boolean doesExistById(Long id) {
    return dataAccessObject.findById(id) != null;
}

is already a code smell. What do you expect it to be used for. Something like

if (doesExistById(id)) {
    return getById(id);
} else {
    return new Something(id);
}

which means you're doing the lookup twice in the first branch. This is not too bad as there's caching somewhere, but it's strange. So I'd prefer to have no such method.

The other thing is that all it does id delegating to the dataAccessObject. Can't you use it directly. It looks like instead of calling

 dataAccessObject.findById(id)

you call

 somethingContainingTheDataAccessObject.findById(id)

Does it make sense? It might, but without more code we can't tell.

It looks like a typical XY problem. You're asking how to improve X (the repetitive doesExist* while having a problem Y (kept secret).

So all we can do is to tell you what not to do.

public final boolean doesExist(Long id, String name, String displayName, String webId) {..}

This could be a good idea if you needed a combined search often. But you're speaking about many methods and converting them into one method with many arguments is a step obviously in the wrong direction. It's much longer on the call site, much more error-prone and slightly less efficient. No gain.

public final Optional<MyObj> byId(Long id) {
    return Optional.ofNullable(dataAccessObject.findById(id));
}

My favorite rant says it all, though in this case it mightn't be that bad. You could use something like

public final Something getOrCreateById(Long id, Function<Long, Something> creator) {
    Something result = dataAccessObject.findById(id);
    return result != null ? result : creator.apply(id);
}

It wouldn't reduce the number of needed methods, but it could make them exactly what you need (remember, Y is kept secret).

With Java 8, it could get pretty compact.


Not only is it bad practice, I'd say it's horrible practice. Save yourself, or others which will be dealing with your code, some future headache and use as few static variables as possible, preferably none! (The reason why I say this is horrible could have something to do with the code I have to deal with at work, anyways, it is still not good practice...)

I'd say that not using the default constructor is perfectly fine, if all your Reporter objects needs a jsonFilePath then it's good to pass it in the constructor. Also, if this value shouldn't change then you can make it readonly.

If by disposing you mean "clearing it's state" or something, then no you don't need to. Garbage collector will take care of that. However, if you keep using the static variables then you might run into problems if you want to create another one.

So, how to get rid of these static variables?
It's quite easy actually: Tell, don't ask.
You haven't given much code here so I'll have to try to explain how it generally works:
In your json class (which I will call Foo from now on since I don't know it's actual name), or whatever you have, instead of using Reporter.ShouldNotify, create an instance variable of the Reporter type. Then if you call/create your Foo class from your Reporter class, you tell the Foo object about it's Reporter. For example:
// In your reporter class
Foo foo = new Foo();
foo.setReporter(this); // sorry for the Java naming conventions here, but I hope you get the idea

In Foo you can then use your Reporter object which you retreived from the setReporter method to use that particular object.
Note that one can take the "Tell, don't ask" thing even further, but with the code in your question this is what I think you need for now.


Prepared statements prevent any form of SQL injection so that is not an issue with your code.

Although it may not be required in your case, I see no user control which would prevent anyone from filling your database with junk, or even deleting all records from it.

As for XSS, the code provided shows no protection from it in any way.  XSS protection implies data validation, sanitizing, and output escaping but none of those are done here.  You should refer to http://www.sitepoint.com/php-security-cross-site-scripting-attacks-xss/ or other similar tutorials to learn more on XSS protection.

Even if XSS wasn't a source of worry, you should never accept user input as is without extensive validation.

Another thing I noticed is that you're repeating the same code in all your scripts for the configuration.  For maintainability, that greatly justifies placing it in another script that gets included by them such as config.php which would include:

$db_conn_config = parse_ini_file('../private/db_conn.ini');
$servername = $db_conn_config['servername'];
$username = $db_conn_config['username'];
$password = $db_conn_config['password'];
$dbname = $db_conn_config['dbname'];
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);


This JavaScript implementation of range is fast. What are it's downsides?

relatively speaking-

1) its a bit heavy on the memory use, requiring the memory for a property + mem of a number for each integer in the possible range

2) always consumes the memory and cpu needed to intialize, even if the script never has use for it.


Logic:

If statements differs only in 2 variables: canvasPlayerX and playerCardsWidthX.

playerCardsWidthX: looks like this var can be converted to local, just like playerCardsHeightX;

canvasPlayerX: you can do one little trick here - add player canvases to a list in initialize() method, and then refer to the i-th player canvas as playersCanvases.get(i);

Moreover, your code didnt even compile, because GameController should implement initialize(..) method;

Codestyle:

playerCardsWidthX - in your code, its not width of player cards, its coordinate, where to draw next card. Consider renaming;
in constructor, exception is caught, and stacktrace is printed, but after that, program will continue its flow. Is this what you want? (see code below for possible solution).
extract constants into private static final fields

public class GameController implements Initializable {
public static final int CARD_WIDTH = 60;
public static final int CARD_HEIGHT = 80;
public static final int CARD_SPACING = 15;

public static final int CARDS_X_DIFF = CARD_WIDTH + CARD_SPACING;

@FXML
private Canvas canvasBoard;
@FXML
private Canvas canvasPlayer1;
@FXML
private Canvas canvasPlayer2;
@FXML
private Canvas canvasPlayer3;
@FXML
private Canvas canvasPlayer4;

private List<Canvas> playersCanvases;

private TexasHoldem game;
private IPlayer board;

public GameController() {
    try {
        game = new TexasHoldem();
    } catch (Exception e) {
        e.printStackTrace();
        Platform.exit();
    }
}

@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
    // in initialize method, because in constructor canvases are not assigned(== null)
    playersCanvases = Arrays.asList(canvasPlayer1, canvasPlayer2, canvasPlayer3, canvasPlayer4);
}

private void showBoardCards() {
    board = game.getBoard();
    showCards(50, board.getCards(), canvasBoard.getGraphicsContext2D());
}

private void showPlayersCards() {
    List<IPlayer> players = game.getPlayers();
    for (int i = 0; i < players.size(); i++) {
        IPlayer player = players.get(i);
        showCards(0, player.getCards(), playersCanvases.get(i).getGraphicsContext2D());
    }
}

private void showCards(int xOffset, List<ICard> cards, GraphicsContext gc) {
    int cardY = 0;
    int cardX = xOffset;
    for (ICard c : cards) {
        Image image = new Image(c.getFilename());
        gc.drawImage(image, cardX, cardY, CARD_WIDTH, CARD_HEIGHT);
        cardX += CARDS_X_DIFF;
    }
}

}


First, use standard Java conventions for interfaces names: not resume or letter but Letter and Resume

Second, I would define e.g. StyleDocumentsFactory API like this

interface StyleDocumentsFactory {
    Letter createLetter();
    Resume createResume();
}

and then implement FuncyStyleDocumentsFactory and CorporateStyleDocumentsFactory instances of this API.

So you will have 2 abstract factories (for creation group of object with common theme: funcy and corporate) with set of factory methods.

Instantiate appropriate StyleDocumentsFactory impl in your main method at the program beginning.


I'd write it as a recursive descent parser since this is quite simple:

http://en.wikipedia.org/wiki/Recursive_descent_parser

Actually I already did this a couple of years back, when I wanted to create something that simply formats and highlights JSON a bit. If you can understand it, then you can modify it to your needs:

        <textarea id="thetextarea" rows="25" cols="70" onKeyUp="go(this.value);">[{"Dies":"Ist ein Beispiel...","mit":["Arrays","und","so"]},{"alles":"sch&ouml;n verschachtelt..."},"tippt einfach json-zeugs in dem grossen Feld.","Die Anzeige aktualisiert sich sofort...","Die Formatierungen sind als &lt;style&gt; gespeichert. Ihr k&ouml;nnt sie so beliebig &auml;ndern.",{"Zahlen":1,"sind":[1,4,55.67],"auch":"sch&ouml;n"}]</textarea>


Characters set permutations with repetitions

I think the code and the approach look good overall. I have just a few comments:

1) The indentation makes it a bit hard to read. A line like:

acc.push(multStr(_.last(acc), space))

Reads better than across many lines in my opinion.

2) You may consider using concat instead of push:

return acc.concat(multStr(_.last(acc), space))

You trade a bit of performance for it though as concat creates a new array.

3) The most notable problem I see with your code is that it is not very reusable. It only works for strings, while the idea and implementation certainly apply to arrays too. We can think of a string as an array of characters, so abstracting for arrays makes the code more reusable, since we can then do the string one trivially with str.split('').

This leads to the name of the function multStr; it is too specific, and hungarian notation means you are probably over-specifying its functionality, it ought to be more abstract.

Intuitively you wrote code that is more abstract than it seems. I find the Haskell equivalent to your code quite elegant and concise, almost by accident:

[1..3] >>= \n -> replicateM n "ab"

The concept at hand is very general: lists are monads.

We can replicate this in JavaScript easily with lodash. We need flatMap, and range:

var {flatMap, range} = require('lodash')

Next we can loosely translate the Haskell implementations of replicateM and sequence to build combinations:

function combinations(n, xs) {
  return flatMap(range(1, n + 1), m => replicateM(m, xs))
}

function replicateM(n, x) {
  return sequence(Array(n).fill(x))
}

function sequence(ms) {
  return ms.reduce((ma, mb) => {
    return flatMap(ma, a => mb.map(b => a.concat(b)))
  }, [[]])
}

Now this is already more general, we pass an array of characters and get an array of arrays of characters that represent all the possible combinations of n length.

To make it work for your case you only need to split then join:

combinations(3, 'ab'.split('')).map(cs => cs.join(''))
/*^
[ 'a', 'b',
  'aa', 'ab', 'ba', 'bb',
  'aaa', 'aab', 'aba', 'abb',
  'baa', 'bab', 'bba', 'bbb'
]
*/


I'd group your code to make it more readable. Something like this:

fun getGson(): Field {
    val fGson = NBTReflectionUtil::class.java.getDeclaredField("gson")
    fGson.isAccessible = true
}

fun removeFinalModifier(field: Field) {
    val modifiersField = Field::class.java.getDeclaredField("modifiers")
    modifiersField.isAccessible = true
    modifiersField.setInt(fGson, fGson.modifiers and Modifier.FINAL.inv())
}

// etc


Estimating Pi with random darts on dartboard - high complexity issues

Performance

The biggest simple performance improvement would be to use xrange() instead of range() for the loop counter in estimatePi().  Note that i is unused; it is customary to use _ as the name of a "throwaway" variable.

I don't see much point in the r, w, and h parameters.  If you make the dartboard a unit circle centered at the origin, then you could do away with the math.sqrt().

outOfCircle is never used.  Its naming is also inconsistent with in_circle.

Plot quality

For a program that aims to visualize the accuracy of the technique to estimate π, you're being awfully sloppy by plotting a horizontal line at y = 3.14 rather than at math.pi.  The easier way to plot a horizontal line is to use axhline().

It makes no sense to use an errorbar plot here, with an arbitrarily chosen yerr=.0001, since you have just one sample at each x.

Looping

Neither loop is as expressive as it could be.

In estimatePi(), you can calculate in_circle using sum() with a generator expression.  (When coerced into an integer, True is treated as 1, and False as 0.)

To make the lists num_darts and PiEstimation, you can use range() and a list comprehension, respectively.

Suggested solution

Take care to follow PEP 8 naming conventions.

from math import pi
from random import uniform
import matplotlib.pyplot as plt

def estimate_pi(n):
    in_circle = sum(
        uniform(-1, 1)**2 + uniform(-1, 1)**2 <= 1
        for _ in xrange(n)
    )
    return 4.0 * in_circle / n

darts = range(10000, 1000001, 15000)
pi_estimations = [estimate_pi(n) for n in darts]

plt.title('Estimating the Value of Pi - Dartboard Simulation')
plt.ylabel('Pi Estimation')
plt.xlabel('Number of Darts')
plt.axhline(y=pi, color="red", linewidth=2.0)
plt.plot(darts, pi_estimations, marker='o')
plt.show('hold')

This runs in under a minute on my machine.


You can simplify it by using Array.prototype.some method and lazy evaluation of && operator

const pageTypes = ['dashboard', 'klantenkaart', 'complexkaart', 'objectkaart', 'collegakaart'];
const subTypes = ['overzicht', 'tijdlijn', 'contracten', 'financieel', 'mededelingen'];

function isOnPageWithFilter(currentUrl) {
    return pageTypes.some(x => currentUrl.includes(x)) && subTypes.some(x => currentUrl.includes(x));
}

console.log(isOnPageWithFilter('foobar.com?dashboard')); // false
console.log(isOnPageWithFilter('foobar.com?dashboard&overzicht')); // true

```


Machine independent C library for printing the binary representation of data types to stdout

You can just call putchar(), which automatically prints to stdout:

putchar('1');

The conditionals can instead be a ternary statement within putchar():

putchar(n & mask ? '1' : '0');

putchar is often better suited for single-character output. putchar only has to pass a character directly to the output. This particular code isn't exactly performance-critical but it's useful to acquire good coding habits from the beginning.


Rounding and formatting hours, minutes, seconds as HH:MM AM/PM

DateTime handling
It's possible that you're prohibited from using the DateTime struct in this method since this is apparently homework. But, in case you're not aware, problems which are as common as parsing and formatting dates and times generally already have very sophisticated and well-designed solutions. In this case, it's .NET's System.DateTime, in particular the overload of ToString which takes a format string, and TryParse. You can find these both documented on the msdn site. Using that, I believe you would be able to condense all your code down to just a few lines.
Naming
By convention, variables local to methods are named in camelCase- i.e. the first letter should be lower case. So Hours should be hours, etc. This also applies for method parameters- Input should be input.
You seem to be using the default naming for your controls- label1, button1, etc. These should be given descriptive names, like all other variables.
You change conventions inside Converter. Why is something which was Hours in a different method now H? Prefer the more descriptive name (hours, once the casing is fixed).
Another convention is that classes should be named as nouns, and methods as verbs. So instead of Converter, you should use Convert. Often, something in the form VerbNoun is the most descriptive: ConvertTime, for example.
Numeric types
Looking at your code, it seems like your hours, minutes and seconds are expected to be integers. So why are you parsing them into doubles? This is going to lead to all sorts of potential issues- rounding can cause unexpected results when doing equality comparisons for example. If you want a variable which only stores whole numbers, it's very important you use an integer type- generally int unless you have a good reason to pick another.
Cleaning up
Okay, here's the big one. It's pretty unpleasant how button1_Click handles a bunch of special cases, then if it's not any of those, hands over to Converter, which itself has a whole lot of complex logic. Let's work out how we can do this better.
As I said earlier, the best way to do this is to use DateTime, but that's not really saying much useful about the code you wrote, and for all I know you may have a requirement not to use those in-built methods. So I'll work on the assumption you have to do all the tricky time handling yourself.
Probably the first thing to notice is that the handling of seconds, minutes and hours are almost completely independent from each other. Here's our aim for each one:

Seconds: Decide whether we need to round up to the next minute
Minutes: Add one if we've rounded up the seconds. Check for the special case that we went from 59 minutes to 60, in which case we need to tick over to the next hour.
Hours: Add one if we rounded up a minute from 59. Decide whether it's AM or PM. If it's PM, subtract 12 from the number.

Let's address these one by one.
Seconds
As you can see from the description above. Seconds are really simple. We really only need to decide whether they're greater than or equal to 30, then we can forget about them. But look at how much complexity they have in the code:
if (M == 59 && S == 59)

and
if (S >= 30)
{
    S = 1;
    if (S==1)
    {
        M = S + M;
    }
}
else
{
    S = 0;
}

Plus the repeated individual checks in button1_click.
So forget all that, we want a super-simple way to ask "do I need to round up my minutes?":
private bool DoMinutesRequireRoundUp(int seconds)
{
    return seconds >= 30;
}

There we go, that's all we need for seconds!
Minutes
Now we get a bit more complex. We have two questions to ask here:
Will rounding up minutes put us into the next hour?
What will the minutes value be after we've done any necessary rounding of seconds?
In your code you've handled this with a bunch of special cases sprayed all over the place of minutes being 59. But again, there's no need for that!
Let's start with the first, again as its own method:
private bool DoMinutesRoundUpToNextHour(int minutes, bool roundUpMinutes)
{
    return roundUpMinutes && minutes==59;
}

Now we have that, we're better equipped to tackle the second
private int GetRoundedMinutes(int minutes, bool roundUpMinutes)
{
    if(DoMinutesRoundUpToNextHour(minutes, roundUpMinutes))
    {
        return 0;
    }
    if(roundUpMinutes)
    {
        minutes++;
    }
    return minutes;
}

See how we've separated out this question from any concern of what exactly the seconds are, or- even more irrelevant- what the hours are.
Hours
And finally, the hours! In your code, you try to do things in a very mixed-up way, in which AM and PM checking is all jumbled up with subtracting 12, rounding minutes, and so on. There are a few steps here, but actually we can address them quite separately as long as we do them in the right order.
Here's what we need to do, and note how each task may be dependent on tasks before it, but not after it:

Add one if the minutes were rounded up from 59 to 00
Subtract 24 if the hours are greater than 23
Decide whether we should display "AM" or "PM"
Subtract 12 if the hours are greater than 12

Not trivial, but taking them one at a time, they're not too bad either. First, numbers 1 and 2:
private int GetRoundedHours(int hours, bool incrementHours)
{
    if(incrementHours)
    {
        hours++;
    }
    return hours % 24;
}

Then 3:
private string GetPeriod(int hours)
{
    return hours < 12 ? "AM" : "PM";
}

And finally 4:
private int Get12HourTime(int hours)
{
    return hours <= 12 ? hours : hours - 12;
}

Gluing it together
So that's a bunch of methods! But now putting it all together is very easy. Let's look at how they'd work in Convert.
First, I'm going to fix the Input thing. This is pretty confusing, as it's never used. Instead I'm going to have the time elements actually passed in and used.
private string ConvertTime(int seconds, int minutes, int hours)
{
    var roundUpMinute = DoMinutesRequireRoundUp(seconds);
    var incrementHour = DoMinutesRoundUpToNextHour(minutes, roundUpMinute);
    var roundedHour = GetRoundedHours(hours, incrementHour);

    var displayMinutes = GetRoundedMinutes(minutes, roundUpMinute);
    var displayHours = Get12HourTime(roundedHour);
    var period = GetPeriod(roundedHour);

    return displayHours.ToString() + ":" + displayMinutes.ToString() + " " + period;
}

One thing this doesn't address is the leading zero for minutes < 10, but this can very easily be done in a few extra lines.
It's hard to do a line-by-line comparison of this to your version, because it's quite structurally different, but the key is to see how we've separated out each individual question we need answered into its own piece of code, and decoupled those questions from each other. We don't do a check like:
if (Hours == 23 && Minutes == 59 && Seconds >= 30)

Because that's conflating 3 different questions ("Do we need to round up to the next minute?", "Do we need to round up to the next hour?", "Do we need to round up to the next day"?) which we should answer separately.


Factory using Structuremap to inject concrete implementation of BaseTask

I believe it is not good to pass builder to constructor as an argument. I recommend to read Constructor Design guidelines from Microsoft. If you have any non-simple calculation in constructor it will be better to move it to a static method. In your case I would firstly create model and then pass the built one to the constructor. Unfortunately I don't see where and how a builder is created so maybe your solution keeps a good balance between complexity, flexibility and beauty.

It seems that here

public TModel Model {  get; set;}

you don't need setter since Model is set via constructor and is not supposed to be changed.

Small note: don't use extra spaces in generics :) IModelBuilder < DateModel > will look better as IModelBuilder<DateModel>.


I see a few areas where you can improve.

You don't need parenthesis around the expressions you and or return:

def is_valid_move(x, y, board):
    return 0 <= x <= 2 and 0 <= y <= 2 and board[x][y] == '_'

Sometimes you do need parenthesis, but only if the operator precedence is wrong otherwise. I.e A and B or C is different from A and (B or C).
Your check_win function is very hard to debug. How sure are you that you did not mess up any of the indices while copy&pasting, and how long would it take you to check that you didn't?

Instead divide the function into sub-responsibilities, which you can name and reason about individually:

def all_equal(it):
    it = iter(it)
    first = next(it)
    return all(x == first for x in it)

def check_rows(board):
    for row in board:
        if row[0] != "_" and all_equal(row):
            return True
    return False

def check_cols(board):
    for col in zip(*board):  # transpose the board
        if col[0] != "_" and all_equal(col):
            return True
    return False

def check_diagonals(board):
    if board[0][0] != "_" and all_equal(board[i][i] for i in range(len(board))):
        return True
    if board[0][2] != "_" and all_equal([board[0][2], board[1][1], board[2][0]]):
        return True
    return False

def check_win(board):
    return check_rows(board) or check_cols(board) or check_diagonals(board)

While this code is longer, it should also be more readable. Also, this way only the diagonal check is still complicated to check for correctness, but at least it is localized.
Your get_input_from_user function can be shortened a bit, at the cost of some readability (at least until you get used to functional programming):

def get_input_from_user(message: str):
    return tuple(map(int, input(message).split()))

Don't iterate over the indices, if what you really want to do is iterate over the elements:

def print_board(board):
    for row in board:
        print(row)

Your main loop and the make_move function. The make_move function has two almost identical branches, the only difference is the player mark. So why not pass that instead of the index? In your main loop you can also change that to just swap between the two players, which lets you use a for loop which is automatically restricted to n iterations:

def make_move(player, board):
    x, y = get_input_from_user(f"Player {player}, please enter a move:")
    while not is_valid_move(x, y, board):
        x,y = get_input_from_user("Invalid move, please try again:")
    board[x][y] = player

if __name__ == '__main__':
    players = "X", "O"
    board = [['_'] * 3 for _ in range(3)]
    for _ in range(9):
        make_move(players[0], board)
        print_board(board)
        if check_win(board):
            print(f"Player {players[0]} is the Winner!")
            break
        players = players[::-1]  # equivalent to players[0], players[1] = players[1], players[0]
    else:    # only runs if no `break` broke the loop
        print("Its a Draw!")

I also used some f-strings for formatting, multiplication of lists, and the else clause of loops to detect a draw.
Python has an official style-guide, PEP8. It recommends always puting a space after commas in parameter lists, etc.


This is almost spotless, congratulations.

When processing the results, you refer to results[0] many times.
I would put that in a local variable to clarify, for example firstResult.
(An IDE can give a warning if you mistype firstResult,
but it cannot give a warning if you mistype the array index (for example  results[2]))

You missed a semicolon at the end of this:

document.getElementById(SEARCH_BUTTON_ID).onclick = function () {
    processAddressInput();
}


Calculating neuron outputs and derivatives

Try to minimaze memory allocations.

Allocate memory for deviceTemp and deviceInputs only once (in the constructor, for example):

cudaCall(cudaMalloc ( (void**)&deviceInputs, some_big_value * sizeof(double) ));
cudaCall(cudaMalloc((void**)&deviceTemp, some_big_value * sizeof(double)));

And in calculateNeuronsOutputsAndDerivatives, reallocate memory only if needed:

if (cur_deviceInputs_size < inputsCount)
{
    cudaCall(cudaFree(deviceInputs));
    cudaCall(cudaMalloc ( (void**)&deviceInputs, inputsCount*sizeof(double) ));
    cur_deviceInputs_size = inputsCount;
}


A central question I ask myself on these is whether the explicit recursion follows an abstractable pattern. In this case, only bk' has explicit recursion, and its pattern is simple - the call tree is always linear and brings l incrementally down to -1.

buildEta applies a transformation to a particular slice of phi.

Why are you working with Ints? These are Bools.

bk :: [Bool] -> (Int,[Bool])
bk ks = (n,phi) where
  State n phi _ _ _ = foldr (bk' ks) (State 0 lenzeroes 0 lenzeroes (-1)) [l,l-1..0]
  lenzeroes = True : replicate l False
  l = length ks

bk' :: [Bool] -> Int -> State -> State
bk' ks l (State n phi s psi r)
  | not dl    = State n phi s psi r
  | n*2 <= l  = State (l+1-n) eta n phi l
  | otherwise = State n eta s psi r
  where dl = discr l ks n phi
        eta = overSlice (l-r) (s+1) (zipWith xor psi) phi

discr :: Int -> [Bool] -> Int -> [Bool] -> Bool
discr l ks n = foldr xor False . zipWith (&&) (reverse $ take (n+1) $ drop (l-n) ks)

overSlice :: Int -> Int -> ([a] -> [a]) -> ([a] -> [a])
overSlice from size f a = b ++ f d ++ e where
  (b, c) = splitAt from a
  (d, e) = splitAt size c


Simple spinlock for C using ASM, revision #1

As you have no doubt noticed, given your follow up post, whilst your current lock is thread safe, it isn't reentrant.

If you perform a double call to atomic_open from the same thread, the second call will fail to enter the gate (because it's already locked) and become deadlocked against itself.

lock xchg %%eax, %[gate]\n" // Exhange eax with gate value.
"test %%eax, %%eax\n"        // 1 = closed, 0 = open.

This is because there's no tracking of which thread opened the gate.

Not checking the thread has the potential to cause another issue (which you might not care about, because it's pretty common with spinlocks) whereby if you have a bug in your code, it is possible for a thread that doesn't own the lock to unlock it (anybody can call atomic_close and it will unlock, even if they didn't call atomic_open first).


Updating / validating mass update rails association

Some notes:

This is a edit_admin_recipe form, so you should POST to Admin::RecipesController#update.
Use Rails infrastructure for the models (accepts_nested_attributes_for) to save nested data. Controllers must be kept simple and clean.


Thread-safe concurrent FIFO queue in C++

You are guarding the state of one variable

std::queue<unsigned char*> _queue_;

So you only have one mutex.

pthread_mutex_t push_mutex;
pthread_mutex_t pop_mutex;

If you have two then push and pop can modify queue at the same time.

Make sure your mutex locking is exception safe by using RAII. Note all operations were you do start operation stop should be done by using RAII. This is the most important concept in C++ look it up.

Don't use pointers in C++. They do not convey ownership symantics (which means you don't know who should delete it (or when it should be deleted)). In this case use std::string it solves all the problems.

I see calls pthread_XXX_init but not the equivalent destroy.

Because you have not defined them the default copy constructor and assignment operator will be created. Since your object contains resources (mutext and conditional) you probably don't want the default behavior. Either define them or disable them.

C++11 has a better set of threading constructs use those rather than the C pthread library.


Find all pairs in an array that sum to a given number without using HashMap

Typo in method name as pointed out by @Stingy. Should be findAllPairs.
Accessing wrong array: You are reading values from input instead of your sorted copy numbers. This is probably a typo. E.g. int sum = input[low] + input[high]; should be int sum = numbers[low] + numbers[high];
Your for loop has an empty update statement, this isn't wrong per-se but a bit unusual. Consider an alternative using while instead:

int low = 0, high = numbers.length-1;
while (low < high) {
    int sum = numbers[low] + numbers[high];
    //...
}

Insufficient test: As evidenced by its failure to catch the bug in 2. the test is too limited to be of much help. Consider checking more than one example (especially corner-cases like an empty input array) and checking against the expected output instead of just its size.


Method to check if TicTacToe board has a winner

Just in case you find the for loops inelegant, here is an alternative solution. I don't know Objective C, but the following Go code uses only simple integer arithmetic and decimal formatting, so it should be easy to translate to almost any other language. It was fun to write, so have fun solving this little puzzle.

package main

import (
    "fmt"
    "strings"
)

type Board struct {
    b [3][3]int
}

func (bo *Board) HasWinner() bool {
    b := bo.b
    st := 555555555 +
        b[0][0]*110010010 +
        b[1][0]*101010000 +
        b[2][0]*100110001 +
        b[0][1]*110001000 +
        b[1][1]*101001011 +
        b[2][1]*100101000 +
        b[0][2]*110000101 +
        b[1][2]*101000100 +
        b[2][2]*100100110
    str := fmt.Sprintf("%d", st%100000000)
    return strings.Contains(str, "2") || strings.Contains(str, "8")
}

func main() {
    b := &Board{[3][3]int{{1, 1, 1}, {0, -1, -1}, {0, -1, -1}}}
    fmt.Println(b.HasWinner())
}

Hints and spoilers:

! The leading 1s in the number block prevent the numbers from being interpreted as octal. The modulo operation later discards these digits. If performance is critical, you can remove each leading 1 and all following 0s, as well as the % operation. Alternatively you can subtract 100000000 from each of the factors, as well as remove the % operation.
! The 555555555 prevents overflow amongst the separate digits. It has to be 9 digits long because of the extra leading 1s in the number block. The st variable could become negative otherwise. If you remove the leading 1s, the leading 5 can be removed as well.
! Each column in the number block represents one winning combination. First horizontally, then vertically, then diagonally. Therefore, each column has exactly three 1s. If your programming language allows underscores in integer literals, each factor should look like 1_hhh_vvv_dd.
! Each digit of st starts at 5 and is incremented or decremented depending on the relevant cells. When there are 3 relevant cells in either direction (+1, -1), it is a winning combination. Since every column has only 3 1s, overflow cannot happen.


Loss function in python is a bit cumbersome

It looks like you need to calculate the same thing over and over again. Instead of doing this separately for the positive, the negative and all labels (not sure that is the correct word), you could do it once and then use that once you need to calculate the sums:
def loss_function(
        self,
        x: torch.tensor,
        groundtruth: torch.tensor,
        weight: float
) -> torch.tensor:

    delta = 0.00001
    foreground_gt = groundtruth[:, 1:, :, :]
    background_gt = groundtruth[:, 0, :, :]
    groundtruth_pos = foreground_gt == 1
    groundtruth_neg = foreground_gt == 0

    foreground_x = x[:, 1:, :, :] + delta
    background_x = x[:, 0, :, :] + delta

    a = foreground_gt * torch.log(foreground_x)
    b = (1 - foreground_gt) * torch.log(1 - foreground_x)
    c = a + b

    loss_foreground_pos = -torch.sum(c[groundtruth_pos])
    loss_foreground_neg = -torch.sum(c[groundtruth_neg])

    loss_background = -torch.sum(background_gt * torch.log(background_x))
                                 + (1 - background_gt) * torch.log(1 - background_x))
    return weight * loss_foreground_pos + loss_foreground_neg + loss_background

Note that sum(a) + sum(b) is the same as sum(a + b) = sum(c).


How to handle Throw exception + close connection

You can skip catch part of try-catch-finally block
You should check that rs is not null


Securely convert and return a user selected file

This script is insecure because there are a few small issues. And such issues can often be combined to produce bigger issues, so it's important to be wary about them.

First, you're not restricting the path of the image to PNG_FOLDER. An attacker can ask for ?id=../../etc/passwd. It will fail because you check that the id ends with '.jpg'. But what if the user sends ?id=../../etc/passwd,some_file.jpg? Did you check that png-to-jpg is not going to try to split on a comma? A simple fix: get a list of all possible file names first and only allow an id which is in the list.

Second, you're sending the full png-to-jpg answer. I don't know how this utility works, but an attacker can probably gain useful information just by looking at the output. He will know that he should look at png-to-jpg vulnerabilites. More generally, any information sent to an attacker is another thing that can be exploited.

Third (this is not necessarily an issue), but it's possible to list all files by simply trying all combinations and see the output. It's even possible to see what's already converted and what's not with timing attacks.

I'm not saying that fixing these issues will make your code fully secure, but it will be a step forward.


Percentage based drop prize on Mob entity kill

/**
 * Gets a random drop for NPC by random percentage
 * @param npc       The NPC id
 * @return  The drop details
 */
public Drop getRandomDrop(int npc) {
    List<Drop> drops = this.drops.get(npc);

    float roll = random.nextFloat();

    for ( Drop d : drops ) {
        float chance = d.getChance();
        if ( roll < chance ) {
            return d;
        }

        roll -= chance;
    }

    // if no drop was selected, return an empty drop
    return Drop::EMPTY_DROP;
}

This is how I would write it.  Note that I changed the random variable to be called roll like a roll of a die.  For each drop, it compares the roll to the chance of getting that drop.  If the roll is less than the drop rate, then that drop is the loot.  Otherwise, reduce the roll by the drop chance (which makes subsequent drops more likely).

This method assumes that the drop chances in the XML add up to 1 or that there is an implicit chance of an empty drop.  If you want to always drop and have drop chances that don't add up to 1, you can normalize the rate.

float totalChance = 0.0;
for ( Drop d : drops ) {
    totalChance += d.getChance();
}

and then in the current loop

        float chance = d.getChance() / totalChance;

You may still have to do some adjustment to get the rounding right in the case of a maximum random.nextFloat result.

You would set the EMPTY_DROP to be a static class constant representing no loot.  Note that this would also be the drop if the NPC's section was missing from the XML file.


Finding pair in an array with the OO approach

The biggest problem here IMO is that, from a OOP point of view, it's a bit difficult to represent an algorithm as an object. Objects usually represent "things" which have methods that represent "actions" that happen to those things. Algorithms are usually used in such actions. The object in this case would be the array, but since in Java arrays aren't objects and Java doesn't have the concept of extension methods, it's difficult to represent a stand-alone algorithm in an OOP way.
EDIT: I just realized, your algorithms are returning a pair of indices instead of values from the arrays. That doesn't correspond to the example, and in most cases the pair of values would be more useful than the indices. Also my remarks are based on the assumption that values are returned.
Never-the-less here are some remarks about the OOP side of things:
class Pair
The biggest problem here is the usage of -1 to represent ... what exactly? Keep in mind -1 is  a completely "normal" valid integer. A developer who uses that class and who doesn't explicitly check for that -1 will get no error message when using it in calculations and instead his program most likely will run fine, but display wrong results. More importantly your program currently displays "(-1, -1)" when there is no solution, but it looks like a possible solution. What if the array contains two -1s and you ask for a sum of -2? How do you distinguish between a correct result and no result.
If you actually should need such an "empty" value of Pair you should use Integers and null. However in your case there is no need for such an empty result. Just drop the default constructor. Instead just have your algorithm return null or - if you don't like using null - use Java 8's Optional.
Pair is a perfect case for an immutable object. There is no reason to change one of the values in the pair after creation. Make the fields private and create getters for them.

PairSum/PairSumFast
Since both classes do the same thing, it would be worth considering have them implement a common interface. For such a small example it may be over-engineered, but it would display some insight into OOP.
Another thing that would show a bit more OOP would be to use the Collection interface instead of an array to provide the input. In Java it is rare to actually use an array as a "top level" data structure, since they are not objects are inflexble and don't fit in with Java's collection infrastructure. Arrays are usually used as a low level data storage structure and hidden in the implementation details of classes.


You code looks fine. One minor issue: in the catch(PDOException $e) branch maybe you want to

log the error (error_log),
show a fancy static error page to the user ("It's not your fault, we have logged the error and we're working on it." or something like this.),
and/or call die().

About the dynamic switch: I would use a whitelist array which prohibit including other files which are not in the array.

$pages['index'] = 'index.php';
$pages['default'] = 'default.php';
$pages['home'] = 'home.php';
$page = '/404.php'
if (isset($pages[$action])) {
    $page = $pages[$action];
}

include $con_dir . '/' . $page;


Extending numpy array by replacing each element with a matrix


DRY version of this one line if/else for property's existence

You can use

my_object.unique_id = my_object.unique_id or 'TBC'

Otherwise, stop worrying about having to repeat a variable name, which is not what people typically mean when they talk about DRY. Variable names are often repeated when you do in-place manipulation of a variable, because you are saying "do something to x and then store the result as x".

If you have lots of similar lines of code then you could submit some more of your code for review; there may be other ways to simplify.


Backbone subviews with non-uniform layout

This looks pretty good. My main suggestion for improvement would be we how you set and create the columns. I would try and make this more dynamic so the amount of columns can more easily change, and can be set from code using this view.

To do this I'd create an array to represent the columns. Each column would have information about whether its narrow, or wide and then how many items it should have in it:

columns = [{type: 'narrow', itemsPer: 3}, {type: 'wide', itemsPer: 2},
  {type: 'narrow', itemsPer: 3}]

And then process the array rather then have variables named for each column. This would also add the items to the columns so it can be done it one loop. I used "shift" to remove the first element of the array so the narrow collection could be used without referencing exact indexes, which would allow it to work for any amount of items per column. I also changed the structure of the narrow and wide variables so they are properties on a items object, which makes the referenced with the same column.type name.

items[narrow] = @collection.where display: 'narrow'
items[wide] = @collection.where display: 'wide'

if narrow.length >= 6 and wide.length >= 2
  for column in columns
    columnHtml = $(@template).addClass('column-' + column.type)
    for i in range(column.itemsPer)
      @addOne(items[column.type].shift(), columnHtml)

    @$el.append(columnHtml)

Another thing, I found the template property to be confusing, because it was the template for each of the three columns where I expected it to be the template for the whole view (which would only be created once). I suggest naming it to something like "columnTemplate"

columnTemplate: '

',

My code examples are in pseudo code, as I'm less familiar with CoffeeScript, but I think you can understand generally what I'm saying.


Implement service with explicit interface implementation

You're only using AsIArchiveService to statically get the name of the current method.  Instead, you could go off the interface directly, nameof(IArchiveService.GetConfiguration), which obviously returns the same value as going through AsIArchiveService.GetConfiguration.

logger.LogInformation($"Start  {nameof(ArchiveService)}:{nameof(IArchiveService.GetConfiguration)}");

If you changed your four usages in your log lines to go this route, you could dispense with the peculiar property you created altogether.


canonical pattern for transactional library state manipulation

Go does have a strong opinion on the use of mutexes vs. channels. In fact, the sync package states: "Other than the Once and WaitGroup types, most are intended for use by low-level library routines. Higher-level synchronization is better done via channels and communication." (See https://golang.org/pkg/sync/ )

This opinion clearly implies your first implementation is suboptimal. I agree, so I'm not going to even review that implementation.

The second implementation is more intriguing, it uses channels, but it's got issues.... and it's not a "canonical" example of what I would expect with a "communication" implementation for concurrency in Go.

The "Stateful" go-routine is one which only that single go-routine accesses, or modifies the state. All interaction with the state is done by communicating with that routine, and communication happens through channels.

You have one channel to communicate the request for accessing the state, and another for returning the response. This is a problem... The request channel command is OK, but the response channel is broken. If you have multiple concurrent commands issued, you won't be able to send the right response to the right command, and things will get mixed up.

The solution to this is to dedicate a channel for each command to get the responses on. Add the channel to the commandDoSomething struct, so that your code looks something like:

func (l *LibraryState) DoSomething(arg int) error {

    // dedicated response channel for communication (of error type, not interface{})
    resp := make(chan error, 1)

    // Perform operation transactionally
    l.command <- commandDoSomething{arg, resp}
    res := <-response
    return res
}

Now your state handler would look like:

func (l *LibraryState) reallyDoSomething(arg int, respondto chan<- error) {

    defer close(respondto)

    // Do something
    fmt.Println("Hello, playground")
    var err error = nil
    respondto <- err
}

and be called like:

for {
    switch c := (<-l.command).(type) {

    case commandDoSomething:
        l.reallyDoSomething(c.arg, c.respondto)
    }
}

Note that you can remove the l.response channel completely.

Edit: Note that by dedicating a response channel for each command, you can do things like return the actual channel from the DoSomething function, like:

func (l *LibraryState) DoSomething(arg int) <-chan error {

    // dedicated response channel for communication (of error type, not interface{})
    resp := make(chan error, 1)

    // Perform operation transactionally
    l.command <- commandDoSomething{arg, resp}
    return resp
}

and as a consequence, "clients" can call the DoSomething method and then potentially do other work while the state is changing, and get the possible error condition later... like:

resp := DoSomething(input)
//... work on other activities
if err := <-resp; err != nil {
    // handle error - perhaps undo some previous optimistic code....
}


This is good work! Well done as a beginner programmer.

def changeNumberIntoLetter(value):
    number=numToLetter(value)
    return number

This function doesn't really do anything useful to be honest. Can't you directly use numToLetter.

if value==1: return 'one'
elif value==2: return 'two'
elif value==3: return 'three'
elif value==4: return 'four'
elif value==5: return 'five'
elif value==6: return 'six'

Instead of creating lot of if statements. Try using a dictionary like this:

NUM_TO_WORD_MAPPING = {1: "one", 2: "two"}

and you can refer the string to number using

if value in NUM_TO_WORD_MAPPING:
    return NUM_TO_WORD_MAPPING[value]
else:
    # ... special cases.

As sergiy-kolodyazhnyy said, you can also use a list or a tuple.

int(str(value)[-1])

use value % 10 to extract numbers easily. This is modulo operator and returns remainder after division.

Bonus Content: Code Style

How your code looks like is as equally important as how you implement it. Because you and other programmers will spend time reading it.

  “Indeed, the ratio of time spent reading versus writing is well over
  10 to 1. We are constantly reading old code as part of the effort to
  write new code. ...[Therefore,] making it easy to read makes it easier
  to write.”

  ― Robert C. Martin, Clean Code: A Handbook of Agile Software
  Craftsmanship

Let's take a look at your function

def numToLetter(value): #The function converts the numbers into letters.

I recommend that you use snake_case (number_to_letter) as it is considered industry standard for python programs. Comments are better done using """ comment """ style.

In this scenario however comment is not really required because your function name says that it's purpose is converting number to letter. People usually forget to update comments and it ends up giving incorrect information. If you want to use documentation comments anyway, make sure that comments are always up to date.

Reading material:

PEP-8 - Coding conventions / standard
PEP-287 - Document comment standard
Documentation related SO Question


Code Review:

Naming Convention: $variableNames and functionNames() should be in camelCase, ClassNames should be in CamelCaps. Keep this convention to make your code more readable!
Use an autoloader: To stop you from being worried about loading classes, use an autoloader. See spl_autoload_register() for registering an autoloading function.
Don't use Singletons: Do not use Singletons. Singletons are global, they introduce hidden dependencies to your code and make it unpredictable and untestable.
No explicit dependncies in sight: What does your user object need in order to work? I'm guessing a database connection, maybe even a user_id? Why are you not passing those to the user's constructor?

$user = new User($db, $_SESSION["user_id"]); // For example

How to improve

This code, contrary to popular belief, is not MVC. MVC stems from good OOP practices, and the separation of concerns. The idea is to separate your application into three major layers:

The Input: The Controller layer.
The Output: The View layer.
The Processing and Logic: The Model layer.

Where each has its own job and responsibilities, its own set of objects, and its own role in the application.

I propose you start with learning about OOP, avoid PHP frameworks, and once you grasp OOP, start looking at MVC.


Creating a Dynamic Select Statement from 2 databases on the same server

The first thing you should improve is to split this method into two methods, one for parsing the input string and one for  building a new query. Doing both in the same method isn't a good practice.

This means that the first method should return a collection of columns that the other one consumes.


Swift HackerRank Missing Numbers Challenge

The "create or update" in the countedSet function
can be simplified using the nil-coalescing operator ??:

func countedSet(array: [Int]) -> Dictionary<Int, Int> {
    var dict = Dictionary<Int, Int>()
    for element in array {
        dict[element] = (dict[element] ?? 0) + 1
    }
    return dict
}

This also saves one dictionary lookup if the value is already present in the dictionary.

I would (but that may be a matter of personal preference) separate the string
conversion completely from the difference computation. Return an integer
array from missingNumbers:

func missingNumbers(listA: [Int], listB: [Int]) -> [Int]

and do the string conversion at the call site:

let missing = missingNumbers(listA: listA, listB: listB)
print(missing.map({String($0)}).joined(separator: " "))

or print the numbers directly, without string conversion:

let missing = missingNumbers(listA: listA, listB: listB)
for num in missing {
    print(num, terminator: " ")
}
print()

The comparisonSet in the missingNumbers function is not needed. Since B is
the "larger" set, it suffices to iterate over the counted set generated from B:

func missingNumbers(listA: [Int], listB: [Int]) -> [Int] {
    var output: [Int] = []

    let ctdSetListA = countedSet(array: listA)
    let ctdSetListB = countedSet(array: listB)

    for (element, count) in ctdSetListB {
        if ctdSetListA[element] != count {
            output.append(element)
        }
    }

    return output.sorted()
}

The next improvement is to use only one counted set: Add the elements from B
and subtract the elements from A. Then check which elements have a positive count
in the end:

func missingNumbers(listA: [Int], listB: [Int]) -> [Int] {

    var ctdSet = countedSet(array: listB)
    for element in listA {
        ctdSet[element]! -= 1 // We know that elements in A are present in B
    }

    let output = ctdSet.filter { $0.value > 0 }.map { $0.key }
    return output.sorted()
}

Generally, a "filter + map" operation can be optimized with flatMap:

    let output = ctdSet.flatMap { $0.value > 0 ? $0.key : nil }

The essential clue however is (I assume) the given constraint

  The difference between maximum and minimum number in B is less than or equal to 100.

which means that we can use a fixed sized array to keep track of the number of
occurrences of each number, and all
dictionary lookups now become "simple" array subscript operations.
This also makes sorting the missing numbers redundant:

func missingNumbers(listA: [Int], listB: [Int]) -> [Int] {

    guard let minValue = listB.min() else { return [] } // Empty input

    var counts = Array(repeating: 0, count: 101)
    for elem in listB {
        counts[elem - minValue] += 1
    }
    for elem in listA {
        counts[elem - minValue] -= 1
    }

    var output: [Int] = []
    for i in counts.indices {
        if counts[i] > 0 {
            output.append(i + minValue)
        }
    }
    return output
}

The final for loop creating the output array also can be written concisely in a functional
way as

    let output = counts.enumerated().flatMap { $0.element > 0 ? $0.offset + minValue : nil }

Another possible performance bottleneck is when the input data is read:

let listA = readLine()!.components(separatedBy: " ").map({Int($0)!})

The input lines can contain up to 1,000,010 integers, which means
that many temporary string are created. An alternative is to use
Scanner from the Foundation framework to read integers directly
from the string. And since the number of integers is known, we
can call reserveCapacity() to avoid reallocations while the
array grows:

func splitToIntegers(_ s: String, count: Int) -> [Int] {
    var result: [Int] = []
    result.reserveCapacity(count)
    var n = 0
    let scanner = Scanner(string: s)
    while scanner.scanInt(&n) {
        result.append(n)
    }
    return result
}

let firstArrayCount = Int(readLine()!)!
let listA = splitToIntegers(readLine()!, count: firstArrayCount)
let secondArrayCount = Int(readLine()!)!
let listB = splitToIntegers(readLine()!, count: secondArrayCount)

This turned out to be much faster in my test.


FormArray total of each formgroup via RxJS

Do I have any memory leaks?

No

Why is it if I stick debounceTime(1) inside the lineItem valueChanges then this stops working where the calculation is out by the last change?

  Beacuse debounceTime(1) delays the response by 1ms inside the lineItem
  and this.linesChange.emit(value['lines']);  is already run with old
  total

The implementation below will sort your problems.

  getLineFormGroup(): FormGroup {
    let lineItem = this.fb.group({
      quantity: new FormControl(),
      rate: new FormControl(),
      total: new FormControl()
    });
    lineItem.valueChanges.pipe(
      takeUntil(this.destroyed$),
      debounceTime(20)
    ).subscribe(value =>
      {
        console.log("should be called first")
        this.calcTotal(lineItem)

        if (!this.formGroup.valid) {
          return;
        }
        this.linesChange.emit(this.formGroup.value['lines']);
      }
    )
    return lineItem
}

Why is it if I remove the {emitEvent: false} and put in a debounceTime as above the total stops working altogether?

  The lineItem.valueChanges observable will fire in a circular fashion
  when you remove this {emitEvent: false}.
  line.controls['total'].setValue() will fire lineItem.valueChanges
  again. Which in-turn crashes the app and stop.

Should i be using some other way like combineLatest? If so how do I collect the valueChanges observables (I'll figure it out from here if this is required)?

  I would suggest not required


Improving conv

To convert a base-10 number to base-N, I don't think it gets faster than the conv function your wrote. I would write it a bit differently though:

void toBaseN(ull num, const char *alpha, int base, char *word) {
    while (num) {
       *(word++) = alpha[(num - 1) % base];
       num = (num - 1) / base;
    }
}

What I changed:

Renamed the function: conv doesn't describe what it does
Rearranged the parameters: base is tightly related to alpha (the length), and I think it's good to have out-parameters as last
Add spaces around the operators to improve readability

For the record, this function doesn't return what I would expect.
It returns the digits in reverse order, which is a bit odd.
For example with the given alphabet,
it returns ba for 33 and ca for 34, when I would expect ab and ac, respectively.

The function has a number expectations with regards to the input:

word is expected to be big enough to contain the digits
word is expected to be filled with nulls
base is expected to be the length of alpha

The first one is reasonable and quite natural,
the others are not, and should be documented in a comment above the function.

Improving main

const char alpha[]="abcdefghijklmnopqrstuvwxyzOSR34";
char *word=calloc(30,sizeof(char));
// word always contains null-terminator
int base=(int)strlen(alpha);
for (nu=1;nu<=1e8;++nu) {

There are a couple of things I don't like about this bit:

Too packed code: add more spaces around operators like I did in the previous point
The comment // word always contains null-terminator seems misplaced. It seems you intended it for the line above it. It's more intuitive and readable to have comments above the line they refer to. The make it even more clear, it would be good to leave a blank line before the comment, and perhaps even after the statement
What is magic number 30? It would be better to make this a global constant
base is derived from alpha, it's tightly related, so I'd move these closer to each other

I suggest this writing style:

const char alpha[] = "abcdefghijklmnopqrstuvwxyzOSR34";
int base = (int) strlen(alpha);

// word always contains null-terminator
char *word = calloc(30, sizeof(char));

for (nu = 1; nu <= 1e8; ++nu) {

Improving speed

As I mentioned above, the general functionality of conv without a context is as fast as it can be. (And incorrect: normally I'd expect digits to be reversed.)

In the context of printing base-N numbers within the range [start : end],
you can do better.
You could convert start and end to base-N,
to do the counting in base-N.
This will be significantly faster than counting in base-10 and converting in every step.


Extracting website names from link code cleanup

As mentioned in the answer by Roland Illig, there is a module for that.

Example:

from urllib.parse import urlparse

def get_domain_name(url: str) -> str:
    """Return domain name from URL
    """
    parsed_uri = urlparse(url)
    return parsed_uri.hostname

get_domain_name('https://www.ucl.ac.uk/alumni/services')

Result:

'www.ucl.ac.uk'

NB: this requires a full URL with http/https scheme.

Third-level domain extensions are handled with no problems. This is the prefered approach. The Python philosophy is that there should be one obvious way of accomplishing a given task. It doesn't have to be more complicated.

if you know all domain names will end in .com and want to get rid of it, just add .replace('.com', '').

A regular expression can also get the job done. Something like this will return walmart:

^https://(?:www\.)?([a-z0-9_\-]+)\.com

Assuming that the URL always starts with https://, and the domain name ends in .com, with www. optional and not included in the capture group.

To explain this bit: (?:www\.)?
The rightmost question mark means the expression in parentheses is optional. ?: means: match the expression but do not capture it.

This is not an all-purpose expression, it is adjusted to your circumstances and should be good enough for your needs but that's it.

Let's say you have more complicated cases with subdomains, as an example:

url = 'www.subdomain.walmart.com'

Once you've got the full domain name, you could do some splitting then extract the relevant portions starting from the right, knowing that .com will be the last element:

bits=url.split('.')
print(bits)
['www', 'subdomain', 'walmart', 'com']
print(bits[-2])
walmart

I think this is slightly more flexible than working with fixed lengths like you're doing.

As for reading/writing files have a look at context managers (using the with statement).

Your code is not very long but you would still benefit by keeping the parsing in one dedicated function (possibly two), out of your loop. That would make the whole code easier to read and maintain.

One remark regarding www.: at some point you will find that some sites do redirect to ww1 or ww2 or stuff like that. Not to mention other types of subdomains. It is not safe to assume that the domain name will always be prefixed with www. or nothing.


Using a Dictionary to retrieve BOOL values

Assuming the values under the id keys always match properties of currentAppswitches.

If you can change currentAppswitches's class to accept an NSNumber object rather than a BOOL you have some convenient options.

If currentAppswitches is KVO compliant you could write:

for (NSDictionary *item in switchesArray) {
  id value = [item objectForKey:@"value"];
  id key = [item objectForKey:@"id"];
  [currentAppswitches setValue:value forKeyPath:key];
}

Alternately you could use:

for (NSDictionary *item in switchesArray) {
  BOOL value = [[item objectForKey:@"value"] boolValue];

  //construct a selector for the property setter
  NSMutableString *selectorName = [item objectForKey:@"id"];
  NSString *firstCharacter = [selectorName substringToIndex:1];
  [selectorName stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[firstCharacter uppercaseString]];
  [selectorName insertString:@"set" atIndex:0];
  [selectorName appendString:@":"];

  SEL selector = NSSelectorFromString(selectorName);
  [currentAppswitches performSelector:selector withObject:value];
}

If currentAppswitches must continue to accept BOOLs then you could create an invocation:

for (NSDictionary *item in switchesArray) {
  id value = [item objectForKey:@"value"];

  //construct a selector for the property setter
  NSMutableString *selectorName = [item objectForKey:@"id"];
  NSString *firstCharacter = [selectorName substringToIndex:1];
  [selectorName stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[firstCharacter uppercaseString]];
  [selectorName insertString:@"set" atIndex:0];
  [selectorName appendString:@":"];

  SEL selector = NSSelectorFromString(selectorName);
  NSMethodSignature* signature = [[currentAppswitches class] instanceMethodSignatureForSelector:selector];
  NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature];
  [invocation setTarget:currentAppswitches];
  [invocation setSelector:selector ];
  [invocation setArgument:&myBoolValue atIndex:2];
  [invocation invoke];
}


Answer by janos is good, but is more about style. Here are some functional/performance observations related to your stated goal of efficiency.

invalidated.add(Math.round(f + 0.0)), huh???
f coerced to double, add a zero, call round(). Why?
Suggest change f from int to long, and just use invalidated.add(f).
while(f <= maxFac){ is done by continually coercing f to double and comparing the double values. Change maxFac to long using cast (truncation is ok here, no need for rounding).
for(long l : invalidated){ primes.add(l); } is a long way of saying primes.addAll(invalidated), except you're adding the overhead of unboxing and reboxing the values.
You have two identical loops of invalidated to determine if prime. Move to reusable method (DRY).
Never do String += String in a loop. Use a StringBuilder.
And again, what's with the i + 0.0?

StringBuilder buf = new StringBuilder();
buf.append(Math.round(i * 100.0 / max)).append("%: ");
for (Long prime : primes)
    buf.append(prime).append('/');
System.out.println(buf);


First and foremost, remember DRY: Don't Repeat Yourself. Secondly, group your related functions (preferably in classes; see #1 below). Thirdly, keep your variable names simple and easy to read.

Here are a few more points and examples, elaborating on the above:

You can create a class for your Board. This can easily be done by subclassing the builtin list type, because your original arena is just a normal list.

class Board(list):

    def __str__(self):
        return "\n".join(" ".join(row) for row in self)

This class has one method, __str__, which modifies the superclass' method. It returns the board in the format you want; space-delimited cells and linefeed-delimited rows.

Now, to create our default board, we'll use a list comprehension:

[["O"] * 5 for _ in range(5)]

We can get rid of repeated literals such as your various "X", "O", and 2s
by creating constant variables:

MARKER_X = "X"
MARKER_O = "O"
START = [2, 2]

We can also put the previous and current player-coordinates into lists. Note that [:] takes the contents of a list; in this case, that list is START.

curr_pos = START[:]
prev_pos = START[:]

Group your functions and other code chunks under a class; I'll call mine Game. I'll split this point into several smaller pieces.

Let's subclass the object builtin. Note that, in Python 3, we can omit (object) because it's implicit.

class Game(object):

Now let's move in those constant variables we created earlier. These are the class variables that we can access via the Game object (i.e. Game.MARKER_X).

class Game(object):

    MARKER_X = "X"
    MARKER_O = "O"
    CTRLS = [
        "left",
        None,
        "right",
        "up",
        None,
        "down",
    ]
    EXIT = "stop"
    START = [2, 2]
    DEFAULT = [["O"] * 5 for _ in range(5)]

I'll explain the CTRLS and EXIT variables farther down.
We need to initialize the game, so we'll write an __init__ method.

class Game(object):

    ... # Existing code

    def __init__(self):
        self.flag = True
        self.arena = Board(Game.DEFAULT)
        self.prev_pos = Game.START[:]
        self.curr_pos = Game.START[:]
        self.move_player()

Now we have:

created a variable, flag which we'll use as an exit flag (the same as your go variable).
arena: a Board created from our defaults.
moved our curr_pos and prev_pos variables (from #2) inside our class. These are instance variables that we can access via self.
setup the player's initial position (explained in detail, below).

Let's handle our player's movements. I'm going to call this move_player, which I mentioned in the previous point. We're going to use the instance's curr_pos and prev_pos variables for this. See the code comments for detailed explanations.

class Game(object):

    ... # Existing code

    def move_player(self):
        px, py = self.prev_pos                        # Split apart the previous x and y coordinates.
        cx, cy = self.curr_pos                        # Split apart the current x and y coordinates.
        if (-1 < cx < 5) and (-1 < cy < 5):           # Check to make sure our coordinates are valid.
            self.arena[py][px] = Game.MARKER_O        # Set the previous position to empty.
            self.arena[cy][cx] = Game.MARKER_X        # Set our current position to our marker.
        else:                                         # If the coordinates are invalid, don't do anything.
            print("Please enter a proper direction.") # Notify the player.
            self.curr_pos = self.prev_pos[:]          # The "new" position becomes the old position.
            self.move_player()                        # Move the player back.

Finally let's add in our user interface. I'm going to call this the play method. I've added code comments for a detailed explanation.

class Game(object):

    ... # Existing code

    def play(self):
        print("You are: \nX")
        while self.flag:
            print(str(self.arena))
            ctrl = input("Move left, right, up, down, or stop?").lower()
            if ctrl in Game.CTRLS:                              # Check to see if the command is valid.
                d = Game.CTRLS.index(ctrl)                      # Find our command's index in the command-list. This is important.
                self.prev_pos = self.curr_pos[:]                # The current position becomes the previous position.

                self.curr_pos[d > 2] += d - (1 if d < 3 else 4) # Here, we take the command's index in the command-list, and determine:
                                                                #   1: whether we're moving horizontally or vertically.
                                                                #   2: which direction we're moving (i.e. left or right).
                                                                # Then, we take the command's index and compensate to move either +1 or -1.
                                                                # For example, if the command is "up", we take the index, 3, and subtract 4 to get -1.

                self.move_player()                              # Try moving the player to his new postion.
            elif ctrl == Game.EXIT:                             # Check to see if the command is to exit.
                self.flag = False                               # Set the flag to False. This will end the game.
            else:                                               # Check if the player used an invalid command.
                print("Please enter a proper direction.")       # Notify the player.

Now we can play the game.

my_game = Game() # Create a game.
my_game.play()   # Start the game.

Here is our final code:

class Board(list):

    def __str__(self):
        return "\n".join(" ".join(row) for row in self)

class Game(object):

    MARKER_X = "X"
    MARKER_O = "O"
    CTRLS = [
        "left",
        None,
        "right",
        "up",
        None,
        "down",
    ]
    EXIT = "stop"
    START = [2, 2]
    DEFAULT = [["O"] * 5 for _ in range(5)]

    def __init__(self):
        self.flag = True
        self.arena = Board(Game.DEFAULT)
        self.curr_pos = Game.START[:]
        self.prev_pos = Game.START[:]
        self.move_player()

    def move_player(self):
        px, py = self.prev_pos
        cx, cy = self.curr_pos
        if (-1 < cx < 5) and (-1 < cy < 5):
            self.arena[py][px] = Game.MARKER_O
            self.arena[cy][cx] = Game.MARKER_X
        else:
            print("Please enter a proper direction.")
            self.curr_pos = self.prev_pos[:]
            self.move_player()

    def play(self):
        print("You are: \nX")
        while self.flag:
            print(str(self.arena))
            ctrl = input("Move left, right, up, down, or stop?").lower()
            if ctrl in Game.CTRLS:
                d = Game.CTRLS.index(ctrl)
                self.prev_pos = self.curr_pos[:]
                self.curr_pos[d > 2] += d - (1 if d < 3 else 4)
                self.move_player()
            elif ctrl == Game.EXIT:
                self.flag = False
            else:
                print("Please enter a proper direction.")

my_game = Game()
my_game.play()


Generators, not lists

Rather than returning a list of Fibonacci numbers, it would be much more useful to simply return an infinite generator of them. That is, yield them. This way, you don't even need the max:

def get_fibonacci_numbers():
    '''
    Generator for all the fibonacci numbers
    '''
    fib1 = 1
    fib2 = 1
    yield fib1
    yield fib2
    while True:
        yield fib1 + fib2
        fib1 = fib2
        fib2 = fib1 + fib2

Note that double assigns are actually better done in one go for clarity:

def get_fibonacci_numbers():
    '''
    Generator for all the fibonacci numbers
    '''
    fib1, fib2 = 0, 1
    while True:
        yield fib2
        fib1, fib2 = fib2, fib1 + fib2

If you want the first n numbers, you can use itertools.islice.

Why a generator?

You can easily turn a generator into a list of specific size, so you're not losing any functionality this way. But there's simply so much you can do with a lightweight generator that you can't do with a list. Consider some simple problems - what's the first Fibonacci number over 1000?

>>> next(dropwhile(lambda x: x < 1000, get_fibonacci_numbers()))

Euler problem #2: find the sum of the even-valued fibonacci numbers under 4 million?

>>> sum(i for i in takewhile(lambda x: x < 4e6, get_fibonacci_numbers()) if i%2 == 0)

Can't do either with a list. At least, not unless you know where to stop up front.

If you want just the nth one, that's:

def get_nth_fibonacci(n):
    return next(itertools.islice(
        get_fibonacci_numbers(),
        n, None))


A single function for implementing Newton forward and backward polynomial interpolation

Don't cast the result from malloc()
Instead, include <stdlib.h> so that the compiler knows it returns a void*.  Also, it's a good practice to use the object name as argument to sizeof, so its type can be changed in one place (e.g. if you wanted to use float or long double instead).  It's idiomatic to test a pointer isn't null by using the ! operator on it.
double *result = malloc(sizeof result * n);
if (!result)
    return -2;

Be careful about memory leaks
I don't see a corresponding free() of result or xList - we should be clear that this is the caller's responsibility.  It's also easily missed that the function won't free an existing poly->coeff or poly->xList before overwriting - I think that's a big magnet for inviting leaks.


Dependency Inversion / Injection? - Networking code in model classes

In GitHub for Mac, we use a combination of AFNetworking and our own Mantle and ReactiveCocoa frameworks for API requests.

AFNetworking makes it trivial to create your own "network manager" type object as a subclass of AFHTTPClient. We enqueue requests on it, ask them to hand back a certain kind of MTLModel subclass, and then subscribe to the resulting signal.

The resulting code looks something like this in the caller:

GHGitHubClient *client = [GHGitHubClient clientForUser:loggedInUser];
[[[client enqueueRequestWithMethod:@"GET" path:@"user" parameters:nil resultClass:GHGitHubUser.class]
    deliverOn:RACScheduler.mainThreadScheduler]
    subscribeNext:^(GHGitHubUser *user) {
        // Do something with the fetched user here.
    } error:^(NSError *error) {
        // Handle errors here.
    }];

There are several advantages to this:

You're building on the strength of AFNetworking. There's really no reason to write networking code from scratch anymore – this framework is validated in many, many applications, and can do almost anything you'd need.
MTLModel provides a way to parse model objects knowing only the desired class. GHGitHubClient can drive the parsing without being coupled to the specific model types.
Signals in ReactiveCocoa are composable, so this code can be easily modified to manipulate and transform the GHGitHubUser, or even perform other fetches and combine the results, before delivering to the main thread.
Your domain model isn't doing network activity. I firmly believe that domain models should care only about data, not the mechanics of persisting or fetching it.


Solving the rod-cutting problem using dynamic programming

I'm not familiar with the problem of rod-cutting, so I cannot reflect on the correctness of the algorithtm.
However, I can give you suggestions for some slight improvements:

union method does not depend on any instance variables --> consider making it static
consider splitting the algorithm into two parts: the constructor could have just some code to store the parameters, and then you could have a separate method to perform the actual calculations (this would make the code more readable)

So, I suggest something like this (not tested):

public class RodCutting {
    private int [] cutLengths;
    private int length;

    RodCutting(int[] cuts, int length) {
        cutLengths = new ArrayList<Integer>();
        for (int i = 0; i < cuts.length; i++) {
            cutLengths.add(cuts[i]);
        }
        Collections.sort(cutLengths);

        this.length = length;
   }

   public void calc() {
        List<List<Integer>> optimalCuts = new ArrayList<List<Integer>>();

        // initialize list
        for (int i = 0; i <= length; i++) {
            optimalCuts.add(new ArrayList<Integer>());
        }

        for (int i = 1; i <= length; i++) {
            // assume 1 is always a valid cut length
            if (cutLengths.contains(i)) {
                for (int j = 0; j < cutLengths.size(); j++) {
                    if (i == cutLengths.get(j)) {
                        optimalCuts.get(i).add(cutLengths.get(j));
                        // nothing larger than the current cut
                    }
                }
            } else {
                for (int j = 0; j < cutLengths.size(); j++) {
                    if (i > cutLengths.get(j)) {
                        List<Integer> newCuts = union(
                                optimalCuts.get(i - cutLengths.get(j)),
                                cutLengths.get(j));
                        if (optimalCuts.get(i).size() == 0
                                || newCuts.size() < optimalCuts.get(i).size()) {
                            optimalCuts.remove(i);
                            optimalCuts.add(i, newCuts);
                        }
                    }
                }
            }
        }

        for (int i = 0; i < optimalCuts.size(); i++) {
            System.out.println(i + ": " + optimalCuts.get(i));
        }

    }

// ... rest of the code


Depth First Search & Breadth First Search implementation

Data Structure

Your terminology is a bit off.  Trees have roots and children.  Arbitrary graphs, on the other hand… I think "origin" and "neighbors" would be more appropriate.

Visited flag: Storing the visited/unvisited flag in the Node hurts flexibility.  Once you perform a dfs() or bfs(), that graph is "ruined".  You won't be able to reset all nodes to the unvisited state.  (Well, you could do it manually, since Node.state is a public field, after all.  But that's nasty too.)  Instead, I suggest that dfs() and bfs() keep a HashSet of visited nodes.  Once the traversal is done, just discard the set.
State.Visiting: That value is never used.
Node.getNode(): The name suggests that it would return a single node, but it doesn't.  Also, by returning the entire array, and the original of the array rather than a copy, you would be letting the caller alter the graph's connections in unapproved ways.  Better to offer ways to iterate through all neighbours and to fetch a specific neighbour.
Child vertex array: The Node constructor says: vertices = new Node[8];  However, addNode() checks if (count < 10).  You should test against vertices.length instead.

If the capacity is exceeded, you should't print to System.out as a side-effect.  Throw an exception instead, so that the caller can decide how to handle it.

Better yet, use an expandable data structure so that you don't have to deal with capacity limits.  A simple substitution would be to use an ArrayList<Node>, but read on…
Graph.vertices vs. Node.child: Those arrays seem to serve the same purpose, redundantly.
Graph.createNewGraph(): It's cumbersome.  Wouldn't it be nice to be able to write

Graph g = new Graph();
g.addEdge("A", "B");
g.addEdge("B", "C");
…
return g;

My suggestion:

public class Graph {
    // Alternatively, use a Multimap:
    // http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html
    private Map<String, List<String>> edges = new HashMap<String, List<String>>();

    public void addEdge(String src, String dest) {
        List<String> srcNeighbors = this.edges.get(src);
        if (srcNeighbors == null) {
            this.edges.put(src,
                srcNeighbors = new ArrayList<String>()
            );
        }
        srcNeighbors.add(dest);
    }

    public Iterable<String> getNeighbors(String vertex) {
        List<String> neighbors = this.edges.get(vertex);
        if (neighbors == null) {
            return Collections.emptyList();
        } else {
            return Collections.unmodifiableList(neighbors);
        }
    }
}

Traversal

Your dfs() and bfs() methods can only ever print the node names.  You can't reuse the code for anything else, since the System.out.print() calls are mingled with the graph traversal code.  It would be better to implement an Iterator so that the caller can decide what to do with each node.

Also, DFS and BFS are two different strategies for accomplishing a similar task.  Therefore, they should be implemented in two classes with a shared interface.  I suggest an Iterator<String>.

The breadth-first iterator is a pretty straightforward translation of your original code, with the main difference being that the iterator is now responsible for keeping track of which vertices have been visited.

public class BreadthFirstIterator implements Iterator<String> {
    private Set<String> visited = new HashSet<String>();
    private Queue<String> queue = new LinkedList<String>();
    private Graph graph;

    public BreadthFirstIterator(Graph g, String startingVertex) {
        this.graph = g;
        this.queue.add(startingVertex);
        this.visited.add(startingVertex);
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean hasNext() {
        return !this.queue.isEmpty();
    }

    @Override
    public String next() {
        //removes from front of queue
        String next = queue.remove();
        for (String neighbor : this.graph.getNeighbors(next)) {
            if (!this.visited.contains(neighbor)) {
                this.queue.add(neighbor);
                this.visited.add(neighbor);
            }
        }
        return next;
    }
}

Unfortunately, you'll find that you can no longer use recursion for depth-first traversal.  Instead, you'll have to rewrite it as an iterative solution using an explicit stack, which makes the code more complicated.  (Alternatively, if you abandon the idea of making an Iterator and use the visitor pattern instead, then you could keep the same recursive code structure).

public class PreOrderDFSIterator implements Iterator<String> {
    private Set<String> visited = new HashSet<String>();
    private Deque<Iterator<String>> stack = new LinkedList<Iterator<String>>();
    private Graph graph;
    private String next;

    public PreOrderDFSIterator(Graph g, String startingVertex) {
        this.stack.push(g.getNeighbors(startingVertex).iterator());
        this.graph = g;
        this.next = startingVertex;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean hasNext() {
        return this.next != null;
    }

    @Override
    public String next() {
        if (this.next == null) {
            throw new NoSuchElementException();
        }
        try {
            this.visited.add(this.next);
            return this.next;
        } finally {
            this.advance();
        }
    }

    private void advance() {
        Iterator<String> neighbors = this.stack.peek();
        do {
            while (!neighbors.hasNext()) {  // No more nodes -> back out a level
                this.stack.pop();
                if (this.stack.isEmpty()) { // All done!
                    this.next = null;
                    return;
                }
                neighbors = this.stack.peek();
            }

            this.next = neighbors.next();
        } while (this.visited.contains(this.next));
        this.stack.push(this.graph.getNeighbors(this.next).iterator());
    }
}

Tests

This problem deserves better testing.  With the original code, which always printed its output to System.out, there was no good way to write unit tests.  Now, you can do anything you want with the results, so it is possible to write proper unit tests.

import static org.junit.Assert.*;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.util.*;

// javac -cp .:junit.jar GraphTest.java
// java -cp .:junit.jar:hamcrest-core.jar org.junit.runner.JUnitCore GraphTest

@RunWith(JUnit4.class)
public class GraphTest {

    public static Graph graph1;

    @BeforeClass
    public static void makeGraphs() {
        Graph g = graph1 = new Graph();
        g.addEdge("A", "B");
        g.addEdge("B", "C");
        g.addEdge("B", "D");
        g.addEdge("B", "A");
        g.addEdge("B", "E");
        g.addEdge("B", "F");
        g.addEdge("C", "A");
        g.addEdge("D", "C");
        g.addEdge("E", "B");
        g.addEdge("F", "B");
    }

    private void expectIteration(String answer, Iterator<String> it) {
        StringBuilder sb = new StringBuilder();
        while (it.hasNext()) {
            sb.append(' ').append(it.next());
        }
        assertEquals(answer, sb.substring(1));
    }

    @Test
    public void preOrderIterationOfIsolatedVertex() {
        expectIteration("Z", new PreOrderDFSIterator(graph1, "Z"));
    }

    @Test
    public void preOrderIterationFromA() {
        expectIteration("A B C D E F", new PreOrderDFSIterator(graph1, "A"));
    }

    @Test
    public void preOrderIterationFromB() {
        expectIteration("B C A D E F", new PreOrderDFSIterator(graph1, "B"));
    }

    @Test
    public void BreadthFirstIterationOfIsolatedVertex() {
        expectIteration("Z", new BreadthFirstIterator(graph1, "Z"));
    }

    @Test
    public void BreadthFirstIterationFromA() {
        expectIteration("A B C D E F", new BreadthFirstIterator(graph1, "A"));
    }

    @Test
    public void BreadthFirstIterationFromB() {
        expectIteration("B C D A E F", new BreadthFirstIterator(graph1, "B"));
    }
}


Here are some suggestions to your code
Every module
I had quite a hard time to understand what it does.
Using eval can be quite dangerous so I would try to avoid it.
eval ary.inspect.split(':')[1] rescue nil

You used a module to monkey patch the Array class which is sensible. Another, even more safe way to monkey patch could be to use refinements.

Refinements are designed to reduce the impact of monkey patching on other users of the monkey-patched class. Refinements provide a way to extend a class locally.

https://docs.ruby-lang.org/en/2.4.0/syntax/refinements_rdoc.html
The safest way of course is to not use monkey patching at all. Maybe something like array.flatten.each could do the trick too?
CoinToss
Initialize reference
Initializing the reference in your constructor looks quite complicated. Maybe it could get extracted to dedicated classes.
class Reference
  def initialize(input, allowed_characters = [])
    @input = input
    @allowed_characters = allowed_characters
  end

  def to_s
    if integer?
      IntegerReference.new(input.to_i)
    else
      StringReference.new(input, allowed_characters)
    end
  end

  private

  attr_accessor :input, :allowed_characters

  def integer?
    Integer(reference)
  rescue
    false
  end
end

class IntegerReference
  def initialize(size)
    @size = size
  end

  def to_s
    build_string
  end

  def valid?
    true
  end

  private

  attr_accessor :size

  def build_string
    "*" * size
  end
end

class StringReference
  def initialize(string, allowed_characters = [])
    @string = string
    @allowed_characters = allowed_characters
  end

  def to_s
    return string if valid?
  end

  def valid?
    string =~ /\A[#{validation_regex}]+\z/
  end

  private

  attr_accessor :string

  def validation_regex
    allowed_characters.join("*")
  end
end

Use getter
You already setup attribute accessors but then fail to use them. Instead of @combins use combins. This has the advantage that you can change the way combins is returned by changing the getter method.
Return data instead of puts
Return data from your methods instead of using a puts. This has several advantages likes

Use the classes outside a terminal (e.g. website)
Easier to test

Naming
There are only two hard things in computer science ... Try to use speaking names and avoid abbreviations like combins, occrs, r, c. This will help to make your program easier to read and understand.
Lazy loading
Instead of setting up everything in the controller, use lazy loading and memoization.
def combinations
  @combinations ||= outcomes.repeated_permutation(@iterations).to_a
end

def iterations
  @iterations ||= reference.length
end