I will address your code in sections and at the end I will provide a full updated code based on the touched subjects.
Application state
You are turning the Application 'off' with:

Application.ScreenUpdating = False
Application.Calculation = xlManual
Application.DisplayAlerts = False

at the beginning of your method and then you turn it back 'on' with:

Application.ScreenUpdating = True
Application.Calculation = xlAutomatic
Application.DisplayAlerts = True

at the end of another method.
It's a good idea to turn things back on within the scope of the same method. In your case you would add the latter 3 lines at the end of the Reformat_ZZ_CM_BNREG method immediately after calling the DeleteRowsAndSheet method. You should not rely on another method to 'clean-up' for you. What if you decide that you don't need to call that method in the future? There is a high chance you will forget to move the 'clean-up' code back in the main method.
How about turning things 'off' and then back 'on'. It's not a good idea to do this, even if it works for you in this situation, because in time you can get used to this kind of approach and repeat it without giving too much thought. Imagine you have another method called Main that turns the application 'off' and then calls your Reformat_ZZ_CM_BNREG method and then does other stuff like calling a method called MyMethod and then finally turns the application back 'on'. Something like:
Sub Main()
    Application.ScreenUpdating = False
    Application.Calculation = xlManual
    Application.DisplayAlerts = False

    Reformat_ZZ_CM_BNREG
    MyMethod

    Application.ScreenUpdating = True
    Application.Calculation = xlAutomatic
    Application.DisplayAlerts = True
End Sub

What if MyMethod expects the calculation to be 'off'? Well, Reformat_ZZ_CM_BNREG actually turns things back 'on' and you can clearly see this is not what MyMethod (or even Main expects).
What if the Calculation needs to be Manual all the time because this is what the user of the Workbook wants?
The best approach, which you should always use, is to make no assumption of what the current state is because you have no control of what other higher-level methods might expect/do with the state. Your method should look like this:
Sub Reformat_ZZ_CM_BNREG()
    Dim appScrUpdate As Boolean
    Dim appCalc As XlCalculation
    Dim appDispAlert As Boolean

    'Store current Application state
    appScrUpdate = Application.ScreenUpdating
    appCalc = Application.Calculation
    appDispAlert = Application.DisplayAlerts

    'Turn state off
    Application.ScreenUpdating = False
    Application.Calculation = xlManual
    Application.DisplayAlerts = False

    'Actual code
    '...
    '...
    '...

RestoreState:
    Application.ScreenUpdating = appScrUpdate
    Application.Calculation = appCalc
    Application.DisplayAlerts = appDispAlert
End Sub

RestoreState: line label can be used in case you want to early exit the method using something like GoTo RestoreState which would still do the 'clean-up'
In short, you restore the state as it was, making no assumptions, to make sure you do not impact logic somewhere else.
There is a lot of boilerplate code to do this so I use a class instead so that I can have multiple instances with stored state at any given time. Here is what I usually use, and the code above would get simplified to something like:
Sub Reformat_ZZ_CM_BNREG()
    Dim app As New ExcelAppState
    app.StoreState
    app.Sleep

    'Actual code
    '...
    '...
    '...

    app.RestoreState
End Sub

Indentation
For me, it is much easier to read this:
Function DoSomething() As Integer
    Dim iNumber As Integer
    For iNumber = 1 To 5
        DoSomething = DoSomething + iNumber
    Next iNumber
End Sub

compared to this:
Function DoSomething() As Integer
Dim iNumber As Integer
For iNumber = 1 To 5
    DoSomething = DoSomething + iNumber
Next iNumber
End Sub

especially when I have a large number of methods. Although your code is working, please consider this aesthetic aspect when writing code. All code that is within the scope of the method should have an extra indentation level than the method definition.
Hardcoding
You are using the same string literals in multiple places: "Disbursements", "ZZ_CM_BNREG", "Bank Register". Consider declaring them as constants so that you only need to change them (if needed) in a single place:
Const searchText As String = "Disbursements"
Const sourceShtName As String = "ZZ_CM_BNREG"
Const targetShtName As String = "Bank Register"

If you ever decide to receive these as method parameters then all you need to do is to move the constants (without the Const keyword) into the method definition without needing other changes e.g. Sub Reformat_ZZ_CM_BNREG(ByVal searchText As String, ByVal sourceShtName As String, ByVal targetShtName). Might not be useful here, but you get the idea.
Worksheet assumptions
You are making the following assumptions:

a worksheet named "ZZ_CM_BNREG" exists
a worksheet named "Bank Register" does not exist
sheet named "ZZ_CM_BNREG" is a Worksheet (it could be a chart sheet)
the workbook is unprotected

Obviously, it works for you but it's better to be a bit precautious to avoid unexpected errors and behaviour. Consider this: if any of the assumptions would fail then a runtime error would be raised, and you would not get the chance to restore the application state (or do other clean-up operations that might be required).
Consider an auxiliary function to retrieve the worksheet:
Public Function GetWorksheetByName(ByVal wsName As String, ByVal book As Workbook) As Worksheet
    On Error Resume Next
    Set GetWorksheetByName = book.Worksheets(wsName)
    On Error GoTo 0
End Function

you could simply use it like this:
Set ws = GetWorksheetByName(sourceShtName, ThisWorkbook)
If ws Is Nothing Then
    'Do something e.g. show a message box if needed, restore state or exit method
    '...
End If

Notice the auxiliary function uses the Worksheets collection instead of the Sheets collection.
How about these 2 lines?

Set newWS = Sheets.Add(After:=Sheets("ZZ_CM_BNREG"))
newWS.Name = "Bank Register"

As mentioned, these would fail if the workbook is protected or if another sheet with the same name already exists. You can guard with something like:
On Error Resume Next
Set newWs = ThisWorkbook.Worksheets.Add(After:=ws)
If Err.Number <> 0 Then
    MsgBox "Cannot insert new worksheet", vbExclamation, "Failed"
    Err.Clear
    'Restore state or exit method
End If
newWs.Name = targetShtName
If Err.Number <> 0 Then
    MsgBox "Cannot rename worksheet", vbExclamation, "Failed"
    'This might not be critical so just resume
End If
On Error GoTo 0

Notice that I haven't retrieved the source worksheet again, unnecessarily. Instead I simply used After:=ws
Finding desired range

In order to search for the last cell, I used a function that finds the last cell with data.

I am not sure what the 3 value does when calling the FindLast method with FindLast(3, "ZZ_CM_BNREG"). I suspect you are starting from the 3rd row.
The commented line Set lastCell = Range(Cells.Find("*", , xlFormulas, , xlRows, xlPrevious, , , False), Cells.Find("*", , xlFormulas, , xlColumns, xlPrevious, , , False)) returns a Range object while the variable was declared as text with Dim lastCell As String. The commented line simply does not compile if I uncomment it. It's missing a trailing .Address and the Set needs to be removed. Anyway, I assume your FindLast function returns the text address of the last row and column with data in a similar manner with the modified commented line.
You are looking for the desired text with:

'Unmerge all cells in Column A & get cell address of searchCell
With ws

   ws.Activate

   Range("A:A").UnMerge

   Set searchCell = .Cells.Find(What:="Disbursements", _
       SearchFormat:=True)

   If searchCell Is Nothing Then
       MsgBox ("Error")
   Else
       firstCell = searchCell.Address
   End If

End With

but although you are unmerging column A you are searching for your text within the whole worksheet with ws.Cells.Find(What:="Disbursements", SearchFormat:=True) (ws is implied from the With block).
Assuming there is no "Disbursements" value in columns A and B but there is such a value in column C then your code copies data starting with column C and lose the information in column A and B. As I am unsure if this is intended functionality or not, I made the assumption that you want all columns of data regardless where the keyword is found.

Instead of deleting the rows below the contiguous range, should I just copy the contiguous rows to begin with? Is there a better way to delete the rows below the first blank row?

Yes, it's faster to simply copy only what you need instead of copying useless data that you are going to delete anyway. Your second question suggests that you are only interested in data up to (but not including) the first blank row.
I do not know what you consider a "blank row" to be. I can see that you find the last row (in the target sheet) with Sheets("Bank Register").Range("A1").End(xlDown).Row but that means you are actually looking for the first blank cell in the 'A' column and you don't care if there is data in the rest of the columns. Anyway, I assumed that you are interested in actual "blank rows" (i.e. no data in any of the columns) not just on the 'A' column. Here is a function that can check if a row is empty for a 2D array:
Private Function Is2DArrayRowEmpty(arr() As Variant, ByVal rowIndex As Long, Optional ByVal ignoreEmptyStrings As Boolean = False) As Boolean
    Dim j As Long
    Dim v As Variant

    For j = LBound(arr, 2) To UBound(arr, 2)
        v = arr(rowIndex, j)
        Select Case VBA.VarType(v)
            Case VbVarType.vbEmpty
                'Continue to next element
            Case VbVarType.vbString
                If Not ignoreEmptyStrings Then Exit Function
                If v <> vbNullString Then Exit Function
            Case Else
                Exit Function
        End Select
    Next j
    Is2DArrayRowEmpty = True 'If code reached this line then row is Empty
End Function

Reading the worksheet's used range into an array should give us the flexibility to find the desired range faster.
It's not really needed to insert a new worksheet (and to turn the application state to 'off' and later back 'on') if we cannot find any data that we want to take across. It makes more sense to first search for the data and only then proceed with the other operations.
Final code
Code in a standard module:
Option Explicit

