A S.I.N checker, using Luhn's Algorithm, and created in swing.

User interface

For portability, you should use a layout manager, not absolutely positioned elements.  Here's what it looks like on OS X:

I don't see a reason for two sets of instructions; the instructional text should be placed together.

"Validation Checker" is redundant.  It's either a "SIN validator" or "SIN checker".

"Valid SIN" could be construed as meaning a number that has been actually been issued by Service Canada to a person.  Perhaps you should clarify that it's merely a "possibly valid SIN".

Why prohibit spaces?  Canadian Social Insurance Numbers are conventionally rendered as three groups of three digits, with spaces or hyphens between groups.  Your program could easily be made more lenient and human-friendly, accepting and ignoring the superfluous punctuation.

To facilitate data entry, you should allow number keypad-only usage and perform the validation when Enter is pressed.  (Currently, you have to press Tab and Space, or click Proceed.)  For that matter, you could automatically perform the validation as soon as nine digits have been entered, without even requiring Enter.

Automatically returning focus to the number field and selecting its contents after validating was a nice touch.

Validation quality

"0" is accepted as a valid SIN.

"-9" is accepted as a valid SIN.

"123456789012345" or "hello" cause a NumberFormatException which is invisible in the UI.  It just looks like either a valid SIN or an invalid SIN, depending on whether the previous validation passed or failed.

Implementation

You should implement the Luhn algorithm check in its own function (if not its own class) rather than in the event handler.  That lets you reuse the code in other contexts such as a text-based UI, a tax-preparation program, or a unit test.

These lines of code are not as clear as they could be:

bl1 = new ButtonListener ();
b1.addActionListener (bl1);

Rather, I would prefer to see the button and text field identified with descriptive variable names.  The ActionListener should be simplified and could be made into an anonymous inner class:

proceedButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        boolean valid = SinChecker.isValid(sinTextField.getText());
        SinChecker.this.announceValid(valid);
        sinTextField.requestFocus();
        sinTextField.selectAll();
    }
});

Since your SinChecker class extends JFrame, I would expect its constructor to behave a specialized JFrame.  In particular, a JFrame constructor would not make the newly instantiated frame visible, nor would it set exit-on-close.  Therefore, your SinChecker constructor shouldn't do those things, either.  If your SinChecker is incorporated as a component within some larger program, exit-on-close might not be appropriate.

Speaking of reusability, consider making your SinChecker a JPanel instead of a JFrame, so that you have the flexibility to use it as a widget that is not its own window.  In that case, your widget should offer a getSin() method that returns a guaranteed valid SIN.

In accordance with the documentation, Swing code must run in the Event Dispatch Thread, not the main thread.

public class SinChecker extends JPanel {
    public SinChecker() {
        this.setBackground(Color.WHITE);
        …
        this.setPreferredSize(…);  // Ideally automatically determined by layout manager
    }

    …

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame f = new JFrame("Social Insurance Number Checker");
                f.setLayout(new BorderLayout());
                f.add(new SinChecker());
                f.pack();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setVisible(true);
            }
        });
    }
}


C# Multi level HTML TagBuilder object - Design pattern Review needed

I would make sure the list is not exposed publicly - the caller can then do whatever they want with that list, even assign null to it.  So I've refactored it a little bit and implemented Add() (you may also want to implement Remove(), etc.):

/// <summary>
/// Simple class that inherits TagBuilder and allow to save sub tags.
/// </summary>
public class MultiLevelHtmlTag : TagBuilder
{
    /// <summary>
    /// List of inner tags.
    /// </summary>
    private readonly IList<MultiLevelHtmlTag> innerTags = new List<MultiLevelHtmlTag>();

    /// <summary>
    /// Initializes a new instance of the <see cref="MultiLevelHtmlTag"/> class.
    /// </summary>
    /// <param name="tagName">The name of the tag.</param>
    public MultiLevelHtmlTag(string tagName) : base(tagName)
    {
    }

    /// <summary>
    /// Gets the inner tag list.
    /// </summary>
    /// <value>The inner tag list.</value>
    public IEnumerable<MultiLevelHtmlTag> InnerTags
    {
        get
        {
            return new ReadOnlyCollection<MultiLevelHtmlTag>(this.innerTags);
        }
    }

    /// <summary>
    /// Adds the specified tag to the inner tag list.
    /// </summary>
    /// <param name="tag">The tag to add.</param>
    public void Add(MultiLevelHtmlTag tag)
    {
        if (tag == null)
        {
            throw new ArgumentNullException("tag");
        }

        this.innerTags.Add(tag);
    }

    /// <summary>
    /// Returns a <see cref="System.String"/> that represents this instance.
    /// </summary>
    /// <returns>
    /// A <see cref="System.String"/> that represents this instance.
    /// </returns>
    public override string ToString()
    {
        var sb = new StringBuilder();

        foreach (var tag in this.innerTags)
        {
            sb.Append(tag.ToString());
        }

        this.InnerHtml = sb.ToString();
        return base.ToString();
    }
}


How about this?

def isPrime(n:Int):Boolean = n match {
  case 1 => false
  case 2 => true
  case 3 => true
  case 5 => true
  case 7 => true
  case n if (n%2==0 || n%3==0 || n%5==0 || n%7==0) => false
  case _ => (Stream.iterate(3, Math.sqrt(n).toInt+1){_ + 2} dropWhile((x:Int) => n%x != 0)).isEmpty
}

The code is straightforward. We know that the prime numbers below 10 are 2, 3, 5, 7. If a given number is the multiple of 2, 3, 5, or 7, is't not a prime. In other case (the last case branch) it generates stream from 3 to ceil(sqrt(n)) with step 2. We know that even numbers can't be a prime. And check that the argument is a multiple of any number in the stream. Basically the same logic with the original code. The reason I use Stream is to use lazy evaluation. With lazy evaluation, we can avoid unnecessary computation.


Add existing models to a relation using nested attributes

Couple of things to improve here:

Firstly - do not use fixtures, use factories. There is a neat library allowing you to do this with ease called FactoryGirl (for rails you will need FactoryGirlRails). Having this in place you can define factories like:

FactoryGirl.define do
  factory :thumbnail do
    name 'Thumbnail name if you have such a field'
    other_field :other_value
  end
end

And then use it as:

thumbnail = FactoryGirl.create :thumbnail

One advantage of factories is that it does not load all the data into the database for each test, but rather allows you tell it what is needed instead.

There are quite a lot of options you can add to your factories, like dynamic field values (useful when you have uniqueness validations), building parameters, building associated objects etc. All are well documented on gem github wiki.

Secondly, accepts_nested_attributes_for already provides you with a method to assign objects using their ids:

@model.children_ids << [1,2,3]

or even modify the whole association in one go

@model.children_ids = [1,2,3]

This is usually more useful in terms of web forms. If you have a form where client can select multiple objects from a list from db, all you need to do is to name those fields children_ids and rails will take care of persisting the association.


Designing a simple Battleship game in Python

Perhaps GamePlan would better be named eg. Board? English is not my mother tongue, but AFAIK game plan == strategy.

1,3,4: The ships are static, they just occupy some space on the board. However, a ship object would be aware which squares belong to the ship, and perhaps should be responsible to determine if it has been sunk.

2: hit is perfect; in OOP the object is often the object also in grammatical sense. Think of file.close().

5: If the player hits the same coordinates twice, you'll report a miss, which is wrong.


I tried to figure it out what changes i have to made if I am using var fse= require("fs-extra");
so my code will look like this

var fse=require("fs-extra");

async function checkFileLoc(folderPath, depth) {
  depth -= 1;
  let files = fse.readdirSync(folderPath);
  files = await Promise.all(
    files.map(async (file) => {
      const filePath = path.join(folderPath, file);
      const stats = fse.statSync(filePath);
      if (stats.isDirectory() && depth > 0) {
        return checkFileLoc(filePath, depth);
      } else if (stats.isFile()) return filePath;
      else return null;
    })
  );
  return files
    .reduce((all, folderContents) => all.concat(folderContents), [])
    .filter((e) => e != null);
}

I replaced my

var fs=require("fs"); to var fse=require("fs-extra");
let files = await fs.readdir(folderPath); with let files = fs.readdirSync(folderPath);
const stats = await fs.stat(filePath); with const stats = fs.statSync(filePath);

now i am getting my desire output


public static TFile Load(TextReader reader)
{
    var file = new TFile();
    file.Rows = file.Read(RowReader.Create(reader));
    return file;
}

In order to get rid of the mutable property file.Rows I suggest taking a look at Autofac's factory delegate for creating TFile immutably and injecting this delegate as a dependency.

Alternatively you could register them via named and keyed services and pick the right factory by TKey with Type as key. I use this techniques quite often.

I guess other dependency injection frameworks could do similar magic.


Packet Scout (show traffic on specified port)

Naming

Methods should be named using PascalCase casing and should reflect by its name what the responsibility of the method is. So instead of downloadbuffer() a more descriptive name would be AppendToRichtextBox() or something similiar.

Talking about responisibilties, a class should usually have only one responsibility, so you should separate the UI related code and the listening code into separate classes.

BackgroundWorker

The BackgroundWorker has an event to report the current progress, so no timer is needed.
The call to CancelAsync() isn't working like you guess it is.

  CancelAsync submits a request to terminate the pending background operation and sets the CancellationPending property to true.

  When you call CancelAsync, your worker method has an opportunity to stop its execution and exit. The worker code should periodically check the CancellationPending property to see if it has been set to true.

Now you will say, but it stops the worker. This is only partial true, because after the said call you are closing the socket which will lead to a ObjectDisposedException at retrieving the socket.Available property.
This exception will be passed to the RunWorkerCompleted eventhandler see the DoWork() event documentation

  If the operation raises an exception that your code does not handle, the BackgroundWorker catches the exception and passes it into the RunWorkerCompleted event handler, where it is exposed as the Error property of System.ComponentModel.RunWorkerCompletedEventArgs. If you are running under the Visual Studio debugger, the debugger will break at the point in the DoWork event handler where the unhandled exception was raised. If you have more than one BackgroundWorker, you should not reference any of them directly, as this would couple your DoWork event handler to a specific instance of BackgroundWorker. Instead, you should access your BackgroundWorker by casting the sender parameter in your DoWork event handler.

Instead of adding to the static buffer variable I would suggest to use the ReportProgress() event and instead of using the string variable you should use a StringBuilder object and passing the built string to the event. By doing so you omit the fact that for each string concatination a new string is created because strings in .NET are immutable.

Like

private void bgw_DoWork(object sender, DoWorkEventArgs e) {
    StringBuilder sb = new StringBuilder();

    sb.Append("Listening on port ")
      .Append(ndoor.Value)
      .Append(endl);

    while (socket != null) {
        if (socket.Available > 0) {
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
            Byte[] recvbytes= socket.Receive(ref ipep);

            sb.Append("Client (")
              .Append(ipep.Address)
              .Append(":")
              .Append(ipep.Port)
              .Append("): ");

            foreach (Byte b in recvbytes)
            {
                sb.Append(b.ToString())
                  .Append(" ");
            }
            sb.Append(endl);

            bgw.ReportProgress(0, sb.ToString());
            sb.Length = 0;
        }
    }

    private void AppendToRichtextBox(string value)
    {
        rblog.AppendText(value);
        rblog.ScrollToCaret();
    }

    private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        AppendToRichtextBox(e.UserState.ToString());
    }

