Function to class migration: constructor best practice

Having a default value is a good idea.
Also, instead of of using the constructor directly, there is a way to convert from a hash table.
This way only works if the class has a default (no-argument) constructor. (If you define a constructor that takes several arguments, you must also explicitly define a no-argument constructor.)

Enum PxLogType { BlankLine; Header; MilieuCondition }
[Flags()] Enum OutputDestination { Console = 1; File = 2 }

class Alignment {
    [char] $Symbol
    [int] $Location

    [string] ToString() { return "{{Symbol='{0}', Location={1}}}" -f $this.Symbol,$this.Location }
}

class PxLogItem {
    [PxLogType] $Type = 'BlankLine'
    [OutputDestination] $Destination = 'Console'
    [int] $Indent = 0
    [Alignment] $Alignment
    [string] $String = ''
}

You can write as follows.

@(
    New-Object PxLogItem -Property @{ Destination = 'File'; String = 'ABC' }
    [PxLogItem]@{ Indent = 12; String = 'DEF' }
    [PxLogItem]@{ Type = 'Header'; Destination = 'Console,File'; Alignment = @{ Symbol = '#'; Location = 10 }; String = 'GHI' }

) | Format-Table -AutoSize

The result:

     Type   Destination Indent Alignment                 String
     ----   ----------- ------ ---------                 ------
BlankLine          File      0                           ABC
BlankLine       Console     12                           DEF
   Header Console, File      0 {Symbol='#', Location=10} GHI

You can also convert strings to objects. This way requires defining a Parse() method.

Enum PxLogType { BlankLine; Header; MilieuCondition }
[Flags()] Enum OutputDestination { Console = 1; File = 2 }

class Alignment {
    [char] $Symbol
    [int] $Location

    [string] ToString() { return "{{Symbol='{0}', Location={1}}}" -f $this.Symbol,$this.Location }
    static [Alignment] Parse($str) { $s,$l = $str.Trim().Split(',', 2); return @{ Symbol = $s; Location = $l } }
}

class PxLogItem {

    [PxLogType] $Type = 'BlankLine'
    [OutputDestination] $Destination = 'Console'
    [int] $Indent = 0
    [Alignment] $Alignment
    [string] $String = ''

    static [PxLogItem] Parse($str) {
        $regex = '^(?:{(?<type>[a-z]+),(?<dest>[cf]+),(?<idt>[0-9]+)(?:,align=(?<align>\S,[0-9]+))?})?(?<text>.*)$'
        if ($str -notmatch $regex) { throw }

        $result = @{ String = $Matches['text'] }
        if ($Matches['type']) {
            $result.Add('Type', $Matches['type'])
            $result.Add('Destination', $Matches['dest'].ToCharArray().ForEach{ "$_" })
            $result.Add('Indent', $Matches['idt'])
        }
        if ($Matches['align']) {
            $result.Add('Alignment', $Matches['align'])
        }
        return $result
    }
}

All of the following are valid conversions.

@(
    [PxLogItem]@{ Destination = 'Console,File'; Indent = 12; Alignment = '=,15'; String = 'ABC' }
    [PxLogItem]'DEF'
    [PxLogItem]'{m,f,8}GHI'
    [PxLogItem]'{header,cf,4,align=#,10}JKL'

) | Format-Table -AutoSize

The result:

           Type   Destination Indent Alignment                 String
           ----   ----------- ------ ---------                 ------
      BlankLine Console, File     12 {Symbol='=', Location=15} ABC
      BlankLine       Console      0                           DEF
MilieuCondition          File      8                           GHI
         Header Console, File      4 {Symbol='#', Location=10} JKL

Using functions makes them more readable.

function New-PxLogItem {

    Param(
        [Parameter(Mandatory, Position=0)]
        [string]
        $String = '',

        [Parameter(Position=1)]
        [PxLogType]
        $Type = 'BlankLine',

        [Parameter(Position=2)]
        [ValidateRange(0,1000)]
        [int]
        $Indent = 0,

        [Parameter(Position=3)]
        [Alignment]
        $Alignment,

        [switch]
        $Console,

        [switch]
        $File
    )

    if (!$Console -and !$File) { $Console = $true }
    $PSBoundParameters.Add('Destination', !!$Console + 2 * !!$File)
    ('Console','File').ForEach{ [void]$PSBoundParameters.Remove($_) }

    [PxLogItem]$PSBoundParameters
}

$item1 = New-PxLogItem "Hello" Header -indent 4 -align "#,10" -c -f


Removing the check on each iteration is definitely a good idea. My advice: have a separate method for each process. E.G.

SelectedRange = GetSelectedRange()

AllCapsRange(SelectedRange)
Process2Range(SelectedRange)

then, if you need to select a case, you only need to do it once, and not \$n^2\$ times.

As a general rule, the ONLY things that should go inside an iterative loop are things which could change during the iteration. Anything else should be declared/set beforehand.


I have an answer in x86 tasm and written under Windows, so I'm not sure if this will help, apologies if it doesn't. Maybe the way its done will give you some ideas.

.model small
.stack 100h
.data

    colour db 00001111b
    input db 10, 0, " " ;

.code

main:

    call initsegs
    call readstring
    call printstring
    call exit

PROC printstring

    push bx dx cx ax bp
    mov bx, 1; 1st (after zero) byte of input we are after, the length
    xor dx, dx; make sure dx contains zero before we play with dh and dl

    mov dl, input[bx]
    mov cx, dx; cx now has the 2nd byte value in the string, ie the length

    mov ah, 13h ; int 13h of 10h, print a string
    mov al, 1 ; write mode: colour on bl
    mov bh, 0 ; video page zero
    mov bl, colour; colour attribute

    mov dh, 10; row
    mov dl, 10; column
    mov bp, offset input ; es:bp needs to point at string..this points to string but includes its max and length at the start

    add bp, 2 ; skip the first two elements which will be the length and amount used
    int 10h;

    pop bp ax cx dx bx

    ret

ENDP printstring

PROC readstring

    push ax dx

    mov ah, 0ah ; function a of 21h - read a string
    mov dx, offset input ; reads string into DS:DX so DX needs be offset of string variable

    int 21h ; call the interrupt

    pop dx ax

    ret

ENDP readstring

PROC exit

    mov ah, 4ch
    INT 21h

    RET

ENDP Exit

PROC initsegs

    push ax

    mov ax, @DATA
    mov ds, ax
    mov es, ax

    pop ax

    RET

ENDP initsegs

end main


CSS Coding Style - Floating and text alignment

CSS, like HTML itself, is essentially an interpreted computer program. That means, among other things, that while img.screenshot.floatLeft is more specific (it targets fewer elements), it's also more costly to evaluate. You can think of this in plain English: is it faster to say "if this is floatLeft" or "is this an img and is this screenshot and is this floatLeft"?

Clearly, the former is shorter, and if you have many images in a document, you might get a fairly modest boost in loading time. You also want to minimize the total number of rules you use to achieve the desired effects.

Inlining styles is generally considered a bad idea, because it associates content with layout, which was the original problem CSS was trying to solve. Before CSS, designers had to use many semantically meaningless elements for the sake of presentation, and inline styles are basically no different.

Given the previous paragraph, this also means that you should avoid wrapping elements for the sake of presentation. It's almost never necessary to have more than a few levels of nesting in a modern browser with reasonable CSS support. If you must do so, consider including aria attributes to improve accessibility.

Pretty much the only time you should inline is by script, where the values are not known ahead of time and must be calculated. I find myself using this most frequently to position dynamic elements. Even then, most of the styles (position, display, color, etc) still go in a CSS file, and I only specify left, right, top, or bottom attributes dynamically.

So, in summary, avoid elements without semantic meaning, make selectors as simple as possible, and inline styles only when necessary.


Prim's Lazy Minimum Spanning Tree Algorithm in Haskell (Project Euler# 107)

I would separate the looping queue logic from the rest. A general implementation of unrollM necessitates a state monad here.

import Control.Monad.State
import Control.Monad.Loops