Sub Reformat_ZZ_CM_BNREG()
    Const searchText As String = "Disbursements"
    Const sourceShtName As String = "ZZ_CM_BNREG"
    Const targetShtName As String = "Bank Register"

    Dim sourceWS As Worksheet
    Dim targetWS As Worksheet

    Set sourceWS = GetWorksheetByName(sourceShtName, ThisWorkbook)
    If sourceWS Is Nothing Then
        MsgBox "Missing worksheet", vbExclamation, "Cancelled"
        Exit Sub
    End If

    Dim rngUsed As Range

    On Error Resume Next
    Set rngUsed = sourceWS.UsedRange
    On Error GoTo 0
    If rngUsed Is Nothing Then
        MsgBox "Sheet has no data", vbExclamation, "Cancelled"
        Exit Sub
    ElseIf rngUsed.Count = 1 Then
        MsgBox "Sheet has only 1 cell of data", vbExclamation, "Cancelled"
        Exit Sub
    End If

    Dim arrData() As Variant: arrData = rngUsed.Value2
    Dim lowRowIndex As Long: lowRowIndex = LBound(arrData, 1)
    Dim uppRowIndex As Long: uppRowIndex = UBound(arrData, 1)
    Dim v As Variant
    Dim i As Long
    Dim firstRow As Long
    Dim lastRow As Long

    i = lowRowIndex
    For Each v In arrData 'Traverses array in column-wise order (faster than For...To)
        If VarType(v) = vbString Then
            If InStr(1, v, searchText, vbTextCompare) > 0 Then
                firstRow = i + 1
                Exit For
            End If
        End If
        i = i + 1
        If i > uppRowIndex Then 'Next column follows - You might want to Exit For if you are only interested in the first column
            i = lowRowIndex
        End If
    Next v

    If firstRow = 0 Then
        MsgBox "Text not found", vbExclamation, "Cancelled"
        Exit Sub
    End If

    'Find last non-blank row
    lastRow = uppRowIndex
    For i = firstRow To uppRowIndex
        If Is2DArrayRowEmpty(arrData, i, True) Then
            lastRow = i - 1
            Exit For
        End If
    Next i
    If lastRow < firstRow Then
        MsgBox "No rows found after desired row", vbExclamation, "Cancelled"
        Exit Sub
    End If

    Dim app As New ExcelAppState: app.Sleep: app.StoreState

    'Prepare Target
    On Error Resume Next
    Set targetWS = ThisWorkbook.Worksheets.Add(After:=sourceWS)
    If Err.Number <> 0 Then
        MsgBox "Cannot insert new worksheet", vbExclamation, "Failed"
        Err.Clear
        app.RestoreState
        Exit Sub
    End If
    targetWS.Name = targetShtName
    If Err.Number <> 0 Then
        MsgBox "Cannot rename worksheet", vbInformation, "Renaming skipped"
        'This might not be critical so just continue
    End If
    On Error GoTo 0

    'Write data
    With rngUsed
        Range(.Cells(firstRow, 1), .Cells(lastRow, .Columns.Count)).Copy _
            Destination:=targetWS.Cells(1, 1)
    End With

    sourceWS.Delete
    app.RestoreState
End Sub

Public Function GetWorksheetByName(ByVal wsName As String, ByVal book As Workbook) As Worksheet
    On Error Resume Next
    Set GetWorksheetByName = book.Worksheets(wsName)
    On Error GoTo 0
End Function

Private Function Is2DArrayRowEmpty(arr() As Variant, ByVal rowIndex As Long, Optional ByVal ignoreEmptyStrings As Boolean = False) As Boolean
    Dim j As Long
    Dim v As Variant

    For j = LBound(arr, 2) To UBound(arr, 2)
        v = arr(rowIndex, j)
        Select Case VBA.VarType(v)
            Case VbVarType.vbEmpty
                'Continue to next element
            Case VbVarType.vbString
                If Not ignoreEmptyStrings Then Exit Function
                If v <> vbNullString Then Exit Function
            Case Else
                Exit Function
        End Select
    Next j
    Is2DArrayRowEmpty = True 'If code reached this line then row is Empty
End Function

and of course, a simplified version of the ExcelAppState class (that I linked to above). This one uses only the 3 application properties that you were using:
Option Explicit

Private m_calculationMode As XlCalculation
Private m_screenUpdating As Boolean
Private m_displayAlerts As Boolean

Private m_hasStoredState As Boolean
Private m_hasStoredCalcMode As Boolean

Public Sub StoreState()
    With Application
        On Error Resume Next 'In case no Workbook is opened
        m_calculationMode = .Calculation
        m_hasStoredCalcMode = (Err.Number = 0)
        On Error GoTo 0
        m_screenUpdating = .ScreenUpdating
        m_displayAlerts = .DisplayAlerts
    End With
    m_hasStoredState = True
End Sub

Public Sub RestoreState(Optional ByVal maxSecondsToWait As Integer)
    If Not m_hasStoredState Then
        Err.Raise 5, TypeName(Me) & ".RestoreState", "State not stored"
    End If
    With Application
        If m_hasStoredCalcMode Then
            On Error Resume Next
            If .Calculation <> m_calculationMode Then .Calculation = m_calculationMode
            On Error GoTo 0
        End If
        If .ScreenUpdating <> m_screenUpdating Then .ScreenUpdating = m_screenUpdating
        If .DisplayAlerts <> m_displayAlerts Then .DisplayAlerts = m_displayAlerts
    End With
    m_hasStoredState = False
End Sub

Public Sub Sleep()
    With Application
        On Error Resume Next
        If .Calculation <> xlCalculationManual Then .Calculation = xlCalculationManual
        On Error GoTo 0
        If .ScreenUpdating Then .ScreenUpdating = False
        If .DisplayAlerts Then .DisplayAlerts = False
    End With
End Sub

Public Sub Wake(Optional ByVal maxSecondsToWait As Integer = 10)
    With Application
        On Error Resume Next
        If .Calculation <> xlCalculationAutomatic Then .Calculation = xlCalculationAutomatic
        On Error GoTo 0
        If Not .ScreenUpdating Then .ScreenUpdating = True
        If Not .DisplayAlerts Then .DisplayAlerts = True
    End With
End Sub


Ruby: possible Poker holds for a hand of length n

Here's a demonstration of how you might solve this problem the Ruby way:
SUITS = %w[ H D C S ]
FACES = %w[ 2 3 4 5 6 7 8 9 T J Q K A ]

CARDS = SUITS.flat_map { |s| FACES.map { |f| "#{f}#{s}" } }

def holds(hand)
  hand.length.times.flat_map do |n|
    hand.combination(n).to_a
  end << hand
end

holds(CARDS.shuffle.take(5))

Where you get results like this:
[[],
 ["AD"],
 ["5H"],
 ["QS"],
 ["4H"],
 ["5D"],
 ["AD", "5H"],
 ["AD", "QS"],
 ["AD", "4H"],
 ["AD", "5D"],
 ["5H", "QS"],
 ["5H", "4H"],
 ["5H", "5D"],
 ["QS", "4H"],
 ["QS", "5D"],
 ["4H", "5D"],
 ["AD", "5H", "QS"],
 ["AD", "5H", "4H"],
 ["AD", "5H", "5D"],
 ["AD", "QS", "4H"],
 ["AD", "QS", "5D"],
 ["AD", "4H", "5D"],
 ["5H", "QS", "4H"],
 ["5H", "QS", "5D"],
 ["5H", "4H", "5D"],
 ["QS", "4H", "5D"],
 ["AD", "5H", "QS", "4H"],
 ["AD", "5H", "QS", "5D"],
 ["AD", "5H", "4H", "5D"],
 ["AD", "QS", "4H", "5D"],
 ["5H", "QS", "4H", "5D"],
 ["AD", "5H", "QS", "4H", "5D"]]

Personally I'd hold the pair of 5s and the Ace.
For educational purposes here's a more Ruby-esque form of your original code:
def possible_holds(hand_size)
  (2 ** hand_size).times.map do |n|
    n.to_s(2).rjust(hand_size, '0').chars.map { |c| c == '1' }
  end
end

It's kind of messy due to the binary string to boolean conversion.

Tip: Try to avoid "casting a boolean to a boolean" as in patterns like x ? true : false or if x; true; else; false like you had in your code. That reduces down to just x. The x == '1' test already returns a true or false value. There is no maybe or kind_of response.


Implementation of a generic thread-safe object wrapper

Correctness
foo can be destructed while another thread is performing an operation on it, because the destructor or its caller don't have to acquire a lock to do so. Technically destroying a mutex while it is locked already is undefined behavior, but it gets worse if another thread happens to modify the now invalid object.
Same reasoning for the move constructor: The object from which will be moved could still be modified concurrently by another thread, so locking would be required.
Also, rule of 3/5 violation: There's a custom move constructor (and there will hopefully be a corrected destructor), so copy constructor, move assignment operator and copy assignment operator should also be provided (currently, they copy without locking neither this nor the other object).
Also, m_mutex should be marked mutable, otherwise a const synchronized<Foo>& can't be accessed.
Other nitpicks

In the second constructor, m should be moved.
object::object(T*, Mutex&) should probably take it's first argument as T& instead, as it should never be nullptr.
object as a name is very broad. Maybe change it to something more concise, like with_lock or locked_handle?