because the Append() method of the StringBuilder is returning a StringBuilder you can fluently call this method like sb.Append("first ").Append("and second !");.

If you want to add a carriage return + new line you can simply call one of the overloaded AppendLine() methods.

You can also use the var type if the right hand side of the assignment makes the type obvious

  Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

Like

var sb = new StringBuilder();


How to Make Strongly-typed References to Web.Config?

I don't do much asp.net, but if this StackOverflow answer applies then you could just do this:

using Settings = MyProject.Namespace.Properties.Settings;

var loadedCode = Settings.Default.LoadedCode;

Like this other StackOverflow answer is saying:

  We prefer to use Properties.Settings (aka. settings.settings) because it's strongly typed.

Now I know for a fact that this works with an app.config, but it might not work with a web.config file... but I think it's worth trying.

Alternatively, this Haacked article describes how to use the configuration API to define your own ConfigurationSection classes, which would be the ultimate way to address this issue. Might be overkill if the above works though.


Rearrange data without using Cut and Insert

To speed it up, I would read it into arrays. One array for column A and one array for column B and then combine them into another array and print that to sheet

Option Explicit
Sub Rearrange()
    Dim lastRow As Long
    lastRow = Library.Cells(Rows.Count, 1).End(xlUp).Row
    Dim firstColumn As Variant
    firstColumn = Library.Range("A1:A" & lastRow)
    Dim secondColumn As Variant
    secondColumn = Library.Range("B1:B" & lastRow)
    Dim totalCount As Long
    totalCount = Application.CountA(firstColumn) + Application.CountA(secondColumn)

    Dim combinedArray As Variant
    ReDim combinedArray(1 To totalCount)
    Dim i As Long
    Dim index As Long
    index = 1

    For i = 1 To lastRow
        combinedArray(index) = firstColumn(i, 1)
        index = index + 1
        If Not IsEmpty(secondColumn(i, 1)) Then
            combinedArray(index) = secondColumn(i, 1)
            index = index + 1
        End If
    Next

    Library.Range("A1:A" & totalCount) = Application.Transpose(combinedArray)

End Sub

Arrays are fast!

Also, as you can see worksheets have a CodeName property - View Properties window (F4) and the (Name) field (the one at the top) can be used as the worksheet name. This way you can avoid Sheets("Library") and instead just use Library.

I also switched your

lastRow = Library.Range("A1").SpecialCells(xlCellTypeLastCell).row

To the standard.

I also used a For loop instead of Do While.


In Python, the best practice is to use exceptions for many more situations than is best practice in Java. In Python, you shoot first, ask questions later .... you seek forgiveness, not permission.... you ... {add cheesy analogy here....}

In Java, Exceptions are expensive. When an exception happens, the virtual machine needs to backtrack the call stack, often synchronizing on critical aspects of the runtime, perhaps bringing the entire application in to a locked state, while the exception is built. The Java compiled code is often inlined, and optimized, and the call stack for the actual optimized code has to be translated back to the source code, etc.

If you expect your input data to have invalid double input, then it is not an exceptional case to have invalid data, is it. In Java, you seek permission before having to seek forgiveness... so, you validate the data before doing the hard work.

The documentation for Double.valueOf(String) even goes so far as to show you exactly how to validate an input String before parsing it... using a regular expression, and shows how to use it too.

So, let's compare two ways of parsing the values.... the forgiveness way:

private static final double parseForgiveness(String value) {
    try {
        return Double.parseDouble(value);
    } catch (NumberFormatException nfe) {
        return 0.0;
    }
}