unrollM :: (Monad m, Ord a) => (a -> m [a]) -> [a] -> m [a]
unrollM f = step . (Heap.fromList :: Ord a => [a] -> Heap.MinHeap a) where
  step queue = case Heap.view queue of
    Nothing -> pure []
    Just (x, queue') -> do
      as <- f x
      (x:) <$> step (foldl (flip Heap.insert) queue' as)

minimumSpanningTreeEdgeSum :: Array (Int, Int) Int -> Int
minimumSpanningTreeEdgeSum adj = sum $ map fst $ (`evalState` Set.singleton 0) $ unrollM minimumSpanningTree'
  [(adj!(0,a),(0, a)) | a <- [1..dim-1], adj ! (0,a) > 0] where
  minimumSpanningTree' :: (Int, (Int, Int)) -> State (Set.Set Int) [(Int, (Int, Int))]
  minimumSpanningTree' (weight, (from, to)) = firstM (gets . Set.notMember) [from, to] >>= \case
    Nothing -> pure []
    Just nextVertex -> do
      modify $ Set.insert nextVertex
      filterM (gets . Set.notMember . fst . snd) $ filter ((>0) . fst)
        [ (adj ! (i,j), (i, j))
        | a <- [0..dim-1]
        , let [i,j] = sort [nextVertex, a]
        ]


Jump game to find minimum hops from source to destination

Code-Style
For the most part, this is good:

return types are good.
Collections are well typed
method names are good
apart from list, a1, and a2, variable names are good

The list is a bad name for a List. The fact that it is a list is obvious... but, what is the list...? I prefer result to list.
a1 and a2 are not bad, but they are not good either. They are just 'OK'.
Algorithm
I have worked the code through, and figure there is a plane-jane O(n) solution to the problem. Your algorithm is something larger than O(n), It is closer to O(n * m) where m is the longest jump.
The alternate algorithm I cam up with sets up a 'range' for the next jump.... It seaches all the values from the current cursor to the current range, and it looks for the jump within that range that would extend the range the furthest.
The method looks like:
public static List<Integer> getShortestJumps(int[] jump) {
    final List<Integer> list = new ArrayList<Integer>();
    if (jump.length == 0) {
        return list;
    }
    int cursor = 0;
    int best = 0;
    int range = 0;
    int remaining = 1;
    while (cursor + 1 < jump.length) {
        if (cursor + jump[cursor] > range) {
            // jumping from here would extend us further than other alternatives so far
            range = cursor + jump[cursor];
            best = cursor;
            if (range >= (jump.length - 1)) {
                // in fact, this jump would take us to the last member, we have a solution
                list.add(best);
                break;
            }
        }
        if (--remaining == 0) {
            // got to the end of our previous jump, move ahead by our best.
            list.add(best);
            remaining = range - cursor;
        }

        cursor++;
    }
    // always add the last member of the array
    list.add(jump.length - 1);
    return list;
}


Just using your pattern on regex101, against the given examples on the documentation link you provided, the pattern fails for a lot of scenarios.

A few points to consider:

Pattern for valid IPv6 targets
Allow for percent encoding
\- You don't have to escape the hyphen if you move the - (hyphen) at the beginning or the end of matchset so that it does not act as rangeset.
Does not support an attribute in the URI in its current form

  PS: You can test the pattern against the given mysql examples for
  initial validations.


There are two ways to solve this problem. The first one is numpy.where, which can take two arrays and it will choose from one wherever a condition is true and from the other wherever it is false. This only works if your piecewise function has only two possible states (as is the case here):

def waf_delay(delays):
    return np.where(np.abs(delays) <= delay_chip*(1+delay_chip/integration_time),
                    1 - np.abs(delays)/delay_chip,
                    -delay_chip/integration_time)

Another more general possibility is to use numpy.piecewise, but that is probably overkill here:

def f1(x):
    return 1 - np.abs(x)/delay_chip

def f2(x):
    return -delay_chip/integration_time

cut_off = delay_chip*(1+delay_chip/integration_time)
y = np.piecewise(x, [np.abs(x) <= cut_off, np.abs(x) > cut_off], [f1, f2])

Note that in both cases no for d in delays is needed, because all functions used are vecotorized (the basic arithmetic operations for numpy arrays are and so is numpy.abs).


Update join table using list of checkboxes in Rails

Actually, Active Record can work with joined collection (including has_many :through) from the box.

So, you just need to pass new collection instead of old, and AR will delete excessive and add new records.

In your code, need to change create method body to:

gig = Gig.find(params[:gig_id])
singer_ids = params[:singer_ids] # [1, 4, 5,]
gig.singers = Singer.find(singer_ids)
redirect_to gigs_path


How to write this code without using 11 if-statements?

Why can't you do:

progressLabel.Text = string.Format("{0}%", progressBar1.Value)

As @MNZ pointed out I potentially didn't answer the question exactly how the OP asked.  So here's a slightly modified alternative option:

progressLabel.Text = FormatProgress(progressBar1.Value, progressLabel.Text)

private string FormatProgress(int currentProgress, string progressDisplayed)
{
    if (currentProgress < 0 || currentProgress > 100)
        throw new ArgumentOutOfRangeException("Current progress is not in a valid percentage range of 0 to 100");

    if (currentProgress == 1)
        return FormatProgress(currentProgress);

    return currentProgress % 10 == 0 ?
              FormatProgress(currentProgress) :
              progressDisplayed;
}

private string FormatProgress(int progress)
{
    return string.Format("{0}%", progress);
}

And a unit test to confirm:

[TestMethod]
public void Test()
{
    Assert.AreEqual("1%", FormatProgress(1, "0%"));
    Assert.AreEqual("0%", FormatProgress(0, "5%"));
    Assert.AreEqual("10%", FormatProgress(10, "6%"));
    Assert.AreEqual("80%", FormatProgress(85, "80%"));
    Assert.AreEqual("100%", FormatProgress(100, "90%"));
    Assert.AreNotEqual("75%", FormatProgress(75, "70%"));
}


Some JDBC-related notes:

use getColumnLabel() instead of getColumnName()
using islast() as part of the ResultSet loop is unconventional (and potentially slow, and potentially not supported). The intended use pattern is while res.next(): ( next() returns true when successful).
you should have a symmetrical mechanism for accessing both the column names, as well as the column values. In your header row, you looped the range(0, meta.getColumnCount()): and in the column values you loop the range range(1, meta.getColumnCount() + 1):. You shoudl pick one, and stick with it (also, yes, everyone agrees with you that JDBC should have been zero-based with column indexes... like ... really?).
In general, do not use ResultSet.getString() unless you know it is a String in the column. In this specific case though, the effort required to check whether the values are numeric, etc. are overkill. Still, do not get in the habit of getString().
This is a short&sweet program, but even then, you should observe the best-practices for JDBC. You shoud close the Statement instance properly (which means you will need to store it in a variable), and also close the ResultSet. In this case, you close the Connection and that may clean things up nicely, but the protocol is to close things in reverse order to opening them.


12% speed-up by simplification

Your code as is takes (with input 10**5):

max depth 96 at n = 92717 of 100000
        4027699 function calls (3764972 primitive calls) in 9.303 seconds

I simplified it by removing the:

    if (j-1, k) in D:
        del D[(j, k-1)]
    if (j+1, k) in D:
        del D[(j+1, k-1)]

And it runs in:

max depth 96 at n = 92717 of 100000
         4027699 function calls (3764972 primitive calls) in 8.129 seconds

So it both runs faster and is less code to maintain, a win-win.


C++ int_cast function for checked casts?

Are there any loopholes in this function I have not accounted for (e.g. undefined behavior)?

No. Static cast will not result in undefined behavior.
If it compiles then the cast is good (assuming integer/float types).

Though some of your cast may potentially result in implementation defined behavior (depending on the sign-dness and size of the types).

signed x = int_cast<signed,unsigned>(-1); // implementation defined behavior.

Since this is only supposed to work on int(s). Then I would make it be a compile time error if you tried to use it with other types. You may also be able to do some compile time range checking when the inputs are literals.

In the following:

(result >= TTo()) != (value >= TFrom())

I am assuming this is some form of signdness test (to make sure both source and destination have the same sign). If you are going to do this please comment the code explaining exactly how you think it works.

There are integer traits that allow you to pull the signdess and size of the template type from the input/output types. You could potentially look at this to help identify things.


The overall structure of your code looks good, but the readability is a tad poor. You should always strive to follow the Framework Design Guidelines. Use proper naming and add a few linebreaks.

Rather than using arrays, create a dedicated "Sprocket" class to hold the parsed input data.

Public Class Sprocket
    Public Property X As Integer
    Public Property Y As Integer
    Public Property R As Integer
End Class

Now, if you add the rest of the non-numeric characters to the separator list you could actually read and parse the file in two lines. (Though you ougth to use the line-continuation character for readability as seen at the bottom)

Dim numbers = File.ReadAllText("C:\Temp\gearinput.txt").Split($"{Environment.NewLine} ,)(".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(Function(n) Integer.Parse(n)).ToArray()
Dim sprockets = Enumerable.Range(0, (numbers.Length \ 3)).Select(Function(i) New Sprocket With {.X = numbers(((i * 3) + 0)), .Y = numbers(((i * 3) + 1)), .R = numbers(((i * 3) + 2))}).ToArray()

Sprocket.vb

Public Class Sprocket

    Public Property X As Integer
    Public Property Y As Integer
    Public Property R As Integer

    Public Overrides Function ToString() As String
        Return $"{{ X={Me.X}, Y={Me.Y}, R={Me.R} }}"
    End Function

End Class

Program.vb

Public Module Program

    <STAThread>
    Public Sub Main()

        'TODO: Read file
        Dim input = "(0, 0, 16),  (100, 0, 16),  (100, 100, 12),  (50, 50, 24),  (0, 100, 12)"

        Dim numbers = input _
            .Split($"{Environment.NewLine} ,)(".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) _
            .Select(Function(n) Integer.Parse(n)) _
            .ToArray()

        Dim sprockets = Enumerable _
            .Range(0, (numbers.Length \ 3)) _
            .Select(Function(i) New Sprocket With
            {
                .X = numbers(((i * 3) + 0)),
                .Y = numbers(((i * 3) + 1)),
                .R = numbers(((i * 3) + 2))
            }) _
            .ToArray()

        Application.EnableVisualStyles()
        Application.SetCompatibleTextRenderingDefault(False)
        Application.Run(New Window(sprockets))

    End Sub

End Module

Window.vb

Public Class Window
    Inherits Form

    Private ReadOnly sprockets As Sprocket()

    Public Sub New(sprockets As Sprocket())

        If (sprockets Is Nothing) Then
            Throw New ArgumentNullException(NameOf(sprockets))
        End If

        Me.sprockets = sprockets

        Me.SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint Or ControlStyles.OptimizedDoubleBuffer, True)

        Me.Text = "Sprockets"
        Me.AutoScaleMode = AutoScaleMode.Font
        Me.ClientSize = New Size(800, 450)

    End Sub

    Protected Overrides Sub OnPaint(e As PaintEventArgs)

        e.Graphics.Clear(Me.BackColor)
        e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.HighQuality

        For Each sprocket In Me.sprockets

            Dim diameter = (sprocket.R * 2)
            Dim rect = New Rectangle(sprocket.X, sprocket.Y, diameter, diameter)

            e.Graphics.FillEllipse(Brushes.Black, rect)

        Next

    End Sub

End Class


Yes, there are a few things which can be done to speed up your code.

You create local variables width and height.  But then you don't use these variables.  Instead you use for x in range(img.shape[1]): which ends up evaluating img.shape[1] a total of height times.  Consider that img.shape retrieves the shape array from img, and then accesses the [1] member of that list.  Using for x in range(width): doesn't have that overhead.

Consider arr[y].append(_).  Again, this code is looking up in the arr list, the [y] element, and to that retrieved list appending a value.  That done once for every pixel.  If you kept a handle to the list that you are appending to, you wouldn't have to look it up each time.

def generateArray():
    arr = []
    for y in range(height):
        row = []
        for x in range(width):
            if img[y][x][0] != 1:
               row.append(1)
            else:
               row.append(0)
        arr.append(row)
    return arr

The above code should be a little faster.

Appending is a time-consuming operation.  If the list is stored as an array, rather than a linked-list, then appending an element will require frequent reallocation of the array capacity, and copying of all of the elements to the new storage area.  We can prevent this reallocating and copying by allocating storage for all of the data all at once:

def generateArray():
    arr = [None] * height          # Correctly sized array of rows
    for y in range(height):
        row = [0] * width          # Correctly sized row, filled with 0's
        for x in range(width):
            if img[y][x][0] != 1:
               row[x] = 1
        arr[y] = row
    return arr

Here, the row array starts off with [0, 0, 0, 0, ..., 0, 0, 0] so it is only necessary to set the elements to 1 where needed.

Looping and list lookup can be slow.  Consider:

        for x in range(width):
            if img[y][x][0] != 1:
                row[x] = 1

which loops over all the x values of a row, and for every x value, looks up the row img[y], and then the pixel in the row img[y][x], for each pixel in that row, and then accesses the [0] element of that pixel.  That's a lot of lookups.  If instead we used:

        for x, pixel in enumerate(img[y]):
            if pixel[0] != 1:
                row[x] = 1

we'd be iterating over the row of pixels, getting their values without the double list lookup.

We could also use list comprehension to build the list.  Since each row is of a fixed, known length, the list comprehension can allocate the correctly sized list, and fill in the elements one-at-a-time, without indexing or appending.

def generateArray():
    arr = [None] * height
    for y in range(height):
        arr[y] = [ 1 if pixel[0] != 1 else 0 for pixel in img[y] ]
    return arr

That also applies to building each row.

def generateArray():
    return [ [ 1 if pixel[0] != 1 else 0 for pixel in row ] for row in img ]

The function generateArray() uses a global variable img.  It would be better to pass img into the function.

def generateArray(img):
    # code which uses img

generateArray() is a terrible name for the function.  Maybe generateMaskFromImage()?

The output arr is not being used by your code.  If you omitted the line:

arr = generateArray()

your code would run much, much faster.   ;-)


Find pairs in an integer array whose sum is equal to n (bonus: do it in linear time)

The map by default returns a list. You do not need another wrapper around it.

Your current implementation is of \$ O(n^2) \$ complexity. The statement:

(n - x, x) not in pairs

is of \$ O(n) \$ time, which lies inside a loop with \$ O(n) \$.

To do this in linear time, generate a dict/hash where you store simply the \$ n - x \$ values in first iteration. In the second (and independent) iteration, simply append the pair $$ \left( min(x,\ n - x),\ max(x,\ n - x) \right) $$ for each x in your list, if the \$ O(1) \$ lookup in the dict is true.


Your code looks good, there's not much for me to review, but here are a couple improvements/changes I would make.

Improvements

Docstrings: You should include a docstring at the beginning of every method/class/module you write. This will help any documentation catch what your code is supposed to accomplish.
If/Else: If you return a value in the if, then you don't need an else. You should just put the else code after the if, instead of inside an else, like so:

if key in self._entry_finder:
    return self._entry_finder[key]
else:
    raise KeyError('Item not found in the priority queue')

to

if key in self._entry_finder:
    return self._entry_finder[key]
raise KeyError('Item not found in the priority queue')

Updated Code

class UpdateableQueue:
    """ An updateable priority queue class """
    def __init__(self, iterable=None):
        self._heap = []
        self._entry_finder = {}
        if iterable:
            for item in iterable:
                self._entry_finder[item[0]] = item[1]
                heapq.heappush(self._heap, (item[1], item[0]))

    def __getitem__(self, key):
        """
        Returns the item with the specified key, if exists. Else,
        it raises a `KeyError` exception
        """
        if key in self._entry_finder:
            return self._entry_finder[key]
        raise KeyError('Item not found in the priority queue')

    def __len__(self):
        """ Returns the length of the queue """
        return len(self._entry_finder)

    def __contains__(self, key):
        """ Returns a boolean based on if the key is in the queue """
        return key in self._entry_finder

    def push(self, key, priority):
        """ Pushses a priority into the queue """
        self._entry_finder[key] = priority
        heapq.heappush(self._heap, (priority, key))

    def pop(self):
        """ Removes a priority from the queue """
        if not self._heap:
            raise IndexError("The heap is empty")

        value, key = self._heap[0]
        while key not in self or self._entry_finder[key] != value:
            heapq.heappop(self._heap)
            if not self._heap:
                raise IndexError("The heap is empty")
            value, key = self._heap[0]

        value, key = heapq.heappop(self._heap)
        del self._entry_finder[key]
        return key, value


Just some random tips in no particular order.

Consistency in naming: keep using camelCase.
(drawsun -> drawSun, drawpyrX -> drawPyrX, walla -> wallA, ...)
Redundance in declaring and inconsistent use of " and '.

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var canvasElement = document.querySelector("#myCanvas");
var ctx = canvasElement.getContext("2d");

Put all variables to the top and use const for the ones you dont want to change. This makes changes easier and safer, because you cant change the constants by accident.

var sunX = 700;
var sunY = 100;
const xDirection = -1;
const yDirection = 0.2;


Thoughts on organizing code for multiple mysql queries in php scripts

You're on the right track, what you're looking for is a DAL (Data Abstraction Layer), a class that represents a database connection.
This will allow you to move your common code into the class so you can simply construct your SQL statement and pass it in, with the method returning the expected data.

At a minimum you'd typically have, but aren't limited to:

Constructor (__construct) to create a new database connection using the relevant permissions.
Method to run your select statement (after input sanitization), returning a result set.
Method to run statements that don't return a result set.
Destructor (__destruct) to clean up and free any resources.

This would give you the following advantages:

Code reuse: only 1 copy of logging, connection initialization code, in 1 place.
Code encapsulation: The details are hidden behind a public interface so you can easily fix bugs and add new features without breaking existing SQL calls.
Pass in a complete SQL statement for centralized execution of SQL code.
Optionally pass in a parameter to specify calling Fetch/FetchAll/FetchColumn.
Easier debugging since your class will very quickly become very reliable as it gets heavily used and bugs are noticed and fixed.
Logging would be done automatically whenever you ran an SQL statement.
Easily add additional methods, such as input validation/sanitization.
Additional methods for specific purposes depending on your requirements.


Server side validation for reCAPTCHA V2 or Invisible reCAPTCHA with Java (Servlet)

One small criticism of you're code that I'll offer is that the loop in the middle which reads a stream could be usefully factored out and put in a general utility.  Reading a stream is a common problem and could be made more general.

In fact I have a small routine to do that sitting here on my hard drive.  Here's my version:

public class IoUtils
{

   private IoUtils() {}

   public static CharSequence readFully( Reader reader )
           throws IOException
   {
      char[] buffer = new char[ 1024 ];
      StringBuilder stringBuilder = new StringBuilder();
      for( int length; ( length = reader.read( buffer ) ) != -1; )
         stringBuilder.append( buffer, 0, length );
      return stringBuilder;
   }

   public static ByteArrayOutputStream readFully( InputStream ins )
           throws IOException
   {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      byte[] bytes = new byte[ 1024 ];
      for( int length; ( length = ins.read( bytes ) ) != -1; )
         bos.write( bytes, 0, length );
      return bos;
   }
}

Use it something like this:

    InputStream res = new URL(url).openStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(res, Charset.forName("UTF-8")));

    CharSequence cs = IoUtils.readFully( rd );

    JSONObject json = new JSONObject( cs.toString() );

