Don't go against the language

  The main arguments can be thought of as being a single argument, but I do not want to force users to quote the entire thing, so when the argument contains spaces I must be able to handle multiple arguments.

If you want to a value containing spaces as a single argument,
then you and your users should double-quote it,
otherwise Bash will perform word splitting.
This is a fundamental principle in Bash,
and it's better to play along with it than to go against.

Trying to go against will get you into all kinds of trouble.
For example, what would you expect for?

my_command this      is   a test -new -- sed "s|a|b|"

That is, multiple spaces between words.
Those spaces will be lost,
the script will behave the same way as if there was a single space in between.

Keep in mind that users will have to quote special characters anyway.
You cannot shelter them from quoting.
It's better to learn the basic rules of word splitting and quoting early,
rather than trying to work around it with hacky solutions.

Assign arrays to arrays

This statement assigns an array to a non-array:

ext_command="${@:count}"

This way you lose the ability to expand the original value correctly quoted.

Take for example this input:

my_command test -new -- sed "s|a| |"

Notice the space in the sed pattern.

And let's say the script uses ext_command like this:

ls | "$ext_command"

This will not work as intended (replacing "a" with spaces), because the original arguments are not preserved correctly.

Using an array you could leave this option open, that is:

ext_command=("${@:count}")

And then later:

ls | "${ext_command[@]}"

Minor points

Instead of this:

local inp=""

You can write simply:

local inp

Instead of this:

count=$((count+1))

You can write simply:

((count++))

Instead of this:

if [[ "$i" == '--' ]]
then
    ext_command="${@:count}"
    break
else
    # a long block of code ...
fi

It's more readable like this:

if [[ "$i" == '--' ]]
then
    ext_command="${@:count}"
    break
fi

# a long block of code ... but less deeply nested


Lazy generator of strings in lexicographical order

It's a great question, and the only improvements I can see are superficial ones:

Your method has incomplete type hints. alphabet should be Iterable[str], and it should return -> Iterable[str] as well.
PEP8 discourages multi-statement lines (your return).

Otherwise, you should reconsider making this a recursive implementation. I see that you were careful to check sys.getrecursionlimit() in your test code, so you're already aware of the fact that this will break given sufficient depth. Python also does not have tail optimization so an iterative implementation will potentially yield performance improvements.


Answer to an implementation of Project Euler #8

Rename your variables and functions to be more specific and do not keep unneeded array data, like so:

def createDigits():
    global digits
    digits = []
    for i in n:
        digits.append(int(i))
    return digits

def calculateProduct(startPosition):
   global digits
   global windowSize
   factors = digits[startPosition: startPosition+windowSize]
   product = 1
   for digit in digits:
       product = product * digit
   return product

createDigits()
maxProduct = 1
windowSize = 13
for i in xrange(0, len(digits - windowSize))
   product = calculateProduct(i)
   if product > maxProduct:
      maxProduct = product

EDIT: Also, might as well not scan products at the end when the window starts to shrink, since they are guaranteed to be less than the last complete window.


Processing a tab-delimited file with vertexes and ages

You should indent the body of the qarray function to make it more obvious where it starts and where it's end (I mean I know it ends at the end of the file in this case, but that's not immediately apparent at first glance).

You should also rename your function f into something more descriptive.

let tableData = File.ReadAllLines tableName

If you're using .net 4.0, you can (and should) use ReadLines instead of ReadAllLines as ReadAllLines reads the whole file into memory before you can start to iterate, while ReadLines loads the file lazily which will be faster for large files.

Note that since ReadLines returns a sequence, not an array, you can not access it using indices any longer. However this is a good thing as getting rid of the indices will lead to more functional code.

// find which row the vertex is in
let vrow = Array.findIndex (fun (s:string) -> s.StartsWith vertexLiteral) tableData
let firstYear = int(tableData.[vrow].Split('\t').[1])

// filter out all the row prior to the column headers e.g. table description and comments
let filteredArray = Array.sub tableData (vrow+1) (tableData.Length-vrow-1)

As I said, you can no longer use an index based approach here. The idiomatic way to get rid of certain elements at the beginning of a sequence is to use skipWhile. Since the first element we want is the one that starts with vertexLiteral, we skip elements while they do not start with vertexLiteral:

// Skip all rows up to the one the vertex is in
let relevantRows = tableData |> Seq.skipWhile (fun s -> not s.StartsWith vertexLiteral)

(Note that by using |> to write tableData first I allowed F# to infer the type of s and thus didn't need a type annotation.)

Now we can use Seq.head to get the first row of relevantRows (the one with the vertex) and Seq.skip 1 to get the remaining rows. So the following lines become:

let firstYear = int((Seq.head relevantRows).Split('\t').[1])

let filteredRows = Seq.skip 1 relevantRows

// use the vertex info to read all lines beyond that, converting to doubles
let f (s:string) = s.Split('\t') |> Array.map double

let fullArray = Array.map f filteredArray

Those lines are fine except that you now need to use Seq.map instead of Array.map (at least on the first line, the second one may stay Array.map as Split still returns an array, but there's no harm in using Seq instead), f needs a better name and fullArray needs to be renamed because it's not an array anymore.

[| for i in 0 .. (120 - startAge - 1) -> fullArray.[startAge + i - 1].[System.Math.Min(startYear - firstYear + i + 1, fullArray.[0].Length)] |]

Ok, here 120 is a magic number, which you did not explain (which you should fix by documenting its meaning), so I'm not sure whether you know that the table will have exactly 120 elements and you have the number in there to avoid a bounds violation or whether the table can contain more than 120 elements and you only want to take the first 120. I'm going to assume the latter is the case.

Further it is not clear to me why you use fullArray.[0].Length instead of fullArray.[startAge + i - 1]. I'm going to assume that all rows have the same length and you chose 0 over startAge + i - 1 for simplicity's sake.

So what you're doing here is basically to skip the first startAge - 2 elements then indexing into each remaining element using the minimum of its length and startYear - firstYear + i + 1 as the index. This can be achieved nicely without an index based loop by using Seq.skip followed by mapi (map with an index), like this:

fullSequence |> Seq.skip (startAge - 2) |>
  Seq.mapi (fun i cols -> cols.[System.Math.Min(startYear - firstYear + i + 1, cols.Length)])

Since this is still a bit long, it might be worthwhile to factor out fun i cols -> cols.[System.Math.Min(startYear - firstYear + i + 1, cols.Length)] into a named function.


I really really hate when the comments (which are supposed to help) don't agree with the code. Because now you don't know which is correct (the code or the comments).
    //random number a from number 0 to n-2
    BigInteger a = Utils.generateRandomNumber(number).add(BigInteger.valueOf(-1));

When writing comments. DO NOT put a comment for each obvious line of code. The code describes itself I don't need you to tell me what the line of code does. I can actually read code (as can everybody that will read your code).
When you write comments describe the algorithm that your code is trying to implement (preferably with a link to a static page that will never move (wikipidia) that not only describes the algorithm but what its trying to do (or put it in the comments at the top of a chunk of code). Describe WHY you are using the algorithm and what the final result will be.
Code:
    //random number a from number 0 to n-2
    BigInteger a = Utils.generateRandomNumber(number).add(BigInteger.valueOf(-1));

If this actually generates a random number in that range then I would seriously kick the implementer of generateRandomNumber for generating an initial range of [1..(number-1))
This comment is even stranger:
    BigInteger tmp = a.modPow(k, number);
    //a^k - 1 (mod n)
    tmp.add(BigInteger.valueOf(-1));

Really. Not sure what the heck is happening here.
What is it with all the usless white space.
            }

        }

    }

}