Suggestion
If targeting C++17 or later, consider providing a partial specialization for std::shared_mutex: const access paths only require a std::shared_lock(read only), while non-const access paths should be locked with std::unique_lock (write access). Also, for convenience, a as_const() member function to explicitly acquire a const reference would help. See this talk by Andrei Alexandrescu for more information on that topic.


Your code is basically correct, but you might want to look at a few things that have changed with HTML and CSS in the last years:

Web Fonts

font-family: Verdana, Geneva, Tahoma, sans-serif;

In the bad old days you could only use fonts in web pages that were
already installed on the client system.  Because theses pre-installed fonts
differed from operating system to operating system, a list of similar looking
fonts was specified.  Here "Verdana" was typically found on windows machines, "Geneva" typically on MacOS, an "sans-serif" is a wildcard to finally
use any sans serif font, if none of the named fonts are available.

Since about 2008 browsers can load fontssee history of web typography.  Now you can specify exactly
the font you want, and maybe add the wildcard at the end in case anything breaks.
See google fonts for free fonts and for the code you need to load them.

So today you would typically write

font-family: 'Open Sans', sans-serif;

instead of the font list.

Layout

You use "float" to arrange divs side-by-side.

Since Spring 2017 you can use CSS Grid instead.

Use it to lay out the whole page on a grid. You will need fewer HTML tags and can forget about "clearfix".

Responsive Design

The Web has many different output devices.  Even if we just look at
screens, we have big differences in resolution and pixel density.

Your page is geared toward a screen width of 1024px.  On smaller displays parts of your page will only by visibly when scrolling horizontally.  On larger displays you will not use the space available in a meaningful way.

The answer to this is responsive design: start designing your page for a smartphone. Then add different CSS for larger devices using media queries.


Var

Use implicit typing when the right-hand side of the declaration makes the type obvious.

uint[] B = new uint[A.Length];

should be

var B = new uint[A.Length];

Naming

Single character variable names are some of the least useful names you could give your variables. Your variables have a purpose. Name them appropriately using these purposes.

B means nothing.

Spacing

Give your code some room to breathe, the compiler will cut it out anyway when it gets to the optimization stage, and there's no sense making it harder to read for maintenance programmers. Also consider surrounding your loop bodies with braces. This way if somebody came in and added a line to the loop body, it wouldn't break.

Design

Use foreach when iterating over every item in a collection, it more accurately conveys your meaning.

Secondly, I cannot find a use for manually specifying max. Instead you should calculate this using:

var max = A.Max();

All things combined, I recommend:

public static uint[] CountingSort(uint[] unsorted)
    {
        var max = unsorted.Max();
        var sorted = new uint[A.Length];
        var count = new int[max +1];

        foreach(var unsortedValue in unsorted)
        {
            count[unsortedValue]++;
        }

        for (var i = 1; i < max + 1; i++)
        {
            count[i] += count[i - 1];
        }

        for (var j = unsorted.Length-1 ; j>=0; j--)
        {
            sorted[--count[unsorted[j]]] = unsorted[j];
        }

        return sorted ;
    }

Optionally

You could consider making this method an extension method of the uint[] type:

public static uint[] CountingSort(this uint[] unsorted)
    {
        var max = unsorted.Max();
        var sorted = new uint[unsorted.Length];
        var count = new int[max +1];

        foreach(var unsortedValue in unsorted)
        {
            count[unsortedValue]++;
        }

        for (var i = 1; i < max + 1; i++)
        {
            count[i] += count[i - 1];
        }

        for (var j = unsorted.Length-1 ; j>=0; j--)
        {
            sorted[--count[unsorted[j]]] = unsorted[j];
        }

        return sorted ;
    }

Then you can call the method like this:

var sorted = unsorted.CountingSort();

But this is optional and depends on your desired use cases.

Secondly, consider using an interface such as IList to allow callers of your method more freedom when specifying data types:

    public static IList<uint> CountingSort(this IList<uint> unsorted)
    {
        var max = unsorted.Max();
        var sorted = new uint[unsorted.Count];
        var count = new int[max +1];

        foreach(var unsortedValue in unsorted)
        {
            count[unsortedValue]++;
        }

        for (var i = 1; i < max + 1; i++)
        {
            count[i] += count[i - 1];
        }

        for (var j = unsorted.Count-1 ; j>=0; j--)
        {
            sorted[--count[unsorted[j]]] = unsorted[j];
        }

        return sorted;
    }

Now you can call:

new List<uint>().CountSort();
new uint[].CountSort();
new Collection<uint>().CountSort();

With way more flexibility.


Two squares or not two squares - constant time optimization

llu root = sqrtl(n); is not safe.  The precision of a long double is not specified by C to give the exact correct answer for all unsigned long long.
Not sure yet why you get TLE (Time Limit Exceeded).  As the page you point to only has 10 small integers to test, there must be horribly wrong with your compilation or yu have an unstated interesting input.
Spent 30 minutes tracking down a bug because I forgot to a braces when extending the following.  Instead, highly reccomend to add breaces in all for(), if(), etc. except maybe in the the most trivial circumstance.

for(i=0;i*i<n/2+1;++i)
  if(isSquare(n-i*i))
    return 1;

// Better
for(i=0;i*i<n/2+1;++i) {
  if(isSquare(n-i*i)) {
    return 1;
  }
}


1 Code

In my opinion, your code would be a little more readable if you had a blank line before and after such constructs as while, for and if. So, instead of

Random ran = new Random();
while (size > 0) {
    inputStack.push(ran.nextInt(size));
    size--;
}
Stack<Integer> orderedStack = sortStack(inputStack);

you could have

Random ran = new Random();

while (size > 0) {
    inputStack.push(ran.nextInt(size));
    size--;
}

Stack<Integer> orderedStack = sortStack(inputStack);

2 printStack

Collections.<Integer>reverse(inputStack);
System.out.println(inputStack);

does the job with funky brackets and commas.

3 Naming

sortStackInAscending is not a very good name. Perhaps StackSorter?

4 Sorting

Usually, sorting routines do not return the sorted result, but rather modify its argument collection. That's the way most production sorts work in practice.

Summa summarum

A sub-point: making your stack sort generic is not hard; see below.

All in all, I had this in mind:

public class StackSorter {

    public static void main(String args[]) {
        Stack<Integer> inputStack = new Stack<>();
        int size = 10;
        Random ran = new Random();

        while (size > 0) {
            inputStack.push(ran.nextInt(size));
            size--;
        }

        sortStack(inputStack);

        System.out.println("Stack is sorted: " + stackIsSorted(inputStack));
        Collections.<Integer>reverse(inputStack);
        System.out.println(inputStack);
    }

    public static <E extends Comparable<? super E>>
        boolean stackIsSorted(final Stack<E> stack) {
        if (stack.isEmpty()) {
            // Trivially sorted.
            return true;
        }

        final Stack<E> workStack = new Stack<>();
        workStack.addAll(stack);

        E previousElement = workStack.pop();

        while (!workStack.isEmpty()) {
            final E currentElement = workStack.pop();

            if (currentElement.compareTo(previousElement) > 0) {
                return false;
            }

            previousElement = currentElement;
        }

        return true;
    }

    public static <E extends Comparable<? super E>>
        void sortStack(final Stack<E> inputStack) {
        final Stack<E> orderedStack = new Stack<>();
        E currentElement;
        int count = 0;

        while (!inputStack.isEmpty()) {
            currentElement = inputStack.pop();

            while (!orderedStack.isEmpty()
                    && currentElement.compareTo(orderedStack.peek()) < 0) {
                inputStack.push(orderedStack.pop());
                count++;
            }

            orderedStack.push(currentElement);

            while (count > 0) {
                orderedStack.push(inputStack.pop());
                count--;
            }
        }

        inputStack.addAll(orderedStack);
    }
}

Hope that helps.


The binary tree here consists of either None or TreeNode, so all
functions should accept both of these objects as arguments, but
is_leaf currently breaks when passed a None node.  This
representation is also a bit problematic, because if you get a None
somewhere, how do you know it's meant to be a tree?

If that case is included, then the first check in is_full can be
removed.  Otherwise I don't see anything else to optimise, though the
results for checking the variables against for None could possibly be
cached so the code is minimally faster for huge trees.

Also,

the indentation is inconsistent, TreeNode has four spaces in
__init__.  You know,
PEP8.
if len(x): is less clear than, e.g. if x:, but in both cases it's
relying on conversions from int/list to bool, so not very clear.


My initial thought is that this function is doing way too much. It is:

reading user input (with no validation)
instantiating a database connection (possibly)
getting a result set from the database
deleting records from the database (possibly)
executing a query to get a row count from the database
generating HTML output
providing end user error messages

This is just too much logic to be put in one function.  I would encourage you to embrace separation of concerns as a key tenant in how you approach programming.

If you properly separate concerns, you move away from having to implement hacky uses of output buffers - something which should typically be reserved for very targeted use cases.  Speaking of your output buffer, I don't see where you are flushing it.  I would think it really poor practice to begin buffering in one area of code and have the buffer flushed/closed in another area of code. You are opening up your code to having to deal with the complexity/fragility of nested buffers if you have this behavior in other areas of code.

Typical convention would have functions/methods in PHP starting with lowercase letters.

Your try-catch block is used here inappropriately.  First, it encompasses way too many lines of code.  There are a number of PDO operations within this code that could throw, yet you only have a single catch block, which seems to consider only that the exception was due to connection failure.  So perhaps any try-catch logic around database connection should be in the include file and not even in this code at all, and you could have try-catch around individual database operations (i.e. query preparations) to give more granular control over how underlying exceptions are handled.