(Note, there's something important in there, I use double and not Double. Using primitives in Java when you can is almost always a better idea for performance than using the full Object version, like Double).

So, the above system begs forgiveness when the data is broken.... what about prevalidating the number...? The code is basically copied from the Javadoc:

private static final double parsePermission(String value) {
    if (DOUBLE_RE.matcher(value).matches()) {
        return Double.parseDouble(value);
    }
    return 0.0;
}

where the DOUBLE_RE is defined as:

private static final String Digits     = "(\\p{Digit}+)";
private static final String HexDigits  = "(\\p{XDigit}+)";
// an exponent is 'e' or 'E' followed by an optionally
// signed decimal integer.
private static final String Exp        = "[eE][+-]?"+Digits;
private static final String fpRegex    =
    ("[\\x00-\\x20]*"+  // Optional leading "whitespace"
     "[+-]?(" + // Optional sign character
     "NaN|" +           // "NaN" string
     "Infinity|" +      // "Infinity" string

     // A decimal floating-point string representing a finite positive
     // number without a leading sign has at most five basic pieces:
     // Digits . Digits ExponentPart FloatTypeSuffix
     //
     // Since this method allows integer-only strings as input
     // in addition to strings of floating-point literals, the
     // two sub-patterns below are simplifications of the grammar
     // productions from section 3.10.2 of
     // The Java Language Specification.

     // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
     "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+

     // . Digits ExponentPart_opt FloatTypeSuffix_opt
     "(\\.("+Digits+")("+Exp+")?)|"+

     // Hexadecimal strings
     "((" +
      // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
      "(0[xX]" + HexDigits + "(\\.)?)|" +

      // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
      "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +

      ")[pP][+-]?" + Digits + "))" +
     "[fFdD]?))" +
     "[\\x00-\\x20]*");// Optional trailing "whitespace"

private static final Pattern DOUBLE_RE = Pattern.compile(fpRegex);

Note that a Pattern is compiled as a single static, and then used to match the String before actually parsing it. That seems like a lot of work, but consider a situation when about half the values are invalid in a String sequence.... how does it affect the performance?

I wrote a UBench tool a little while ago to test performance of these sorts of exercises. The first thing I do is write a function to generate an input array of 50% valid values, and 50% invalid. Here's that code:

private static final char[] alpha = " `1234567890-=~!@#$%^&*()_+qwertyuiop[]\\QWERTYUIOP{}|asdfghjkl;'ASDFGHJKL:\"zxcvbnm,./ZXCVBNM<>?".toCharArray();

private static final String wordRand(Random rand) {
    int len = rand.nextInt(10) + 3;
    char[] chars = new char[len];
    IntStream.range(0, len).forEach(i -> chars[i] = alpha[rand.nextInt(alpha.length)]);
    return new String(chars);
}

private static String[] buildInput(int size) {
    List<String> values = new ArrayList<>();
    Random rand = new Random(size);
    for (int i = 0; i < size; i++) {
        values.add(Double.toString(rand.nextDouble() * i));
        values.add(wordRand(rand));
    }
    return values.toArray(new String[values.size()]);
}

That buildInput method will return an array of Strings where half the values are guaranteed valid float Strings, and the other half are almost certainly not valid (thought it's possible they may be). Then, I run it through a comparative benchmark using the following code:

private static final double[] parseAll(String[] values, ToDoubleFunction<String> parser) {
    return Stream.of(values).mapToDouble(parser).toArray();
}

public static void main(String[] args) {
    UUtils.setStandaloneLogging(Level.INFO);
    String[] values = buildInput(1000);
    UBench bench = new UBench("Parsing");
    bench.addTask("Permission", () -> parseAll(values, DoubleParser::parsePermission));
    bench.addTask("Forgiveness", () -> parseAll(values, DoubleParser::parseForgiveness));
    bench.press(1000).report();
}

That's complicated, I guess, but really it sets up two tests, one which parses 2000 input values using the forgiveness method, the other test uses the permission method. It runs each test 1000 times, and then takes some measurements of each run, and reports on it. The report, on my computer, looks like:

INFO   2015-08-07 12:13:03.058 net.tuis.ubench.UBench(<init>): Creating UBench for suite Parsing
INFO   2015-08-07 12:13:06.860 net.tuis.ubench.UBench(press): UBench suite Parsing: completed benchmarking all tasks using mode INTERLEAVED in 3785.000ms
Task Parsing -> Permission: (Unit: MILLISECONDS)
  Count    :     1000      Average  :   1.1980
  Fastest  :   1.0339      Slowest  :  26.8094
  95Pctile :   1.3693      99Pctile :   2.9096
  TimeBlock : 1.702 1.265 1.143 1.176 1.073 1.086 1.168 1.194 1.076 1.096
  Histogram :   977    17     5     0     1

Task Parsing -> Forgiveness: (Unit: MILLISECONDS)
  Count    :     1000      Average  :   2.5568
  Fastest  :   2.3117      Slowest  :  12.5496
  95Pctile :   2.8740      99Pctile :   5.5604
  TimeBlock : 3.054 2.539 2.522 2.645 2.411 2.471 2.470 2.591 2.419 2.446
  Histogram :   978    20     2

What that means, is that the average time to parse 2000 values using the regex is 1.20 milliseconds, and using the exception system is 2.56 milliseconds - more than twice as slow.

Additionally the fastest parse is 1.03 milliseconds, vs. 2.31 - again more than twice as slow.

Bottom line is that in Java (unlike Python), you should not use exceptions to handle data validation when you expect data to regularly be invalid....


Personally I don't see any value in introducing such objects. Especially given you are inclined to functional programming, which is a real trademark of your code, whereas such "POPOs" indeed look alien in it.

Either way, there is one plain mistake in the code, an Error by no means is a Form, so UserForm never can be a parent for the UserFormErrors. Even for sake of sparing you from writing a couple lines of code.


Populating a vector with alternating numbers

If you know how large the vector needs to be, the specify the size in the constructor so that it doesn't need to guess.

vecCoeffs[i]; is a useless statement.

It would be clearer to pull the assignment of starting and ending coefficients out of the loop, and to avoid assigning vecCoeffs[10] twice.  You could assign the starting and ending coefficients in the same statement.

The if-else would be better as a ternary conditional.

vector<double> vecCoeffs(11);
// Starting and ending coefficients
vecCoeffs[0] = vecCoeffs[vecCoeffs.size() - 1] = 1;
// Put the coefficient 2 into each odd index and 4 into each even index
for (int i = 1; i < vecCoeffs.size() - 1; i++) {
    vecCoeffs[i] = (i % 2 ? 2 : 4);
}

But the modulo operator is relatively slow.  You would be better off with two loops…

vector<double> vecCoeffs(11);

// Starting and ending coefficients
vecCoeffs[0] = vecCoeffs[vecCoeffs.size() - 1] = 1;

for (int i = 1; i < vecCoeffs.size() - 1; i += 2) {
    vecCoeffs[i] = 2;                // Odd coefficients
}
for (int i = 2; i < vecCoeffs.size() - 1; i += 2) {
    vecCoeffs[i] = 4;                // Even coefficients
}

… or maybe just one, but getting the termination correct is trickier.  This version might eliminate an instruction or two from the loop, but I don't recommend it.

vector<double> vecCoeffs(11);
for (int i = 0; i < vecCoeffs.size() - 1; i += 2) {
    vecCoeffs[i] = 4;                // Even coefficients
    vecCoeffs[i + 1] = 2;            // Odd coefficients
}
// Starting and ending coefficients
vecCoeffs[0] = vecCoeffs[vecCoeffs.size() - 1] = 1;


This doesn't look too bad to me, though it would be nice to have the full source code that I could run. I'll comment on the things that stand out to me, though.

Unncessary logic

public boolean hasNext() {
    if (position < this.trie.nodeCount()) return true;
    return false;
}

can be written simply as

public boolean hasNext() {
    return position < this.trie.nodeCount();
}

Whitespace is your friend

This is purely stylistic, but to me

    if (hasNext()) {

is much easier on the eyes than

    if(hasNext()){

A lot of IDEs provide automatic formatting to do this for you, too (In Eclipse, Window -> Preferences -> Java -> Code Style -> Formatter).

More on the next method

Avoid nulls if you can. See Google Guava's rational and Effective Java Item 43. If you initialize next to "" instead of null, you can avoid some potential errors downstream.
This can be simplified:

position++;
current = current.children[position];

to just

current = current.children[++position];

Alarm bells should be going off anytime you're iteratively adding to a String. You should be using a StringBuilder instead. Read more about them here.
Using an if statement without brackets is rarely a good idea.
Some standards discourage more than one return statement per method.

With that said, here is how I would refactor the method:

public String next() {
    StringBuilder next = new StringBuilder();

    if (hasNext()) {
        current = trie.root.children[position];
        while (!current.children[position].isEndOfWord()) {
            next.append(current.children[++position]);
            if (current.isEndOfWord()) {
              break;
            }
        }
    }

    return next.toString();
}

Regarding TrieNode

Why are the fields protected? This suggests that the class is to be extended. If that's the case, TrieNode should be abstract (See Open-Closed principle and Effective Java Item 17: "Design and document for inheritance or else prohibit it").
If letter and parentNode variables don't change, you can make them final (again, IDEs like Eclipse can also do this automatically for you).
On the line

protected TrieNode[] children = new TrieNode[26];

26 is a magic number, and should be replaced with a constant.

Final thoughts on addWord

Use a for loop instead of the current while loop. Then you can remove two lines that deal with updating index.
Instead of

TrieNode child = current.children[letters[index] - 97];

you should be able to go

TrieNode child = current.children[letters[index] - 'a'];

which has the benefit of not using a magic number and is more clear.


Initializing complex constant in Constants interface

If you only need constant of java.util.List type you can use static method java.util.Arrays.asList:

import static java.util.Arrays.asList;

...

public static final List<String> MY_CONSTANT = asList("foo", "bar", "baz");

which creates immutable list instance with passed values.

In cases when more complex object needs to be initialised I like to use static methods which create my constant:

public static final SomeComplexObject constant = createMyConstant();

private static SomeComplexObject createMyConstant() {
    SomeComplexObject constant = new SomeComplexObject();
    constant.setProp1(...);
    constant.setProp2(...);
    ...
    return makeItSomehowImmutable(constant);
}

In your case you won't be able to declare private static method inside interface, so the only thing I find reasonable is to create separate utility class with static methods which create constants, declare your method there and reuse it just like with java.util.Arrays.asList method.

Hope this helps...


Some things come to mind when I read your code.

There is a nice feature on arrays in C# called CopyTo(). It gives you the possibility to copy an array without using a loop. Like so:

int[] newNums = new int[n];
nums.CopyTo(newNums, 1);
newNums[0] = newNums[n-1] = 1; //This line I really like.

There is also something called a multidimensional Array which basically does the same thing as int[][]. This gives you the possibility to do this:

int[,] memo = new int[n,n];

Use them together and you can remove all your loops from int maxcoins.

Regarding your actual work method Burst I would say that you make things rather confusing. When debugging, the first thing that happens is that you cache a number series which is not allowed until 3 balloons are popped. It adds [0][1][5] to the cache. A more reasonable approach would have been [0][1][2] then [0][1][3] up to [0][1][5]. After that switch to [0][2][3] etc.  When you reach [0][4][5] you start over at [1][2][3].

To do that you would have to create nested loops in your Burst method:

        for (int i = left+1; i < right; ++i)
        {
            for(int j = i+1; j<= right; ++j)
                ans = Math.Max(ans, numbers[left] * numbers[i] * numbers[j]
                                + Burst(memo, numbers, left, i)
                                + Burst(memo, numbers, i, j));
        }

However, there is an even more simple approach to this problem and that is to actually pop the balloons in the array. This can be done easiest with a list instead of an array. But both are possible. So what you would do is to create a new set of balloons after each pop. So here caching is out of the question because you never really know what range you processed before. And to be honest I guess it would most likely slow down the process and make the code harder to read. I use the same variable names as you but in reality I would name nums and numbers as balloons and newNumbers would be named remainingBalloons. I did however change the variable i to baloonToPop to make it easier to understand what it represents. I left the adding of the ones in the code because it simplifies the Burst method.

    public void MaxCoins(List<int> nums)
    {
        nums.Insert(0, 1); //Add the ones to the array
        nums.Add(1);
        int result = Burst(nums);
    }

    private int Burst(List<int> numbers)
    {
        int result = 0;
        for (int baloonToPop = 1; baloonToPop < numbers.Count-1; baloonToPop++)
        {
            List<int> newNumbers = new List<int>();
            newNumbers.AddRange(numbers);
            newNumbers.RemoveAt(baloonToPop);
            int sumFromBaloonPop = numbers[baloonToPop - 1] * numbers[baloonToPop] * numbers[baloonToPop + 1];
            result = Math.Max(result, Burst(newNumbers) + sumFromBaloonPop);
        }
        return result;
    }

To do it with an array (in case there is a library restriction) you would have to create a new Array and then copy Subranges from the initial one instead of creating a copy of the List using AddRange + RemoveAt as above:

int[] newNumbers = new int[numbers.Length-1];
Array.ConstrainedCopy(numbers, 0, newNumbers, 0, baloonToPop);
Array.ConstrainedCopy(numbers, baloonToPop + 1, newNumbers, baloonToPop, numbers.Length - (baloonToPop + 1));


SEDE query to find users with exactly one post in a particular tag

Half of the tricks with optimizing SQL is knowing the database schema.

The schema documentation can be found in this Meta post: Database schema documentation for the public data dump and SEDE.

There are four functional issues I see with your query, and a couple of suggestions after that:

Use PostTypeId - it describes what the Post is (Question == 1, Answer == 2) and is well indexed.
you are querying closed posts (which have a non-null ClosedDate)
you join to Tags for a single record. This can be resolved independantly
you have Posts three times in your query, and it can be there only twice if you do double-duty in the 'Only One Question' part of the query....

As for the suggestions:

I like parametrize things, and being able to change the tag you are interested makes sense, so I would parametrize that.
The SQL Server syntax allows for 'with' sections in a query, and that makes the code a lot more readable than the query-in-from-clause syntax

Using these suggestions I restructured your query to do a few things:

add a User-Name sort column (SEDE does not sort [User Link] columns well)
parametrized the tag, with a default value of identification
made the group-by and having a much smaller component in the query.
added the closed-query support (and community-wiki - if there are).

I forked your query here... ... for me it ran through in 33 milliseconds

-- Find users who have exactly one post
-- with that post being a question
-- and the question has the [xxxx] tag (default identification)

declare @tag as nvarchar(25) = ##tag:string?identification##
;
declare @tagid as int
;

-- get the tag id here so it is not needed as a join table
select @tagid = Id
from Tags
where TagName = lower(@tag)

;

print 'Tag for ' + @tag + ' is ' + Convert(NVarchar(10), @tagid)

;

with Answerers as (

    select distinct OwnerUserId as [UserId]
    from Posts p
    where PostTypeId = 2 -- answers
      and CommunityOwnedDate is null -- not CW
      and ClosedDate is null -- not closed

), SingleQ as (

    Select OwnerUserId as [UserId],
           Min(Id) as [FirstPost],
           Sum(Score) as [Score],
           count (*) as [QCount]
    from Posts p
    where PostTypeId = 1 -- question
      and CommunityOwnedDate is null -- not CW
      and ClosedDate is null -- not closed
      and not exists (
            select UserId
            from Answerers
            where UserId = OwnerUserId) -- active answerers.
    group by OwnerUserId
    having count(*) = 1
)

SELECT
  ROW_NUMBER() OVER (order by Users.Id Desc) as [Recent],
  Users.Id AS [User Link],
  Users.DisplayName AS [Sort By Name],
  SingleQ.FirstPost AS [Post Link],
  SingleQ.Score AS [Score]
FROM Users
     INNER JOIN SingleQ ON Users.Id = SingleQ.UserId
     INNER JOIN PostTags ON SingleQ.FirstPost = PostTags.PostId
WHERE PostTags.TagId = @tagid
ORDER BY
  Users.Id DESC  -- newest users first.


Using a list-matrix to supply indices to N-dimensional array

Using your 2D example, doing mx[c(1, 1, 2, 3, 4, 4), c(1, 1, 2, 3, 3)] is the obvious solution, both elegant and fast. So your way of generalizing the use of [ via do.call to handle any number of dimensions is what I would consider the optimal approach. The rewrite below won't make the code faster but maybe a little more simple and robust. The main improvement is the computation of the idx using Map rather than a for loop. And I added a number of stopifnot checks to verify all the assumptions you are making regarding your inputs.

padreplicate <- function(a, padSize) {
   stopifnot(is.array(a),
             is.vector(padSize),
             is.numeric(padSize),
             length(padSize) == length(dim(a)),
             padSize >= 0L)
   idx <- Map(function(p, n) c(rep(1L, p), seq(n), rep(n, p)),
              padSize, dim(a))
   do.call( `[`, c(list(a), idx))
}


1. Bugs

It doesn't work! On OS X 10.9.4, with Clang/LLVM, when I run it, I get the output:

Producer Thread Created
Consumer Thread Created

... and then it hangs. Here's an LLDB session:

(lldb) run
Process 29359 launched: './a.out' (x86_64)
Producer Thread Created
Consumer Thread Created
^C
(lldb) thread backtrace all
* thread #1: tid = 0x5461f, 0x00007fff8752ca3a libsystem_kernel.dylib`__semwait_signal + 10, queue = 'com.apple.main-thread', stop reason = signal SIGSTOP
  * frame #0: 0x00007fff8752ca3a libsystem_kernel.dylib`__semwait_signal + 10
    frame #1: 0x00007fff862c17f3 libsystem_pthread.dylib`pthread_join + 433
    frame #2: 0x0000000100000e17 a.out`main + 135 at cr55792.c:102

  thread #2: tid = 0x54646, 0x00007fff8752c746 libsystem_kernel.dylib`__psynch_mutexwait + 10
    frame #0: 0x00007fff8752c746 libsystem_kernel.dylib`__psynch_mutexwait + 10
    frame #1: 0x00007fff862c0779 libsystem_pthread.dylib`_pthread_mutex_lock + 372
    frame #2: 0x0000000100000c5b a.out`consumer(b=0x0000000100001070) + 155 at cr55792.c:66
    frame #3: 0x0000000100000d57 a.out`THREAD_CONSUMER(arg=0x0000000000000000) + 71 at cr55792.c:90
    frame #4: 0x00007fff862bd899 libsystem_pthread.dylib`_pthread_body + 138
    frame #5: 0x00007fff862bd72a libsystem_pthread.dylib`_pthread_start + 137

Thread #1 is the main thread. It is waiting at line 102 to join the consumer thread:

pthread_join(T2,NULL);

Thread #2 is the consumer. It is waiting to take the lock in the function consumer at line 66:

pthread_mutex_lock(&(b->mutex));

The producer thread has finished.

Obviously the mistake is at line 66 of consumer: it should say pthread_mutex_unlock. The question for you is, how did you miss this? This is not some mysterious race condition: it ought not to be possible for consumer to take the lock twice in succession.
With bug #1 fixed, the program runs to completion. Sometimes it produces the correct output:

Producer Thread Created
Consumer Thread Created
Inside queue: W
substring: Hello

but about half the time it produces the output:

Consumer Thread Created
Producer Thread Created
Inside queue: W
substring:

Why is this? It's because this call in consumer is not blocking when it should:

sem_wait(&(b->full));

Let's see why, by changing this to:

if (sem_wait(&(b->full)) != 0) {
    perror("sem_wait");
    exit(EXIT_FAILURE);
}

Sure enough, this check fails with:

sem_wait: Bad file descriptor

Reading the manual page for sem_wait:

  [EINVAL]           sem is not a valid semaphore descriptor.

Why is that? Let's add an error check to the sem_init call:

if (sem_init(&(b->full),0,0) != 0) {
    perror("sem_init");
    exit(EXIT_FAILURE);
}

This check fails with:

sem_init: Function not implemented

This is because OS X does not support unnamed semaphores (sem_init, sem_destroy). On this operating system, it's necessary to use named semaphores (sem_open, sem_close, sem_unlink) instead (that is, if you need to restrict yourself to POSIX; if you're writing OS X-only code then you could use the Mach semaphores).

The lesson here is that writing portable Unix programs is hard! I wouldn't necessarily suggest that you replace your unnamed semaphores with named semaphores (although that's what I've done in my revised code below), just that you check the result of sem_init and other functions so that portability problems like this are easily discovered and diagnosed.

2. Review

You don't check error codes! Read the manual pages for sem_wait, pthread_mutex_lock and so on and you'll see that they can all fail. Checking error codes would have immediately identified the cause of problem #2 above.

Checking for errors is vital in multi-threaded code, where race conditions are often hard to reproduce. I was lucky that this particular error occurred about 50% of the time: had it been rare I would probably have missed it altogther.

Always check error codes! It's burdensome to start with, but not technically difficult, to develop a simple error-reporting system, and apply it to all fallible function calls. And once in a while this will save your ass.
There are no comments. What do these functions do? What is the meaning of each variable?
Some of your names are lower case (queue, producer), some are uppercase (BUFFER, THREAD_PRODUCER), and some are mixed (initializeBuffer), but there doesn't seem to be any consistent meaning in this distinction. It's worth paying careful attention to names.
You use names inconsistently. For example, is it a BUFFER or a queue?
The names T1 and T2 are rather obscure. One is the producer thread and the other the consumer thread, but which is which? It is hard to remember.
In the BUFFER structure, the in and out members are non-negative indexes into buff, and the count member is a non-negative count of unconsumed items, so they should be represented by unsigned integers, for example size_t.
The count member is not actually used for anything. Use it or remove it! I would suggest using it by adding an assertion before you decrement it.
You have unnecessary parentheses in expressions like:

&(b->empty)
(b->in)++;

which suggests that you are not confident about operator precedence and associativity. I would suggest having an operator precedence table open in a tab somewhere until you get used to it, rather than adding parentheses when you are unsure.

You'll see from the table that -> has higher precedence than &, so it's safe to write:

&b->empty

You'll also see that -> and (postfix) ++ have the same precedence but associate from left to right, so it's safe to write:

b->in++;

There's no need to call pthread_exit at the end of the thread function. If you read the manual, you'll see that:

  An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it. The function's return value serves as the thread's exit status.

3. Revised code

#include <assert.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>

/* If expr is false, print error message and exit. */
#define CHECK(expr, msg)                        \
    do {                                        \
        if (!(expr)) {                          \
            perror(msg);                        \
            exit(EXIT_FAILURE);                 \
        }                                       \
    } while (0)

/* Thread-safe queues */

#define MAX 10                  /* maximum number of characters in queue */

typedef struct {
    char buffer[MAX];           /* circular buffer */
    size_t in;                  /* position of producer in buffer */
    size_t out;                 /* position of consumer in buffer */
    size_t count;               /* number of unconsumed items */
    pthread_mutex_t mutex;      /* mutex protecting buffer, in, out, count */
    sem_t *empty;               /* semaphore counting empty slots in buffer */
    sem_t *full;                /* semaphore counting full slots in buffer */
} queue_s, *queue_t;

void queue_init(queue_t q)
{
    q->count = 0;
    q->in = 0;
    q->out = 0;

    CHECK(pthread_mutex_init(&q->mutex, NULL) == 0, "pthread_mutex_init");
    q->full = sem_open("full", O_CREAT, 0600, 0);
    CHECK(q->full != SEM_FAILED, "sem_open");
    CHECK(sem_unlink("full") == 0, "sem_unlink");
    q->empty = sem_open("empty", O_CREAT, 0600, MAX);
    CHECK(q->empty != SEM_FAILED, "sem_open");
    CHECK(sem_unlink("empty") == 0, "sem_unlink");
}

void queue_destroy(queue_t q)
{
    CHECK(pthread_mutex_destroy(&q->mutex) == 0, "pthread_mutex_destroy");
    CHECK(sem_close(q->full) == 0, "sem_close");
    CHECK(sem_close(q->empty) == 0, "sem_close");
}

/* Wait, if necessary, for a slot to become available in the queue,
 * and then append the character c. */
void queue_append(queue_t q, char c)
{
    CHECK(sem_wait(q->empty) == 0, "sem_wait");
    CHECK(pthread_mutex_lock(&q->mutex) == 0, "pthread_mutex_lock");

    q->buffer[q->in] = c;
    q->in++;
    q->in %= MAX;
    assert(q->count < MAX);
    q->count++;

    CHECK(pthread_mutex_unlock(&q->mutex) == 0, "pthread_mutex_unlock");
    CHECK(sem_post(q->full) == 0, "sem_post");
}

/* Wait, if necessary, for a slot to become full in the queue, and
 * then pop and return the first character. */
char queue_pop(queue_t q)
{
    CHECK(sem_wait(q->full) == 0, "sem_wait");
    CHECK(pthread_mutex_lock(&q->mutex) == 0, "pthread_mutex_lock");

    char val = q->buffer[q->out];
    q->out++;
    q->out %= MAX;
    assert(q->count > 0);
    q->count--;
    assert(q->count == (q->in + MAX - q->out) % MAX);

    CHECK(pthread_mutex_unlock(&q->mutex) == 0, "pthread_mutex_unlock");
    CHECK(sem_post(q->empty) == 0, "sem_post");
    return val;
}

/* Test harness */

queue_s queue;
char substring[5];

void *producer(void *arg)
{
    char array[] = "HelloWorld";
    size_t i = 0;
    printf("Producer Thread Created\n");
    while (array[i] != '\0') {
        queue_append(&queue, array[i]);
        i++;
    }
    return NULL;
}

void *consumer(void *arg)
{
    size_t i = 0;
    printf("Consumer Thread Created\n");
    for (i = 0; i < 5; i++) {
        substring[i] = queue_pop(&queue);
    }
    return NULL;
}

int main()
{
    pthread_t producer_thread, consumer_thread;
    queue_init(&queue);
    CHECK(pthread_create(&consumer_thread, NULL, consumer, NULL) == 0,
          "pthread_create");
    CHECK(pthread_create(&producer_thread, NULL, producer, NULL) == 0,
          "pthread_create");
    CHECK(pthread_join(consumer_thread, NULL) == 0, "pthread_join");
    CHECK(pthread_join(producer_thread, NULL) == 0, "pthread_join");
    printf("Next character in queue: %c\n", queue.buffer[queue.out]);
    printf("substring: %s\n", substring);
    queue_destroy(&queue);
    return EXIT_SUCCESS;
}


To start off, your module should be the bare minimum, but extendable (like jQuery). That way, you won't have problems with scalability and maintenance. Here's a simple module template, where everything gets declared in the Module namespace:

//this is a simple module declaration:
(function(Module){

  //everything here is private unless attached to the Module namespace
  var imPrivate = 'cant see me!';

  //here's an example of an exposed functionality
  Module.imaPublicProperty = 'public property here';

  Module.imaPublicFunction = function(){
    console.log('im public');
  }

  //here's an example privileged methods, public methods that have access
  //to the private scope. These are your "setters and getters" in Java-speak
  Module.imaPrivilegedFunction = function(){
    console.log(imPrivate);
  }

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

I suggest you build a helper function that actually appends your sections to your namespace. That way, the module would scale easily. Also, you don't have to fiddle with the base-code and lose commas along the way.

Here's a simple, yet incomplete implementation using this new approach (it lacks the document.ready part). It is long, yet it's modular and easily maintainable. You can even split the section codes in separate files.

(function (ns) {

  ns.addSection = function (name, def) {
    ns[name] = new def();
  }

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

//adding config
Module.addSection('Config', function () {
  var systemName = 'mySystem',
    version = '1.1.4',
    section = this;

  section.getSystemInfo = function () {
    return systemName + ' v' + version;
  }

});

//adding Dialog
Module.addSection('Dialog', function () {

  var section = this;

  section.onDocumentReady = function () {
    $('.showDialog').on('click', function () {
      var obj = {
        element: this,
        foo: 'foo',
        bar: 'bar',
        target: $('#title')
      };
      section.setParam(obj);
      section.show();
    })
  }

  section.setParam = function (config) {
    console.log('config set for dialog box');
    console.log(config);
  }

  section.show = function () {
    console.log('dialogbox show | ' + Module.Config.getSystemInfo());
  }

  section.close: function () {
    console.log('dialogbox close');
  }

});

//Savescreen section
Module.addSection('Savescreen', function () {

  var section = this;

  section.setParam = function (config, foo) {
    console.log('config set for savescreen');
  }

  section.show = function () {
    console.log('savescreen show | ' + Module.Config.getSystemInfo());
  }

});

Here's how it's possibly used:

Module.Config.getSystemInfo();
//mySystem v1.1.4

So basically, you have base code and you just append to the namespace the sections via a helper function. Keeps the code clean and loose.

I suggest looking at KernelJS, which implements this pattern


Calculating the sum of the digits in 2^1000

I see some things that may help you improve your code.

Eliminate "magic numbers"

The code, is full of "magic numbers" -- that is, raw numbers in the code that don't have obvious meaning.  For example, we have this:

int dec[320] = {1, };
// and later ...
for (j = 0; j < 302; j++) {

It's unclear, whether 302 and 320 is just a typo or has some signficance.  Better would be to use a #define for this.  I'd use this:

#define BITS 1000
#define DIGITS 302

Write in idiomatic C

Lines like these are a little peculiar to an experienced C programmer:

dec[q] = dec[q] % 10;
dec[q + 1] = dec[q + 1] + 1;

The idiom instead would be to write them like this:

dec[q] %= 10;
++dec[q + 1];

Avoid potentially expensive operations

Since you're only doubling each digit each pass, it's certain that the maximum possible value is 9*2 = 18, so rather than using the % operator, it's sufficient to simply subtract 10.

Make only a single pass through

There's no need to make two passes through the array for each doubling.  It can be done in a single pass like this:

for (int i = BITS; i; --i) {
    int carry = 0;
    for (int j = 0; j < DIGITS; j++) {
        dec[j] = 2 * dec[j] + carry;
        if (dec[j] > 9) {
            dec[j] -= 10;
            carry = 1;
        } else {
            carry = 0;
        }
    }


You can use Seq.initInfinite and Seq.find to do this, though I'm not sure it's actually better:

let repeatingPrompt predicate (message:string) =
    let prompt _ =
        Console.WriteLine(message)
        Console.ReadLine()

    Seq.initInfinite prompt |> Seq.find predicate


Your loop uses 2 jumps (je/jmp) on every iteration!  Jumping is expensive, so a solution that needs only 1 jump (jne) will be more effective.

strlen:
  xor rdx, rdx
  dec rdx          ; This compensates for the INC that is happening first.
.next:
  inc rdx
  cmp byte [rsi + rdx], 0
  jne .next
  ret

Do keep things logically together. There's no point in setting RAX before the call to strlen.

puts:
  ; string passed through rsi
  call strlen      ; Result is in RDX

  mov rax, 1
  syscall


Graph implementation for solving graph problems (java)

Don't store method flow flags as state in classes. This is a breach in object-oriented design.

class Node
{
    public boolean visited;
    // .. other
}

Search methods like dfs should use a map of some sort to store which nodes are visited.

By storing this flag incorrectly as state, you'll get in trouble when multiple threads search the graph concurrently.


PHP & Mysqli Code - Is this code safe for a simple search?

It is not safe, you are completely open to SQL Injection. You need to use prepared statements.

Apart from that:

don't use short variables names (q, c, etc)
don't just echo an error, but actually handle it (if there is no db connection, there is no need to execute queries)
try to reduce your nesting, eg by including guard clauses:

Example of guard clauses:

if(!isset($_GET['q']) || $_GET['q'] == ' '){
    // return, die, etc
}

// perform query

if($c == 0){
    // return, die, etc
}

// handle query output


This code is perfectly safe. The only issue with sanitization in this code is that it makes the data, so to say, overly-sanitized.

The way you are getting your input variables, makes them suitable for the HTML output. But there is no HTML output in the code present. Which makes such santitization slightly misplaced. It is considered a better practice to "sanitize"  the data right before use, instead of doing that prematurely.

The way you are doing it now could result in some undesired consequences.    For example, imagine a honest girl named Sarah O'Hara going to register with your site. Your code will make her name "Sarah O&#039;Hara" to be saved in the database. Next time she will try search for her name, a search for "Sarah O'Hara" will find nothing.

Therefore it is recommended to sanitize a variable just before the actual use. E.g. making it suitable for the HTML output right before the actual output. Given modern template engines such as Twig are doing an auto-escaping, it will take you no trouble having the user data properly sanitized.

In this regard I would get input variables without any HTML related sanitization, I.e.

$firstname = trim(filter_input(INPUT_POST, 'firstname'));
$lastname = trim(filter_input(INPUT_POST, 'lastname'));

whereas actual sanitization being done before the actual output.


Simple server using async and HttpListener

Visual Studio will warn if you don't use the Task object returned from the function, either immediately with an await statement or by storing it in a variable.  The reason is that this is the only connection you have with the Task that you have started, and without it there is no way to find out if it has completed or to get the return value.

Stylistically, methodOne is not a good name for that variable, something like handler or callback would make more sense.  It also might make sense for the signature to be a little more complex, like accepting a dictionary of parameters and returning an object to serialize to the response.

The other thing to realize is that the called function doesn't know what you do or don't do with the Task, so its behavior can't depend on that.  Therefore "using async and having it run on the main thread" does not accurately describe what happens in your situation.  The task is run asynchronously on a background task either way, but in your case the main thread does not block on its completion.  If you step in with a debugger, you'll see that the code up to the first await (in the while loop) is executed on the calling thread, and at that point control returns to the caller, who could then maintain a reference to the Task if it wants.

As for whether async and Task are right for your job: it sounds like your needs are pretty modest and that there isn't a real argument to be made for or against.  If there aren't many requests coming in, it doesn't really matter how you handle them.  If there could be a lot coming in and you wanted to limit the impact on the rest of the system, maybe it would make sense to do the work synchronously on a single thread (that you create for that specific purpose).


Avoid using java.util.Timer. See Checking if a Java Timer is cancelled and java.util.Timer: Is it deprecated? Instead use a ScheduledExecutorService.
When changing to a ScheduledExecutorService, don't cancel or shutdown your ScheduledExecutorService, instead cancel the FutureTask that you will get when scheduling a task.
Don't decrease a counter once a second. Nothing guarantees that it will be called with exactly 1000 ms periodicity.

In your reset method, use System.nanoTime() (not System.currentTimeMillis) to calculate when the time is up, such as:

this.targetTime = System.nanoTime() + seconds * 1_000_000_000;

Then calculate in getSecondsLeft, by using System.nanoTime() again, how many seconds remain until the target nanosecond value has been reached.


mov dl, byte [ecx]
cmp dl, 0; read byte and comp to 0
je _exit

There are various alternatives, for example:

cmp byte [ecx], 0
je _exit

And:

mov dl, [ecx] ; note: BYTE would be redundant, but you can put it if you like
test dl, dl
jz _exit

For that loop overall,

_label:
    mov dl, byte [ecx]
    cmp dl, 0; read byte and comp to 0
    je _exit
    add ecx, 1
    jmp _label

This is a "2 jump loop", but it can be a "1 jump loop", for example:

_label:
    mov dl, [ecx]
    inc ecx
    test dl, dl
    jnz _label

Or:

    dec ecx
_label:
    inc ecx
    cmp byte [ecx], 0
    jne _label

(here are some details about inc vs add)

For fast loops like this, having two jumps in the loop can easily slow them down to half the speed.

repnz scasb is an option, but it's not that great. Small loops like this can run in 1 cycle per iteration on most CPUs anyway, and repnz scasb is not better than that (often worse, such as 2 cycles per byte on Ryzen and Haswel). The special optimizations for rep movs and rep stos don't apply to rep scas.

There are faster ways to implement strlen, that are not based on byte-by-byte loops but detect the presence of a zero inside a bigger block, using SIMD (example) or SWAR (example). That way speeds much higher than 1 byte per cycle can be reached. Perhaps some future processor would implement a "fast rep scas" feature in a similar way..

mov ecx, arg_err
mov edx, len_arg_err
call _print
int 0x80

This is mysterious, there is no _print function and there is a stray system call without selecting any particular entry point, or perhaps _print was meant to put a suitable value in eax?


Looking at the random number generation, a lot of duplicated code can be easily removed.

Starting at the 4th line: import random. The only function that is used is randint, so you could do from random import randint and then use randint everywhere, instead of random.randint.

Another repetition that can be avoided concern the arguments of randint: you can unpack the tuple using the *.

def start_delay(self):
    '''Return random delay within <start_delay_range>.'''
    return randint(*start_delay_range)

And your (repetitive) properties are now much shorter!


Filtering users by criteria in Ruby on Rails

I'd say to first make a service object to keep the controller lean and clean, and to give yourself a place to put all the logic without fear of polluting the controller. Plus: It's reusable!

# app/services/user_search.rb

class UserSearch
  ORDER_MAPPING = {
    "cost"          => "rcost",
    "quality"       => "rquality",
    "time"          => "rtime",
    "experience"    => "rexperience",
    "communication" => "rcommunication"
  }.freeze

  def initialize(params)
    @params = params
  end

  def results
    @results ||= begin
      records = User.scoped.joins(:user_skills)
      records = scope(records)
      records = order(records)
    end
  end

  private

  def param(key)
    @params[key] if @params[key].present?
  end

  def scope(scoped)
    scoped = add_scope(scoped, 'user_type = ?', param(:user_type))
    scoped = add_scope(scoped, 'user_skills.skill_id in (?)', skill_ids)
    scoped = add_scope(scoped, 'availability = ?', param(:availability))
    scoped = add_scope(scoped, 'location_country = ?', param(:location))
    scoped = add_scope(scoped, 'rate < ?', max_rate)
  end

  def add_scope(scope, sql, *params)
    scope.where(sql, *params) if params.all?(&:present?)
    scope
  end

  def order(scope)
    terms = sanitized_order_terms || default_order_terms
    terms.each { |term| scope.order(term) }
    scope
  end

  def sanitized_order_terms
    terms = param(:filter).try(:split, ",")
    terms = terms.map { |term| ORDER_MAPPING[term] }
    terms = terms.compact
    terms if terms.any?
  end

  def default_order_terms
    ["id asc"]
  end

  def skill_ids
    param(:s_skills).try(:map, &:to_i)
  end

  def max_rate
    param(:max_rate).try(:to_i)
  end
end

I've intentionally kept the pagination in the controller, as it's pretty independent of the scoping and ordering. However, it'd be simple to add as arguments to the #results method

In your controller:

def search
  @users = UserSearch.new(params).results.page(params[:page]).per(PER_PAGE)

  advanced_params = %w(location max_rate availability).map { |p| params[p] }
  @advanced_link = advanced_params.all?(&:blank)

  render :index
end

I'd probably pick a more direct way of determining the @advanced_link, such as sending an advanced parameter along, and simply looking at that instead of the implicit state you have now.

I have no idea what Code Climate thinks of the code above, but I imagine it'll be happier.


Using JS/JQuery to serve ads from a self-hosted advertisements solution

A few suggestions:

A function declaration is a bit simpler and more robust regarding hoisting compared to a function expression which assigns an anonymous function to a variable.
Supplying null as the first callback parameter on success is a bit quirky, either always supply the HTTP status or fail silently without calling the callback. If needed you can always introduce an error callback which might be called on xhr.onerror, too.
The async parameter of xhr.open defaults to true and can be removed
Your getAds function could be split into a generic getJSON function and a getAd function which supplies the specific ad URL to the former.
Your current getAds callback requires knowledge about the specific JSON returned by your ad server. This logic should be part of your "rw-ads.js" library and e.g. become part of the new getAd function.

Exemplary code:

function getJSON(url, success) {
  var xhr = new XMLHttpRequest();
  xhr.open('get', url);
  xhr.responseType = 'json';
  xhr.onload = function() {
    if (xhr.status === 200) {
      success(xhr.response);
    }
  };
  xhr.send();
};

function getAd(id, success) {
  getJSON('http://localhost/ads/complete/index.php/ads/adjson/' + id, function(data) {
    if (data.success) {
      success('');
    }
  });
}

getAd(1, function(html) {
  document.getElementById('ad1').innerHTML = html;
}

General considerations:

Since you don't rely on an external ad network but a self-hosted solution, you might want to inject your ads into your HTML document on the server side, without the asynchronous client side ajax request.


Make a new design of Stack with a new function

It's O(1) no loops or recursion that I can see.

You shouldn't have to keep 2 stacks though. You can instead a second minNext field in the Node. It should be null except for when it contains the minimum of all subsequent elements (or it would be the top if the min stack).

public void push(int data) {
    Node newNode = new Node(data);
    if (top == null) {
        this.top = newNode;
        this.min = newMin;
    } else {
        newNode.next = this.top;
        this.top = newNode;
        if (newMin.data < this.min.data) {
            newNode.nextMin = this.min;
            this.min = newNode;
        }
    }
}

public int pop() {
    if (top == null) {
        return -1;
    }
    int tempInt = this.top.data;
    if (this.top == this.min) { // check for equality of the nodes themselves
        this.min = this.top.nextMin;
    }
    this.top = this.top.next;
    return tempInt;
}


A Summation Function For Arbitrary Nested Vector Implementation In C++

The template seems reasonable, although inputArray is a misnomer. However, there is a major drawback that can be remedied with a single &: use call-by-reference instead of call-by-value (see guidelines):
template<class T>
inline long double Sum(const std::vector<T> &inputArray)
{
    ...
}

Other than that it's perfectly fine for summing arbitrary nested std::vector<double>.
That being said, there is some room for further experiments:

enable Sum for anything that has begin() and end()
enable Sum for other types than double (e.g. int)

Also, I'm a little bit concerned by the comment that declaration and definition were split. While it's possible, it's usually not intended.


If readability is a concern, why use single-character variable names? Replace them with something a bit more meaningful: v -> value, n -> next_, etc.

If you followed Python's data model your class could be used more easily and conventionally. For example, implementing size as a method seems a bit odd - if you called it __len__, then it would behave correctly with len and in a boolean context. Looking at the documentation for other, similar data structures can help with picking sensible names (I would expect an insert to take an index, for example, like the other sequences); in your case, maybe start with the deque's interface.

If you follow the conventional implementation, any of the following should work in a predictable way:

if thing in linked_list:
for thing in linked_list:
list(linked_list) (which would really simplify your __str__ implementation)
if linked_list:

You could also leverage Python's abstract base classes; if you inherit from Sequence and implement the required methods, for example, you get some additional behaviour for free.

In general you're following the style guide, but Node as a temporary variable name sticks out. It shadows the class you just instantiated and naming a variable in CamelCase is not the convention, it should be snake_case. In fact, it's entirely pointless; why not just self.node = Node(v, self.head)?


To my taste it's doing way to much. You'd be better off if you implemented the paging logic for a collection without mixing it with console interaction.

Write another method that expects a collection, page, page length etc. and do the navigation in another method.

If you do this you can test the paging alogorithm without the console and without key input. You'll be also able to test the navigation separately.

Even better, your paging method will be reusable.

To speed up the paging you could group the items by page. If you then ToList() it you can access each page directly without reiterating the collection each time:

public static IEnumerable<IGrouping<int, T>> GroupByPage<T>(this IEnumerable<T> values, int pageSize)
{
    var currentPage = 0;
    var page = new Func<int, int>(index => index > 0 && index % pageSize == 0 ? ++currentPage : currentPage);
    return values
        .Select((v, i) => new { v, i })
        .GroupBy(x => page(x.i), x => x.v)
        .ToList();
}

Here's another example with a decorator:

First we create an interface:

public interface IPager<out T>
{
    int PageIndex { get; }
    int PageSize { get; }
    int PageCount { get; }
    IGrouping<int, T> CurrentPage { get; }
    IGrouping<int, T> this[int page] { get; }
    void Next();
    void Prev();
}

Then we create a general pager:

public class Pager<T> : IPager<T>
{
    private int _pageIndex;

    private readonly IEnumerable<IGrouping<int, T>> _pages;

    public Pager(IEnumerable<T> values, int pageSize)
    {
        PageSize = pageSize;
        var currentPage = 0;
        var page = new Func<int, int>(index => index > 0 && index % pageSize == 0 ? ++currentPage : currentPage);
        _pages = values
            .Select((v, i) => new { v, i })
            .GroupBy(x => page(x.i), x => x.v);
    }

    public int PageIndex => _pageIndex;

    public int PageSize { get; }

    public int PageCount => _pages.Count();

    public IGrouping<int, T> this[int page] => _pages.ElementAtOrDefault(page);

    public IGrouping<int, T> CurrentPage => this[_pageIndex];

    public void Next() => _pageIndex++;

    public void Prev() => _pageIndex--;

}

Now we create another pager but this time it can display the item in the console:

public class ConsolePager<T> : IPager<T>
{
    private readonly IPager<T> _pager;

    public ConsolePager(IPager<T> pager)
    {
        _pager = pager;
    }

    public int PageIndex => _pager.PageIndex;

    public int PageSize => _pager.PageSize;

    public int PageCount => _pager.PageCount;

    public IGrouping<int, T> CurrentPage => _pager.CurrentPage;

    public void Next() => _pager.Next();

    public void Prev() => _pager.Prev();

    public IGrouping<int, T> this[int page] => _pager[page];

    public void Run()
    {
        var pageWidth = Console.WindowWidth - 1;
        var keyInfo = new ConsoleKeyInfo();

        do
        {
            if (keyInfo.Key == ConsoleKey.RightArrow || keyInfo.Key == (ConsoleKey)0 || keyInfo.Key == ConsoleKey.LeftArrow)
            {
                if (keyInfo.Key == ConsoleKey.RightArrow && _pager.PageIndex < _pager.PageCount - 1)
                {
                    _pager.Next();
                }
                else if (keyInfo.Key == ConsoleKey.LeftArrow && _pager.PageIndex > 1)
                {
                    _pager.Prev();
                }
                Console.Clear();
                Console.BackgroundColor = ConsoleColor.White;
                Console.ForegroundColor = ConsoleColor.DarkRed;
                var headerText = string.Format("Page:[{0}]/[{1}] │ Records:[{2}] ║ [◄] Previous │ [►] Next │ [Esc] Escape", _pager.PageIndex + 1, _pager.PageCount, _pager.CurrentPage.Count());
                Console.WriteLine(headerText.PadRight(Console.BufferWidth - 1, ' '));
                Console.ResetColor();

                foreach (var item in _pager.CurrentPage)
                {
                    var row = item.ToString();
                    if (row.Length > pageWidth)
                    {
                        row = row.Substring(0, pageWidth);
                    }
                    Console.WriteLine(row);
                }
            }
            keyInfo = Console.ReadKey(true);
        } while (keyInfo.Key != ConsoleKey.Escape);
    }
}

Usage:

new ConsolePager<int>(
    new Pager<int>(Enumerable.Range(1, 1000),
    Console.WindowHeight - 2)
).Run();


Ugly optimized caching of SimpleDateFormat

What about using a WeakHashMap?  The memory leak is not really an issue since the memory can be reclaimed at any time.

Also, if I were using a map, I would define a FormatAndLocale util class, with valid hashCode and equals, to be used as keys.


Firstly, this can be rewritten as:

if(((letter == 'E' || letter == 'R')&& secondLetter == 'Q' && DoFlip == false)||
   ((letter == 'E' || letter == 'R') && secondLetter == 'A' && DoFlip == true)
    {
      //DoSmth here
    }

According to distributive law -

A && B || A && C = (B || C) && A

In your logic - (letter == 'E' || letter == 'R') can take place of A with (secondLetter == 'Q' && DoFlip == false) as B and (secondLetter == 'A' && DoFlip == true) as C.

So your logic can be simplified to -

if((letter == 'E' || letter == 'R') &&
   ((secondLetter == 'Q' && DoFlip == false) ||
   (secondLetter == 'A' && DoFlip == true))


Find spiral 2D matrix (List of Lists) of ints in a clockwise spiral

Just reviewing solution 1.

The solution is clever (repeatedly extract the first row and rotate the remainder by a quarter-turn) and the code terse.
However, the code destructively modifies the input matrix by popping the first row. This would be surprising to the caller and might make it more difficult to use or to test.
The code does not work in Python 3: it fails with the exception:

TypeError: 'zip' object is not subscriptable

In Python 3 you would have to write list(zip(...)). Since Python 2.7 is close to its end of life it is a good idea to write code that would be easy to port to Python 3. In this case you could use

from future_builtins import zip

to get a version of the built-in zip function that's compatible with Python 3.
If the input is an \$n×n\$ matrix, then rotating the remainder takes \$O(n^2)\$ and this has to be done \$O(n)\$ times, leading to a total runtime of \$O(n^3)\$. But intuitively it ought to be possible to output the spiral in \$O(n^2)\$.

We can achieve this by implementing the same approach (repeatedly extract the first row and rotate the remainder by a quarter-turn) but instead of modifying the matrix, we instead modify our system of coordinates. This is probably easiest to see if I give the code first:

def find_spiral_2(matrix):
    "Return list of elements of matrix in clockwise spiral order."
    h, w = len(matrix), len(matrix[0]) # Height and width of remainder
    i, j = 0, -1                # Current position in spiral
    di, dj = 0, 1               # Current direction of movement
    spiral = []
    while h > 0:
        # Output top row
        for _ in range(w):
            i += di
            j += dj
            spiral.append(matrix[i][j])
        # Remove top row and rotate quarter-turn
        h, w = w, h - 1
        di, dj = dj, -di
    return spiral

The way this works is that we maintain the state of the algorithm in the form of the height \$h\$ and width \$w\$ of the remainder of the matrix, the coordinates \$(i, j)\$ of our current position along the spiral, and a vector \$(di, dj)\$ giving the current direction of movement along the spiral path.

To output the top row, we follow the current direction for \$w\$ steps, leaving us in the top-right corner of (the remainder of) the matrix. Then, as in your solution, we remove the top row and rotate the remainder though a quarter-turn—or rather, we modify our coordinates to have this effect. Removing the top row subtracts 1 from \$h\$. Rotating the remainder through a quarter-turn causes \$w\$ and \$h\$ to swap (height becomes width and vice versa) and the current direction of movement to rotate through a quarter-turn. You should check that the line di, dj = dj, -di achieves this.

It should be clear that this does not modify matrix, and runs in \$O(n^2)\$ as required.


Create user in users table and insert data into second table with one form in Laravel Relationships

It's a correct way to do it like this.
Few suggestions:

Add validation before creating user. You don't want to fail on save for duplicate user email. For better UX if you can it's a good idea to do it even before form submit (with ajax request when email field is changed).

If your app has more user related things like user profile, user control panel I will suggest you to auto login user after form submit. Just before redirect() add Auth::login($user)


Make change for a given amount given denominations

You have implemented the greedy algorithm for making change: starting with the largest denomination, divide, then use the smaller coins to handle the remainder.

That works for many coin systems, but in the general case, it fails to produce optimal results:

  Greedy method

  For the so-called canonical coin systems, like the one used in US and many other countries, a greedy algorithm of picking the largest denomination of coin which is not greater than the remaining amount to be made will produce the optimal result. This is not the case for arbitrary coin systems, though: if the coin denominations were 1, 3 and 4, then to make 6, the greedy algorithm would choose three coins (4,1,1) whereas the optimal solution is two coins (3,3).

Therefore, if you want to use as few coins as possible, where the set of denominations is arbitrarily picked by the user, you have to use a different algorithm — typically one based on dynamic-programming.

So, either your code is wrong, or needs a comment to warn of that significant caveat.


Python 'check if number is divisible by 2' program

Well, first of all, you should put code in an if __name__ == '__main__': block to make sure it doesn't run whenever the file is imported.  Thus, just copy pasting:

if __name__ == '__main__':
    print 'Question 4. \n'

    num = float(raw_input('Enter a number that is divisible by 2: '))
    while (num%2) != 0:
        num = float(raw_input('Please try again: '))

    print 'Congratulations!'

The next thing to notice is that a number being even is actually a fairly common check to make.  Such things should be turned into functions.  Mostly copy-pasting again:

def is_even(num):
    """Return whether the number num is even."""
    return num % 2 == 0

if __name__ == '__main__':
    print 'Question 4. \n'

    num = float(raw_input('Enter a number that is divisible by 2: '))
    while not is_even(num):
        num = float(raw_input('Please try again: '))

    print 'Congratulations!'

Notice the docstring:  it's important to document your code, and while the purpose of is_even is obvious, getting into the habit of adding documentation is good.  You could also put the following docstring at the top of the file:

"""Provide the is_even function.

When imported, print prompts for numbers to standard output and read numbers
from standard input separated by newlines until an even number is entered.  Not
entering an even number raises EOFError.

"""

In my opinion, you should get into the habit of programs working on files, not on user input; you'll find that programs are much easier to chain that way.

Possible further improvements are handling the EOFError (catching it and printing something like "No even numbers entered."), splitting the repeating functionality into a main function (questionable use), and maybe adding a read_float function that would be something along the lines of

def read_float(prompt):
    """Read a line from the standard input and return it as a float.

    Display the given prompt prior to reading the line.  No error checking is done.

    """
    return float(raw_input(prompt))

Here too, there is plenty of room for error checking.

I removed the parentheses around (num%2) as I went along; PEP8 discourages these, if I remember correctly.  Either way, it is a very valuable read.


Scraping website for book listings, checking if database contains relevant listings, and displaying result in a Django view

After I process the URL to get the book info, I see if we have it in our database. If we don't, I move on, that's fine.

I guess you're referring to this part of the code:

try:
    book = books.get(book_num=book_num,
                     object_type_cd_id=object_type_cd.upper())
except book.DoesNotExist:
    pass

This doesn't do what you described,
because after the pass,
the rest of the loop body is executed instead of moving on the next iteration.
Perhaps you meant to use continue there instead of pass.

Instead of having an empty if block and an else block here,
it would be better to flip the condition and have only an if block without an else:

if (BookTextVer.objects.filter(
    book=book,
    book_text_ver_type__short_name=book_type.upper()).exists()):
    pass  # matching book type exists, no processing needed
else:
    data.append({"book": object_type_cd.upper() + book_num,
                 "book_type": book_type.upper()})

The query on BookTextVer tries to match by short_name.
Is that field indexed in the database.
If not, the query will be inevitably slow,
and indexing should be a significant improvement.

The current implementation runs 1 or 2 queries for every node in tree.getchildren().
You might get better performance if you first collect all the book_num, book_type, object_type_cd values from the document,
and formulate a single database query or constant number of database queries.
That would be a major change,
and possibly you might need to forego Django's OR-mapping benefits,
but the reduced number of database queries could make a big difference.


LD R0, x001f  ; fetches data from x3020, stores into R0
LD R1, x001f  ; fetches data from x3021, stores into R1
ST R2, x001B  ; Stores result into x3022

All of these instructions are correct. When the first instruction is being executed the PC is at x3001. Adding x001F to it will correctly address location x3020. When the third instruction is being executed the PC is at x3007. Adding x001B to it will address location x3022.
From the manual we learn

  Program Counter; 16-bit register that contains the memory address of the next
  instruction to be fetched. For example, during execution of the instruction at address
  A, the PC contains address A + 1, indicating the next instruction is contained in
  A + 1.

and also

  Memory address space 16 bits, corresponding to 65,536 locations, each
  containing one word (16 bits). Addresses are numbered from 0 (i.e, x0000)
  to 65,535 (i.e., xFFFF).

Here's an alternative to your OR solution

NOT R1,R1
AND R0,R0,R1
NOT R1,R1
ADD R0,R0,R1

The less registers you use the better on the very limited architecture of the LC-3.


Extension methods for methods and properties that don't use non-public data

My personal view is create an extension method if:

The class/interface you wish to extend is not created by you.
The class/interface is created by you but the behavior of the extension method is only required in an assembly that doesn't contain the class (e.g. class Person is defined in MyApp.dll, but GetAge() is only required in MyApp.UI.exe).
The behavior can be defined against a more generic abstraction than the class itself where the implementation is the same but the classes don't share a common base. e.g. create an ILifeSpan interface with DateTime DateOfBirth and DateTime DateOfDeath properties and create the extension method public static double GetAge(this ILifeSpan lifeSpan)

FYI extension methods are just a compiler trick, the generated IL just calls the static method, the this keyword just allows you to write less code in visual studio.

when you call person.GetAge();, it is compiled to PersonExtensions.GetAge(person);


Django view to display weather measurements for selected location and dates

Not sure this will solve all your problems, but you can give those GET parameters default values in case they don't exist. In my example below, they are given the default value of None. This should simplify things a bit.

def index(request):

    print('hello')

    location = request.GET.get('location', None)
    selectstartdate = request.GET.get('selectstartdate', None)
    selectenddate = request.GET.get('selectenddate', None)

    if location is not None or selectstartdate is not None and selectenddate is not None:

        # Get locations from db.
        locations = Location.objects.all()

        # Prepare locations dictionary for google map layer js.
        locs_ls = []
        for loc in locations:
            lat = loc.latitude
            lon = loc.longitude
            name = loc.name
            site_id = loc.site_id

            locs_ls.append({'site_id': site_id, 'name': name, 'lat': lat, 'lon': lon})

        context = {
            'locs_ls': locs_ls,
        }

        return render(request, 'locations/index.html', context)

    else:

        params = {
            'location': location,
            'selectstartdate': selectstartdate,
            'selectenddate': selectenddate,
        }

        context = single_location(**params)

        return render(request, 'locations/location.html', context)


If your goal is to optimize efficiency, you can do a little better by only looking at each character in the string once. The first remainder characters of the string will occur quotient + 1 times. The remaining characters will occur quotient times. So you can loop once from 0 to remainder and do some math, then loop from remainder + 1 to s.length() and do some math, and you'll have your result. It's unclear without testing whether it's faster to do the multiplication outside or to add the correct amount in your loop. Also, your short-circuit for inputs of length one is not helpful unless you expect that most of the inputs will be a single-character. It's probably safe to pull it.

If your goal is to avoid overcomplicating things, websites like HackerRank may not be ideal. They tend to provide algorithmic challenges that reward hyper-optimized code. By their nature, those kinds of solutions will be complicated. It turns out it's hard to write an AI that will grade readable code, but easy to write one that will grade performant code. So even though readable code is much more desirable, performant code is what scores well.


Well, there's no need to copy the short into an array of (unsigned) char:
Treating any type as an array of (optionally signed/unsigned) char is an explicit exception from the strict-aliasing-rule.
(I assume your targets byte-order is big-endian for that. Or you will need to byte-swap it first.)
Unless prefix_A and/or prefix_B should ever be dynamically changed, mark them as const so you don't change them accidentally, and the compiler knows they cannot change so it will optimize accordingly.

So it becomes:

// constants
const short prefix_A = 3 << (4+8);
const short prefix_B = 11 << (4+8);

void send_cmd(bool A, short cmd){
    assert( cmd < 4096);
    cmd |= A ? prefix_A : prefix_B;
    cmd = htons(cmd); // byte-swap if little-endian
    wiringPiSPIDataRW(0, (unsigned char*)&cmd, 2);
}


Let's look at your questions individually:

Am I utilizing dependency injection correctly?
Yes and no. You are, essentially, injecting the routes. That's fine. But you extract them from a $config object. If you are working out some MVC (micro-) framework, then chances are that config object is an instance of a specific class.

As your code-base grows, so will the config, and chances are pretty good that the Route class will need more data from the config. Instead of passing an array to the constructor then, I'd simply pass the whole $config object, and type-hint that.
That way, when you only have to refactor the Route constructor (as opposed to all code that creates a new Route instance) if you decide to add to the config object, something the Route class needs. For example: a list of approved/registered classes that the load method can instantiate:

private $routes = null;
private $classMap = array();
public function __construct(Config $conf)
{
    $this->routes = (array) $conf->routes;
    foreach ($conf->classMap as $class => $paramData)
    {//paramData could contain which arguments are required
     //which are optional, or default values
        $this->classMap[$class] = array(
            'required' => isset($paramData['required']) ? $paramData['required'] : array(),
            'defaults' => isset($paramData['defaults']) ? $paramData['defaults'] : array()
        );
    }
}

The load method... There is a lot to say about this, but as it now stands, I have a couple of suggestions:

Why not group the $routes by method? Suppose you have 100 routes in total, 20 of which are POST routes, what good does looping through all 100 routes do?

You are not properly escaping the path regex. Suppose there is a question mark in the $regex string? By calling str_replace('/', '\/', $regex); you're also not quite doing what you thing you are doing. You're creating an escape sequence, escaping the forward slash, not the backslash you effectively need!
You want to escape the delimiter, so you should escape the backslash: use str_replace('/', '\\/', $regex);
However all this is pretty useless anyway, simply because there exists a ready-made PHP function that can escape a string that is going to be used in preg_match a lot better anyway:

 $regex = preg_quote($regex, '/');

And instead of calling this function every time the load function is called: use a setter (or 2 setters) for the $this->routes property:

public function setRoutes(array $routes)
{
    //assume GET && POST keys, too:
    $this->routes = array(
        'GET' => array(),
        'POST' => array()
    );
    foreach ($this->routes as $method => $x)
    {//ignore $x
        if (!isset($routes[$method]))
            continue;//ignore. Be weary: case sensitive, a class would be useful here
        foreach ($routes[$method] as $regex => $class)
        {
            //optionally check $class is allowed by $this->classMap!
            $this->routes[$method][preg_quote($regex, '/')] = $class;
        }
    }
}

Now this is written off the top of my head, and a bit messy. What follows is messier still, but just so you know: you can write this as a one-liner, if you use / as the regex delimiter:

$this->routes = array(
    'GET'  => array_combine(
        array_map(
            'preg_quote',
            array_keys($routes['GET'])
        ),
        $routes['GET']
    ),//same for POST
);

If you decide to use a different delimiter:

$this->routes = array(
    'GET'  => array_combine(
        array_map(
            'preg_quote',
            array_keys($routes['GET']),
            array_fill(0, count($routes['GET']), '~')//~ is now your delimiter
        ),
        $routes['GET']
    ),
);

Now, the $method and $params arguments from the constructor are only really used in the load method. Why pass them to the constructor? Why not pass them to load, and make them optional? If ever you want to write tests for this class, surely it would be easier to be able to pass invalid/impossible requests to this class.
And even when not testing: Sometimes you want your controller to perform the actions defined in 2 distinct controller actions. By changing the route, and call load again, you could do just that.

Making them optional implies that calling load will have load fall back to the $_SERVER super-global. Even so, let me now tell you why you shouldn't refactor this Route class too much, by answering your next question:

Any parts of my class that I should decouple?
Perhaps you should first ask yourself what this class is? Its name, to me, suggests it is a router class. What is a router class's job? Surely, it is to parse, validate, generate URLS, and perhaps redirect.
The URL it extracts from a request can then be used by a dispatcher or front-controller to create an instance of a specific controller, and invoke methods.

A router can indeed check to see if there are some request parameters, but processing and validating those parameters falls, in turn, under the responsibility of a Request object.
On more details on this matter, you can check this answer of mine, which reviews a Request object.

So: the answer to this question is: yes. Your code is not SOLID, as it violates the single responsibility principle by acting as a dispatcher, router, and in some ways request object factory.
Well, it doesn't function as a request object just yet, but it passes the request params to the classes it instantiates. Chances are that, in time, you'll be adding some validation methods to this class, or create a new object (Params or something), and have your Route class create those instances as it passes them to the classes load creates...

Anything I could improve in my code when it comes to OOP (and MVC)?
At this point: you're going to have to work on this some more: you show one class that is quite small. There are signs of promise, but I can't honestly assess your OO skills or correctness of your understanding of OO paradigms and MVC pattern.

The only thing I really can and will criticize on is your coding style. Now you may think this is a simple matter of personal preference, but really: it's important to follow certain standards! Such standards exist: Python has PEP, PHP has FIG, their site: PHP-FIG.
One of the things I've noticed is your tendency of prepending every non-public property/method with an underscore. This practice stems from the days where PHP didn't (yet) have access modifiers - back in the days of PHP4.
Read through the PSR documents, and conform to those standards as much as you can.
I try to conform to everything in there, except for my Allman brackets. I know, I need to practice what I preach, but a single deviation from the standards is not that bad, IMO, especially if you have a good IDE, simply re-format your code before commiting to GIT, and nobody need ever know :).

On the last, I have one thing that is rather worrying to me: You create an instance of a given class, and pass the request params to either a GET or POST method. That sounds to me like you have 1 class for each possible URL. That is absolutely not the way to go

Before you start, always see what is already out there: Symfony2, Zend, CI, Cake... are all MVC frameworks that have been around for a long time. They are all open-source, and have a routing component. Just check the source code of those projects, and see if you can't get any ideas from that

Remember: A good programmer is a lazy one. Don't invent something that already exists.


Find maximum distance between elements of an array

...and welcome to Scala :)

I will show changes in several steps:

a) Almost automatic changes without changing any part of the logic:

object CycleProblem extends App {
  val input: Array[Int] = Array(-1000, 1000, -30, 70, 80, 20, 100, 110, -120, -180, 120)
  val minVal = input.min
  val maxVal = input.max
  var maxDistance = 0
  var index = minVal - 1
  for (i <- minVal to maxVal) {
    var distance = 0
    for (j <- input.indices) {
      distance = distance + Math.abs(i - input(j))
    }
    if (distance > maxDistance) {
      maxDistance = distance
      index = i
    }
  }
  println(s"Park the bicycle in this location: $index. The distance(maximum when compared to to other indices) from all other parked location is: $maxDistance")
}

Replaced the main method with extends App
Removed a couple of semicolons ;
Used string interpolation
Used plain min and max methods instead of reduce
Used .indices instead of 0 to input.length-1. You can also use the prettier 0 until input.length.

b) Important enough to get its own step: Separate your algorithm into a (stateless) function! Stateless means that the same input always produces the same output (what you intuitively expect from a function).

object CycleProblem extends App {
  val input: Array[Int] = Array(-1000, 1000, -30, 70, 80, 20, 100, 110, -120, -180, 120)

  val (index, maxDistance) = findValueInRangeWithMaxTotalDistance(input)

  println(s"Park the bicycle in this location: $index. The distance(maximum when compared to to other indices) from all other parked location is: $maxDistance")

  private def findValueInRangeWithMaxTotalDistance(input: Array[Int]): (Int, Int) = {
    val minVal = input.min
    val maxVal = input.max
    var maxDistance = 0
    var index = minVal - 1
    for (i <- minVal to maxVal) {
      var distance = 0
      for (j <- input.indices) {
        distance = distance + Math.abs(i - input(j))
      }
      if (distance > maxDistance) {
        maxDistance = distance
        index = i
      }
    }
    (index, maxDistance)
  }
}

c) Now come the real changes: The algorithm I use is exactly the same, but expressed via functional methods on collections. You can also uncomment my println comment for check the logic of your algorithm.

object CycleProblem extends App {
  val input: Array[Int] = Array(-1000, 1000, -30, 70, 80, 20, 100, 110, -120, -180, 120)
  val (maxValue, maxDistance) = findValueInRangeWithMaxTotalDistance(input)
  println(s"Park the bicycle in this location: $maxValue. The distance(maximum when compared to to others) from all other parked location is: $maxDistance")

  def findValueInRangeWithMaxTotalDistance(input: Array[Int]): (Int, Int) = {
    def distance(a: Int, b: Int) = Math.abs(a-b)
    val valueRange = input.min to input.max
    val valuesInRangeWithTotalDistance = valueRange.map { numInRange =>
      val sumOfAllDistances = input.map(itemInInput => distance(numInRange, itemInInput)).sum
      //println(s"$numInRange, $sumOfAllDistances")
      (numInRange, sumOfAllDistances)
    }
    //valuesInRangeWithTotalDistance.foreach(println)
    valuesInRangeWithTotalDistance.maxBy(_._2)//_2 is the second element, i.e. the distance
  }
}

d) When you get accustomed to functional expressions, you can collapse the code into a few neat lines of code:

object CycleProblem extends App {
  val input: Array[Int] = Array(-1000, 1000, -30, 70, 80, 20, 100, 110, -120, -180, 120)
  val (maxValue, maxDistance) = findValueInRangeWithMaxTotalDistance(input)
  println(s"Park the bicycle in this location: $maxValue. The distance(maximum when compared to to others) from all other parked location is: $maxDistance")

  def findValueInRangeWithMaxTotalDistance(input: Array[Int]): (Int, Int) = {
    def distance(a: Int, b: Int) = Math.abs(a-b)
    val valuesInRangeWithTotalDistance = (input.min to input.max).map(numInRange => (numInRange, input.map(distance(numInRange, _)).sum))
    valuesInRangeWithTotalDistance.maxBy(_._2)
  }
}

Note my very long function name: I am reducing noisy lines of code that obscure the essence of the code (don't take it personally, it is inherent in java-like code) and add long names to describe the logic of the encapsulated algorithm.

e) To highlight my point about clarity, note that the return type of our function is (Int,Int). It is not clear what is what, lets fix it by adding a case class to hold our result:

object CycleProblem extends App {
  val input: Array[Int] = Array(-1000, 1000, -30, 70, 80, 20, 100, 110, -120, -180, 120)
  val result = findValueInRangeWithMaxTotalDistance(input)
  println(s"Park the bicycle in this location: ${result.value}. The distance(maximum when compared to to others) from all other parked location is: ${result.distance}")

  case class ValueAndDistance(value: Int, distance: Int)
  def findValueInRangeWithMaxTotalDistance(input: Array[Int]): ValueAndDistance = {
    def distance(a: Int, b: Int) = Math.abs(a-b)
    val valuesInRangeWithTotalDistance = (input.min to input.max).map(numInRange => ValueAndDistance(numInRange, input.map(distance(numInRange, _)).sum))
    valuesInRangeWithTotalDistance.maxBy(_.distance)
  }
}

Again, adding code is good, as long as it makes the logic more clear and fool-proof to your colleagues or the future-you.


Getting functional Common Lisp code for handling state in a SDL animation

I would use CLOS for that. The game state is an CLOS object then. If the thing needs a history, then I would add the history to the CLOS object.

Named slots of something in the history of Lisp:

assoc lists (ca. 1960)
hash-tables
structures (70s)
classes (70s/80s...)

If you look at your update a few things don't look nice:

progn is not needed
way to many SETQs, construct a return value instead
the use of an association list, where a CLOS object should have been used
no explicit return value

(defun update-coords (state)
  (acons 'h-coord (+ (cdr (assoc 'h-coord state))
                     (cdr (assoc 'h-speed state)))
         (acons 'v-coord (+ (cdr (assoc 'v-coord state))
                            (cdr (assoc 'v-speed state)))
                state)))

Sometimes I would want to get rid of the nesting in above function.

(defun update-coords (state)
  (list* (cons 'h-coord (+ (cdr (assoc 'h-coord state))
                           (cdr (assoc 'h-speed state))))
         (cons 'v-coord (+ (cdr (assoc 'v-coord state))
                           (cdr (assoc 'v-speed state))))
         state))

Alternatively you can use the backquote notation. , evaluates. ,@ evaluates and splices the result in.

(defun update-coords (state)
  `((h-coord . ,(+ (cdr (assoc 'h-coord state))
                   (cdr (assoc 'h-speed state))))
    (v-coord . ,(+ (cdr (assoc 'v-coord state))
                   (cdr (assoc 'v-speed state))))
    ,@state))

I would add Practical Common Lisp by Peter Seibel to the reading list. It teaches a larger subset of more idiomatic Common Lisp than for example On Lisp.

With CLOS the code looks much simpler. Example without history:

(defclass game-state ()
  (h-coord v-coord h-speed v-speed))

(defmethod update-coords ((state game-state))
  (with-slots (h-coord h-speed v-coord v-speed)
      state
    (incf h-coord h-speed)
    (incf v-coord v-speed))
  state)