Reading a stream as UTF-8 is so common you might even want to make a separate method just for that.  Then you could do

JSONObject json = new JSONObject( IoUtils.readFullyUtf8(
         new URL(url).openStream() ).toString() );

Some might find a single line of code more clear to read.


Handle concurrent HTTP requests with a generic .ashx

A generic ASP.NET ASHX handler can handle concurrent HTTP requests perfectly fine out of the box. This is partially thanks to the hosting infrastructure and ASP.NET itself. There's no need for all of this. I'm saying this because I'm not sure this is what you really want.

But maybe you're referring to asynchronous handlers which means something else entirely, in which case I'd refer to this: http://msdn.microsoft.com/en-us/magazine/cc164128.aspx


Is there a better, more efficient way than Dictionary(Of Tuple(), MyClass)?

If you're stuck with Tuple<T1,T2> as a key, you want to provide an IEqualityComparer<Tuple<T1,T2>> implementation in the constructor of your dictionary.

If you can change the TKey type, you might want to provide a custom class that implements IEquatable<T>.

The problem with the current code is that comparison between keys of type Tuple<string, string> is not efficient.


Removing duplicate words from an unsorted list

This question boils down to the number and sequence of operations. If you are building one large list but removing lots of duplicates, use a hash table or sort and uniquify the list.

Sorting and making the list unique is O(n log n) at best. Removing a duplicate is O(n) at worst so removing m duplicates is O(m * n). While in general O(k * n) = O(n), once m exceeds log n the one-time cost of sorting the set pays for itself. And additional lookups remain O(1).

You must evaluate the costs with realistic values for m and n to decide which method is better. Of course, their values will vary over time along with the relative costs of CPU versus RAM versus disk. But for most "probable" values of m and n over time, relying on standard library collection classes--with a sprinkle of tuned variations from Guava and the like--is the hands-down winner.


Setting a value of an iframe in the parent

The simplest would be to use window.top if F1 is part of the top-most window, or possibly go top down window.top.someframe.someotherframe.F1.

An alternative might be to write a helper something like:

function getFrame(name) {
  var current = this;
  while (current) {
    if (current.document[name])
      return current.document[name].document;
    current = current.parent;
  }
  return undefined; // not found
}


If I understand correctly, the program counts the occurrences of some words in a file. I have the following observations:

Error handling

I would recommend throwing exceptions instead of/additionally to writing to cout and cerr (btw., I think if you do write to these streams, you should stick to one of them, most probably cerr).

EDIT: Note, that as the constructor is written currently, we can end up having an object in an invalid state after calling it. This would be prevented by throwing an exception.

Encapsulation, state of the class

I suggest making setWord private, or at least protected. As it is now, one could call:

file test("stdafx.h");
test.searchFile("hey");
test.setWord("fooBar");
test.output(cout) << endl;

Also note, that currently it is possible that a client calls test.output straight away:

file test("stdafx.h");
test.output(cout) << endl;

In this case, he would probably get meaningless results. I therefore suggest introducing a check at the beginning of the implementation of the  output method (if you need it at all, see below), and e.g. throw an exception if no search was performed yet.

Constructors

In this particular case, I would suggest initialising fileName only in the body of the constructor, after checking the validity of the parameter. In other words, I would first validate, and only then initialise, instead of initialising with a (possibly invalid) parameter and then cleaning up.

Also, it is not clear to me what the purpose of the default constructor is. Would an object constructed through that constructor work correctly? If not, then you can probably remove it, and keep only the parametrised one.

Destructors

I recommend adding a destructor to this class, where the file stream opened in the constructor is closed again.

Idempotency

Note, that currently it is possible to call searchFile only once. After the first call, we will be at the end of the input stream, and thus it is not possible to read from it anymore.
I therefore recommend to either reset the stream (or close/open it again), or introduce a similar check as mentioned above for the state of the object (i.e., throw an exception if searchFile is called twice).

Responsibility of the class

Instead of the method ostream &output(ostream&) const;, I would rather introduce a method int getWordCount() const, which would return the actual count, and then leave it up to the client how/if he wants to print this count (of course this would also need the above mentioned check, whether the object is in the right state).

Maybe it would be even better to have searchFile return the count directly (and throw an exception if the word we are looking for is empty, instead of communicating this fact through the return value).

Naming

I recommend changing the name of the variable fileName to something which better reflects what it is, e.g. fileStream. (fileName makes me think of a string holding the name of the file, not a stream through which the contents can be read).

Code blocks

I suggest always adding braces around code blocks, e.g. for the code above:

if (test.searchFile("hey")) {
    test.output(cout) << endl;
}

A modified version

I have modified the original code to demonstrate usage of exceptions, and include some of the other suggested changes. Note, that by removing some of the methods most of the "illegal state" problems can be fixed as well.
I did not address the "idempotency" issue.

// search.cpp

//#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class FileNotFoundException {};
class IllegalArgumentException {};

class file {
public:
    file(const string &fileN) : fileStream(fileN.c_str()) {
       if (!fileStream) {
          cerr << "Invalid file closing" << endl;
          throw FileNotFoundException();
       }
    }
    ~file() {
       if (fileStream) {
          fileStream.close();
       }
    }

    int searchFile(const string&);
private:
    ifstream fileStream;
};