The second problem may make all this moot though, in that you should really only be catching exceptions if you are going to do something meaningful in the recovery operation.  Meaningful might be something like:

logging some aspect of code state before re-throwing the exception to caller;
gracefully recovering from exception such that caller can continue working in an acceptable state;
wrapping/rethrowing the exception to abstract underlying details from calling code.

You are not really doing such a thing here.  You are basically swallowing the exception such that the calling code, which is probably in a better position to understand how to deal with such an exception (i.e. by messaging end user or similar),  has no idea at all that anything went wrong. Don't swallow exceptions.

I appreciate that you are trying to move into using exceptions in your code, but you really need to think of exceptions as a way for one piece of code to communicate to calling code that it was not able to fulfill the contract/promise of what the calling code expects it to do.  If that calling code doesn't know how to recover from or handle such an exception in the code it calls, then it should let that exception continue to "bubble" up the call stack until there is code that is designed to handle the failure.

My next comment is related to the above exception handling comment, in that code that is not designed to message the end user about error conditions, should not do so.  Don't just leak out end user error messaging about DB connections failing with technical exception messages.  For the end user you likely want to clean up the messaging to something more meaningful as well as something that doesn't potentially leak sensitive application state information to the end user.  Typically, code up the call stack from code that is actually interacting with the database is much better positioned to handle this end user messaging.

Consider changing $start to $offset which is much more common terminology with regards to pagination.  Consider changing $limiet to $limit (the correct English word) if you are going to be writing your variable names in English.  Also consider naming your GET/POST parameters in English for consistency (again, that is if your desire is to have your code written in English).  Mixed-language code can be confusing to the reader.

You are not using $page at all in determining your offset for the LIMIT clause, so your pagination is not really working.

I would think your delete use case should be in a separate function altogether.

Consider using SQL_CALC_FOUND_ROWS in your LIMIT query in conjunction with FOUND_ROWS() to optimize this call pattern.

I would encourage you to move away from SELECT * when querying the database in favor of explicitly naming the fields you need in the result set. This may take you a minute or two extra when first writing the query, but it:

makes it clear to the reader of the code as to what fields will be available in the result set - they don't need to go look at the database schema to know what fields are available.
is oftentimes more efficient with regards to bandwidth and memory utilization. Why pull and store fields that you are not going to work with?
can make your application less fragile to schema changes.  For example, if at some point you add a field to this table, if a particular section of code does not need that field, you don't have to change it at all.  With a * select, you could actually break your application if you start introducing new fields that are not expected.

Why are you setting a refresh header here? It doesn't make sense by itself here.  Do you actually want to do a redirect?  If you move the code into different function or before the output from section above, can you get rid of the output buffer?

Again separation of concerns will help you here, as the typical approach one should take in a PHP web application is to do all your PHP back-end logic (dealing with user input, interacting with databases, setting header, performing redirects, preparing data for output, etc.) before you ever get to the point of rendering a view to the browser.

You should validate user input.  Prepared statements are great defense against SQL injection, but they are no defense against useless input.  What if your values for page and checkvakje are not integer representations?  Why would you even attempt a (relatively expensive) query with non-sensical input?

Your spacing around assignment operators is inconsistent.

Is there any reason you are using loose comparison operators (==, !=) instead exact comparisons here?  I would recommend getting in the habit if using exact comparisons by default and only using loose comparisons when there is a true use case for doing so.  this will make your could less fragile to unexpected truthy/falsey condition evaluations.

You have potential XSS vulnerability in that you are working with unvalidated user input in $page. Never trust user input.

You are inconsistent in bracket placement after flow control structures. Sometimes they start on same line, sometimes on following line.  You should strive to be consistent in your styling.  I would recommend a good PHP static code analysis tool like code sniffer or phpMd to help to enforce consistent styling as well as point our other questionable coding practices.

  if(isset($_GET['page'])) {
    $page   = $_GET['page'];
  } else {
    $page   = 1;
  }