Maybe I should kick the implementor of generateRandomNumber
public static BigInteger generateRandomNumber(BigInteger number){

That is not doing what the name suggests it is doing.
Yep sure the loop is going to work:
do {
    random = new BigInteger(number.bitLength(), new SecureRandom());
} while (random.compareTo(number) >= 0);

But why have the loop. Why not generate a random one smaller than the max than add one.
Also why are you creating a new random number generator on each iteration new SecureRandom(). You just create than once (in the entire life cycle of the program) then use the instance every time.


Moving a rover and receiving current coordinates

Validation

Your validation is weird, and probably not what you intended.

move_rover(-1, -1) appears to succeed, even though it's not within your 1000 × 1000 grid.
move_rover(-1, 1001) is a no-op.  move_rover(1001, 500) is a no-op.

move_rover(2000, 2000) prints a message.  However, it would be more idiomatic to raise some kind of ValueError.  Printing the error message directly limits the reusability of your code.

Output

Similarly, I advise against having your move_rover() function also print the new coordinates.  Each function should do one thing only.  Printing should be a separate operation.

There is repetition in the code to format the position in the success and error cases.  The formatting code should be factored out to a common routine.

Representation

Using a dictionary with keys named 'x' and 'y' seems cumbersome.  You could use a tuple, a namedtuple` or class.  A class probably make sense, since your rover should act as an object that responds to messages.

Suggested implementation

from random import randint

MIN_COORD, MAX_COORD = 1, 1000

class Rover(object):
    def __init__(self):
        """Places the rover randomly in the coordinate range with a uniform
        distribution"""
        self.x = randint(MIN_COORD, MAX_COORD)
        self.y = randint(MIN_COORD, MAX_COORD)

    def move(self, x, y):
        if MIN_COORD <= x <= MAX_COORD and MIN_COORD <= y <= MAX_COORD:
            self.x, self.y = x, y
        else:
            raise ValueError('Invalid position: %s' % (self))

    def __str__(self):
        """Reports the position of the rover"""
        return 'x{} y{}'.format(self.x, self.y)

You run it like this:

>>> from rover import Rover
>>> rover = Rover()
>>> print(rover)
x944 y556
>>> rover.move(234, 789)
>>> print(rover)
x234 y789


(1..5).each do |i|
  e = c.send("e#{i}")
  next if e.nil?
  found = Extra.find(e)
  array.push("#{found.name} (#{number_to_currency(found.aufschlag, unit: "EUR ")})")
  extpreis += found.aufschlag
end

If you can be certain that c.e1 etc. never becomes false, then:

(1..5).each do |i|
  next unless e = c.send("e#{i}")
  found = Extra.find(e)
  array.push("#{found.name} (#{number_to_currency(found.aufschlag, unit: "EUR ")})")
  extpreis += found.aufschlag
end


Counting letter frequencies from an input file

Your explode function is almost just equivalent to Seq.toArray<char>. There's no need to have a ToUpper function just to call a method, especially if you're using it just once. And there is already a .ToCharArray() method anyway. I would recommend getting rid of both of those functions and using method calls instead: let numLetterInWord (word:string) = word.ToUpper().ToCharArray() |> Array.countBy id
Similarly, it seems like overkill to have div and mul functions just so they can be used in a pipeline. Their usage later on can be replaced by a single lambda: fun x -> x / total * 100.0
The sumTupArray isn't used and not really necessary. At one point you just do an inline Array.sumBy snd instead and that's fine.
Regarding the portion you're concerned about: Note that you can do pattern matching in function arguments just like you can in a let binding. So this pattern...

|> Array.map (fun z ->
     let e, f = z

... can be replaced with |> Array.map (fun (e, f) ->

The Array.tryFind can be replaced with Array.tryFind (fst >> (=) e) (using the function composition operator >> and the curried prefix version of =). If you don't like that you can still just use a lambda: Array.tryFind (fun (f,_) -> e = f)
F# has its own more concise version of Convert.ToInt64 called int64. Ironically, it's less type-safe than Convert.ToInt64 because it also tries to convert other things like strings and can throw an exception if they're not valid. I would still use it in this case since we know an int can always be converted to int64.
I think that most people don't use the style of indentation that you have used because it quickly uses of a lot of horizontal space. Instead of this, I would suggest starting a new line and indenting by four spaces. This can mean using a bit more vertical space, but it's worth it in my opinion.

With these suggestions applied, we end up with something a bit more concise and readable:

open System
open System.IO

let numLetterInWord (word:string) = word.ToUpper().ToCharArray() |> Array.countBy id

let rec CalcNextLine (reader:StreamReader) accumulator =
    match reader.EndOfStream with
    | true -> accumulator
    | false ->
        let line = reader.ReadLine()
        let count = numLetterInWord line
        accumulator
        |> Array.map (fun ((e, f) as z) ->
            match count |> Array.tryFind (fst >> (=) e) with
            | Some x -> (e, int64 (snd x) + f)
            | None -> z)
        |> CalcNextLine reader

let CalcLetterFreqOfFile (path:string) =
    let reader = new StreamReader(path)
    let start = [| for c in [|'A'..'Z'|] -> (c,0L) |]
    CalcNextLine reader start

[<EntryPoint>]
let main _ =
    let occurences = @"dictionary.txt" |> CalcLetterFreqOfFile

    let total = occurences |> Array.sumBy snd

    let freqs = occurences |> Array.map (fun (e, f) ->
        let percentage = float f / float total * 100.0
        (e, Math.Round(percentage, 2)))

    printfn "%A" freqs
    printfn "%A" (freqs |> Array.sortByDescending snd)
    0

I just realised your original time was 14 minutes, not 14 seconds! Which explains a lot. I found a solution that I think is a good balance of fast and simple:

open System
open System.IO

let countByIdBig xs =
    let counts = Collections.Generic.Dictionary<_,_>()
    for x in xs do
        match counts.TryGetValue x with
        | true, c -> counts.[x] <- c + 1L
        | false, _ -> counts.[x] <- 1L
    counts
    |> Seq.map (fun (KeyValue kv) -> kv)

let CalcLetterFreqOfFile (path:string) =
    seq {
        for line in File.ReadLines path do
        for c in line do
            if Char.IsLetter c then yield Char.ToUpper c }
    |> countByIdBig

The countByIdBig is similar to Seq.countBy id but it counts using int64 instead of int32. It uses a mutable dictionary for performance in a very contained way.

Then it's just a matter of getting a seq of characters to count and passing them to countByIdBig.


Is the Button, an  element with svg code and hidden link content inside, ARIA conform and well laid out?

SVG has a desc and a title tag that you're meant to use to describe the SVG:

<a href="#menu" class="head__toggle" title="Toggle Menu">
    <svg viewBox="0 0 70.115 53.162" class="head__btn">
        <desc>Toggle Menu</desc>
        <use xlink:href="#skmenu"></use>
    </svg>
</a>

When you run it through CodeSniffer, you get this notice instead:

  Notice: Check that text of the link describes the purpose of the link.

That said, I don't buy that inline SVGs are the way to go, as it increases the size of the document and cannot be cached in a meaningful way.  I mean, it's not considered a good practice to place the entire contents of your CSS file in the head tag to reduce HTTP requests, why would it be good for SVGs?

You can still get most of the benefits Mr. Coyier talks about in his SVG For Everybody talk by using an external SVG embedded via the img tag, in addition to being able to cache it.

Take advantage of CSS for styling purposes (including media queries)
SVG sprite stack technique, meaning you won't have to set the viewBox information.


Project Euler #11 - Largest product in a grid C++

Input

Using magic numbers like 48 and -16 makes your code very cryptic and hard to understand. Consider comparing with the characters instead.

Algorithm / Logic

I think two things that could really simplify your code are:

Limit the loops iterations from [0, 0] to [16, 16]. This will make you avoid some unnecessary checks.
Only try to get the 4 numbers in the forward direction. There is no need to check in the backward direction as well since it's already checked in the forward direction.


I would strongly consider storing the various variables that define the transformation in a structured object like this:

let transformConfig = {
    rotate: {
        x: ...,
        y: ...,
        z: ...
    },
    scale: {
        x: ...,
        y: ...
    },
    translate: {
        x: ...,
        y: ...,
        z: ...
    },
    skew: {
        x: ...,
        y: ...
    }
};

That gives you the ability to easily iterate over this object to create transformation strings.  An example of this iteration might be:

function createTransformString(transformConfig) {
    // a variable to store array of individual transform strings
    var transformStrings = [];

    // store functions that build strings for each transform type
    // not shown here but you may want to consider ECMA6 templating
    var buildString = {
        rotate: function(rotate) {
            for (dim in rotate) {
                transformStrings.push( 'rotate' + dim + '(' + rotate[dim] + 'deg)' );
            }
        },
        scale: function(scale) {
            scale.x = scale.x || 1;
            scale.y = scale.y || 1;
            transformStrings.push( 'scale(' + scale.x + ',' + scale.y + ')' );
        },
        translate: function(translate) {
            for (dim in translate) {
                transformStrings.push( 'translate' + dim + '(' + translate[dim] + 'px)' );
            }
        },
        skew: function(skew) {
            skew.x = skew.x || 0;
            skew.y = skew.y || 0;
            transformStrings.push( 'skew(' + skew.x + 'deg,' + skew.y + 'deg)' );
        }
    };

    // iterate the config object to generate strings
    for (transformAction in transformConfig) {
        let transform = transformConfig[transformAction];
        buildString[transformAction](transform);
    }
    return transformStrings.join(' ');
};

Usage:

let transformConfig = { ... };
let transformString = createTransformString(transformConfig);

This approach would limit the repeat code you have for each transformation string and would also take care of your if concern in that only those transformation types specified in the config would be executed.

This also more directly injects the transformation configuration information into the function that generates the strings, meaning you no longer have to rely on variables that may or may not be present in inherited scope.  This means you could now have your createTransformString() function declared in a wholly separate include file from the code where the actual transformation(s) values are generated, promoting code re-use.

Since you are using ECMA6, I would also consider building this as a class (or classes).

Finally, from a stylistic standpoint, I would recommend sticking with camelCase instead of snake_case, as this is pretty much the de facto standard for javascript. At a minimum, don't intermingle the two. Additionally, I would suggest watching your line length. You should strive to keep lines of code under ~80 characters per line to improve code readability.


Shipping calculator consisting of one field

Getting rid of backbone, you can simplify this a lot.

HTML

Калькулятор доставки

Город отправления

          <input type="text" class="form-control" id="fldCityOfDeparture">

Рассчитать

JS

function validate(city) {
    return city.length == 0     ? 'Это поле не может быть пустым' :
           isNaN(city) == false ? 'Это поле не может быть цифрой' : '';
}
function showError(error) {
  document.getElementById('errorMessageCityOfDeparture').innerHTML = error;
}
document.getElementById('calculatorSubmitButton').onclick = () => {
  var city = document.getElementById('fldCityOfDeparture').value,
      error = validate(city);
  showError(error);
};

Here's a new fiddle, which shows the error messages on the page, rather than in the console.

https://jsfiddle.net/5uygd9s1/

NOTE: Currently I'm only using the not_valid class, since the border will not display when the error is empty.  If you want, you can change the class too depending on if there is an error or not.  The important point is finding a simple solution, especially when the problem is simple.  With all the available js frameworks today, it's easy to over-engineer.


Since you've only posted partial code, all we can do is offer some suggestions:

Google suggests that the performance of stdext::hash_map might be improved by adding #define _SECURE_SCL 0. See this MSDN article for background.
Your if's look like they might become victim to branch misprediction. This StackOverflow answer explains that better than I ever could.
If you haven't done so already, take care to allocate your vertices (and their internal data) contiguously. The simplest way to do that is usually to shove everything into a vector.


Is there a way to optimise my Perlin noise?

Your check

if (array[x, y] <= -0.2)
    color = Color.DarkBlue;

serves no purpose, if your number is indeed lessthan or equal -.2 then it will also hit the next check if it is lessthan or equal to 0.

A prettier way to write if-else blocks like yours would have been to use the ternary operator...

color = array[x, y] <= 0.0  ? Color.DarkBlue       :
        array[x, y] <= 0.1  ? Color.Blue           :
        array[x, y] <= 0.2  ? Color.Beige          :
        array[x, y] <= 0.22 ? Color.LightGreen     :
        array[x, y] <= 0.40 ? Color.Green          :
        array[x, y] <= 0.75 ? Color.DarkGreen      :
        array[x, y] <= 0.8  ? Color.LightSlateGray :
        array[x, y] <= 0.9  ? Color.Gray           :
        array[x, y] <= 1.0  ? Color.DarkSlateGray  :
                              Color.DarkSlateGray  ;

Your method draw is a public method, and should be PascalCase not camelCase

Your worst case scenario for the if-else chain is that you have to hit every single one of those IFs.
If you structured those in binary search design, ie. start from the middle and eliminate half of the spectrum at a time and work your way out, worst case scenario is that you have to hit half of your IFs. The code for this may look ugly, but it would help.

The most inefficient thing about your code though, and the reason it is taking so long to process is most likely your quadruple nested for-loop

for (int y = 1; y < resolutieY; y++)
{
    for (int x = 1; x < resolutieX; x++)
    {
        //color calculations

        for (int i = 0; i < tileSize; i++)
        {
            for (int j = 0; j < tileSize; j++)
            {
                afbeelding.SetPixel(((x - 1) * tileSize) + i, ((y - 1) * tileSize) + j, color);
            }
        }
    }
}

I would recommend instead, to create the 2d array of colors in that first double for-loop, then, loop over that Color[,]  and set the pixels.

If possible, instead just create a max resolution version of your image, and rely on the PictureBox's ability to scale the image for you.


Get Worksheet Data Array (Standard Methods)

UnhideWsCellsAndRemoveFilters()

Well thats a real strange name. Wouldn't it be better to replace Unhide with Show? Like ShowWsCellsAndRemoveFilters() ?

CellContainingStringInRange()

You should declare your variables as near as possible to their usage. This together with reverting the if condition to return early would lead to

Public Function CellContainingStringInRange(ByRef rngSearch As Range, ByVal strSearch As String) As Range

    Set CellContainingStringInRange = rngSearch.Find(strSearch, LookIn:=xlValues)
    If CellContainingStringInRange IsNot Nothing Then
        Exit Function
    End If

    Dim errorMessage As String
    errorMessage = "Couldn't find cell """ & strSearch & """ in " & rngSearch.Worksheet.name
    PrintErrorMessage errorMessage, stopExecution:=True
End Function

GetWsDataRange()

At first glance at this

Dim wbSource As Workbook, wsSource As Worksheet
Set wbSource = ActiveWorkbook
Set wsSource = ActiveSheet

it will be overseen that wbSource and wsSource are different objects. You should consider to use some vertical spacing to separate these and/or to use different names like sourceBook and sourceSheet. The same is true for the method arguments wbTarget and wsTarget.

Generally declaring multiple variables on the same line should be avoided because it is much harder to read/maintain.

Having the dataRange As Range doesn't provide any value because it is only used "once". You can assign the return value directly.

Implementing this points and having the declarations as near to their usage as possible and on separate lines will lead to

Public Function GetWsDataRange(ByRef targetBook As Workbook, ByRef targetSheet As Worksheet, ByVal topLeftCellText As String, ByVal useCurrentRegion As Boolean _
                            , ByVal searchStartRow As Long, ByVal searchStartColumn As Long _
                            , ByVal searchEndRow As Long, ByVal searchEndColumn As Long) As Range

    Dim sourceBook As Workbook
    Set sourceBook = ActiveWorkbook

    Dim sourceSheet As Worksheet
    Set sourceSheet = ActiveSheet

    targetBook.Activate
    targetSheet.Activate
    ShowWsCellsAndRemoveFilters ws

    Dim searchRange As Range
    Set searchRange = targetSheet.Range(Cells(searchStartRow, searchStartColumn), Cells(searchEndRow, searchEndColumn))

    Dim topLeftCell As Range
    Set topLeftCell = CellContainingStringInRange(searchRange, topLeftCellText)

    Dim dataRange As Range

    If useCurrentRegion Then
        Set GetWsDataRange = topLeftCell.CurrentRegion
    Else
        Dim lastRow As Long
        lastRow = Cells(Rows.Count, topLeftCell.Column).End(xlUp).row

        Dim lastCol As Long
        lastCol = Cells(topLeftCell.row, Columns.Count).End(xlToLeft).Column

        Set GetWsDataRange = targetSheet.Range(topLeftCell, Cells(lastRow, lastCol))
    End If

    sourceBook.Activate
    sourceSheet.Activate

End Function


Preserve formatting for mail merge Excel & Word 2016

You can't read the Text property from a multi-cell range the same way you can with (eg) Value, but you can change the number format and set the value for the whole block using only two single operations, so something like this is much faster:

Public Sub RemoveNumberFormat2(ByVal columnName As String, _
                               ByVal lastColumn As Integer)
    Dim d(), rng As Range, i As Long

    Set rng = Range(columnName & "2:" & columnName & lastColumn)

    ReDim d(1 To lastColumn - 1, 1 To 1)

    'read the text values: this you have to do in a loop...
    For i = 1 To rng.Cells.Count
        d(i, 1) = rng(i).Text
    Next i

    'these you can do as a block...
    With rng
        .NumberFormat = "@"
        .Value = d
    End With
End Sub

In my testing on a ~3000-row column this was about 10x faster.


It seems fine if there is not any simpler Java or Apache Commons API.

I'd modify a few small things:

The isValid boolean would be unnecesary if you return immediately when you know the return value. (Flattening Arrow Code)
(address == null || address.trim().isEmpty()) could be changed to StringUtils.isBlank.
According to the Code Conventions for the Java Programming Language if statements always should use braces.

public static boolean isValidInetAddress(final String address) {
    if (StringUtils.isBlank(address)) {
        return false;
    }
    if (InetAddressValidator.getInstance().isValid(address)) {
        return true;
    }

    //not an IPV4 address, could be IPV6?
    try {
        return InetAddress.getByName(address) instanceof Inet6Address;
    } catch (final UnknownHostException ex) {
        return false;
    }
}


GroupBy over a clustered iterator in Scala

I'd like to add a completely different answer. The task can be very well solved with a concept called pipes or conduits (also iteratees).

I'll give a solution using my experimental library called scala-conduit (disclaimer: I'm the author).

A Pipe[I,O,R] is a thing that can read input elements of type I from one side (request) and emit output elements of type O on another side (respond). When it finishes, it produces a final result of type R. It decides on its own when it requests and when it responds. This is ideal for the task - we receive inputs and decide when to emit the cluster of equal elements. A pipe also knows when the input finishes. This was problematic with using Streams or other native Scala collections, because folding, mapping, etc. don't notify the function that it hit the end. We didn't know easily when to output the last accumulated buffer. With conduit it is easy, our pipe will get notified when it runs out of input. The solution would look like this:

import conduit._
import conduit.Pipe._
import conduit.Util._

def cluster[A](implicit eq: Equiv[A]): Pipe[A,Seq[A],Unit] = {
  // no finalizers used here, import the empty implicit
  implicit val fin = Finalizer.empty;

  def loop(xs: Seq[A]): Pipe[A,Seq[A],Unit] =
    request(
      y => xs match {
        case Seq(x, _*) if eq.equiv(x, y) => loop(xs :+ y);
        case Seq()                        => loop(Seq(y));
        case _                            => respond(xs, loop(Seq(y)))
      },
      // When upstream finishes producing output,
      // we just respond the buffer and finish.
      _ => if (xs.isEmpty) done else respond(xs)
    )

  loop(Seq.empty);
}

The elements accumulated so far are kept in loop's argument xs. When we hit an non-equal element, we respond the buffer and start with a new one. When we hit the end, we respond the buffer (if it's non-empty).

Then we can construct a source pipe from an interator and combine the result into a collection:

def runCluster[A](xs: Iterator[A])(implicit eq: Equiv[A]): Seq[Seq[A]] =
  runPipe(fromIterator(xs) >-> cluster >-> toCol);

println(runCluster(Stream(1,1,2,2,2,3,4,4,4,5).iterator));

Processing of pipes is single-threaded and fully lazy. A pipe is processed only if its downstream pipe requests an input and only until it produces its output, then it's suspended again. And if a pipe terminates (means stops receiving input), its upstream pipes are notified and any registered finalizers are executed.

For example we could read the source values from a file, process it with cluster and do something with the clustered output. And if the right-most (sink) pipe decided to terminate early, the file would be automatically closed, without reading unneeded input.

(We can't convert a pipe to an Iterator or to a lazy Stream. We must run it and extract its final, definite output. The reason is that if extracted values lazily, we wouldn't be able to detect when no more values are requested and finalizers should be run. However this is not a big problem, we simply build the whole computation from Pipes.)


Is this PHP email validation comprehensive and complete?

Use filters

You are a lot better off just using the built in validation filters:

$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_b) email address is considered valid.";
}

Handling International email addresses

International domain names are not really UTF-8 - they are punycode encoded strings (ascii). A UTF-8 local name isn't considered valid by most servers - i.e.

foo@çupærman.dc valid (after converting the domain to punycode)
foo@xn--uprman-quaf.dc valid (this is the above puny code converted)
çupærman@foo.dc INvalid

if you just want to prevent injection - run the email address through striptags before processing; you could also follow this advice and use loose validation and simply send a mail to confirm the mail exists.


Pidfile single process instance mechanism

I don't know much about file locking, but I can guide you in Rust.

I'd suggest changing your write_pid to use writeln!. I think you can simplify it to this.

fn write_pid(mut file: &File) -> Result<(), io::Error> {
    writeln!(file, "{}", process::id())
}

I'd also prefer to reduce the nesting in exclusive, perhaps something like this:

pub fn exclusive(pidfile: &path::Path) -> Result<bool, io::Error> {
    let pf = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(pidfile);

    match pf {
        Ok(file) => {
            lock_pidfile(&file, pidfile)?;
            write_pid(&file)?;
            return Ok(true);
        }
        Err(ref e) if e.kind() == ErrorKind::AlreadyExists => {}
        Err(e) => return Err(e),
    }

    let mut file = OpenOptions::new().read(true).write(true).open(pidfile)?;
    lock_pidfile(&file, pidfile)?;
    let mut id_str = String::new();
    file.read_to_string(&mut id_str)?;
    let id: u32 = id_str.trim().parse().map_err(|_| {
        Error::new(
            ErrorKind::Other,
            format!("Failed to parse pidfile: {}", pidfile.display()),
        )
    })?;
    // Kill None just checks if process exists.
    // Same as kill(pid, 0); in C
    if kill(Pid::from_raw(id as i32), None).is_ok() {
        Ok(false)
    } else {
        file.seek(SeekFrom::Start(0))?;
        write_pid(&file)?;
        Ok(true)
    }
}


First, you should read the Python style guide it has a lot of info on good practices for code readability.

But as for your code, part of the reason the smarter way is slower is that you're creating the whole list every time. It's not stored at all when you create it and this means that instead you're just taking extra time because it has to go through the effort of building the list every time even though you only need the last value. Also, you're not limiting what primes you test for division, so you've lost the root optimisation you used before.

If you cached this list as part of the function then you actually would have time saved on repeated calls, though it would still be slower initially due to building the initial list. There is a way to set up a cache pretty easily, using default parameters. If you're unfamiliar with them, leave a comment and I can explain more about how they're generally used, though I'm using them in a different way than normal here.

If you change def prime(n) to def prime(n, cache=[2]) then you'll have a list called cache created containing 2, the first prime. Each time you call prime it refers back to the same list, so if you append your primes to it, it will be retained and save you all that work.

First of all, this means you might not need to calculate anything when you start. You can just try to return your prime value immediately:

def prime(n, cache=[2]):
    try:
        return cache[n - 1]
    except IndexError:
        pass

To explain, try except is used to attempt a piece of code that may generate an error. So it tries to return the nth prime (use n-1 because lists are indexed from 0) but if it can't find that value in the list it will throw an IndexError. Our except will catch this and just pass, meaning it goes on to run the rest of the function.

The other benefit is you can start your while loop from the last point in that list. So m (which I'd rename as num) can just be the last prime cached + 1 and i can be set as len(cache), since that's the amount of previous primes we're skipping.

i = len(cache)
num = cache[-1] + 1

Now you can begin your while loop, skipping the previously found values but still having them as your divisor check. Note also, you can collapse this with some other syntax and smarter logic. Python has else syntax for a for loop. If you never call break from a for loop then the else will be run, but otherwise it will be skipped. With this in mind you can remove multiple lines where you had to use flag before. Also if you're calling m = m + 2 in both cases, it should just be at the end for both conditions. And lastly, you can shorten var = var + 1 to var += 1 in Python, so I did that too.

while i < n:
    for prime in cache:
        if num % prime == 0:
            break
    else:
        cache.append(num)
        i += 1
    num += 2

Here's how the fully rewritten code would look:

def prime(n, cache=[2]):

    try:
        return cache[n - 1]
    except IndexError:
        pass

    i = len(cache)
    num = cache[-1] + 1

    while i < n:
        for prime in cache:
            if num % prime == 0:
                break
        else:
            cache.append(num)
            i += 1
        num += 2

    return cache[-1]


Connect to streaming Twitter API, parse tweets, and write to CSV in real-time

MyListener is not a very descriptive name. Maybe CSVWriter would be a better one. And that name already suggests something else, that it should take the file name as a parameter:

class CSVWriter(StreamListener):
    def __init__(self, file_name, *args, **kwargs):
        self.file_name = file_name
        StreamListener.__init__(*args, **kwargs)

    def on_data(self, data):
        try:
            tweet = parse_tweet(data)
            content = extract_content(tweet)
            with open(self.file_name, 'a') as f:
                writer = csv.writer(f, quotechar = '"')
                writer.writerow(content)
        except Exception as e:
            logger.warning(e)
        return True

It is also enough to except Exception. BaseException will catch a bit more than you would probably want, namely KeyboardInterrupt (so you can press Ctrl-C to stop the program).
        ...

twitter_stream = Stream(auth, CSVWriter("tweets.py"))

There seems to be no need to first save tweet['CREATED_AT'] = parser.parse(tweet['created_at']) and then later do tweet['CREATED_AT'].strftime('%Y-%m-%d %H:%M:%S'). Just do the correct conversion at the end (I don't know which one exactly, because I don't know what format it is in, orginally).

I would also reduce the number of blank lines. While some are nice for readability (to separate blocks of code) or are recommended by PEP8, blank lines between before elif or else block just break up the reading and reduce readability.


First thing I notice is that you're actually not using jQuery all that much. The point of jQuery is really its convenience compared to the native DOM. You're foregoing that convenience in some places, and relying on jQuery in others. You can of course do it all directly using the DOM and skip jQuery, but you're not quite doing that either. My point is really just that you should decide one way or the other in order to keep the code consistent.

Also, while it's not enforced, convention dictates that function names are lowerCamelCase. If you use PascalCase it implies that a function is a constructor. I.e. your Sort function should be just sort.

However, the sort function is not necessary. Provided you always search in a "master list" of options, and those are already sorted, then the filtered options will retain that order.

The hidden select element isn't necessary either; you can clone the full option list into memory, and filter it from there without having to store it in the document.

In fact, by keeping a master list, you can "prepare" that list to make it faster to filter later.

Here's a demo of my take and here's the code:

$(function () {
    var customerSelect = $("#customer"),
        searchField    = $("#search"),
        options        = customerSelect.find("option").clone(); // clone into memory

    // generic function to clean text
    function sanitize(string) {
        return $.trim(string).replace(/\s+/g, ' ').toLowerCase();
    }

    // prepare the options by storing the
    // "searchable" name as data on the element
    options.each(function () {
        var option = $(this);
        option.data( "sanitized", sanitize(option.text()) );
    });

    // handle keyup
    searchField.on("keyup", function (event) {
        var term = sanitize( $(this).val() ),
            matches;

        // just show all options, if there's no search term
        if( !term ) {
            customerSelect.empty().append(options.clone());
            return;
        }

        // otherwise, show the options that match
        matches = options.filter(function () {
            return $(this).data("sanitized").indexOf(term) != -1;
        }).clone();
        customerSelect.empty().append(matches);
    });
});

You could do a few more things, but I'll leave that as an exercise:

If the search term contains the previous search term, you can filter the customer select directly, instead of filtering the entire "master list". I.e. if the last search was for "foo" and the next is for "foobar", you already have the results that match "foo", and only have to find a further subset that contains "foobar" rather than starting from the beginning.
If you have a very long list, or you're retrieving the search results via ajax, it's beneficial to have a delay between searches. I.e. on keyup wait, say, 100ms before filtering the list, to see if the user's still typing.


What you are describing are simply functions.

To take a related example from mathematics,

          /   x, if x >= 0
abs(x) =  |
          \  -x, otherwise

And you are just composing functions: f(g(x)).

You can somewhat make the correspondence to monads, but it is a bit of a stretch.  I think it is more that monads are extensions of functions rather than the other way around.

flatMap would be the composition operator: o  , ie (f o g)(x) = f(g(x)).  And unit would just be the identity operation: I(x) = x.

The three monad laws:

Associativity: f o (g o h) = (f o g) o h
Left unit: I o f = f
Right unit: f o I = f

So instead of defining your If class, you can just stick to def, the usual function definition.  Functional programming!!!  In your case you can compose all your functions in any order since they always input/output Foo type.  You can compose functions in Scala with val h = f _ compose h _, or using andThen.


Printing out relative date from current time

I've commented your code:

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

int main(int argc, char *argv[])
{
    int i = 1;
    struct tm date = {0};
    char relativeDays[80];

Check For Proper Input

    if(argc != 2)
    {
        printf("Two arguments required!\n");
        return -1;
    }

    char *temp = strtok(argv[1], "/");

temp will be NULL if empty.  Also, add a break after case 3: for consistency.  If you think you'll need to handle unexpected cases, use default at the end.

    while(temp != NULL)
    {
        switch(i++)
        {
            case 1:
                date.tm_mon  = atoi(temp) - 1;
                break;
            case 2:
                date.tm_mday = atoi(temp);
                break;
            case 3:
                date.tm_year = atoi(temp) - 1900;
                break;
            default:
        }

Be consistent with spacing.

        temp = strtok(NULL, "/");
    }

Add comments so people know what your intentions are.  Why are you dividing by 86400?

    i = (int)difftime(time(NULL), mktime(&date)) / 86400;
    sprintf(relativeDays, "%d", abs(i));

Use spaces to make everything more readable.

    if(i > 0)
        printf("%s\n", strcat(relativeDays, " days ago."));
    else if(i < 0)
        printf("%s\n", strcat(relativeDays, " days from now."));
    else
        printf("Today\n");

    return 0;
}

Edit:

This while block can be changed to the following. Though it doesn't change the operation, it may improve the aesthetics.

while(temp != NULL)
{
    int num = atoi(temp);
    switch(i++)
    {
        case 1:
            date.tm_mon = num - 1;
            break;
        case 2:
            date.tm_mday = num;
            break;
        case 3:
            date.tm_year = num - 1900;
            break;
        default:
            printf("Unexpected input. Blowing up now!\n");
            break;
    }

    temp = strtok(NULL, "/");
}


Defining of new, temporary, variables or usage of already known ones?

public static ErrCode checkStatePhoneLen(final String state, final String phoneNo)
{
    String  stateTmp = state.trim();
    String  phoneTmp = phoneNo.trim();

The issue is that stateTmp is less readable than state.trim(), so if you want to create a new variable, make sure that the name carries your intent. You can go for "normalizedState", but since you're only trimming (and are not normalizing capitalization for example) then a variable is useless.

    Integer phoneLen = new Integer(phoneTmp.length());

This one is useful! phoneLen is clearer than phoneNo.trim().length(). This answers your first question: it depends! Use new variable names when they do make thing clearer, but never use dummy names like phoneTmp, phone1, and so on. By the way, I may be mistaken, but are you certain Integer is necessary? Java should do autoboxing. I would simply write int phoneLen = phoneNo.trim().length().

    if (statePhoneNoMap.containsKey(stateTmp) && !phoneLen.equals(statePhoneNoMap.get(stateTmp)))
    {
        return ERROR;
    }
    return SUCCESS;

To answer your second question, you don't need to explicitely check for null: it's simpler to compare phoneLen and statePhoneNoMap.get(stateTmp) directly. If the latter is null, then the comparison will return false. If phoneLen is null, you don't want to return a value but throw an exception anyway, and this is what happens with your current code because null.equals(...) throws.
It makes more sense to check for success and return ERROR if something went wrong.
If you have an ErrCode type instead of a boolean, you have to return more explicit codes! Otherwise just return the condition directly.

The code becomes:

public static ErrCode checkStatePhoneLen(final String state, final String phoneNo)
{
    int phoneLen = phoneNo.trim().length();
    int stateTrimmed = state.trim();

    if (statePhoneNoMap.containsKey(stateTrimmed)
        && phoneLen == statePhoneNoMap.get(stateTrimmed))
    {
        return SUCCESS;
    }
    return ERROR;
}


Per the answer to this question, storing the variables into a matrix works.

VN_ANOVA<- function(A){

  mean_of_means <- mean(colMeans(A))
  n<- ncol(A)

  LPM_ratio = numeric(0L)
  MAD_CDF = numeric(0L)

#Continuous CDF for each variable from Mean of Means
  for (i in 1:n){
      LPM_ratio[i] <- LPM(1,mean_of_means,A[,i])/
                 (LPM(1,mean_of_means,A[,i])+UPM(1,mean_of_means,A[,i]))

#Continuous CDF Deviation from 0.5
      MAD_CDF[i]<- abs(LPM_ratio[i] - 0.5)
      }

  Mean_MAD_CDF <- mean(MAD_CDF)

#Certainty associated with samples
  VN_ANOVA_rho <- (0.5 - Mean_MAD_CDF)/0.5

#Graphs
  boxplot(A, las=2, xlab= "Means", horizontal = TRUE,
       main="ANOVA", col=rainbow(n))

#For ANOVA Visualization
  abline(v=mean_of_means,col="red",lwd=4)
  text(mean_of_means,pos=4, .25,"Mean of means", col = "red")

  return(c("Certainty of Same Population"=VN_ANOVA_rho))

}


Provably fair coin flip system in Laravel

So why are you saving both the $secret and the hash of the $secret in the DB?

$bet->secret_key = $secret;
$bet->secret_hash = hash('sha256', $secret);

Also how does the hash of the $secret allow you to ensure that the outcome is fair? Do you ever use this hash anywhere?

Also carrying out any critical operations that you expect to remain secure on a client that allows someone to view and alter the code via a console cannot be considered secure. Basically the game should be run entirely on the server with input from the clients, such as the bet amount and bet acceptance, and then the results can be distributed to the clients for display.

Do you have some mathematical proof showing that the distribution of numbers in the second position of a string generated from a HMAC hash after non-number characters are removed is actually random? If not then you cannot assert that this method is truly random and would give you the 50/50 chance you desire.

Since PHP already has a built int cryptographically secure pseudo-random integer generator, int random_int ( int $min , int $max ), why don't your just use that to generate you numbers between 0 and 9?


React Hooks - Did I write this correctly?

Probably the biggest issue I see here is naming. In particular, isTrue is very vague - perhaps is isHovered would be better? And conventionally you use set... rather than handle... with useState so this should be setIsHovered. Similarly, I think you should rename setArg to setIconType.

Also, I don't think you can pass 2 seperate functions as a prop. You maybe want to instead do this:

<div
  onMouseEnter={() => {
    setIsHovered(true)
    setIconType('careers')
  }}
>
</div>

Other than that, it looks fine to me.


Generate set of random numbers and remove lowest

This seems like a nice thing to do with your kids!

Python has these things called comprehensions.
For example a list comprehension for the first 5 multiples of 2 could be either:

[i * 2 for i in range(1, 6)]
[i for i in range(11) if i % 2 == 0]

The latter one is a bit harder to understand, and you don't need to know it. So I'll give you an example of what the first one would be if it were not a comprehension.

list_ = []
for i in range(1, 6):
    list_.append(2 * i)

You could change rolls to be a list comprehension, and remove some varibles:

stats = []
for _ in range(7):
    rolls = [random.randint(1, 6) for _ in range(4)]
    stats.append(sum(rolls) - min(rolls))
stats.remove(min(stats))
print stats

There's a way you could do this all in two comprehensions.
But you are not allowed to define variables in comprehensions.
So you would need to use sorted and a slice to get the rolls.
I personally think this is harder to understand, and could be a challenge to teach your kids.

roll = sum(sorted(random.randint(1, 6) for _ in range(4))[1:])

However if you think it's nice, you could use it:

stats = [
    sum(sorted(random.randint(1, 6) for _ in range(4))[1:])
    for _ in range(7)
]
stats.remove(min(stats))
print stats

It's a lot shorter than your original, mostly due to not defining variables like roll.
But could be harder to understand.


AutoSuggest: Better way to implement focus after inserting a snippet

I do feel that negative numbers seems a bit backwards compared to most other libraries I have used. I am not sure what all would be involved with reworking this code to utilize positive numbers but it seems it may be hefty. Though maybe you could accept positive numbers and convert them to negatives by subtracting them from the length of the string.

I see one spot that may have a possible performance improvement- in the recursive call to setSelection():

setSelection(
    lastFocus - lastNode.textContent.length,
    Array.from(lastNode.childNodes),
    method
);

here Array.from() is called to copy the array of nodes from the childNodes collection  from lastNode. The spread operator can also be used to put those child nodes into an array (from the node collection), allowing you to eliminate that extra function call.

setSelection(
    lastFocus - lastNode.textContent.length,
    [...lastNode.childNodes],
    method
);


Implementing Passport authentication with promises

When writing your custom functions that operate on promises, a good habit is to return resulting promises in order to have ability to chain them. For instance:

return DBM.getUser(user_props.id_google).then( (res) => { (from getOrCreateUser)
or:
return DBM.createUser(user_props).then(() => {

It will ensure that getOrCreateUser and createUser operations will be chained together properly.

The passportjs uses different API. It does not use promises but callbacks.
As I see, you mixed them together by mistake! For instance in DBM.createUser from inside your promise you returned an object returned just by done callback when resulting value/other promise is expected. Same in DBM.getUser from passport.deserializeUser
It might be only mine (a little bit nerdy) custom, but I have a habit to wrap 3rd party non promise APIs into promise adapters.

For instance (an easy one):

function serializeUser(idProviderPromise) {
    let resultDeffered = Promise.defer();
    passport.serializeUser((profile, done) => {
        idProviderPromise(profile).then(function (profileId) {
            done(null, profileId);
            resultDeffered.resolve();
        });
    });
    return resultDeffered;
}

Usage:

passportPromiseApi.serializeUser(new Promise(profile => profile.id_google));

It can help make us sure not to mix different APIs together.

At the first glance it can look a little bit over complicated, but please take a look how it simplifies more complex cases:

function configure(getOrCreateUserPromise) {
    let resultDeffered = Promise.defer();
    function getOrCreateUser(accessToken, refreshToken, profile, done) {
        getOrCreateUserPromise(accessToken, refreshToken, profile).then(function (userProps) {
            done(null, userProps);
            resultDeffered.resolve(userProps);
        }).catch(function (error) {
            done(error, null);
            resultDeffered.fail(error);
        });
    }
    passport.use('google', new GoogleStrategy(helper.getPassport(), getOrCreateUser));
    return resultDeffered;
}

Usage:

passportPromiseApi.configure(new Promise(function (accessToken, refreshToken, profile) {
    const userProps = obtainProps(profile);
    return DBM.getUser(userProps.id_google).then(res => {
        return res[0] ? Promise.resolve(userProps) : createUser(userProps);
        //Instead Promise.resolve(userProps) simply userProps should work as well
        //But it is also a good practice for return type in any JS function to be consistent.
    });
}));

function createUser (userProps) {
    return DBM.createUser(userProps).then(() => userProps);
    //Error handling is already done by our adapter.
    //We can focus only on business logic here!
}

Last less important thing: let assume some consistent naming convention for function parameters and local variables respectively. You have to decide whether to use xxx_yyy or xxxYyy (camel case). 3-rd party usages doesn't count as it must be used exactly.


Memory management for fetching a list of drive letters on Windows

Your code is leaking memory. If you throw an exception, free no longer gets called. Using a std::vector makes sure the memory is freed.

Iterating through the array returned is quite straight-forward, considering that each drive letter has a null-terminator and than the whole vector has an extra null-terminator (requiredSize = writtenChars + 1)

auto requiredSize = GetLogicalDriveStringsW(0, nullptr);

std::vector<WCHAR> buffer(requiredSize + 1);
auto writtenChars = GetLogicalDriveStringsW(requiredSize, buffer.data());

if (writtenChars > requiredSize)
{
    //MSDN: If the buffer is not large enough, the return value is greater than nBufferLength.
}

if (writtenChars == 0)
{
    //handle error
}

const WCHAR* currentString = buffer.data();

while (*currentString != 0)
{
    std::wcout << currentString << L'\n';
    //pass currentString to other methods
    currentString += wcslen(currentString) + 1;
}


Taking and saving pictures using promises

Promises were meant to provide a linear appearance of async code instead of callbacks, as well as make it appear that the control is in one place rather than handing it off to other functions.

Also, functional programming is also of help. Not to the strict sense though, but trying to avoid side effects as much as possible as well as isolating code that mutates stuff to a few known locations can help you reason about your code.

// Let's just move out the handler so both getPictures and takePictures
// look the same.
$scope.takePictures = function () {
  document.addEventListener("deviceready", _takePictures, false);
}

$scope.getPictures = function () {
  // Taking this as an example, we call an async operation
  getImagesFromDevice({
    quality: 50,
    destinationType: Camera.DestinationType.DATA_URL,
    sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
    targetWidth: 200,
    targetHeight: 200
  }).then(function(imageData){
    // When the operation succeeds, this function is called. The nice thing
    // about promises is that if you return a promise, the next chained
    // then listens to that promise instead of the original.
    return saveFileToParse(imageData);
  }).then(function(response){
    // What the above means is that this function now listens to
    // saveFileToParse instead of getImagesFromDevice
    //
    // Also notice that we isolate mutation to the scope to only here
    // and removed it from the other functions.
    $scope.activeExercise.images.push(response._url);
    $scope.$apply();
    $scope.customImage = true;
  });

  // In the end, your operation looks linear
}

function _takePictures() (
  getImagesFromDevice({
    quality: 75,
    destinationType: Camera.DestinationType.DATA_URL,
    sourceType: Camera.PictureSourceType.CAMERA,
    allowEdit: true,
    encodingType: Camera.EncodingType.JPEG,
    targetWidth: 200,
    targetHeight: 200,
    popoverOptions: CameraPopoverOptions,
    saveToPhotoAlbum: true
  }).then(function(imageData){
    return saveFileToParse(imageData);
  }).then(function(response){
    $scope.activeExercise.images.push(response._url);
    $scope.$apply();
    $scope.customImage = true;
  });
}

// These operations do not concern what you're doing with the data. All
// they know is that they receive options, operate, and hand you back
// the data when done. Pretty functional don't you agree?

// Another perk about promises is when you don't return a promise in the
// sequence, all chained thens will resolve using the same value. This
// allows us to chain a then for logging in between without affecting
// the result.

var getImagesFromDevice = function (options) {
  return $cordovaCamera.getPicture(options).then(function (imageData) {
    // logger for success
  }, function (err) {
    // logger for error
  });
}

var saveFileToParse = function (imageData) {
  return (new Parse.File("mypic.jpg", {
    base64: imageData
  })).save().then(function (response) {
    // logger for success
  }, function (error) {
    // logger for error
  });
}

Now if I were to write all this code synchronously, which is how a normal person would go about imperative programming (commands one after the other), the code appears 95% the same.

$scope.takePictures = function () {
  document.addEventListener("deviceready", _takePictures, false);
}

$scope.getPictures = function () {
  var imageData = getImagesFromDevice({
    quality: 50,
    destinationType: Camera.DestinationType.DATA_URL,
    sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
    targetWidth: 200,
    targetHeight: 200
  });

  var response = saveFileToParse(imageData);

  $scope.activeExercise.images.push(response._url);
  $scope.$apply();
  $scope.customImage = true;

}

function _takePictures() (
  var imageData = getImagesFromDevice({
    quality: 75,
    destinationType: Camera.DestinationType.DATA_URL,
    sourceType: Camera.PictureSourceType.CAMERA,
    allowEdit: true,
    encodingType: Camera.EncodingType.JPEG,
    targetWidth: 200,
    targetHeight: 200,
    popoverOptions: CameraPopoverOptions,
    saveToPhotoAlbum: true
  });

  var response = saveFileToParse(imageData);

  $scope.activeExercise.images.push(response._url);
  $scope.$apply();
  $scope.customImage = true;

}

var getImagesFromDevice = function (options) {
  var imageData $cordovaCamera.getPicture(options);
  imageData ? /* success logger */ : /* error logger */;
  return imageData;
}

var saveFileToParse = function (imageData) {
  var response = (new Parse.File("mypic.jpg", { base64: imageData })).save();
  response ? /* success logger */ : /* error logger */;
  return response;
}

Now I'm assuming here that you use a "standard" promise. Angular's $q has a weird quirk where if you don't return anything from the resolve or reject handler, instead of resolving or rejecting with the same value from the original promise, it resolves regardless.

The fix is to manually return data or a reject.

var getImagesFromDevice = function (options) {
  return $cordovaCamera.getPicture(options).then(function (imageData) {
    // logger for success
    return imageData;
  }, function (err) {
    // logger for error
    return $q.reject(err);
  });
}


concatenate string, with different first and last iteration

You should use String.Join() here. Its easier to read and shorter as well.
Like
string[] arr = { "A1", "A2", "B3", "D4", "WHATEVER STRING" }; // can be any string value
string result = "=" + string.Join("-", arr) + "=";


For your module definition, I suggest the following:

;(function(ns){

  function internalFunction(...){...}

  function anotherInternalFunction(...){...}

  ns.addDelegateEvents = function(...){...};

  ns.anotherFunction = function(...){...};

  ns.yetAnotherFunction = function(...){...};

}(this.editable = this.editable || {}));

This is more from the readability standpoint and not at all different from your approach. Your closure gets a reference to an existing global or creates one. Then you simply attach to it. You don't have to define this huge object at the end of the module.

            editElement.on("keypress", function(event) {

                if (event.which == 13) {
                    //send ajax call then re-populate the list
                    var newVal = editElement.val();
                    var obj = {};
                    obj[ajaxAttr] = newVal;
                    $.ajax({
                        method: "PUT",
                        url: url,
                        data: JSON.stringify(obj),
                        contentType: "application/json; charset=utf-8",
                        success: function(data) {
                            console.log('sheet updated');
                            // Very careful here : the RESTapi should return a JSON
                            // with the updated infos
                            originElement.text(data[ajaxAttr]);
                            editElement.replaceWith(originElement);

                        },
                        error: function() {
                            console.log('error on sheet update');
                            editElement.replaceWith(originElement);
                        }
                    });
                }
                if (event.which == 27) {
                    editElement.replaceWith(originElement);
                }
            });

Separation of concerns. Don't mix DOM code with AJAX code.

Move the AJAX into another function. Make it return a promise, which the caller can listen to. The DOM operation remains in the handler. It should be something like:

// This block of code is all DOM-related, with the exception of that AJAX
// function call. The AJAX code is moved out.
editElement.on("keypress", event => {

  if(event.which === 13){
    return theAjaxFunction(...).then(data => {
      // DOM operation on success
    }, error => {
      // DOM operation on error
    });
  }
});

// Meanwhile, somewhere else in your module
function theAjaxFunction(...){
  return $ajax(...);
}

if (event.which == 13) {
    ...
}
if (event.which == 27) {
    ...
}

To avoid foot-guns, put an else to avoid JS having to evaluate the second condition. One issue that might arise here is when some rogue code accidentally changes the value of event.which somewhere before the second if statement is evaluated. You will have a case where both blocks will be executed.

var addEditDelegateEvents = function(element, selector, url, idInUrl, idAttr, ajaxAttr) {

While there's nothing wrong with a sequence of arguments, it's often very hard to remember which one is which and the order they come in. Also, it's hard to set defaults. Suggesting you accept an object for configuration.

// Your module accepting options and merging it to defaults.
var defaults = {};

var addEditDelegateEvents = function(options){
  var mergedOptions = Object.assign({}, defaults, options);

}

// Usage
editable.addEditDelegateEvents({
  element: $("p.editable_sheet_date_end"),
  selector: "span",
  url: "/api/v1/sheets/ID/update",
  idInUrl: "ID",
  idAttr: "sheet_id",
  ajaxAttr: "end"
});

element.on("click", selector, function(event) {
  ...
  editElement.on("keypress", function(event) {

Nested event handlers can be hard to debug. It requires you to perform one action before you can test the other. What I suggest is to use event delegation for this. This way, you avoid nesting handlers, allowing you to attach handlers in advance, even when the element isn't present yet.

element.on('click', selector, function(event){
  // Create edit element with class "aClassOnEditElement"
});

// Listen for our element from an ancestor element
ancestorOfEditElement.on('keypress', '.aClassOnEditElement', function(){
  // Handle edit element event.
});

var DELAY = 300,
    clicks = 0,
    timer = null;

Major nitpick, but I suggest you do a var per variable. One issue you will have with this approach is during refactoring. You cannot easily re-arrange variables easily without having to re-add var, adjust commas and semi-colons.

Try putting timer as the first variable in the group with just cut-and-paste, you'll get what I mean.


Compiler for grond, a language-in-the-making

String.prototype.reverse = function() {
  return this.split("").reverse().join("");
}

Firstly, don't modify objects you don't own. It could cause incompatibility problems if some other code had its own String.prototype.reverse function which had different functionality.

Secondly, this is a bad implementation of reversing a string. For example, calling this function on the following string:

'foo  bar'

returns:

'rab �� oof'

You use many meaningless identifiers, for example wc, y, OK, OK2. It's hard to tell what purpose they serve.

while (true)

Instead of using an infinite loop and break-ing it, I recommend you using a do-while loop. In your case it could look like that:

var condition = false
do {
  // the actual loop content

  condition = lastWC === wc
} while (!condition)

See Is while (true) bad programming practice?.

I highly recommend you wrapping your code in an IIFE (see Ben Alman's article for more details). In the current state, all your variables are global, which is a bad practice. See Why are global variables considered bad practice?.

I had to spend quite a while to work out how the replace function works. It seems that you wanted to re-invent the g regex modifier (read MDN RegExp docs). You could get rid of the loop at all if you used it.

I don't see any point in reversing the wc variable two times, except of making the code less readable.

Calling wc.replace() multiple times and assigning the result to wc looks ugly. You could at least chain the .replace() calls like that: wc.replace(...).replace(...).replace(...), or even better, make an array of matches and replacements and loop through them:

var matchesAndReplacements = [
  ["§", ""]
 ,["Ś", ""]
 ,[/\(a(?!\w)/g, "(trela"]
]

for (let i of matchesAndReplacements) {
  let [match, replacement] = i
  wc = wc.replace(match, replacement)
}

And most importantly, this doesn't work. Writing a programming language compiler using regex is a very naive idea, and IMHO even worse than trying to parse HTML with regex. A simple example: what if you had a .l fragment in a string? It would be incorrectly changed to .length.

var source = prompt("Enter Source");

prompt() is a pretty primitive way to make an I/O. Even if you decide so, it shouldn't be somewhere in the middle of the code. Create a function, named compile for example, which takes input as argument and returns output, and then at the end of the code place alert(compile(prompt("Enter Source"))).

var source = prompt("Enter Source");
var sourceCopy = source;

When you declare multiple variables at once, you can use the var keyword only once, and separate the variables declarations with a comma, like that:

var source = prompt("Enter Source")
   ,sourceCopy = source

However, in this case it would be better to use const for source, as you don't intend to modify it.

var y = (a) => {
  for (let char in fullASCII) {
    if (!source.contains(char)) {
      source.replace(a, char);
    }
  }
}

If your arrow function has only one parameter, you don't need to use parentheses, so it could be var y = a=> {}.

Also, this function seems to be no-op, because it doesn't return any value and doesn't assign any value to any variable.

var OK = false;
var OK2 = false;
for(let char in fullASCII){
  if(!source.contains(char)){
    OK2 = OK? true:false;
    OK = true;
  }
}

That looks ugly for me. You could rewrite it like that:

const isOK = fullASCII.map(source.contains.bind(char)).filter(x=>x).length >= 2

One liners FTW!

var sourceSplit = sourceCopy.split("\'");

You don't need to escape apostrophes if you use double quotes to make a string. Besides, I would name the variable sourceSplitted, because now it looks more like a function name.

if (oSS[0] == "§") {

Always use === instead of ==. See Does it matter which equals operator (== vs ===) I use in JavaScript comparisons?.

To conclude: yes, this code is ugly. You have a lot to learn.


For a beginner this code looks okay. Good job using strict equality comparisons - i.e. ===. The indentation is mostly consistent, although the first indentation level is 4 spaces while all subsequent levels appear to be 2 spaces.
The biggest thing I would change is spacing. For the sake of readability, it helps to add spacing around operators - especially binary operators like ===, >, =, etc. You could utilize a linter like ESLint, JSHint, etc. ESLint has rules like space-infix-ops.

While formatting preferences are very personal, a number of style
guides require spaces around operators, such as:
var sum = 1 + 2;

The proponents of these extra spaces believe it make
the code easier to read and can more easily highlight potential
errors, such as:
var sum = i+++2;

While this is valid JavaScript syntax, it is hard to
determine what the author intended.

1
I tried passing 0 to the function and it returned [0, 1], which is the same output if I pass 2. Theoretically it should return an empty array when 0 is passed.
The first and second else cases could be simplified to just an else, since the loop won't run unless i is less than n and for the case of 2 it would never be the case that 3 is less than 2. So it can be simplified like this:
function fibonacciGenerator (n) {
    var output = [];
    if (n === 1) {
      output = [0];
    } else {
      output = [0, 1];
      for (var i=3; i <= n; i++) {
        output.push(output[i-3] + output[i-2]);
      }
    }
    return output;
}

In more advanced JavaScript the const keyword could be used to declare output so it can't be over-written, which would require exclusively using the .push() method to add elements to the output array. Using const when re-assignment isn't needed is a good habit because it can help avoid accidental re-assignment and other bugs.
Alternatively, the function could return early in the base cases - e.g. when n is 1.


Your code is pretty much perfect, the only problem is that you chose to sacrifice some performance in most cases (non 0 operands) for the sake of making the rare case faster. Here's a slight improvement based on the assumption that most of the times none of the operands will be 0.

The trick is to keep it efficient in the case of 0 without wasting time on special checks that don't help the actual calculation. If the carry is 0 then you know you're done. Storing the output (a ^ b) in the same variable removes the need for an if statement for returning b instead of a.

Also 1 bitwise operation and assignment is saved by shifting the carry at the start of the loop, so there is no extra unused shift at the end. (note: it would slow the function down in case of overflow, but that's a rare case and it's expected that the programmer will avoid overflow anyway)

public int GetSum(int a, int b)
{
    int carry = a & b;
    a = a ^ b;

    while (carry != 0)
    {
        b = carry << 1;
        carry = a & b;
        a = a ^ b;
    }

    return a;
}


Producer

protected BlockingQueue queue = null;

Why not apply generics? BlockingQueue<Integer> avoids awkard casting later on.

Why is this protected? Fields are typically private, and there doesn't seem any motivation in your example to widen visibility on the field itself

} catch (InterruptedException e) {
    e.printStackTrace();
}

This is not the proper way to handle an InterruptedException. The ExecutorService uses interruption for forced shutdown (shutDownNow()), but since you eat the interruption the ExecutorService will not be responsive to forced shotdown. In general you would always propagate interruption to the caller.

Consumer

Actually the remarks for Producer go for Consumer as well.

but also

while (ExecutorTest.isRunning) {

Alternatively you could simply use interruption to stop the task : while (!Thread.currentThread().isInterrupted()).
But what's worse is that isRunning is actually a field on ExecutorTest, This means Consumer class depends on ExecutorTest class for its proper working.

ExecutorTest

ExecutorService executorService = Executors.newFixedThreadPool(4);

executorService.execute(consumer);
executorService.execute(consumer);
executorService.execute(consumer);
executorService.execute(consumer);

Perhaps a small for loop, and make the literal 4 variable or a constant.

// wait for the threads to finish
while (isRunning) {
};

This is unnecessary, you already do executorService.awaitTermination(10, TimeUnit.SECONDS);
A busy wait like this is also a poorer way to await some other thread, as you are wasting CPU cycles.


I think you trying to overengineer solution a bit. First of all View should not do any stuff at all. View is just a View, sheet of paper. Maximum of view's responsibility is layouting himself. So controller should take care of other view-related stuff.

In this case I probably prefer to think about gridView as legitimate subview of GameBoard. I really doubt Demetra suffering when you doing something like [self.view.titleLabel sizeToFit].

So my advice is to use [self.gameBoard.gridView doStuff]; as simplest and straightforward solution.


Create new columns using groupby in pandas

I don't know if I fully understand the end goal, it's difficult to tell without some sample data, however there are certainly better ways to make this call.

I noticed the manipulations over each column could be simplified to a Pandas apply, so that's what I went for.

suffixed = [i + '_rank' for i in df.columns]

g = df.groupby('date')

df[suffixed] = df[df.columns].apply(lambda column: g[column.name].rank() / df['counts_date'])

There could be a way to precompute the group ranks and then concatenate those columns straight to the original, but I didn't attempt that.

Apply will almost always be faster than a for loop.


Removing objects from a list that don't appear in a list of ID's

You can do this without external iteration, if you are using java-8:

items.removeIf(item -> !mediaIds.contains(item.getMediaId()));

It's not necessary to create a new list, this will modify the existing one.


Avoiding code repetition while handling exceptions

I was originally going to add this as a comment, but it works better as an answer.

Why don't you just have a variable among one of the method's arguments which determines whether to run the code for a custom or random alias by utilizing a single if statement?

For example:

def persistAlias(self, alias, custom_alias):
"""Please place relevant description here,
    The "custom_alias" argument determines whether to
    persist a custom or random alias."""
    try:
        self.em.persist(alias)
        self.em.flush()
    except DBALException as e:
        if e.previous.code != 23000:
            raise e
        self.reloadEM()

        if custom_alias:
            existing = self.findByNaturalKey(alias.name)
            if existing != alias:
                raise DuplicateNameException('The requested name is already taken', e)
        else:
            self.persistAlias(alias, 0)


Since you key is const it would be nice to mark it as such (and avoid accidents of changing your key):

void encodeStr(string const& encryptKey, string& inputToEncrypt) {
//                    ^^^^^

To save the cost of the copy I would also make it a reference.

No idea what these are:

assert(minVal < maxVal);

The extra set of variables seems like a good idea but actually makes the code harder to read as you need to understand what the variable represents:

size_t countEnd = inputToEncrypt.length();
while (count < countEnd) {

// Simpler to

while (count < inputToEncrypt.length()) {

When is this condition every going to fail and give you 0?

keyCount = (count < inputToEncrypt.length()) ? inputToEncrypt[count] : 0;

If it was going to fail then you should have the same precautions on this:

inputToEncrypt[count] = remainder;

This is also bound to result in truncation of reminder. As inputToEncrypt as a string and thus each position is a char while remainder is the sum of 2 integers both greater than minval.

inputToEncrypt[count] = remainder;


First of all, you can improve on reading the command-line arguments and, instead of manually parsing the sys.argv, use argparse module. Something like:

import argparse

def parse_args():
    """Parses command-line arguments."""

    parser = argparse.ArgumentParser()

    parser.add_argument('infile', type=argparse.FileType('r'))
    parser.add_argument('informat', action='store', choices=HASH_FORMATS)
    parser.add_argument('outfile', type=argparse.FileType('w'))
    parser.add_argument('outformat', action='store', choices=HASH_FORMATS)

    return parser.parse_args()

if __name__ == '__main__':
    args = parse_args()
    # ...

The format selection logic can be simplified if you would use a dictionary:

HASH_FORMATS = {
    'john': JohnHash,
    'hashcat': HashcatHash,
    'mana': ManaHash
}

# get the input and output hash classes beforehand
input_hash_class = HASH_FORMATS[args.informat]
output_hash_class = HASH_FORMATS[args.outformat]

for line in args.infile:
    parsed_line = input_hash_class.parse(line)
    converted_line = output_hash_class.format(parsed_line)
    args.outfile.write(converted_line)

And, as a side note about defining the Hash-based classes - I think you can make use of Abstract Base Classes with abstract methods which may lead to a cleaner object-oriented design.


Avoid unnecessary special case handling
You exit early if the size of the array is less than 3, but this is unnecessary: the rest of the code already handles arrays of size 0, 1 and 2 correctly. You might save a cycle if you feed it a small array, but you pay for this check with a cycle or two for every time the function is called with std::size(nums) > 2.
Use std::size_t for indices
You made index a std::int_fast32_t, but this has a different size (likely) and a different signedness than the result of std::size(nums). This means the compiler should have warned you about a comparison between signed and unsigned integers. While things work out here, since you know the size of the input array is constrained, it is best to use std::size_t here to avoid the compiler warning. Performance is likely not going to differ one bit, since index can be kept in a CPU register at all times.
There is no need to use std::to_string() when using << on a std::ostream
When writing to a std::ostream, operator<< will already cause the argument to be formatted, so there is no need to call std::to_string(). In fact, you can tell the stream to format a bool as text:
int main() {
    std::vector<int> nums = {3, 4, 2, 3};
    std::cout << std::boolalpha << Solution().checkPossibility(nums) << "\n";
}


There's a few things you could do to improve this code:

Don't assign inside a case statement.

You assign a value to leader inside this case statement:

scoreDifference =
  case nextPlayer1 > nextPlayer2 do
    true
      ->
      leader = nextPlayer1
      nextPlayer1 - nextPlayer2
    false
      ->
      leader = nextPlayer2
      nextPlayer2 - nextPlayer1
  end

Support for this is deprecated in Elixir, and I assume will eventually be removed.  The Elixir compiler will complain about this when it sees it, and you should listen to it.  Generally you should find a different way to express this.  One option is to return a tuple from your case:

{scoreDifference, leader} =
  case nextPlayer1 > nextPlayer2 do
    true ->
      {nextPlayer1 - nextPlayer2, nextPlayer1}
    false ->
      {nextPlayer2 - nextPlayer1, nextPlayer2}
  end

Use if when appropriate.

A cond statement that has one branch with conditions and one true branch is basically just an if statement.  So it'd be simpler to just use an if:

if (scoreDifference + 1) >= 2 and leader >= game.winningScore do
  IO.puts "SOMEONE IS ABOUT TO WIN"
else
  IO.puts "NO-ONE IS ABOUT TO WIN"
end
{:reply, :ok, game}

(I've also moved the reply out of the if statement there, since it was the same across each.  If you wanted to do different things you could move it back in easy enough).

Use Pattern Matching to destructure the scores.

Assuming you are only ever expecting 2 entries in your score list, you could use pattern matching to extract the two scores.

[nextPlayer1, nextPlayer2] = game.score

I'm not adding 1 to the scores here, because this isn't neccesary to calculate the difference correctly. (It is neccesary to add one to check if someone has a winning score, but I'll come to that).

Simplifying the logic

You can just subtract one score from the other and then call abs on the result to get a positive number for the score difference:

scoreDifference = abs(nextPlayer1 - nextPlayer2)

Then you can find the leader with Enum.max:

leader = Enum.max(game.score)

Putting it all together

If you take all these improvements you might end up with something like:

[nextPlayer1, nextPlayer2] = game.score
scoreDifference = abs(nextPlayer1 - nextPlayer2)
leaderScore = Enum.max(game.score)
if scoreDifference + 1 >= 2 and (leaderScore + 1) >= game.winningScore do
  IO.puts "SOMEONE IS ABOUT TO WIN"
else
  IO.puts "NO-ONE IS ABOUT TO WIN"
end
{:reply, :ok, game}


Check if array has the same number of even and odd values in Python

There's no need to keep counts at all.  All you need to do is keep track of whether the sequence is balanced or not as you check every element.  And the special tests you had for an empty list or odd list length are redundant.

def balanced(lst):
    tilt = 0
    for item in lst:
        if item % 2 == 0:      #even
            tilt += 1
        else:                  #odd
            tilt -= 1
    return tilt == 0

Or if you prefer terseness over readability, you can turn it into a one-liner.

def balanced(lst):
    return sum(1 if item % 2 else -1 for item in lst) == 0


Easier way to handle a Console Theme System

var keyword:

Use the var keyword wherever you can instead of declaring your variables explicitly. The compiler will determine the type and your code looks cleaner. Example:

var dateTime = new DateTime();
var time = dateTime.ToLongTimeString();

Small changes:

Variable names: l, ts or t are names that don't mean a thing, not for you, not for others. Use meaningful names such as userLevel or time.
DateTime: in the chat you want to show the time. I think you mean to use DateTime.Now instead of new DateTime(). The latter will just return 0:00:00 when you're calling the ToLongTimeString().
String.Format: don't concatenate hardcoded values and variables. Use the String.Format method. Following line:

Console.Write("[" + t + "] ");

will become:

Console.Write("[{0}] ", time);

This is easier to read and maintain.

Shorten your code:

Finally the point where you've been waiting for. Although there is a difference depending on the user-level, it is small. And certainly small enough to create a small method to avoid repetition. First, get the code based on the level and use the result to write to the console. This is done in following method:

private static string GetCodeFromUserLevel(UserLevel level)
{
    switch (level)
    {
        case UserLevel.Admin: return "[A] ";
        case UserLevel.Broadcaster: return "[B] ";
        case UserLevel.Moderator: return "[M] ";
        case UserLevel.Subscriber: return "[S] ";
        case UserLevel.Turbo: return "[T] ";
        default: return "";
    }
}

Now that you have this, you can use the result to write your message. This is done in the already existing message, but it looks cleaner now:

public static void WriteLine(UserLevel level, string userName, string message)
{
    var dateTime = DateTime.Now;
    var time = dateTime.ToLongTimeString();

    Console.BackgroundColor = ConsoleColor.Black;
    Console.Write("[{0}] ", time);
    Console.ForegroundColor = ConsoleColor.Green;
    Console.Write("<");

    Console.ForegroundColor = ConsoleColor.Blue;
    Console.Write(GetCodeFromUserLevel(level));
    Console.ForegroundColor = ConsoleColor.White;
    Console.Write(userName);

    Console.ForegroundColor = ConsoleColor.Green;
    Console.Write("> ");
    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine(message);
}

This code already looks better but you can take this a step further. You see three similar blocks with following structure:

Set a color
Write a part
Set a color again
Write a part again

This can be extracted in two ways: take step 1 and 2 and place it in a method or take step 1 to 4 and extract it. Here's the method when taking all steps in one method:

private static void WritePart(ConsoleColor startColor, ConsoleColor endColor, string partOne, string partTwo, bool newLine)
{
    Console.ForegroundColor = startColor;
    Console.Write(partOne);
    Console.ForegroundColor = endColor;
    Console.Write("{0}{1}", partTwo, newLine ? Environment.NewLine : "");
}

And here's the usage for the three blocks:

WritePart(ConsoleColor.White, ConsoleColor.Green, String.Format("[{0}] ", time), "<", false);
WritePart(ConsoleColor.Blue, ConsoleColor.White, GetCodeFromUserLevel(level), userName, false);
WritePart(ConsoleColor.Green, ConsoleColor.White, "> ", message, true);

I know that in your code you first set the BackgroundColor, you can add that line separatly before the above three lines.

Perhaps more logic is to only take step 1 and 2 and extract it in a method as it avoids repetition. Here's what it would look like:

private static void WritePart(ConsoleColor color, string value, bool newLine)
{
    Console.ForegroundColor = color;
    Console.Write("{0}{1}", value, newLine ? Environment.NewLine : "");
}

And the usage:

WritePart(ConsoleColor.White, String.Format("[{0}] ", time), false);
WritePart(ConsoleColor.Green, "<", false);

WritePart(ConsoleColor.Blue, GetCodeFromUserLevel(level), false);
WritePart(ConsoleColor.White, userName, false);

WritePart(ConsoleColor.Green, "> ", false);
WritePart(ConsoleColor.White, message, true);

It's what you prefer. Hope this helps!

Update:

Another tip on the method to get the code depending on the level. You have to options here make it shorter/cleaner.

Use following method. This is certainly not the cleanest solution but since the code is the first letter of the enum value you can use this:

private static string GetCodeFromUserLevel(UserLevel level)
{
    return level == UserLevel.Normal ? "" : String.Format("[{0}] ", level.ToString()[0]);
}

The other method is coming from this question on StackOverflow: Enum to String?. Check out the answer and you can apply this too.


Given a random section of text delimited by line breaks, get the first paragraph

Stating Your Requirements
It's important to have a clear defintion of what you want to achieve before you start writing code, even though there are many different ways of achieving that, for instance by practicing Test-Driven Development or writing a formal specification.
The important part is that without a clear definition, you can't validate whether you're done. In your case, the question contains a description that is completely different than the code and quite unclear.
The above is vital even if you're only writing the code as an exercise for personal use or learning.
Testing and Edge Cases
In the following code:
word_in_next_line = lines[li+1].split()[0]

Why are you assuming that

there will be a next line? What if the text consists of only one paragraph?
the next line will not be empty?

These assumptions are unreasonable and when I first tried out your code on some text, it immediately threw an exception.
Naming

Be careful with historically significant terms such as ss (Google it if you don't know what I mean).

Expressive names are better than abbreviations! Replace:

ss with source_text
ll with line (this looks like the number 11!)
lens with line_lengths
avglen with average_length
maxlen with maximum_length
in the for loop, li with index and ll with line

Conclusion
Without a clear explanation of what you are trying to accomplish, how the input data looks and how you define a paragraph, it's impossible to show you a better way of solving the problem.


Intro to Java - determine valid unique numbers

It looks alright, but there are some improvements you can do. First of all, you can still split your program into smaller functions still, which really helps readability.

Also, something glaring to me is that your functions in "main" are acting as instance variables for the rest of the class, which should not be the case. You should choose where you declare your variables based on the necessity of their scope. If you only use the input int as a store from user input, it should only be declared in the method that gets input from the user.

For instance, you could omit the input int from main and declare it locally in the GetInputFromUser method.

In main:

for (int i = 0; i < validNumber.length; i++) {
     GetInputFromUser(validNumber, uniqueNumber);
}

The method:

public static void GetInputFromUser(int[] validNums, int[] uniqueNums) {
     int input = userInput.nextInt()
     while (!isValid(input)) {
          System.out.print("\nEnter an integer: \t");
          input = userInput.nextInt();
     }
     //Code ommitted

}

I didn't really have time to read all of the specifications carefully, but I hope this helped a bit! Also, you may want to declare the int arrays as instance variables to avoid passing them around all the time.


Make this implementation of counting sort Pythonic

My two cents:

You can get rid of def find_min(a_list): and def find_max(a_list):. Instead, use python's built-ins min() and max():

  min(iterable[, key])

  Return the smallest item in an iterable
  or the smallest of two or more arguments.

  If one positional argument is provided, iterable must be a non-empty
  iterable (such as a non-empty string, tuple or list). The smallest
  item in the iterable is returned. If two or more positional arguments
  are provided, the smallest of the positional arguments is returned.

  max(iterable[, key])

  Return the largest item in an iterable or the
  largest of two or more arguments.

  If one positional argument is provided, iterable must be a non-empty
  iterable (such as a non-empty string, tuple or list). The largest item
  in the iterable is returned. If two or more positional arguments are
  provided, the largest of the positional arguments is returned.

So you'll have:

...
min_element, max_element = min(a_list), max(a_list)
...

Now, regarding you algorithm, you can avoid those hacks you were talking about by rewriting your function as:

def count_sort(array):
    min_element, max_element = min(array), max(array)
    count_array = [0] * (max_element - min_element + 1)

    for val in array:
        count_array[val - min_element] += 1

    sorted_array = []
    for i in range(min_element, max_element + 1):
        if count_array[i - min_element] > 0:
            for j in range(0, count_array[i - min_element]):
                sorted_array.append(i)

    return sorted_array

More, as @ChatterOne mentioned, instead of the final for loop with append, you could do:

sorted_array.extend([i] * count_array[i - min_element])

So, your final code would look like this:

def count_sort(array):
    min_element, max_element = min(array), max(array)
    count_array = [0] * (max_element - min_element + 1)

    for val in array:
        count_array[val - min_element] += 1

    sorted_array = []
    for i in range(min_element, max_element + 1):
        if count_array[i - min_element] > 0:
            for j in range(0, count_array[i - min_element]):
                sorted_array.append(i)

    return sorted_array

if __name__ == '__main__':
    my_array = [3, 2, -1, 1, 5, 0, 10, 18, 25, 25]
    print(count_sort(my_array))

or

def count_sort(array):
    min_element, max_element = min(array), max(array)
    count_array = [0] * (max_element - min_element + 1)

    for val in array:
        count_array[val - min_element] += 1

    sorted_array = []
    for i in range(min_element, max_element + 1):
        if count_array[i - min_element] > 0:
            sorted_array.extend([i] * count_array[i - min_element])

    return sorted_array

if __name__ == '__main__':
    my_array = [3, 2, -1, 1, 5, 0, 10, 18, 25, 25]
    print(count_sort(my_array))

Extras:

You can see that I also added if __name__ == '__main__'. By doing the main check, you can have that code execute only when you want to run the module as a program, and not have it execute when someone just wants to import your module and call your functions themselves.

I also changed the names min and max(which are already built-ins in Python) to min_element and max_element, respectively.

And the result:

[-1, 0, 1, 2, 3, 5, 10, 18, 25, 25]


Long function as a lambda, right or wrong?

I think it should be a separate method rather than a lambda expression. If the method is as large as 50 lines then you should seriously think about breaking it up anyway, being an anonymous method only compounds the issue. It may be better to extract portions of the method instead, but that is a decision that you will need to make based on the actual code in the method.

My general rule-of-thumb is that if an anonymous method spans more than half the screens height then it's too big and should be a separate named method.

Update in response to Timwi's comments:

When a method is well named, the name helps to describe what the method is intended to do, both where it is used and where it is defined. Anonymous methods don't get this, and so to understand it you need to rely on the context more. This is fine when if the anonymous method is simple but if its large and/or there is deep nesting involved (within or containing various control structures) the behavior can become much less obvious.

The "exact" example used by the OP is not too bad because the containing method is very simple, but I don't see any real benefit (for either performance or readability) and so would still prefer to have it as a separate method.

Of-course, "readability" is a bit subjective. Most people will agree on the extreme cases but the edge cases are probably better discussed with, and a consensus drawn from those actually responsible for maintaining it.


Check which numbers satisfy the condition [A*B*C = A! + B! + C!]

Hello and welcome to Code Review.

Surprisingly, a, b, and c are probably the best variable names you can come up with. They are conventionally given as canonical examples of bad names, but when the task is to implement a mathematical function using the same variable names as in the spec is more important.

As to the single loop question, the short answer is "not easily". You are trying to check all combinations of three independently varying things. That means you naturally want three loops, and anything else would lose out on readability.

Aside from your questions, I have a few observations about this code that might be worth fixing.

When you have a loop that is counting up to something, it is convention to prefer a for loop to a while loop.
Factorial is what is known as a "pure function" which means that its output only depends on its input. Such functions within loops are often good candidates for caching so that you don't have to waste time calculating the same output a hundred and eleven times for each input number.
Both + and * are commutative, which means that if a, b, and c pass then b, a, and c also pass. You should check whether you need to display all reorderings of the same sets of numbers.
It is unclear where 11 has come from. It seems like a magic number, which would benefit from being moved to a named constant and having a comment explaining why that value is used.


Sum even fibonacci numbers up to a limit

If you dig a little deeper in the math, it is very straightforward to realize that every third Fibonacci number can be computed with the formula:

\$F_{n+6} = 4 F_{n+3} + F_{n}\$

You can reuse your function if you work the recursion backwards a couple of steps, and do something like:

private static IEnumerable<int> GetEvenFibonacciNumbers()
{
    var first = 2;
    var second = 0;
    while (true)
    {
        var nextFibonacciNumber = first + 4*second;
        yield return nextFibonacciNumber;

        first = second;
        second = nextFibonacciNumber;
    }
}

This will not only make your code ~3x faster, but will render your other functions trivial to write.