int file::searchFile(const string &tWord) {
    if (tWord.empty()) {
       cerr << "Word is empty" << endl;
       throw IllegalArgumentException();
    }
    string temp;
    int occured = 0;
    while (fileStream >> temp) {
        if (temp == tWord) {
            ++occured;
        }
    }
    return occured;
}

int main(int argc, char * argv [])
{
    try {
        file test("stdafx.h");   // does not exist on my system
    }
    catch (const FileNotFoundException &) {
        cerr << "FileNotFoundException caught!" << endl;
    }

    file test2("search.cpp");  // it is this file
    const int foundCnt = test2.searchFile("file");

    cout << "Found " << foundCnt << " occurrences. " << endl;

    file test3("search.cpp");
    try {
        const int foundCnt2 = test3.searchFile("");
    }
    catch (IllegalArgumentException &) {
        cerr << "IllegalArgumentException caught!" << endl;
    }

    return 0;
}

Note that by having the constructor throwing an exception if the file name is invalid, we prevent the file object from being used in an invalid state. The reason is, that (in our example above), we cannot use the object test after this line:

  file test("stdafx.h");   // does not exist on my system


#include

The code was in error until I prefixed it with

#include <vector>
#include <iostream>

~CircularBuffer()

There's no need to define a destructor that does nothing - just let the compiler generate a default one.

If you wanted this to be a base class, you would provide a virtual destructor, but you can explicitly default it:

virtual ~CircularBuffer() = default;

I'd say that you are right to omit copy constructor and assignment operator, as the compiler-provided ones will work correctly.

empty()

The reason containers have empty() is so that it can be quicker than testing size is non-zero.  So implementing empty() in terms of size() should be a last resort.  In this case, we set head negative to indicate an empty buffer, so we can just test that:

bool empty() const
{
    return head < 0;
}

Note that I've made this a const method, as we may want to call it on a buffer we don't intend to modify.

size()

There's no need for the sz variable, as we set it only to return immediately:

size_t size() const
{
    if (head < 0)
        return 0;
    if (next > head)
        return next - head;
    return next + (data.size() - head);
}

I've made this const, too, and changed the return type to be more in line with what users will expect.  If I were to be really pedantic, I'd consider std::vector<char>::size_type, and adjust the head and next members accordingly.

You could write a single return with a tertiary expression here, but I think the if ladder is slightly clearer - that's obviously a judgement call.

push()

As in empty(), it's inefficient to call size() when we just want to know whether the container is full.  Instead, we can just test next == head.  If you must produce output, send it to std::cerr, not std::cout!  Generally, in a library, it's better to report the error to the caller (by exceptions, or perhaps as a return value) rather than to output diagnostics ourselves, but I'll let that stand for now.

It wasn't obvious at first reading that if head was negative, then we could depend on next being zero.  I would probably not made that assumption, and written something like:

    data[next] = val;
    if (head < 0)
        head = next;
    if (++next == data.size())
        next = 0;

pop()

Most of the critique of push() applies here, so I won't repeat it.  It's not clear why -1 is chosen as the value to return on failure - was this specified in the requirements?

main()

You provide no main() function, which is a shame - it would have been nice to use your unit tests when refactoring.

Modified version