Avoid unnecessary code branches (such as the unnecessary else shown in the example above). This could be:

  // here with a bonus validation suggestion
  $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT)) {
  if(empty($page) || $page < 1) {
      $page = 1;
  }

  // here a suggestion without meaningful validation
  $page = 1;
  if(!empty($_GET['page'])) {
      $page = $_GET['page'];
  }

This may seem trivial, but this is more about getting the right mindset that code branches are to be designed away if possible, as the more code branches you have, the harder your code is to test and the more buggy your code is likely to be.


The thread pool is not storing messages on a queue; it is storing Runnable tasks.  However, each Runnable task has access to the effectively final StringBuffer message variable from the calling context.
See this StackOverflow question.  Each is a ThreadPoolExecutor, just with different parameters to control how many threads are created and the type of queue.  I would lean in favour of the FixedThreadPool with 1 thread for each CPU core, but many other factors can and will impact that; profile to be sure.
No.  Making processMessage() synchronized will mean you are single threaded ... worse, because the overhead of multiple threads being scheduled to process the task queue in a single threaded fashion.   At 150 messages/10 seconds, with one thread the function would need to complete in 66ms.  If you have 8 cores, with 1 thread per core, each thread could take a leisurely 500ms to process the message, as long as they can run independently.  You may have parts of processMessage that you may need to make synchronized, but you’ll want to make those regions as small and fast as possible.

Other comments:

A StringBuffer is a mutable object;  since message is being passed to another thread, for safety, I’d want the message to be transformed into a immutable String so the caller doesn’t clear the message buffer while the executor thread is processing it.

processMessage() does not need to be public; private would be more appropriate.

It looks like executor should be private and final as well.


Key and value mapping from one object to another

If there's no "logical" correlation between the key you have, and the key you want (i.e. no consistent way to rewrite them) then you basically have to use a lookup of some sort to do the translation.

So your "reading keys from a hash" strategy is your best bet, but it can be improved a little.

You can be more functional and just use map:

lookup = { data1: :LINE1, data2: :LINE2, data3: :LINE3 }

result = Hash[ lookup.map { |in, out| [out, have[in]] } ]

Or you can just go through the ones in the input hash, and translate the ones that are actually there, discarding ones without a translation:

result = Hash[ have.map { |k, v| [lookup[k], v] if lookup[k] }.compact ]

And for either of those, if you ever need to translate the other way, you can just use lookup.invert to flip the keys/values around.

Lastly, for you spec, don't put an expectation in a after(:each) block. Put the expectation in the spec itself.


Only targeting public string[] Convert(string input)

Because this is a public method you should validate the input. Right now if one passes null this will throw an ArgumentNullException which isn't that bad but the stacktrace belongs to System.Linq.Enumerable.Contains() which you should hide.
Just testing against null or using string.IsNullOrWhiteSpace()` will do the trick.
You are calling input.Split('\n') many many times. It would be much better to call it once and store the result in a variable.
Don't use Count() method on an array, Using Count() use the Length property instead.
You should use the overloaded Split() method which takes a [StringSplitOptions][2] enum like StringSplitOptions.RemoveEmptyEntries.
Instead of using double.Parse() you should consider to use double.TryParse() which won't throw an exception if the current string doesn't represent a double like e.g a letter.
This string.Format("{0}", value * ConversionRate); can be safely removed because the result isn't assigned to anything.
Instead of returning a string[] you should consider to use an IEnumerable<string or better just an IEnumerable<double> which is more straightforward. Sure that means you need to change your interface as well.
Using a foreach will make the code shorter because you won't need to check for \n.

Implementing the mentioned points will lead to

string version

public IEnumerable<string> Convert(string input)
{
    if (string.IsNullOrWhiteSpace(input))
    {
        yield break;
    }
    var values = input.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
    foreach (var value in values)
    {
        double current;
        if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out current))
        {
            yield return (current * ConversionRate).ToString();
        }
    }
}

double version

    public IEnumerable<double> Convert(string input)
    {
        if (string.IsNullOrWhiteSpace(input))
        {
            yield break;
        }
        var values = input.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
        foreach (var value in values)
        {
            double current;
            if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out current))
            {
                yield return (current * ConversionRate);
            }
        }
    }

Ok, I need to target Controller.Convert() as well

This is really really bad:

string output = "";
for (int i = 0; i < converter.Convert(text).Count(); i++)
{
    output += converter.Convert(text)[i] + Environment.NewLine;
}

return Content(output);

Assume you have text = "\n1\n2\n3\n4\n5.......\n1000" then your code will once call converter.Convert() at
for (int i = 0; i < converter.Convert(text).Count(); i++)
which results in Count() = 1000 hence the loop will be executed 1000 times which calls converter.Convert(text) 1000 times.
In addition using output += on strings will lead to very bad performance because each time a new string object is created because strings are immutable.
Better use a StringBuilder.

Assuming you use the IEnumerable<double> Convert() this will lead to

    StringBuilder sb = new StringBuilder(1024);
    foreach (var value in converter.Convert(text))
    {
        sb.AppendLine(value.ToString());
    }

    return Content(sb.ToString());


Right, your object is, like Rene said, just a container of functions. Though, in theory, that's what objects are for (group functionality together), the way you went about this, you're actually using classes as modules. It's not what you call SOLID code.

Edit:
Perhaps you might want to scroll down first, because throughout the answer I've used rather messy examples to explain things, but at the bottom I've added a really simple example that might help you to understand the access modifiers and inheritance better.

Anyhow, I'm not going into details on how you should refactor this to be SOLID compliant, that's part of the learning curve. The simple fact of the matter is that, yes OOP is confusing at first, and at first you might not even need constructors, access modifiers (public, protected or private), let alone destructors. Especially if you haven't come to terms with inheritance. But let me explain a few things that, hopefully, will clarify one or two things.

Class methods share state:
That's just a fancy way of saying that class methods have access to variables, without having them passed as arguments. Of course, not just any variable will do: it's the properties of the class that are accessible. In your snippet, you're passing $conn to various methods, like you would if they were functions. The difference is, that classes can be assigned properties, too.

class RefactoredFunctions
{
    private $conn = null;
    public function setConn($conn)
    {
        $this->conn = $conn;
    }
    public function retrievePassword($userNAme)
    {
        //your code here, but replace $conn with $this->conn
    }
}

Now you can call the retrievePassword method, without having to pass the $conn param over and over again. Though, this code would fail, if $conn wasn't set prior to calling retrievePassword. How can we fix that?
Enter constructors. A constructor is a method, like any other, except for the fact that it can't be called manually. It's called automatically, when an instance of the class is created. You could define a constructor that expects an argument, and pass the connection to it, ensuring the $conn property will be set:

public function __constructor($conn)
{
    $this->conn = $conn;
}
//using this class:
$instance = new RefactoredFunctions($conn);
$instance->retrievePassword('userFoo');//conn is set through constructor!

That's all a constructor does (9/10 times): setting properties your class requires to work properly. These properties are sometimes called the dependencies of that class. The class depends on them.
Now, an argument that is called $conn is clearly supposed to be a DB connection in your case, but how do we make sure nobody passes a string? Simple: we use type-hinting, another benefit of OOP:

public function __construct(PDO $conn)
{
    $this->conn = $conn;
}
//usage
$instance= new RefactoredFunctions(new PDO());//works fine
$error = new RefactoredFunctions('foobar');//fatal error string is not PDO instance

This makes your code more failsafe. Use type-hints to avoid bugs. That's an order!
Now, all this time, I've been using $this->conn which is a property declared as private. Why? Simple. I've used type-hints to ensure the value of $this->conn is guaranteed to be an instance of PDO, but if I would have declared public $conn, I'm able to access the property (and thus assign it a new value) simply bypassing the setter/constructor:

//assume public $conn
$instance= new RefactoredFunctions(new PDO());//works fine
$instance->retrievePassword('userFoo');//still OK
$instance->conn = 'reassign conn';
$instance->retrievePassword('userFoo');//ERROR!

Now, with private properties:

$instance= new RefactoredFunctions(new PDO());//works fine
$instance->conn = 'reassign conn';//ERROR!!
$instance->retrievePassword('userFoo');//will never get this far

What's the benefit of this? Simple: the bug is easy to find. Imagine if I would've reassinged the conn property by accident, and then call a method 50 lines further down the script, or pass an instance to another class (defined in another file), and call the method there. I'd get an error, with a file & line number that contains the call, not the cause (reassignment statement).

OK, you got this far, and this is still making sense? On to protected... Where does that tie in?
Well, the more objects you have, chances are some of them share functionality. Rather than writing the same methods several times, we extend classes from each other. So far, we have:

class RefactoredFunctions
{
    private $conn = null;
    public function __construct(PDO $conn)
    {
        $this->conn = $conn;
    }
    public function setConn(PDO $conn)
    {
        $this->conn = $conn;
        return $this;
    }
    public function retrievePassword($userNAme)
    {
        //your code here, but replace $conn with $this->conn
    }
}

Now, suppose I wanted a DB class per table (quite common). I have this base class, that holds a connection instance, and some methods to query a DB. What if I moved the constructor, $conn property and setConnection method to a generic class, and create child classes per table? that would save me 2 methods/class to write. If I have 10 tables, that's 20 methods. Of course I'll do that:

class BaseTable
{
    private $conn = null;
    private $tblName = null;//to hold the table their linked to

    public function __construct(PDO $conn)
    {
        $this->conn = $conn;
    }

    public function setConn(PDO $conn)
    {
        $this->conn = $conn;
        return $this;
    }

    public function setTable($tblName)
    {//set table name for each instance
        $this->tblName = $tblName;
        return $this;
    }
}
//a child
class UserTbl extends BaseTable
{
    public function getUsers()
    {
        $this->conn->prepare('SELECT * FROM '.$this->table);
        //etc...
    }
}
//usage:
$users = new UserTbl(new PDO());
$users->getUsers();

Ok, so I didn't have to write those properties and methods, but the code above won't work! Why? because private means the properties/methods are only visible to the class in which they were defined, in this case BaseTable, not the child class. protected means that properties/methods can be accessed in both the class that defined them, and its children. So, would you make the $conn property protected? Of course NOT.
There's a number of reasons why you wouldn't do this, but I might go into those in a future edit. ATM, we have some more important things to focus on.

Have you noticed how the connection is guaranteed to be available thanks to the constructor, but the tablename isn't? yet, we're using the table name in our queries. How do we fix that? You have 3 options:

Make $tblName protected and assign it a value in the child's definition, and remove the setTable method
override the parent constructor (less secure)
A combination of the first two

So, if in the base class, we now have protected $tblName = null; you can write this, in the child:

protected $tblName = 'users';

Job done. The second approach would look like this:

//in child
public function __construct(PDO $connection, $tblName)
{
    $this->tblName = $tblName;
    parent::__construct($connection);//explicit call required
}

To combine the two would require using abstract, final and all that, here's an example of this, but I'm not going into all that now.

All this time, we still have to deal with the private $conn being invisible to the child classes. How would you deal with that? The answer to that question is surprizingly simple:

//in BaseTable
protected function getConnection()
{
    return $this->conn;
}

This protected method is visible to the children, and returns the connection, so all we have to do now is write:

$this->getConnection()->prepare('SELECT ...');

instead of $this->conn. There we are, problem solved, you should be able to get these classes working now.
Note that there's a lot of things left to be done. For example the getUsers methods is nothing but a select * from tbl query. We could just as well have written that in our BaseTable class, but using another name and access modifier:

protected function getAll()
{//protected: it's for internal use only
    $res = $this->conn('SELECT * FROM '.$this->tblName);
    return $res->fetchAll();
}

Then, in each child class:

//UsersTable:
public function getUsers()
{
    return $this->getAll();
}
//LogsTable
public function getLogs()
{
    return $this->getAll();
}

You could even add arguments in the child methods, and process the return value of the getAll method accordingly:

protected function getAll()
{
    return $this->conn->query('SELECT * FROM '.$this->table);
}
//UsersTable:
public function getUsers($asArray = false)
{
    $asArray = $asArray ? PDO::FETCH_ASSOC : PDO::FETCH_OBJ;
    return $this->getAll()->fetchAll($asArray);
}

One last thought on inheritance: Assume the classes BasteTable and UserTable extends BaseTable. When using type-hinting, this is good to know:

$base = new BaseTable();
$user = new UserTable();
if ($base instanceof BaseTable) echo 'Yes';//will echo, of course
if ($user instanceof UserTable) echo 'Duh';//of course, this is true

That's as you'd expect it, but:

if ($base instanceof UserTable) echo 'WTF';//You won't see this
if ($user instanceof BaseTable) echo 'Yes';//will echo!!

So all instances of UserTable are instances of BaseTable, too, but not all instances of BaseTable are instances of UserTable. Now this might seem odd, at first but think of it like this:

class Room
{
    public $door;//can be opened from outside
    protected $window;//can only be opened from within ANY room, all rooms have to access this
}
class Bathroom extends Room
{
    private $mirror;//this room has a mirror, can only be accessed in a bathroom
}
class Bedroom extends Room
{
    private $bed;//this one has a bed, can only be used when inside a bedroom
}

Now you see: both a bedroom and a bathroom are rooms, but a bedroom is no bathroom, hence:

$bath = new Bathroom;//instanceof Room, not instanceof Bedroom
$bed = new Bedroom;//instanceof Room, not instanceof Bathroom
$genericRoom = new Room;//instanceof Room
//not specified which, so no mirror or bed, so not instance of any child

I hope this clears one or two things up for you. If you have a follow up question, don't hesitate to ask. I'm not going to add any more info, as this is quite a lot to deal with already


Using mocking to test that a Django view renders as expected

How about doing things in two steps?

render_context = mock_render.call_args[0][2]
self.assertTrue(len(render_context["words"].object_list) == 1

This way it should be reasonably easy to figure out what call_args[0][2] are.

Although, I'm not sure if it's a good idea to test things this way. There still could be a bug if the template's broken, and you're essentially testing the internal API (the context data structure) in the middle of the function. Unless that is what you want to test, of course.

Maybe it would be a better idea to factor the querying logic to its own function. I guess, one possible way of doing this would be probably a class-based view, like some ListView derivative.

This way you could test its get_queryset() (not the get_context_data) to return the dataset you expect.

And you can also use test Client to return a sanely-looking rendered template - parse it with something like lxml or BeautifulSoup, or just check response string with "Word Editors" in response (although it may make sense to use more "unique" strings, like UUIDs in this case).


Simple function to generate a list of letters

Some notes on your code:

def f(arg = False) -> def f(arg=False) (PEP8)
case = case.lower() Usually it's not a good idea to reuse variables: new values, new variable names.
else + indent + if = elif
Use (true_value if condition else false_value) for short conditional expressions.
ascii_uppercase[i] for i in range(n). This will fail if n is greater than the size of letters.
[choice(alphabet) for i in range(n)]. This repeats characters, is that ok? It seems more fitting to use random.sample(alphabet, n), which does not repeat elements.
case: It's not idiomatic to send strings this way. Use a boolean argument instead (as @oliverpool proposed).

I'd write:

from random import sample
from string import ascii_uppercase, ascii_lowercase

def get_letters(n, random=False, uppercase=False):
    """Return n letters of the alphabet."""
    letters = (ascii_uppercase if uppercase else ascii_lowercase)
    return (sample(letters, n) if random else list(letters[:n]))


Fastest path on a snakes and ladders board

Don't use mutable default arguments. If you need to default to a list then default to None and then change to an empty list.

Take the following example code:

>>> def example_list_builder(value, list_=[]):
    list_.append(value)
    return list_

>>> example_list_builder(1)
[1]
>>> example_list_builder(2)
[1, 2]

This makes list_ a really poorly defined singleton variable, that can't be accessed globally.

Your code looks like it's something like \$O(6^n)\$ where \$n\$ is the size of the board.

You can instead make it \$O(l^2)\$ where \$l\$ is LADDERS and SNAKES.

To improve your code, you should remove the simulation and instead only work with the LADDERS and SNAKES variables.

For each snake and ladder you should traverse it, and then traverse the snake or ladder after this. You should note the distance, there are two ways to do this:

Least tiles visited.
Least turns taken.

For the latter, you'll have to check for collisions with other snakes and ladders.

You should take snakes into account, as the fastest path for the following is 4 turns:

NUMBER_SQUARES = 1000
LADDERS = {1: 502, 501: 999}
SNAKES = {503: 500}


Factory to instantiate and configure Selenium WebDriver

Quick Simplifications

The 0-args constructor is not used. Remove it.
close() can not be called in a meaningful way. Nobody can obtain an instance of DriverFactory, so making that an instance method is not useful in any way.
You're misusing fields as variables. Everything you're doing can be put into the factory method itself. There's no need for any instance data, you're not accessing it anywhere.

Let's consider instead:

static WebDriver getWebDriver(Properties properties) throws MalformedURLException {
    LOG.fine(properties.toString);
    final URL url = new URL(properties.getProperty("url"));
    final String driver = properties.getProperty("driver");
    final String gecko = properties.getProperty("gecko");
    final List<String> commandLineOptions = new ArrayList<>();
    commandLineOptions.add(properties.getProperty("option01"));

    final FirefoxBinary ffBinary = new FirefoxBinary();
    commandLineOptions.forEach((commandLineOption) -> {
        LOG.fine(commandLineOption);
        ffBinary.addCommandLineOptions(commandLineOption);
    });
    System.setProperty(driver, gecko);

    final FirefoxOptions ffOptions = new FirefoxOptions();
    ffOptions.setBinary(ffBinary);

    WebDriver result = new FirefoxDriver(ffOptions);
    result.get(url.toString());
    LOG.fine(webDriver.getTitle());
    LOG.fine(webDriver.getCurrentUrl().toLowerCase());
    return result;
}

This does mostly the same as the code you presented. We can see here that opening yourself up to MalformedURLException is not necessary. You're reading the String from properties into a URL and then call .toString() on it.

What we can see pretty easily now is that you're reading the contents of the passed Properties into variables to just use them once. It might be easier to reimagine the code as something like the following:

public static WebDriver getWebDriver(Properties properties) {
    final FirefoxBinary ffBinary = discoverBinary(properties);
    setSystemProperties(properties);
    final FirefoxOptions ffOptions = buildOptions(ffBinary);
    return createWebDriver(ffOptions, properties);
}

This makes the code comparatively abstract and easy to follow. You can grasp what happens without needing a deeper understanding of Selenium itself (not that the original code required a lot of it).

This abstraction just makes it easier to understand what's going on. The methods themselves are pretty trivial :)


Using Wreq and Lens libraries to query Prosper for account info

You're on the right path! You're asking great questions.

  I feel like I really went overboard with the let bindings, but I couldn't figure out how to break up some absurdly long lines in another way.

This is sort of unavoidable with wreq (or any HTTP client library in general probably), as you have to pass around a lot of state to communicate on a stateless protocol. You do a little better if you pass your options as a single Options value. Leads to friendlier type signatures too.

  All my maybeXXX functions. I needed them to operate on the Maybe typeclass in the way I was expecting, but I feel like there is a more elegant use of Monads that could avoid these auxiliary functions.

You can use fmap or <$> instead of constructing these maybeWobble helpers, but as we see below there's an even better option.

  The creation of the MResult type was done just to parse the response body of the web API. There must be a way to use Lens to extract that field and parse it as a list of Note directly.

There is! Your usage of the lens-aeson package is right on the money. To grab all the prosper_rating :: Text of all the notes in the result key, we can simply write this lens traversal:

_ratings = responseBody . key "result"
                        . _Array
                        . traverse
                        . key "prosper_rating"
                        . _String

(Traversal just means that you need to use ^.. instead of ^. and that you'll get back a list of values instead of one when you do so.)

The other way you could be using more lens is to import the text lens module, which provides two "once you learn of them you can't stop using them" helpers:

packed, unpacked: isomorphisms between Text and String. Never import qualified Data.Text again!
utf8: a prism that converts a ByteString to a Text, when possible. Never import qualified Data.Bytestring again!
_Show: a prism (in Control.Lens actually, but we'll toss it onto this list) that lets you convert any Show a => a value into String. Earn a combo bonus when you compose it with packed to get a Text.

One other note is that you should use param and := from the wreq library to construct parameter strings and POST bodies. They handle the text massaging for you.

OK, putting everything together:

{-# LANGUAGE OverloadedStrings #-}

module Free_D where

import Control.Lens
import Data.Aeson
import Data.Aeson.Lens
import Data.Monoid ((<>))
import Data.Text.Strict.Lens
import Network.Wreq

import Data.Text (Text)

-- String Constants
prosperAddress, clientID, clientSecret, userID, password :: Text
prosperAddress = "https://api.prosper.com/v1/"
clientID = "cicicicici"
clientSecret = "ssssssssssssssss"
userID = "uuuuuuuuuu"
password = "pppppppppp"

prosperURL :: Text -> String
prosperURL target = (prosperAddress <> target) ^. unpacked

-- | Retrives the OAuth2 token from the Prosper server.
oauthToken :: IO Text
oauthToken = do
    let opts =
          defaults
            & header "Accept" .~ ["application/json"]
            & header "Content-Type" .~ ["application/x-www-form-urlencoded"]
    let body =
          [ "grant_type" := ("password" :: Text)
          , "client_id" := clientID
          , "client_secret" := clientSecret
          , "username" := userID
          , "password" := password]
    resp <- postWith opts (prosperURL "security/oauth/token") body
    return (resp ^. responseBody . key "access_token" . _String)

-- | Performs a GET request to the provided target using the provided
-- OAuth token.
getTarget :: Options -> String -> Text -> IO (Response Value)
getTarget opts url token = do
    getWith (opts & header "Authorization" .~ rawr) url >>= asJSON
    where
        rawr = ["bearer " <> utf8 # token]

-- | Retrives the list of currently owned notes from Prosper.
--
-- Note: The query responses are paginated to 25 results per response.
getNotesList :: Text -> Int -> IO [Text]
getNotesList token offset = do
    resp <- getTarget opts (prosperURL "notes/") token
    let ratings = resp ^.. _ratings
    remainder <- if length ratings == 25 then return [] else getNotesList token (offset + 25)
    return (ratings ++ remainder)
    where
        opts = defaults & param "offset" .~ [offset ^. re _Show . packed]
        _ratings = responseBody . key "result" . _Array . traverse . key "prosper_rating" . _String

main :: IO ()
main = do
    token <- oauthToken
    notes <- getNotesList token 0
    print notes

(I got the code compiling but, as I don't have an account, I was unable to run and test it.)


\$0! = 1\$, which is a case not handled by the code.

The method should throw an ArgumentOutOfRangeException if n is negative.

You could also replace this

if (n % 2 != 0)
    result *= (BigInteger)Math.Round((double)n / 2, MidpointRounding.AwayFromZero);

with this

if (n % 2 != 0)
    result *= n / 2 + 1;

if you find it clearer.


Parameter names
This is one of my pet peeves:
Inode(const std::string &);

The point of a header file / class definition at least in my head is to separate the interface to your code from the implementation of your code.  Not putting parameter names in your function declarations makes your interface incomplete.  Sure, you know what the parameter is, but your wrote the code.  From reading your class header I don't have a clue what the string might represent, there's no comments to tell me, no name, so I'm either relying on your documentation (?) or have to look at the implementation to figure it out.
Default parameters
Default parameters only effect code that can see them.  You've defined default parameters for your methods, but only in your implementation file.  I find that a little odd.  If it's a good default, it should be in the header.
Naming
Descriptive naming is important and significantly reduces the learning time for people new to your code.  I had to look Inode up to see what it was.  It probably makes sense if you have experience in that area, but as an implementation of a folder structure it's not the first name I'd be looking for.  pwd to me means 'print working directory', so pwd_path_ seems like an odd name.  Perhaps wd_path would be better.  buffer_ is very non-descript.  It's a list of metadata, why not call it that?
You have a similar issue with your method naming.  DumpBuffer doesn't really say 'read the directory and return the meta data to me`.
Blank Lines
Some of your blank lines don't really make sense to me, they make your code harder to read.  Consider this:
if ( strcmp(diritem->d_name, ".") != 0 &&
           strcmp(diritem->d_name, "..") != 0 )

        buffer_.emplace_back( new InodeMeta{ std::string(diritem->d_name),
          std::string(pwd_path_) + "/" + std::string(diritem->d_name),
      diritem->d_type} );

You set up an unbraced if statement and then leave a blank line between the if and the code that belongs to it.  This is an invitation to be misinterpreted. I feel much the same about the else condition at the end of the function:
}

  else return false;