I changed the index types to size_t, and defined a constant to indicate empty (as size_t doesn't have negative values).

#include <vector>
#include <stdexcept>

class CircularBuffer
{
    static const size_t EMPTY = ~0u;

    std::vector<char> data;
    size_t next = 0;               // index at which next insert will occur
    size_t head = EMPTY;           // index of next pop, or EMPTY marker

public:
    CircularBuffer(size_t size)
        : data(size)
    {
    }

    virtual ~CircularBuffer() = default;

    bool empty() const
    {
        return head == EMPTY;
    }

    size_t size() const
    {
        if (empty())
            return 0;
        if (next > head)
            return next - head;
        return data.size() - head + next;
    }

    void push(char val)
    {
        if (next == head)
            throw std::logic_error("Buffer overrun");

        data[next] = val;
        if (empty())
            head = next;
        if (++next == data.size())
            next = 0;
    }

    char pop()
    {
        if (empty())
            throw std::logic_error("Buffer underrun");

        const char popVal = data[head];

        if (++head == data.size())
            head = 0;

        if (head == next)
            head = EMPTY;

        return popVal;
    }
};

Future directions

If you want to set yourself some more challenges, I'd recommend looking at the standard containers (especially std::queue) and seeing how you can make the interface look more like theirs.  Implement front() and back() (easy!), emplace(), and some iterators.

Also, you might want to make this a template class, so it can hold any kind of element, not just char.


As you may have probably suspected, the list comprehension in processTweets makes this non-streaming and eat a lot of memory, as it has to contain the entire result dictionary in memory before returning to the caller. Which might be fine, as it's just a list of integers.

You can make this streaming by turning this method into a generator:

def processTweets(path, sentimentsDict):
    with open(path) as fh:
        for tweet in fh:
            yield processTweet(tweet, sentimentsDict)

Note that I renamed your variables (file -> path, tweetFile -> fh, because file shadows an existing Python class name (and usually syntax highlighted), and because I like to use fh for throwaway filehandles ;-)

You don't need the default False value in tweetJson.get('text', False), this will work just fine, because the .get will return None, which is falsy:

tweetText = tweetJson.get('text')
if tweetText:
    return extractSentiment(tweetText, sentimentsDict)
else:
    return 0

In processTweet, you catch ValueError and raise an Exception. Since you are not doing anything special to handle the ValueError, you could just let the error bubble up, and it might speed up the process a bit if Python doesn't need to wrap the code within a try-catch for every single tweet.


Your main.js does not have a direct dependency on Animal class, so much there is no reason to import it there.  In fact, from standpoint of minimizing browser calls to include files, it might make better sense to keep all classes in a related hierarchy together in a single file. So, I would probably have Animal, Human, Cat and Dog in the same file unless the was a compelling reason to split them - like Human was used on every page while Cat an Dog were only used sparingly in the site.

Generally, it is a good idea to be consistent about what sort of “side effects” a piece of code (class) makes.  I know this is just an example, but it seems odd for these classes to log out the results of the speak() methods, when it really is the caller that should determine what happens with the result of the method call (logging it, updating Page with it, etc.)

Main.js seems a little odd with regards to why you are exporting the updateScreen function. This function doesn’t really do anything different after the first time it is executed so not sure why it is exported as a function. Also, this module creates the side effect off all of the instantiated objects speaking upon inclusion of the module.  This would happen even if the updateScreen function was never called. Again this seems like odd behavior to be happening upon import.

In Human class, is date of birth a property specific only to humans, or should this exist on Animal class.  You should consider passing and setting a proper date object for this property.  Should age be a property on the object?  This is able to be determined in the constructor, right? It seems odd to me to have getter method for this “property” and not the others. In the age getter, there is reference to “now” variable that is undefined and you are further trying to perform subtraction using dob string value that has not been converted to proper Date object.  Use Dates here for this math.

In Dog class to have especially questionable side effect in the speak method in that you have hard coded a reference to a div to be updated.  This class should not need to understand Dom at all. The way it is now limits reuse of this class because it is tightly coupled to the Dom via this logic which has nothing to do with a dog at all.


Generic dynamic array implementation in C

See
this Stackoverflow answer for
a discussion on the optimal growth factor for dynamic
arrays. The gist of it is that it depends, but growth
factors around the golden ratio are easier for the memory allocator to
handle. I'd recommend using 1.5 because it is easy to implement:

DEST->cap += DEST->cap / 2

It likely fares worse on artifical benchmarks but better on real
workloads. This requires that the minimum capacity of the dynamic
array is 2 which is reasonable. But a more realistic minimum size
likely should be 8 or 16 since
the minimum malloc size is 32
bytes.

In aAppend you are always realloc:ing which will cause performance
to suffer if many small dynamic arrays are collected into one big one
in a loop. Instead, you want something like:

size_t req = DEST->size + X->size;
if (req > DEST->cap) {
    aResize(DEST);
}
memcpy(DEST->data + DEST->size, X->data, X->size * X->typeSize);
DEST->size = req;

The last thing I'd change is the alignment of the capacity to a power
of two in aInit. On realistic workloads, a good chunk of all
variable arrays never grow so the alignment just wastes space. But
if you insist on alignment, this function is better than the loop:

static inline int
next_pow2(int v) {
    v--;
    v |= v >> 1;
    v |= v >> 2;
    v |= v >> 4;
    v |= v >> 8;
    v |= v >> 16;
    v++;
    return v;
}

I also wonder why you are using macros when C99 has inline functions?
They have many advantages in comparison to code macros.


Finding if a given number is in a given range based on a flag

The logic is confusing. A direct translation of the problem specification is possible, and clearer.

Let's deal with the first half of the problem:

  Given a number \$n\$, return True if \$n\$ is in the range \$1 ..10\$, inclusive.

Then it's natural to write:

def in1to10(n):
    return 1 <= n <= 10

Now we can deal with the second half:

def in1to10(n, outside_mode):
    if outside_mode:
        return n <= 1 or n >= 10
    return 1 <= n <= 10


I would approach that like this:

Have an array with all the fields you

var mandatoryFields = ['firstAttr','secondAttr'];

Then have a validate function that takes attrs, mandatoryFields and errors

function validate( o , mandatoryFields, errors )
{
  for( var i = 0 , i < mandatoryFields.length ; i++ )
  {
    var field = mandatoryFields[i];
    if(!o[field])
      errors.push(field + " mandatory");
  }
}

Note that I replaced attrs with fields but fare more readable, I also added a new-line  after that if statement for readability.


The API of your class: in my opinion, there should be one more method: getMin that returns the minimum element but not removes it. The only way to get it now without deleting is to call deleteMin and then re-insert it into the heap, which is inconvenient and inefficient.
There is a bug in the deleteMin method. The fact that pos * 2 + 1 is less than size does not imply that pos * 2 + 2. It can lead to a NullPointerException. I have written a simple unit test that exposes the problem:

import org.junit.Test;

import static org.junit.Assert.*;

public class HeapTest {

    @Test
    public void testDelete() throws Exception {
        Heap<String> aHeap = new Heap<String>();
        aHeap.insert("a");
        aHeap.insert("b");
        aHeap.insert("c");
        assertEquals("a", aHeap.deleteMin());
    }
}

The result:

java.lang.NullPointerException
    at java.lang.String.compareTo(String.java:1142)
    at java.lang.String.compareTo(String.java:111)
    at Heap.deleteMin(Heap.java:33)
    at HeapTest.testDelete(HeapTest.java:13)

You should always test your code in a systematic manner. Unit tests are a good way to do it. They will help you to find and fix bugs and to make sure that it works properly(but not to prove its correctness, of course). They will increase maintainability and reliability of your code. You should write unit tests for all public methods. Do not forget to test edge cases(deleting an element from an empty heap and so on).
You expand an array when necessary, but you never shrink it. It can lead to a big memory overhead. For example, if we insert a lot elements into the heap and then remove most of them, the array will not shrink, consuming much more memory than necessary. You can fix it by either adding a shrinkArray method or by using a List instead of an array here. An ArrayList can handle all required operations for you. So I would use it, unless you decided not to use a List on purpose as an exercise. If it is the case, I'd still recommend creating another class that implements the List interface(or provides a similar functionality) to decouple a heap from a dynamic array. It will make your code more readable, flexible(what if you decide to change the implementation of a dynamic array one day?) and testable.
Code style:

It is conventional to surround binary operators with whitespaces. There should also a whitespace between an if, for or while keyword and an opening parenthesis. Here is a small piece of your code rewritten according to the style conventions:

while (pos != 0 && array[pos].compareTo(array[pos / 2]) < 0) {
    temp = array[pos / 2];
    array[pos / 2] = array[pos];
    array[pos] = temp;
    pos /= 2;
}

Blank lines: a lot of blank lines inside one method don't look good, in my opinion. They can be used for separating different logical blocks of code from each other(but in this case it might be better to create two separate methods instead), but they are definitely redundant in small methods(which is the case here).
In general, it is possible to make your code more concise by using the Java standard library. For instance, you can use an Arrays.copyOf method instead of the expandArray. But I believe that it is fine here because it is an exercise, not a production code(otherwise, you could have just used a PriorityQueue, but that's obviously not what you want in this case).

You should write doc comments for all public classes and methods.

Summary:

To improve you code, you can do the following:

Write unit-tests.
Write doc comments.
Adhere to the code style conventions.
Design classes in such a way that one class is responsible for one concern.


Circular buffer offsets and sorted set of offsets sorted on their index

One way is to supply uint16_t as the third template argument to boost::counting_iterator so that it allows wrapping around, allowing the code to be greatly simplified:

#include <algorithm>
#include <deque>
#include <boost/iterator/counting_iterator.hpp>

// Assumes _count == 65536 (0x10000)
typedef boost::counting_iterator<uint16_t,
                                 boost::use_default,
                                 uint16_t> uint16_wrapping_counting_iterator;

// Insert the inclusive range [beginOffset, lastOffset] into the recentItems
// ordered deque of offsets.  The offsets are into a circular array of 65,536
// items, so the range may wrap around.  The ordering of the offsets is based
// upon the index that corresponds to each offset.  For example, a beginOffset
// of 65,000 and a lastOffset of 100 means to insert the range of offsets
// [65000, 65535] into the deque at insertionPoint followed by the range of
// offsets [0, 100] and the beginOffset of 65,000 may correspond to an index of
// 65,000 but the lastOffset of 100 could correspond to an index of 65636 for
// the first time the circual buffer to which these offsets refer wraps around.

void
insertRecentRange(const int beginOffset,
                  const int lastOffset,
                  std::deque<int>::iterator insertionPoint,
                  std::deque<int> &recentItems)
{
  const uint16_t startOffset = uint16_t(beginOffset);
  const uint16_t endOffset   = uint16_t(lastOffset + 1);

  // The recentItems is an ordered set of offsets that have been noted.
  recentItems.insert(insertionPoint,
                     uint16_wrapping_counting_iterator(startOffset),
                     uint16_wrapping_counting_iterator(endOffset));
}


Comparing products sold by several merchants

The ORDER BY inside the inner-most sub-select is pointless - it's going to get thrown out.  Also, you should never rely on MySQL's behaviour of selecting a 'random' value for non-grouped columns - always explicitly specify the transformation that needs to happen on the data.  You should also review what you think your Company columns are, as I am going to pretty much guarantee that the company isn't the same for every cell in the column.

EDIT:

Actually, I was thinking your ORDER BY in the GROUP_CONCAT() was just fine - I have issues with how you're doing your inner-most SELECT... ORDER BY (that you then do a GROUP BY off of, without specifying your transforms).
Assuming that the tuple [parts_data.part_id, parts_data.date] is unique (although, that's the date of what?  Insert, update, your birthday?  Please name more descriptively), here's how I would have structured this (in a system without CTEs and OLAPs):

SELECT `a`.`part_number`, GROUP_CONCAT(`a`.`seller_id` ORDER BY `b`.`price` ASC),
                          GROUP_CONCAT(`b`.`part_id` ORDER BY `b`.`price` ASC),
                          GROUP_CONCAT(`b`.`price` ORDER BY `b`.`price` ASC)
FROM `parts` as `a`
LEFT JOIN (`parts_data` as `b`
           INNER JOIN (SELECT `part_id`, MAX(`date`) AS `date`
                       FROM `parts_data`
                       GROUP BY `part_id`) as `c`
           ON `b`.`part_id` = `c`.`part_id`
           AND `b`.`date` = `c`.`date`)
ON `a`.`part_id` = `b`.`part_id`
GROUP BY `a`.`part_number`
ORDER BY `a`.`part_number`

Please note that I do not in fact have a MySQL instance to test against.  I also don't know if this will be faster for your database (please note we now have a self-join).  However, it's much clearer what you're expecting the system to do, meaning it's easier to maintain.

EDIT:

Here's an alternate version, which may be slightly faster.  I don't work with MySQL (and I have some fairly serious hardward backing me up on DB2), so I'm not up on all the ins and outs.

SELECT `a`.`part_number`, GROUP_CONCAT(`a`.`seller_id` ORDER BY `b`.`price` ASC),
                          GROUP_CONCAT(`b`.`part_id` ORDER BY `b`.`price` ASC),
                          GROUP_CONCAT(`b`.`price` ORDER BY `b`.`price` ASC)
FROM `parts` as `a`
LEFT JOIN (SELECT `b`.`part_id`, `b`.`price`
           FROM `parts_data` as `b`
           WHERE NOT EXISTS (SELECT '1'
                             FROM `parts_data` as `c`
                             WHERE `c`.`part_id` = `b`.`part_id`
                             AND `c`.`date` > `b`.`date`)) as `b`
ON `b`.`part_id` = `a`.`part_id`
GROUP BY `a`.`part_number`
ORDER BY `a`.`part_number`

You may want to try removing the ORDER BY a.part_number clause, and see if that helps.


Since you state that you're using Java 8, you should use the variety of new Comparator static methods to extract the relevant fields for comparison:

public int compare(Sku o1, Sku o2) {
    Comparator<Sku> c1 = Comparator.nullsLast(null);
    return c1.thenComparing(Sku::getSkuNumber,
            Comparator.nullsLast(Comparator.naturalOrder())).compare(o1, o2);
}

When Comparator.nullsLast(Comparator) is given a null argument, it considers two non-null argument to be equal. This is the basis of our first comparator.
We then need to compare by getSkuNumber(), so we pass the method reference Sku::getSkuNumber to Comparator.thenComparing(Function, Comparator) as our second comparator. However, since SKU numbers may be null, we use a nested (or tertiary?) null-friendly comparator, Comparator.nullsLast(Comparator) again, as the second argument. The final comparator in use is just Comparator.naturalOrder(), which performs the final straightforward integer comparison if both SKU numbers are non-null.

edit: @Simon mentioned a good point that since your existing compare(Sku, Sku) method is likely to be the implementation for implementing Comparable<Sku>, you should consider making the Comparator I suggested above a public static final field, so that it doesn't have to be created every time, e.g.:

public static final Comparator<Sku> COMPARATOR =
                        Comparator.nullsLast((Comparator<Sku>) null)
                            .thenComparing(Sku::getSkuNumber,
                                Comparator.nullsLast(Comparator.naturalOrder()));


Bringing content from other pages without refreshing the entire page

You seem to have some copy pasted code there.

How about

function enableLinks( selector , path , container )
{
  /* Allow ajax to work */
  $( selector ).click( function()
  {
    var page = this.hash.substr(1);
    $.get( path + page + ".php", function( html )
    {
      $( container ).html( html );
    });
  });
  /* Allow bookmarks to work */
  if ( location.hash )
    $("a[href="+location.hash+"]").click();
  else
    $(selector).click();
}

$(function()
{
  enableLinks( "#nav-tabs-list a" , "content/" , "#content-container" );
  enableLinks( "#sidebar-container #sidebar-tabs-container a" ,
               "content/sidebar-content/" ,
               "#sidebar-content-container" );
});

The things you do with location.hash are a bit of a mystery to me.


Generate 6 random numbers for lottery in PHP

Your algorithm is functional, but is not necessarily very efficient, and it will collide more, and more often if the count of numbers increases.

It's generally neater to start off with a unique set of numbers, and to extract a random selection of those numbers, instead of selecting random numbers, and testing for uniqueness.

PHP makes this relatively neat, because it has a built-in shuffle function (that's essentially doing a Fisher-Yates shuffle using the same random system that you are).

So, get an array of the unique values, shuffle it, take a selection of it, and sort the result:

$count = 6;
$highball = 45;
$numbers = range(0, $highball);
shuffle($numbers);
$drawn = array_slice($numbers, - $count);
sort($drawn);

Note, using named variables instead of constants makes it clearer what you are doing.

See this running on ideone: https://ideone.com/1Hh0y8


simplifying regex expression for timestamp

Some minor tips:

Add "^" and "$" to your regex to ensure your input string doesn't contain anything but a date
No brackets are needed around the [M] - A simple M means the same thing
Instead of checking for AM/PM with [A|P][M], keep the AM/PM characters together, like this: (AM|PM) - it makes it much more readable.
Since it's impossible to accurately test numeric ranges of a date-string in regex, I wouldn't even attempt it. If you really want to ensure the numbers fall into a valid range, do so after the fact, outside of the regex. Inside the regex, you can simply use \d to match any digit.

After applying these tips, you'll be left with a pretty simple regex that looks like this:
/^\d\d-\d\d-\d\d\d\d \d\d:\d\d (AM|PM)$/

As an aside, you might notice it's possible to remove a little repetition in the regex with \d{2} or \d{4}, but don't bother. There's not really a lot of repetition, and the {2}/{4} will just obfuscate what you're trying to accomplish here.
Depending on your use case, simply using the above regex might be good enough, but if you also want to ensure the numbers fall into a valid range, I would actually parse the numbers out of the date-string, feed them into Javascript's Date class, and verify the numbers using the date instance. Relying on the built-in Date class will help with edge cases, such as leap years. In the below code snippet I am assuming that these date-strings are in UTC

function validateDateString(dateStr) {
  const regex = /^(\d\d)-(\d\d)-(\d\d\d\d) (\d\d):(\d\d) (?:AM|PM)$/;
  const match = regex.exec(dateStr);
  if (!match) return false;

  const [month, day, year, hr, min] = match.slice(1).map(Number);
  const date = new Date(Date.UTC(year, month-1, day, hr, min));
  return (
    year === date.getUTCFullYear() &&
    month === date.getUTCMonth() + 1 &&
    day === date.getUTCDate() &&
    hr === date.getUTCHours() &&
    min === date.getUTCMinutes()
  );
}

console.assert(validateDateString('11-30-1999 12:34 AM'));
console.assert(!validateDateString('13-30-1999 12:34 AM'));
console.assert(!validateDateString('1x-30-1999 12:34 AM'));
console.log('Done')

The important thing to understanding how the above code snippet works, is to understand what happens when you give new Date() (or in this case, date.UTC()) a too-big number. If, for example, you passed in 5 for the hours and 70 for the minutes, then it'll normalize the values by moving an hour worth of time from the minutes to the hours, leaving it with 6 as the hours and 10 as the minutes.
Here's what this looks like in action:
> const d = new Date(0, 0, 0, 5 /* hours */, 70 /* minutes */)
> d.getHours()
6
> d.getMinutes()
10

In the above example, it's easy enough to test that a numeric overflow happened, we just need to compare our input numbers with our outputs. We can quickly see that 5 !== 6 and 70 !== 10, so some sort of overflow must have happened, which means our date string was not valid. This is the same principle being used in the above code snippet - we just test each input with each output to ensure nothing overflowed.


Matching a set of conditions based on keywords to text

1. Difficulties

The approach taken in the post is to use string operations to transform the input into a Python expression and then evaluate the result.

The trouble with this approach is that the string comes from a user, who may not enter exactly what you expect. So handling of erroneous input is vital. For example, suppose I want to know if text contains "dog". The first thing I would try is dog:

>>> eval(text2cond(_text, 'dog'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 0

    ^
SyntaxError: unexpected EOF while parsing

Ok, maybe I need parentheses? What about (dog):

>>> eval(text2cond(_text, '(dog)'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    (False
          ^
SyntaxError: unexpected EOF while parsing

Ok, I suppose I have to use an operator too? I'll try (dog OR dog):

>>> eval(text2cond(_text, '(dog OR dog)'))
True

Suppose that I want case-insensitive matching of two words? I might try *(dog AND horse)*:

>>> eval(text2cond(_text, '*(dog AND horse)*'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'Falseand' is not defined

Ok, maybe I need more parentheses? What about (*(dog AND horse)*):

>>> eval(text2cond(_text, '(*(dog AND horse)*)'))
False

Which is misleading — what I should have written is (*dog* AND *horse*):

>>> eval(text2cond(_text, '(*dog* AND *horse*)'))
True

I think that users will find this behaviour hard to cope with. Of course you can go through the code and try to fix up these cases as users discover them. But how can you be sure you have caught everything? And even if you've caught all the cases, the SyntaxError that you get if the user makes a mistake are not likely to be very friendly.

>>> eval(text2cond(_text, '(dog AND horse OR cat)'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    (True and or False)
               ^
SyntaxError: invalid syntax

The other problem is that using eval on text that comes from the user is risky — if you didn't manage to completely sanitize the input, then the user may be able to run arbitrary code.

2. The standard approach

The standard approach to this kind of problem is parsing. The idea is to break down the problem into three processing stages:

Tokenization. In this stage the input string is turned into a sequence of tokens (pieces which can't be further broken down). For example, given this input:

((dog OR cat) AND *Horse*)

the tokenizer might emit this sequence of tokens:

'(', '(', 'dog', 'OR', 'cat', ')', 'AND', '*', 'Horse', '*', ')', '<end of input>'

Parsing. In this stage the sequence of tokens is turned into a parse tree, a data structure corresponding to the syntactic structure of the input. For example, given the input above, the parser might construct the following data structure:

BinOp(
    left=BinOp(
        left='dog',
        op='OR',
        right='cat'),
    op='AND',
    right=IgnoreCase(
        body='Horse'))

Evaluation. This is easy to do by a depth-first pass over the parse tree.

There are several good reasons to solve the problem using this approach:

It's the standard approach, so other programmers will easily understand how it works.
It's efficient: each stage needs to pass over its input exactly once.
Splitting the work into steps with clearly defined inputs and outputs makes it easier to test.
The approach extends to more complicated applications, such as interpretation of programming languages.

3. Tokenization

In Python an easy way to tokenize a string is to use the finditer method on regular expressions. A little bit of care has to be taken to avoid gaps between tokens (other than whitespace, which you are allowing). This is done by having a "catch-all" alternative (\S) which matches any non-whitespace character that doesn't belong to a valid token.

import re

# Regular expression matching a token (group 1) or an error (group 2).
_TOKEN_RE = re.compile(r'\s*(?:([()*]|\w+\b)|(\S))')

# Token representing the end of the input.
TOKEN_END = '<end of input>'

def tokenize_condition(s):
    """Generate the tokens in the condition s.

    >>> list(tokenize_condition("((dog OR cat) AND *Horse*)"))
    ['(', '(', 'dog', 'OR', 'cat', ')', 'AND', '*', 'Horse', '*', ')', '<end of input>']

    """
    for match in _TOKEN_RE.finditer(s):
        token, error = match.groups()
        if error:
            raise SyntaxError("unexpected character {!r}".format(error))
        yield token
    yield TOKEN_END

4. Parsing

(In this section I'm using a simplified version of your language, lacking the NOT operator.)

First, we'll need a data structure to represent the parse tree. Here I'm going to use collections.namedtuple:

from collections import namedtuple

# Binary operation with left operand, operator and right operand.
BinOp = namedtuple('BinOp', 'left op right')

# Ignore case when matching against body.
IgnoreCase = namedtuple('IgnoreCase', 'body')

A word to be matched like dog will be represented by a string.

Second, the parser. There are lots of different techniques for writing parsers. I could use a parser generator like pyparsing, that constructs the parser from a representation of a formal grammar, but I think it's more illustrative to write a recursive descent parser by hand.

def parse_condition(tokens):
    """Parse a condition given by an iterator of tokens, and return a
    parse tree.

    >>> tokens = tokenize_condition("((dog OR cat) AND *Horse*)")
    >>> parse_condition(tokens)
    BinOp(left=BinOp(left='dog', op='OR', right='cat'), op='AND', right=IgnoreCase(body='Horse'))

    """
    token = next(tokens)           # The current token.

    def error(expected):
        # Current token failed to match, so raise syntax error.
        raise SyntaxError("Expected {} but found {!r}"
                          .format(expected, token))

    def match(*valid_tokens):
        # If the current token is found in valid_tokens, consume it
        # and return True. Otherwise, return False.
        nonlocal token
        if token in valid_tokens:
            token = next(tokens)
            return True
        else:
            return False

    def term():
        # term ::= ( binop ) | * binop * | WORD
        if match('('):
            tree = binop()
            if match(')'):
                return tree
            else:
                error("')'")
        elif match('*'):
            tree = binop()
            if match('*'):
                return IgnoreCase(tree)
            else:
                error("'*'")
        elif token in (')', 'AND', 'OR'):
            error("term")
        else:
            t = token
            match(token)
            return t

    def binop():
        # binop ::= term | term OR term | term AND term
        left = term()
        op = token
        if match('AND', 'OR'):
            right = term()
            return BinOp(left, op, right)
        else:
            return left

    tree = binop()
    if token != TOKEN_END:
        error("end of input")
    return tree

5. Evaluation

I'll leave the details of evaluating of the parse tree as an exercise. What we want is something like this:

def evaluate_condition(text, tree, ignorecase=False):
    """Return true if the expression given by the parse tree matches the text.

    >>> tokens = tokenize_condition("((dog OR cat) AND *Horse*)")
    >>> tree = parse_condition(tokens)
    >>> evaluate_condition("horse", tree)
    False
    >>> evaluate_condition("cat on a horse", tree)
    True
    >>> evaluate_condition("horse with a dog", tree)
    True

    """
    if isinstance(tree, str):
        # search for tree in text, ignoring case if ignorecase=True
    elif isinstance(tree, BinOp):
        # evalute tree.left (and maybe tree.right) recursively; apply op
    elif isinstance(tree, IgnoreCase):
        # evaluate tree.body, passing ignorecase=True
    else:
        # raise an error

6. Conclusion

The code here is substantially longer than the code in the post, but has these advantages:

It handles the difficult examples I gave in section 1.
It generates reasonable (if not great) syntax error messages.
Because you are in charge of generating the error messages (rather than delegating them to Python) you can improve them if you need to.
It is straightforward to extend this to handle more syntax features (such as the NOT operator).
You can start to think about how to improve the performance, for example if your have a node in the parse tree of the form BinOp(left=word1, op='OR', right=word2) then you could evaluate this in just one pass over the text instead of two. This kind of transformation is much easier to do here when you have a parse tree to work on.


Writing unit tests for exception should be thrown case

You should be using the Chai assert.throws operator instead (http://www.chaijs.com/api/assert/#method_throwsO so your code might look like:

it('should throw exception if config.env.json is malformed', async () => {
  // Arrange: beforeEach
  const fakeFsStub = sinon.stub(File, 'readFileAsyc');
  fakeFsStub.withArgs('./src/configuration/config.json').returns(mockConfig);
  fakeFsStub.withArgs('./src/configuration/config.test.json').returns(FakePromise.resolve(`{"key"}`));

  chai.assert.throws( () => {
      // Act
      await Configuration.getConfiguration('test');
    },
    SyntaxError,
    'test case failed: [should throw exception if config.env.json is malformed]'
  );

});

Also it is not generally a good idea to test the string returned by an exception. There is no guarantee that it will be the same between different browsers or different browser versions. If you need to check the position you should use the lineNumber and columnNumber properties of SyntaxError (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError)

Lastly concating with '' to perform a string conversion is not the best option either use e.messaage attribute of an exception or the toString() method available on pretty much all objects.


Inserting a node at a specific position in a linked list

Avoid special cases

If position == null the new node becomes head no matter what, and you don't need to care what the head was before.

Similarly, the validity of position is determined in a traversal loop (if (current == null) condition); testing specifically for head == null && position != 0 is premature.

BTW, the code handles invalid position inconsistently. Yet another cause to avoid special cases.
Avoid naked loops

Every loop does an important job, and deserves a name. The loop

for(i = 0; i < position; i++)

serves a purpose of finding a node at the particular position. Factor it out into a method and name it properly.


Finding the positive numbers count in an ECMAScipt array

I don't think there is much to review, it looks ok. I would just do it inline, and there is no need to list arguments you are not using:

var positiv = arr.reduce(function(acc, x) {
  return x > 0 ? acc + 1 : acc;
}, 0);


First the obvious stuff: the real std::latch::arrive_and_wait is specified to take a ptrdiff_t parameter that defaults to 1, but would also support e.g. myLatch.arrive_and_wait(2). Also, there are more member functions than just arrive_and_wait.

I'd call your thing a "spinlatch" (by analogy to "spinlock"), because it doesn't actually put the thread to sleep — it has an operation named arrive_and_wait that doesn't actually do any waiting! It just keeps loading and loading the atomic variable until it sees zero.

To make it actually wait, you could use the also-new-in-C++20 futex facilities of std::atomic, like this:

void arrive_and_wait(int n = 1) {
    int current = (count -= n);
    if (current == 0) {
        count.notify_all();
    } else {
        while (current != 0) {
            count.wait(current);
            current = count.load();
        }
    }
}

No comment on the memory orders.


Return a rank for string of letters based on alphabetical permutations

Your program should be able to accept any word 25 letters or less in length

The largest possible answer then is \$25! = 15511210043330985984000000\$. This value won't fit in an int, a long, or even a ulong. I would recommend using a BigInteger.


#includeing source files

A very big issue - especially if you're planning on writing a library:

You include a C source file to use printDebug. You shouldn't do that to avoid possible name collisions between the #includeing file and the #included file, as all of the advantages you had from the header guards are absent when you import the source file itself instead of the header.

The header represents the public interface of the code, so always include that to avoid name collision issues and not depend on implementation details, like internal functions (not that you do that now, but for the future).

The problem with doing this right now would be that you have not put your function declarations in the header. Declare printDebug in the header (I guess you already know how to do this, as you've already done it for evaluate), and you're ready to use it from your main source - just include debug_util.h instead of debug_util.c.

Weird and missing #includes

What is that #include <zconf.h> doing in debug_util.h? as far as I could find out, it's for the compression library zlib, which you don't seem to be using. Also, you should #include <stdarg.h> in debug_util.h to get standards-compliant behavior and compiler portability for the va_* macros you use in debug_util.c.

You should #include <stdio.h> in your main file too, as you're using printf. The header guard is in debug_util.h to save you from the multiple-include problem.

Style and Convention

Your coding style is fine, but you should use int main(void) to indicate that main takes no parameters, as main() indicates (counterintuitively) that main
 can take any number of parameters.
return 0; at the end of main is only optional in C99 mode and above, so you might want to document that.
ALL_CAPS names are generally reserved for macro definitions - use normal variable naming for constants.
DEBUG as declared in debug_util.c and debug_util.h could be const bool - don't assign it in debug_util.c and just leave it for the user to do it.
Or you could use a DEBUG macro definition and #ifdef/#ifndef checks to do this, as every debug library does by convention; using #ifdef checks means you can even choose to leave out the compilation of printDebug in release builds (it can be an empty function in release builds given its conditional definition, which would cause the call to printDebug to be optimized away.

An example of this idea:

debug_util.h

#ifndef DEBUG_UTIL_H
#define DEBUG_UTIL_H

#ifndef _STDIO_H_
#include <stdio.h>
#endif

#ifndef _STDBOOL_H
#include <stdbool.h>
#endif

int printDebug(const char*, ...);

#endif //DEBUG_UTIL_H

debug_util.c

#include "debug_util.h"

//Only prints if the global DEBUG flag has been set to true
//Replicates code from printf()
int printDebug(const char *format, ...)
{
#ifdef DEBUG
     int done = 0;
     va_list arg;

     va_start (arg, format);
     done = vfprintf (stdout, format, arg);
     va_end (arg);
#else
     return 1;
#endif
}

In the main code, just do a #define DEBUG 1 after #include "debug_util.h", or pass the -DDEBUG=1 option to gcc when compiling the main code.


Using Comprehensions to Handle a Large Dataset in Python 2.7

As requested:

Sort the list according to the component names. To achieve a correct order, either swap component names when necessary, or supply the custom comparator (which will account for (componentA, componentB) being the same thing as (componentB, componentA)).

Once the list is sorted, the entries to be tallied are adjacent, and an actual tallies could be computed in a single pass over the list.


I consider your solution to be hard to read, and also inefficient.

Readability

String tmpCh = new String("");
String tmpChRe = new String("");
String tmp = new String("");
int l = s.length();
int n = 0;
int j =0;

Of the six variables declared at the top, the only one whose meaning is obvious is l — and since you use l in only one place, I wouldn't even bother making a variable for it.

Your variable naming is problematic.  "tmp" is always meaningless as part of a local variable name; local variables are always, by definition, temporary.  Furthermore, a better way to indicate the temporary nature of these variables is to place them in the proper scope.  Instead of resetting them to empty strings at the end of your while(n>0) loop, declare and initialize them at the top of the loop, so that they are properly scoped:

// Useless assignment.  It gets reassigned right away inside the loop.
// j = 0;

// You only ever use n-1, then n is decremented at the end of the loop.
// So you might as well decrement it right away.
while (n-- > 0) {
    // Formerly j
    int parenStart = T[n] + 1;
    int parenEnd = s.indexOf(')', parenStart);

    // Formerly tmpCh
    String contents = s.substring(parenStart, parenEnd);

    // No need for tmpChRe.  No need for tmp.
    s = s.substring(0, T[n]) +
        new StringBuilder(contents).reverse() +
        s.substring(T[n] + contents.length() + 2);
}
return s;

Please put some spaces here:

for(int i=0;i<l;i++){

This would be more conventional and easier to read:

for (int i = 0; i < l; i++) {

Efficiency

Strings in Java are immutable.  Any time you concatenate strings using a + b, the compiler actually writes new StringBuilder(a).append(b).toString();.  That creates a lot of garbage, and it also involves copying the entire contents of both strings.  So, when you loops like this, which work build strings one character at a time, are hugely inefficient!

while(s.charAt(j)!=')'){
        tmpCh = tmpCh + s.charAt(j);
        j++;
}
for(int q=tmpCh.length()-1;q>=0;q--)
        tmpChRe = tmpChRe + tmpCh.charAt(q);

If you need to build a string by repeatedly appending characters, create one StringBuilder and append to it.  Note that StringBuilder also has a .reverse() method that would be helpful.

Suggested solution

This solution performs all of the manipulation within one char[] array, so there is hardly any new memory allocated.  It also validates that the input string's parentheses are properly matched; your code would either ignore mismatches or crash with an ArrayIndexOutOfBoundsException.

public static String reverseParentheses(String s) {
    char[] chars = s.toCharArray();
    int[] openPosStack = new int[chars.length];
    int openPosTop = -1;

    for (int i = 0; i < chars.length; i++) {
        switch (chars[i]) {
          case '(':
            // Push the index of the open parenthesis onto the stack
            openPosStack[++openPosTop] = i;
            break;
          case ')':
            // Reverse substring from the matching open parenthesis to here
            if (openPosTop < 0) {
                throw new IllegalArgumentException("Parenthesis mismatch");
            }
            int a, b;
            for (a = openPosStack[openPosTop--], b = i; a < b; a++, b--) {
                char swap = chars[a];
                chars[a] = chars[b];
                chars[b] = swap;
            }
        }
    }
    if (openPosTop >= 0) {
        throw new IllegalArgumentException("Parenthesis mismatch");
    }

    // Remove parentheses from output
    int o = 0;
    for (int i = 0; i < chars.length; i++) {
        switch (chars[i]) {
          case '(': case ')':
            break;
          default:
            chars[o++] = chars[i];
        }
    }
    return new String(chars, 0, o);
}


Using tweet as command to shut down Ubuntu

import tweepy
import os
from datetime import datetime
p=None

Use of single letter variable names is confusing, I have no idea what p is for.

api= tweepy.API()

Put spaces around your =

for status in api.user_timeline('tweetneag4'):
    while p==None:    #so that it checks only the first tweet

What are you thinking here? If p doesn't get set to a true value, you'll loop over the next block repeatedly in an infinite loop. If you only want the first tweet pass count = 1 to user_timeline

        if status.text.count(str((datetime.now().hour)+1))< 2 and str((datetime.time.now().hour)+1)==10:

            p=1

Setting flags is ugly. If you must set boolean flags use True and False not None and 1.

            pass
        elif str((datetime.now().hour)+1) in status.text:
            print "System shut down in 20 mins."
            os.system('shutdown -h +20')
            p=1

It seems to me that a much more straightforward way of doing this is to look at the time at which the status was posted. It seems to be available as status.created_at. Based on that you know that outage is either 30 or 10 minutes after that. So if it has been more then 30 minutes since that message, it must have already happened and we aren't concerned.

Something like this:

import tweepy
import os
from datetime import datetime, timedelta

api= tweepy.API()

status = api.user_timeline('tweetneag4', count=1)[0]
age = datetime.now() - status.created_at
if age < timedelta(minutes = 45):
    print "System shut down in 20 mins."
    os.system('shutdown -h +20')

NOTE: I get negative ages when I run this, I'm assuming that's time zones. Its also possible my logic is screwy.

If you really do need to get the actual time from the text, your current strategy of searching for numbers in the text is fragile. Instead you could do something like this:

# split the message up by whitespace, this makes it easy to grab the outage time
outage_time = status.split()[4]
# find everything up to the colon
hour_text, junk = outage_time.split(':')
# parse the actual hour
hour = int(hour_text)

Finally, for more complex examples using regular expressions to parse the text would be a good idea.


This is overall pretty reasonable code. It's very straightforward. Here are some things that could be improved:

Readabality

I find a few things hard to read. For example, putting not only multiple variable declarations on the same line, but assigning each one to a function call result is not fun to read. I would write each on its own line so it's more clear:

Line2d ab = t.getAB();
Line2d bc = t.getBC();
Line2d ac = t.getAC();

Same with the startY and endY variables:

int startY = (int) t.getA().getY();
int endY = (int) t.getC().getY();

Also, even though it's legal to omit the braces on single line if and for statements, it's a good idea to include them to avoid future bugs. I've seen plenty of code where someone added a line to a 1-line if statement without the braces and that line ended up always being executed. It ends up looking like this:

if (foobar)
    callFunction()
    callOtherFunction()

Because there are no braces, callOtherFunction() is always called regardless of the value of foobar.

Naming

Most of your function and variable naming is pretty good, but I would rename the set() function to setPixelColor() to make it more clear what you're setting. The names set() and get() are very overused in programming today, so it helps to be more specific.

Use Points in set() Function

Why separate out the x and y values of the point when calling set()? You should just make it accept a point parameter and do the getX(), getY() and type casting inside the function.

In fact, you do actually pass separate x and y values that are calculated inside the loop, so you might even want to overload it and create 2 versions, 1 that takes a point, and one that takes 2 coordinates, like this:

void setPixelColor(int x, int y, Color pixColor);

and

void setPixelColor(Point2d p, Color pixColor)
{
    setPixelColor((int)p.getX(), (int)p.getY(), pixColor);
}

Renderer Stuff

Most 3D renderers, like OpenGL, DirectX, Metal, etc. make a guarantee to never draw the same pixel twice for triangles that share an edge. I notice that your loops are including the start and end points of each row and column of pixels in the triangle. You might want to change the end condition to just < instead of <= to get this same sort of functionality.

Also, why are you coloring the corners of every triangle red? Was that just for debugging purposes?


(Self-answering for posterity.)

There's a major flaw in my above implementation of when_all: It calls .get()! This can cause the thread to block indefinitely. We need to eliminate that .get somehow, or at least make sure that we only ever call .get on a future that has just been passed in as the argument of a .then callback.

The reason I was calling .get was to work around a type incompatibility: the type of

auto SUBEXPRESSION =
    std::apply(w, rest).then([f = std::move(f)](auto future_of_tuple_of_rest) {
        return std::tuple_cat(std::make_tuple(std::move(f)), future_of_tuple_of_rest.get());
    })

is std::future<std::tuple<F, Rest...>>, which means that the type of

auto EXPRESSION =
    f.then([...](auto f) {
        return SUBEXPRESSION;
    });
});

is std::future<decltype(SUBEXPRESSION)>, which is to say std::future<std::future<std::tuple<F, Rest...>>>. That's too many futures! So I was trying to work around this by calling .get right before returning the "inner" future.

Turns out that boost::future and std::experimental::future (in the Concurrency TS) already have a solution for this problem. It's called .unwrap, and the idea is that if decltype(f) is future<future<T>>, then decltype(f.unwrap()) is future<T>.

In Boost's case, this is currently provided as a constructor explicit future(future<future>&&) instead of as an .unwrap member function, but there's a bug open to provide .unwrap directly.

In the Concurrency TS, .then also implicitly calls .unwrap on the callback's return value if that return value is seen to be of type future<future<T>>.

So my solution was simply to add a call to .unwrap (well, the Boost explicit constructor), and then everything was happy.

There's another showstopping problem with the above code: it doesn't compile for more than one argument, because I'm missing the mutable keyword on both of the lambdas involved. You can't "move out of" the captured f unless f is non-const, which means you need mutable on the inner lambda; and at least GCC is unhappy with std::apply(w, rest) unless rest is non-const, which means you need mutable on the outer lambda too.

Finally, I decided to stop trying to capture references to things, and just replaced everything with capture-by-value. This simplified the code to the point where I didn't see any reason to keep move_as_tuple as its own function at all.

My final code:

auto when_all() {
    promise<tuple<>> p;
    p.set_value({});
    return p.get_future();
}

template<class F, class... Rest>
auto when_all(F f, Rest... rest) {
    return future<tuple<F, Rest...>>(
        f.then([rest = make_tuple(std::move(rest)...)](auto f) mutable {
            auto w = [](auto... as) { return when_all(std::move(as)...); };
            return apply(w, std::move(rest)).then(
                [f = std::move(f)](auto future_of_tuple_of_rest) mutable {
                    return tuple_cat(make_tuple(std::move(f)), future_of_tuple_of_rest.get());
                }
            );
        })
    );
}


Print all possible sequences that could have created this BST

public class Solution {
    ArrayList<LinkedList<Long>> result;
    /*Return the children of a node */
    ArrayList<TreeNode> getChilden(TreeNode parent) {
        ArrayList<TreeNode> child = new ArrayList<TreeNode>();
        if(parent.left != null) child.add(parent.left);
        if(parent.right != null) child.add(parent.right);
        return child;
    }
    /*Gets all the possible Compinations*/
    void getPermutations(ArrayList<TreeNode> permutations, LinkedList<Long> current) {
        if(permutations.size() == 0) {
            result.add(current);
            return;
        }
        int length = permutations.size();
        for(int i = 0; i < length; i++) {
            TreeNode node = permutations.get(i);
            permutations.remove(i);
            ArrayList<TreeNode> newPossibilities = new ArrayList<TreeNode>();
            newPossibilities.addAll(permutations);
            newPossibilities.addAll(getChilden(node));
            LinkedList<Long> newCur = new LinkedList<Long>();
            newCur.addAll(current);
            newCur.add(node.val);
            getPermutations(newPossibilities, newCur);
            permutations.add(i,node);
        }
    }

    /*This method returns a array of arrays which will lead to a given BST*/
    ArrayList<LinkedList<Long>> inputSequencesForBst(TreeNode node) {
        result = new ArrayList<LinkedList<Long>>();
        if(node == null)
            return result;
        ArrayList<TreeNode> permutations = getChilden(node);
        LinkedList<Long> current = new LinkedList<Long>();
        current.add(node.val);
        getPermutations(permutations, current);
        return result;
    }
}

My solution. Works perfectly.


There's nothing wrong with this kind of assignment logic per se, but you usually don't want it cluttering up the rest of your application logic so it usually belongs in a constructor method. If you're using the GetBreakDownsReport() method to construct the source for a datagrid, replace your anonymous object with a BreakdownsReportViewModel object and make a constructor that handles all property assignments. This will have the added benefit of making your GetBreakdownsReport() method signature more expressive and easier to read.


SQL stored procedure that returns a boolean value?

Since SQL Server has no Boolean data type, and since the bit values 1 and 0 are widely used and understood to represent true and false in many programming languages, I would simply return 0x1 or 0x0 as appropriate. I don't think that actually declaring @true and @false variables adds anything to the code.

What might add something would be to return the value in an output parameter with a useful name:

CREATE PROCEDURE dbo.foo
    @IsTrue BIT OUTPUT
AS
BEGIN

IF (condition)
    SET @IsTrue = 0x1
ELSE
    SET @IsTrue = 0x0
END

Especially if your procedure is called from other TSQL code, it is much easier to use an output parameter in the calling code than a result set. But if you're calling it from some other language then you can make that decision based on the calling language and framework. An output parameter is the preferred way to return scalar values from a procedure: use SELECT for returning result sets and RETURN for indicating the status of the procedure execution itself (succeeded, failed, failed with reason X etc.).

And by 'useful name' I mean a name that indicates that the purpose of the variable is to store a true/false condition. Names starting with Is or Has are usually good. But please do not use a double-negative name: something like if @IsNotEnabled = 0x0 is extremely difficult to parse mentally without interrupting your thoughts. IsEnabled = 0x1 is far better.

And depending on your condition, you might be able to use CASE:

SET @result = CASE WHEN (condition) THEN 0x1
              ELSE 0x0
              END

Whether or not that's preferable in this specific case is probably a question of taste, but CASE seems more 'SQL-like' to me. But IF and CASE do different things so you can't always substitute one for the other.


Writing a byte array image to disk with an automatically generated filename

You're not closing the output stream! If that doesn't fix your issue, you'll have to post more contextual code, because after you free the output stream, the rest of this method should just free its resources after it is done.


Codewars: Reduce strings to one character

First I would choose a different representation of the colors during
the computation, to avoid the “expensive” COLORS-{a, b}).pop()
    operation, which is executed
$$
   (n-1) + (n-2) + \ldots + 1 = \frac{(n-1)n}{2}
$$
times for an input string of length \$ n \$. It becomes simpler if we
represent the colors as numbers instead, for example
$$
   \text{Red} = 0, \text{Green} = 1, \text{Blue} = 2 \, .
$$
Now the combination of two colors a and b can be computed as

a if a == b else 3 - a - b

without requiring any set or dictionary lookup. This leads to the
following implementation:

def color_to_num(col):
    """ Translate the colors 'R', 'G', 'B' to the numbers 0, 1, 2. """
    return 0 if col == 'R' else 1 if col == 'G' else 2

def num_to_color(num):
    """ Translate the numbers 0, 1, 2 to the colors 'R', 'G', 'B'. """
    return 'R' if num == 0 else 'G' if num == 1 else 'B'

def triangle(row):
    numbers = [color_to_num(col) for col in row]
    while len(numbers) > 1:
       numbers = [ a if a == b else 3 - a - b for a, b in zip(numbers, numbers[1:])]
    return num_to_color(numbers[0])

In my test (on a 1.2 GHz Intel Core m5 MacBook) this reduces the time for
an input string with 10,000 characters from (approximately) 18 seconds to
5.5 seconds.

But one can do better. The above solution still has a \$ O(n^2) \$ complexity.
In order to get rid of that, we need some mathematics (compare
Three Color Triangle Challenge
on Mathematics Stack Exchange).

The are two key observations:

If all (numeric) colors are viewed “modulo 3” then the combination of
\$ a \$ and \$ b \$ is just \$ -(a+b) \$.
The final color can be computed “directly” from the initial row, using
binomial coefficients (the numbers from Pascal's triangle).

Here is an example for the first observation: The combination of Red and Blue
is computed as
$$
  - (0 + 2) \bmod 3 = -2 \bmod 3 = 1
$$
and that is Green.

And an example for the second observation with an initial row of 4 colors:
$$
 a_0, a_1, a_2, a_3 \\
 -(a_0 + a_1), -(a_1 + a_2), -(a_2 + a_3) \\
 a_0 + 2a_1 + a_2, a_1 + 2a_2 + a_3 \\
 -(a_0 + 3a_1 + 3 a_2 + a_3)
$$

The general formula for an initial row of \$ n+1 \$ colors
$$
 a_0, a_1, \ldots, a_n
$$
is
$$
 \text{FinalColor} = (-1)^n \sum_{k=0}^n \binom{n}{k} a_k \bmod 3 \, .
$$

There is still one problem: the calculation of the binomial coefficients.
Using the definition
$$
 \binom{n}{k} = \frac{n(n-1) \cdots (n-k+1)}{k!}
$$
can lead to large intermediate results and has complexity \$ O(k) \$,
so that the total complexity is still \$ O(n^2) \$.

Here we need mathematics again: Lucas's theorem
provides a way to calculate \$  \binom{n}{k} \bmod p \$ efficiently
if \$ p \$ is a prime number. Luckily, 3 is a prime number!

This gives the following code:

def binomial_mod3(n, k):
    """ Compute the binomial coefficient C(n, k) modulo 3.

    It is assumed that 0 <= k <= n.

    The implementation uses Lucas's theorem, see for example
    https://en.wikipedia.org/wiki/Lucas%27s_theorem .
    """
    result = 1
    while n > 0:
        n3 = n % 3
        k3 = k % 3
        # 'Ad hoc' computation of C(n3, k3):
        if k3 > n3:
            return 0  # Return immediately if a factor is zero.
        temp = 1 if k3 == 0 or k3 == n3 else 2
        result = (result * temp) % 3
        n = n // 3
        k = k // 3
    return result

def color_to_num(col):
    """ Translate the colors 'R', 'G', 'B' to the numbers 0, 1, 2. """
    return 0 if col == 'R' else 1 if col == 'G' else 2

def num_to_color(num):
    """ Translate the numbers 0, 1, 2 to the colors 'R', 'G', 'B'. """
    return 'R' if num == 0 else 'G' if num == 1 else 'B'

def triangle(row):
    # Compute the sum of C(n, k) * col[k] modulo 3:
    n = len(row) - 1
    result = 0
    for k, col in enumerate(row):
        temp = binomial_mod3(n, k) * color_to_num(col)
        result = (result + temp) % 3
    # Invert the result if n is odd:
    if n % 2 == 1:
        result = (- result) % 3
    return num_to_color(result)

Note that we iterate over the given input string, so that
no additional lists are created.

In my test this computes the final color for an input string with 10,000
characters in approximately 0.1 seconds, and for 100,000 characters in
about 0.2 seconds.