You close the if, leave a blank line then put the else.  It makes the else feel detached.
Pointers
What are you getting from storing pointers in your buffer_, rather than instances of InodeMeta.  Since you return copies anyway from your DumpBuffer method, it feels like you've just added extra handling requirements for little to no benefit?  If you want to save duplication then storing and returning a shared_ptr instead might be more efficient.
Hidden Behaviour
I'm not sure that having DumpBuffer behave differently depending on whether or not you pass it an empty string is a great idea.  If I pass in "/someFolder" then the folder is read.  If I pass it in again, "/someFolder", then the folder is read again (so any new files would be noticed for example).  If instead for the second call I had passed in "" then the original folder contents would have been returned.  If this is desired behaviour, then I'd at least put a comment in the header / documentation because it's not what I would expect.


Checking whether number is in given range

Should I throw exceptions if range_a is less than range_b?

This depends on your requirements.
 - Does the user of this function have to provide the input in correct order because a wrong order is a follow up of serious problem in her preceding code? Then you should throw an exception and this might even be a checked custom type to make the user aware of it.
 - Or is the wrong order something that is likely to happen and no problem outside your method? The reordering and going on inside your method is  appropriate.

  Should I throw exceptions if range_a is less than range_b?

This also must be specified by the requirements. If there was no requirement add a Javadoc comment explaining that and why you (not) return true in this situation.

  I'm using camelcase for methods and variables

as expected by the java naming conventions.

  Underscore is used to show that values are connected. and used together:
  Example: pos_x, pos_y or range_a, range_b

Why not posX, posY and rangeX, rangeY

or even better: since Java is an object oriented language, why not using objects to group things that belong together?

class Tupel {
  long a,b;
  Tupel(int a, int b){
    this.a = a;
    this.b = b;
  }
}

Tupel pos = new Tupel(10,30);
Tupel range = new Tupe(5,59);
// ...
if (range.a > range.b) {
  range = new Tupel(range.b,range.a);
// ...

  Why isn't checkMode an enumeration? – Alexander

The good thing about Java enums is that they can hold logic. The enum constants are classes that extend the enum class. This way enums can improve your code by resolving if/else cascades or switch constructs with polymorphism.

  You don't need to access the enum's raw values.[...] – Alexander

With that in mind you have only 2 enum constants

enum CompareMode{
  RANGE_EXCLUSIVE{
    @Override
    protected abstract boolean isInRange(long value, long range_a, long range_b){
      return value > range_a && value < range_b;
    }
  },
  RANGE_INCLUSIVE{
    @Override
    protected abstract boolean isInRange(long value, long range_a, long range_b){
      return value >= range_a && value =< range_b;
    }
  };
  public boolean inRange(long value, long range_a, long range_b){
     if(range_a > range_b)
       return isInRange( value,range_b,range_a);
     else // <- not needed but her for readability
       return isInRange( value,range_a,range_b);
  };
}

you complete logic is inside the enum, no extra method needed.

Now lets join that with the Tupel class:

enum CompareMode{
  RANGE_EXCLUSIVE{
    @Override
    protected abstract boolean isInRange(long value, Tupel range){
      return value > range.a && value < range.b;
    }
  },
  RANGE_INCLUSIVE{
    @Override
    protected abstract boolean isInRange(long value, Tupel range){
      return value >= range.a && value =< range.b;
    }
  };
  public boolean inRange(long value, Tupel range){
     if(range.a > range.b)
       range=new Tupel(range.b,range.a);
     return isInRange( value,range_a,range_b);
  };
}

The benefit of that solution is:

the parameter list is shorter and has no more possibility to mix the values passed in accidentally.
if you later add another CompareMode (which is hard to imaging, but try...) the only thing you have to change is the lines for the new mode and the code where you decide which mode to use. The code that actually needs the result does not need to change.

  Also, how are you calling methods in enum? – Michael

like this:

   Tupel range = new Tupel(4,5);
   for(CompareMode compareMode : CompareMode.values()){
    System.out.println(4+" is in range with compareMode "+compareMode +" ="+compareMode.inRange(4,range);
    System.out.println(5+" is in range with compareMode "+compareMode +" ="+compareMode.inRange(5,range);
   }


Counting from 0 to a number and back to zero, and space-padding the result to be a given length

You can simplify the logic that prints the numbers going from 0 to number anc back to 0.

They are: number - Math.abs(number - x). Let's explain why. With the number 5, the wanted output is:

01234543210

As a pre-requisite, let's consider the (simpler) output

54321012345

We want to model that with a single variable x going from 0 to 2 * number. Clearly, there are 2 paths: one decreasing and one increasing.

                     5   4   3   2   1   0   1   2   3   4   5
value of x           0   1   2   3   4   5   6   7   8   9   10
value of 5 - x       5   4   3   2   1   0  -1  -2  -3  -4  -5
value of abs(5 - x)  5   4   3   2   1   0   1   2   3   4   5  <-- output

Now that we have that, it is clear that our real wanted output is simply 5 minus that one, i.e. number - Math.abs(number - x).

Putting this into code:

public static void counter(int number, int length) {
    int space = (length - number * 2 + 1) / 2;
    for (int a = 0; a < space; a++) {
        System.out.print(" ");
    }
    for (int x = 0; x <= number * 2; x++) {
        System.out.print(number - Math.abs(number - x));
    }
    for (int b = 0; b < space; b++) {
        System.out.print(" ");
    }
}

Other comments:

Add spaces before each operator, it adds to readability.
Don't use a mixed form of curly braces and single line statement. Either add curly braces everywhere and then have a proper line break or make it a single line without them.
There is no need to store into local variables when you only use it once. In this case having numberFull and spaceFull don't really add to clarity and it is much simpler to have int space = (length - number * 2 + 1) / 2;.
There is no validation on the number and the count of spaces. You might want to add some.
Instead of letting the counter method print the String directly, it would be better to let it build the String and return it. The caller can then decide to print it or not. For that, take a look at the StringBuilder class.


I would allow the default constructor and make it default to a 0 size array. with the optimization that b_array is a nullptr.

Then you can also add move constructors/assignment. Where the moved-from object gets a b_array = nullptr;

On of the basic functionalities of a container is iteration. So you should add a begin() and end() that return the b_array and b_array+array_size resp. Don't forget the const versions.


Just a simple case of css hierarchy and not covering my bases with undoing twitter bootstrap's .hidden class. This does the trick:

@media(min-width: 1279px) {
  section:hover {
    menu.hidden {
      display: block;
      visibility: visible;
    }
    .section-wrapper {
      border: 1px #ddd solid;
      padding: 14px;
    }
  }
}

As for performance, it was this block that was causing a much bigger slow down:

  $(window).bind('load resize orientationchange', function(){
    $('#main_menu').trigger('testfit')
    if ($(window).width() < 1278) {
      $('section').find('menu').removeClass('hidden')
      $('section').find('div.section-wrapper').addClass('active')
    } else {
      $('section').find('menu').addClass('hidden')
      $('section').find('div.section-wrapper').removeClass('active')
    }
  })

Using a timeout will speed things up since it doesn't need to run everytime the browser size changes by 1 pixel: https://stackoverflow.com/questions/599288/cross-browser-window-resize-event-javascript-jquery


turn a dict that may contain a pandas dataframe to several dicts

I'm assuming that the code works as intended.

Firstly, let me tell you that your code looks very pythonic - this is a huge plus.

My comments:

Introduction

You state that

  I have a dict that may be 'infinitely' nested

Keep in mind that since you seem to be doing recursive calls your stack is limited hence is your ability to retrive nested dict.

map_keys_by_type

Argument d is not informative, try using dic (if you want to follow your change type->typ) or dictionary.

Although, this is not extreamly important you might consider changing p to something more informative. When I've read the code first time I almost immediacy forgot what this variable stands for. However, as I said this is not very important because the function is small.

nested_get

This bit

for k in nested_key:
    internal_dict_value = internal_dict_value.get(k, None)
    if internal_dict_value is None:
        return None

in my opinion would be clearer if you did:

if k not in internal_dict_value:
    return None
else:
    internal_dict_value = internal_dict_value[k]

not in shows your intention directly.

Everything else looks okay for me.


The shorter version seemed better to me at first sight (because it is simpler), but actually it is incorrect. Both if statements intend to compare the same two values, but incrementing index1 changes data1[index1] for the second statement. You could fix this by assigning the values to variables:

while index1 < len(data1) and index2 < len(data2):
    value1, value2 = data1[index1], data2[index2]
    if value1 <= value2:
        index1 += 1
    if value1 >= value2:
        index2 += 1

Updating ks_stat one value at a time feels a bit awkward to me. You could collect all the absolute differences in a list and take max() of it in the end. Or, extract the loop into a generator to avoid the list.


Ask user for a number, and count from that number up to 300

I would avoid making num1 a top level variable. Instead make it a local and pass it around. You also don't need to clear num1 every time. It will be cleared by the prompt method.

var num1 = prompt("Please enter a number: ");
outNum(num1)
function outNum(num1) {
  ...

Instead of do..while I would recommend a for loop.

Use more meaningful variable names.

This is a minor point for a learning exercise, but if efficiency is your goal try to reduce the number of times you modify the DOM (use document.write or anything similar s it is relatively expensive.

Lastly, though it is a somewhat personal preference and there is no hard and fast rule, I dislike using recursion to solve this type of input problem.

I would write this something like:

function run() {

  while (true) { // this loop runs forever

    var input = prompt("Please enter a number or press enter to exit: ");
    if (!input)
      break;        // leave the loop

    input = parseInt(input)

    if (isNaN(input)) {
        alert("That is not a number!");

    } else if (input < 150) {
        alert("The number is too low for this function.");

    } else if (input > 300) {
        alert("The number is too high for this function.");

    } else {
        printNumbers(input);

    }

  }  // end of while loop

}

function printNumbers(number) {
  var output = "";

  for (; number <= 300; number++) {
    output = output + number + "
"
  }

  output = output + "############################
";
  document.write(output); // Just change the document once
}

run();


Writing a chunk of a file to a socket in Swift

The type annotations in

let bufferSize:Int = 1024
var read:Int = 0

are not necessary, this can be simplified to

let bufferSize = 1024
var read = 0

The variable names can be improved:
read is not ideal since there is a system call
read() with the same name. The past participle of "to write" is
"written", not "writed", a better variable name might be totalBytesWritten since it contains the accumulated number of
bytes written to the target file.

The conversion to Int in

    let remaining = Int(count - writed)

can overflow on a 32-bit architecture. If the number of bytes to
read is computed as

    let readAmount = Int(min(count - totalBytesWritten, Int64(bufferSize)))

instead then it can not overflow and only one call to pread()
is needed.

There is a bug in

        writed += UInt64(writeCounter)

which should be

        writed += UInt64(writeResult)

otherwise the number of bytes written is added multiple times to
the total counter if multiple write() calls were necessary
(and then count - writed can crash).

With the outer loop

while true { ... }

pread() is called once more if all data has been copied. That can be
avoided by changing the outer loop to

while totalBytesWritten < count { ... }

Then also the logic becomes clearer and the condition in

    while writeCounter < read, writed < count { ... }

can be simplified.

Your function can only return 0 (on success) or -1 (on error),
therefore the return type Int64 makes no sense.

One possibility would be to change the return type to Bool to indicate
success or failure. Another possibility is to return the total number
of bytes copied in the success case (which can be less than the count
parameter if end-of-file was encountered), or nil on failure.
Yet another possibility is to throw an error, that allows to report
details on the problem to the caller.

I would not use empty external parameter names (_), a call

sendChunk(source: sfd, target: dfd, offset: 2, count: 5)

is more descriptive than

sendChunk(sfd, dfd, 2, 5)

The offset parameter could be defined with an default value zero.

Putting it all together the function could look like this:

func sendChunk(source: Int32, target: Int32, offset: off_t = 0, count: UInt64) -> UInt64? {

    let bufferSize = 1024
    var buffer = [UInt8](repeating: 0, count: bufferSize)

    var totalBytesWritten: UInt64 = 0
    while totalBytesWritten < count {
        let readAmount = Int(min(count - totalBytesWritten, UInt64(bufferSize)))
        let bytesRead = pread(source, &buffer, readAmount, offset + off_t(totalBytesWritten))
        guard bytesRead > 0 else {
            return bytesRead == 0 ? totalBytesWritten : nil
        }

        var bytesWritten = 0
        while bytesWritten < bytesRead {
            let amount = write(target, &buffer + bytesWritten, bytesRead - bytesWritten)
            guard amount > 0 else {
                return nil
            }
            bytesWritten += amount
        }
        totalBytesWritten += UInt64(bytesWritten)
    }

    return totalBytesWritten
}

Possible speed improvements: Most time will be spent in the read/write
system calls. One thing that you can do is to increase the
buffer size.


Program looks for correct balance of ( [ and { in expression

if (!stack.isEmpty());

This statement does absolutely nothing. You should remove it.

else if (stack.isEmpty()){
    System.out.println("Correct grouping pairs.");
}

Just because you removed the last pair does not mean you're done. Take, for instance, this line of code:

int x = getArray(getArrayID())[[0];

Your program first says Correct grouping pairs, before complaining about the "[[ ]" not being correctly balanced.

Next, your program is hardcoded to check for (), {} and []. But what if we wanted to add <>? Then you'd have a problem, because you'd need to change the code in a lot of places.

My first thought of a solution for this is to use two strings, and then using indexOf to see if our token is in the string. It's not the best solution, I think, but it would work pretty well:

String leftHandTokens = "[{(<";
String rightHandTokens = "]})>";

Then use like so:

if(leftHandTokens.contains(token)){
   //lefthand token
} else if(rightHandTokens.contains(token)){
   //righthand token
}

Next, finding out whether the two tokens are a correct pair:

if(leftHandTokens.indexOf(popped) == rightHandTokens.indexOf(token)){

Naturally this assumes that either of them is IN the token list in the first place. Else it will say (-1 == -1) = true.

You could simplify your code a lot like that:

String leftHandTokens = "[{(<";
String rightHandTokens = "]})>";

while (tokens.hasMoreTokens()) {
    String token = tokens.nextToken().trim();
    //Push opening delimeter to stack
    if (leftHandTokens.contains(token)) {
        stack.push(token);
    } else if (rightHandTokens.contains(token)) {
        String popped = stack.pop();
        //make sure that there is a corresponding closing delimiter   for every opening
        if (leftHandTokens.indexOf(popped) != rightHandTokens.indexOf(token))   {
            System.out.println("Incorrect grouping pairs.");
            break;
        } else if (stack.isEmpty()){
            System.out.println("Correct grouping pairs.");
        }
    }
}

I removed some of your comments, because splitting up if-elseif branches with comments makes it VERY hard to understand. You'd think that if you see a statement like this

if(condition){
    doSomething();
}

//if there was no condition, we gotta handle the thingmabob...

You'd say that the if statement is just that. But then what you do...

else {
   handleThingmabob();
}

Is throw some else at the bottom! That's scary! I'd have to read to the next statement to be sure whether there isn't anything else coming! Worst, with comments in there, the distance between if and else might be huge! If you've got something to say, say it before you start your if-statement.

But we're not entirely done.

You currently handle outputting whether everything was correct inside your loop.

That's a bad idea.

What you'd want to do is wrap the whole thing in a function, and the moment you find a problem, you'd return false. And when you're out of tokens, you check whether the stack is empty. That way your program will run faster for faulty inputs and will be able to determine cases where you provide blah( as a string to be faulty.


To review the code as it is:

It would be better not to even have result as a variable, and swap the order of operations inside the else-ifs that assign result from (result = X, gameResult++) to (gameResult++, return X)
You don't need semi-colons on the end of if statements:

} else {
    return false;
};

Rather than individually testing (userInput == X, then X == cpuInput), remove them and add the following if statement to the top.

if (userChoice === cpuChoice){
    ties++;
    return "Tie";
}
//The rest follows

Onto fixing the if-else!

So, instead of a long  if-else statement, I'd use an object, which lets you specify key and value pairs, which really cleans the process up, because you don't have to iterate over all the options before finding the one you need.

Here's what I came up with:

var results = {
    wins: 0,
    loses: 0,
    ties: 0
};

function RPSLZ(userChoice, cpuChoice) {
    var RULES = {
        rock: {
            lizard: 'Rock crushes lizard',
            scissors: 'Rock crushes scissors'
        },
        paper: {
            spock: 'Paper disproves Spock',
            rock: 'Paper covers rock'
        },
        scissors: {
            lizard: 'Scissors beheads lizard',
            paper: 'Scissors cuts paper'
        },
        lizard: {
            spock: 'Lizard poisons Spock',
            paper: 'Lizard eats paper'
        },
        spock: {
            scissors: 'Spock distroys scissors',
            rock: 'Spock vaporizes rock'
        }
    };
    if (userChoice == cpuChoice) {
        results.ties++;
        return 'Tie';
    } else if (!userChoice in RULES){
        return 'Invalid Input';
    } else {
        return (cpuChoice in RULES[userChoice]
                    ? (results.wins++, RULES[userChoice][cpuChoice])
                    : (results.loses++, RULES[cpuChoice][userChoice])
                );
    }
}

  How does it work?

That's a good question. It follows the following logic flow:

Declare the results outside the function, so it can continue recording results with more function calls (There is a way to do this inside the function, but I couldn't figure out how.)
Declaring the game RULES (Notice the all-caps, meaning it's a constant)
There's two special rules: tie and Invalid Input. They can be tested like described above, and like testing whether the input exists inside the RULES variable, because if it didn't, it would be undefined.
By using the same undefined testing rule, the cpuChoice can be tested to see whether it's inside the object of the userChoice, depending on the result, the respective counter is incremented, and the result returned.


Should Golang interface be shared among different packages of an application?

Personally I would define it in each package that uses it. It would only be a small amount of duplication but has many advantages:

It keeps the package self contained.
You mentioned that not all packages use the same method so it stops the interface getting very large.
If not every package uses each method it makes it explicit which method a package does use.