PHP MySQLi Prepared Statements: Can this select query be hacked/injected?

Given an answer on Stack Overflow suggests almost identical code for protection, let alone using exactly the same principle you can safely assume that your query is protected.

If you want to know how it works, I also wrote an answer on Stack Overflow, https://stackoverflow.com/a/8265319/285587

Nevertheless, as this site is for the code reviews offering some suggestions, I would suggest to use PDO for database interactions instead of mysqli. Simply because PDO API is much more versatile and easier to use. see your snippet rewritten in PDO:

$stmt = $mysqli->prepare("SELECT * FROM myTable WHERE name = ?");
$stmt->execute([$_POST['name']]);
if($stmt->rowCount() === 0) exit('No rows');
while($row = $stmt->fetch_assoc()) {
  //do some stuff
}

as you can see some nagging operations are just gone. I wrote a tutorial on PDO, which I would quite expectedly recommend.


Find the total volume traded for each stock and also find the high and low for each of those stocks

I see a number of things that could help you improve your code.

Don't abuse using namespace std

Putting using namespace std within your program is generally a bad habit that you'd do well to avoid.

Don't redefine standard names

This definition is a problem:

typedef basic_string<char> string;

It redefines std::string (because you've used the global namespace).  Better would be to simply use std::string without redefining it.

C++ is case sensitive

Your code includes a line:

Map<std::string, int> TotalVolumes;

There is no Map, but there is std::map.  Write the line like this instead:

std::map<std::string, int> TotalVolumes;

Don't rely on unspecified execution order

The code currently contains this:

sscanf(line, "%s %d %d %f %f",
    Stocks[i], &Intervals[i],
    &Volumes[i], &Highs[i], &Lows[i++]);

The problem is that it appears you're assuming that i is incremented after the sscanf completes, but that's not guaranteed by the standard and the code is ambiguous.  Instead, write it like this:

sscanf(line, "%s %d %d %f %f",
    Stocks[i], &Intervals[i],
    &Volumes[i], &Highs[i], &Lows[i]);
++i;

Use const where possible

The CHighLow::getSum function does not (and should not) alter the underlying data structure and should therefore be declared const.

Don't return a reference to a local variable

The CHighLow::getSum() function is written as returning a reference to an int.  In addition to this being somewhat unusual, in this case, it's also incorrect.  The reason is that it's returning a reference to sum which is a local variable within the function.  When the function returns the variable goes out of scope and is destroyed, so the reference is now pointing to unallocated memory.  That's a serious bug!  Instead, just return an int as in:

int getSum() const
{
        return nCurLow + nCurHigh;
}

Eliminate unused variables

Unused variables are a sign of poor code quality, so eliminating them should be a priority.  In this code, sum is set to 0 within main() but then never actually used.  My compiler also tells me that.  Your compiler is probably also smart enough to tell you that, if you ask it to do so.

Check array length before dereferencing

If the user fails to give the program command line arguments, this line will fail:

FILE*   file = fopen(argv[2], "r");

It would fail because there might might not be any argv[2] so you should check the argc value first and exit with an error, perhaps telling the user what the program requires, if there aren't enough arguments.

Make member data private

The the two data members of the CHighLow class are public so any function or code can alter their contents.  This is not generally good design.  Instead, make them private.  Because the only instance their needed is for output, that can be neatly solved with the next suggestion.

Write a custom stream inserter for a class

The code currently contains this:

std::map<std::string, CHighLow>::iterator itr = HighLows.begin();
while (itr != HighLows.end())
{
        std::cout << (*itr).first << "," << (*itr).second.nCurLow << "," <<
                     (*itr).second.nCurHigh << std::endl;

        ++itr;
}

There are a number of things that could be improved here.  First, use a "range-for" and second, use a custom stream inserter.  That results in this code:

for (const auto &stock: HighLows) {
    std::cout << stock.first << "," << stock.second << '\n';
}

Then in the class, create a custom inserter:

friend std::ostream& operator<<(std::ostream &out, const CHighLow &hilo) {
    return out << hilo.nCurLow << "," << hilo.nCurHigh;
}

Use C++ file I/O

Don't use the ancient FILE* I/O but instead use modern C++ std::fstream.  The interface is neater and you can write a nice class extractor instead of having all of the details for extracting data placed within main.

Don't use std::endl if '\n' will do

Using std::endl emits a \n and flushes the stream.  Unless you really need the stream flushed, you can improve the performance of the code by simply emitting '\n' instead of using the potentially more computationally costly std::endl.

Don't return nonzero from main unless there's an error

The convention in programming in C and C++ is that the returned integer from main() is considered by the operating system to be construed as an error code.  For that reason, the non-error condition is signalled by returning a 0.  Your code ends with return 1 which will be interpreted by most operating systems as an indication that an error was encountered.  Because the compiler will automatically generate the equivalent of a return 0; at the end of main(), I'd advocate simply omitting it.


Determining if the mouse is on top of a box

I don't see a convenient way to do a for loop, but you could extract common functionality into a single function:

bool CheckAndModify(PictureBox pb)
{
    if (displayCollision(drop, pb) && (display != pb))
    {
        display.Location = pb.Location;
        display.Size = pb.Size;
        pb.Location = defaultLocation;
        pb.Size = defaultSize;
        return true;
    }
    return false;
}

And then:

bool modified = CheckAndModify(pbDisplay1) ||
                CheckAndModify(pbDisplay2) ||
                CheckAndModify(pbDisplay3) ||
                CheckAndMovify(pbDisplay4);

Or, I suppose a loop would be possible:

foreach (var pbDisplay in new[]{pbDisplay1, pbDisplay2, pbDisplay3, pbDisplay4})
{
    if (CheckAndModify(pbDisplay))
    {
        break;
    }
}


You could make the code better (and shorter) by using regex to split any delimiters that occur in the string, for example, in Hello.world, the string (list form) would then be like ['', 'Hello', ''] (after splitting the first word from delimiters) and then you can access the first word from index [1] (always). Like this,

import re
def first_word(s):
    return re.split(r"(\b[\w']+\b)(?:.+|$)", s)[1]

Here are some tests:

tests = [
"Hello world",
"a word",
"don't touch it",
"greetings, friends",
"... and so on ...",
"hi",
"Hello.world",
"Hello.world blah"]

for test in tests:
    assert first_word("Hello world") == "Hello"
    assert first_word(" a word ") == "a"
    assert first_word("don't touch it") == "don't"
    assert first_word("greetings, friends") == "greetings"
    assert first_word("... and so on ...") == "and"
    assert first_word("hi") == "hi"
    assert first_word("Hello.world") == "Hello"
    assert first_word("Hello.world blah") == "Hello"
    print('{}'.format(first_word(test)))

(\b[\w']+\b)(?:.+|$) is used above, where (\b[\w']+\b) calls the first word of the string (in list form). \b allows you to perform a "whole words only" search using a regular expression in the form of \b"word"\b. Note that using [\w'] (instead of [\w+]) leaves the apostrophe in don't. For (?:.+|$), you can take a look here.

Here are the expected outputs:

Hello
a
don't
greetings
and
hi
Hello
Hello

After timing it -

%timeit first_word(test)
>>> 1.54 µs ± 17.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

NOTE - A delimiter is a sequence of one or more characters used to specify the boundary between separate, independent regions in plain text or other data streams. An example of a delimiter is the comma character, which acts as a field delimiter in a sequence of comma-separated values.

Hope this helps!


Remove the useless functions
There's already a sum function. It's called +
Instead of
Console.WriteLine(Sum(n1, n2));

and
static Decimal Sum(Decimal n1, Decimal n2)
{
    Decimal sum;
    sum = n1 + n2;
    return sum;
}

just write
Console.WriteLine(n1 + n2);

... and the exact same thing applies to all the other calculation functions you wrote.
The same thing in every branch of an if
No matter what op is, you do Console.ReadLine();. So delete it from each if/else if/else and just add it after the end of the if.


I don't think there is much to simplify with your code.

Used short array syntax, since you're running PHP 5.5.
Renamed $model to $user: It increases readability + it's one less character.
If-statement syntactical sugar brackets removed.

Code:

$row = [
  'id'         => 123,
  'username'   => 'Testing',
  'status'     => 1,
  'created_on' => '2014-09-20',
  'created_by' => 1,
  'updated_on' => null,
  'updated_by' => null
];

$user             = new User();
$user->id         = (int) $row['id'];
$user->username   = $row['username'];
$user->status     = (int) $row['status'];
$user->created_by = (int) $row['created_by'];

if ($row['created_on']) $user->created_on = new DateTime($row['created_on']);
if ($row['updated_on']) $user->updated_on = new DateTime($row['updated_on']);
if ($row['updated_by']) $user->updated_by = (int) $row['updated_by'];

I have the impression that your User class is just a container and everybody can edit its properties directly. You might wanna enforce some encapsulation here by using setters and getters. This way you can hide its internal properties and have room to validate any values being set and make sure a User object can never reach a state it wasn't meant to be in.

About your update:

  Am I making the codes more complicated?

Yes! Do you really want to sacrifice all this readability just to get a more "simplified" solution? Really, it ends up over-complicating the solution instead.

Remember that if your code is made out of a bunch of complex and over-complicated logic  because you wanted to "simplify" things, only a computer would understand that with no problem. In a week when you come back to look at your code, you will not be able to understand what's happening at a glance. It will take you a minute, and more often then not it makes you forget how the piece of code you're trying to understand fits in the bigger picture.

Martin Fowler said: "Any fool can write code that a computer can understand. Good programmers write code that humans can understand". And that goes especially if you work in a team. You should value readability over simplified code that over-complicates the solution. It will save you (and your team) a lot of time now and in the future.

  The reason I made the 2nd version is that I worried the 1st version expands if the $row expands.

It's completely acceptable that if your user table gets a new usable column that you would also need to add an extra setter in your code for it. Generally it's something that would rarely happen often.

The solution in your post isn't even complete in regards to your concern. For example, what if you decided to update your table with a column modified_on? You still would have to append || $k == 'modified_on' to the if-statement expression and add the class property for this new column.


I'm not a C++ programmer, but there are a few things that I notice that I feel are important in any language.

Be Consistent:

While you'll find many people that are passionate about different naming conventions and coding styles, one thing that they'll all agree on is to at least be consistent in your choice. There are a few inconsistencies in your code:

You declare a private member of your Component class named parent, and go on to introduce Hungarian notation in your GameObject class with a member named m_Components.
You declare a pointer with a space on either side of the asterisk: Component * parent; and go on with this style in your constructors, but you also connect the asterisk to the type in some other cases: GameObject* GetParent() and SetParent(GameObject* parent).
In your GameObject destructor, you have a for with a single-line body and choose to omit curly braces, but in it's AddComponent member function, you have an if with a single-line body but keep the curly-braces. If you're going to omit curly-braces in the former, you may as well omit them in the latter.
If you insist on omitting the curly-braces, the former could also be written in a more readable manner:

for (size_t i = 0; i < m_Components.size(); ++i)
    if (m_Components[i]->GetParent() == this)
        delete m_Components[i];

Also:

virtual std::string What() { return "Basic Component"; } "What" is not a very descriptive identifier. Consider replacing it with something along the lines of "GetName()"
The dynamic cast:

component_type* c = dynamic_cast<component_type*>(comp);
    if (c) return c;

I've often seen dynamic_cast in this form, which I find more readable:

if (component_type* c = dynamic_cast<component_type*>(comp))
    return c;

You use std::vector for your collection of Components. Any time where you loop through the elements of an std::vector in order to find a single element, you should consider using std::map. Using data structures like these to locate a Value object using a Key object will be much faster than looping through a vector, because it will take the same amount of time regardless of how many items are in the collection. This approach would result in a much faster GetComponent() method

I'm not sure if this is the approach used to implement GetComponent in Unity, but I know that it's advised against using GetComponent in the Update method in Unity because of how slow it is. If you used an std::map to implement your GetComponent method, it would be a marginal difference compared to doing the lookup in advance and storing the result (which is currently the recommended approach in Unity).

That's the only real feedback I have on your object-oriented design. For the most part, it seems like a pretty accurate C++ representation of Unity's component system.


Note that isSorted has a bit of an off-by-one error. It will check outside the bounds of its argument. This actually works OK, because it compares the last element of the array to undefined which always results in false. However, you should really only check up to index_outer < length - 1.

I haven't looked too closely at your implementations of the basic sorting algorithms, but assuming they are correct, then there isn't much that could be said about their efficiency that hasn't already. It's all well defined.


Printing Pascal’s triangle for n number of rows in Python

One issue with your approach is your memory usage is \$O(n^2)\$.  You are building up the entire Pascal's Triangle, and subsequently printing it.  If you simply want to print Pascal's Triangle, you don't need to keep the entire triangle in memory.  You can simply generate and print it row by row.  Since you generate the next row from only the previous row, the memory requirement is simply two rows, which is \$O(n)\$.

>>> row = [1]
>>> for _ in range(5):
...    row = [1] + [x + y for x, y in zip(row[:-1], row[1:])] + [1]
...    print(row)
...
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
>>>

Demystifying [1] + [x + y for x, y in zip(row[:-1], row[1:])] + [1]:

row[:-1] is all the values in row, except the last one.  For example, if row is [1, 3, 3, 1], then row[:-1] is [1, 3, 3].  Similarly, row[1:] is all the values of row except the first, so [3, 3, 1].  zip() takes the first value of each of the lists, and returns those as the tuple (1, 3), which get assigned to x and y respectively, which get added together to get 4.  Then, zip() emits the next pair of values, (3, 3) which results in 6, and then the final pair (3, 1) results in 4, producing the list [4, 6, 4].  The [1] + ... + [1] adds the bookends, which results in the next row of the triangle: [1, 4, 6, 4, 1].

Instead of needing to keep track of the last row, and feed that back to generate the next row, we can package that up into a generator function, which can prime the loop and do the feedback itself:

>>> def pascals_triangle(n):
...     row = [1]
...     yield row
...     for _ in range(n):
...         row = [1] + [x + y for x, y in zip(row[:-1], row[1:])] + [1]
...         yield row
...
>>> for row in pascals_triangle(5):
...     print(row)
...
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
>>>

Format the resulting rows as desired.

>>> for i, row in enumerate(pascals_triangle(5)):
...     print(("   "*(5-i) + "{:6}"*(i+1)).format(*row))
...
                    1
                 1     1
              1     2     1
           1     3     3     1
        1     4     6     4     1
     1     5    10    10     5     1
>>>


Sieve of Eratosthenes for prime generation

Removing a single number from a TI-BASIC list takes O(N) time where N is the size of the list. It's simply not practical. Here is the fastest idiom for removing the Xth element:

seq(L₁(A+(A≥X)),A,1,dim(L₁)-1→L₁

As for the indentation, the TI-BASIC interpreter needs to step through one colon at a time, which is relatively fast but not instantaneous. I expect each extra colon to take a TI-84 series calc about 0.1 ms each time through. If you want to maximize speed, get rid of the indentation.

As for other optimizations:

Rather than using E->dim(L1:Fill(1,L1:cumSum(L1->L1 to generate the list, use

cumSum(binomcdf(E-1,0→L₁

which has the same effect.

You can prescan for numbers not divisible by 2, etc; try this:

augment({2},1+2cumSum(binomcdf(int(.5E),0

to generate only the odd numbers.

As a different approach, you can generate prime numbers by adding to, not removing from, a list:

{2
For(,3,E,2)       ;close parenthesis to fix parser bug; step by 2 to catch odd numbers
If min(fPart(/L₁
n→L₁(1+dim(L₁
End
L₁

It should be of comparable speed or faster.

As a small tip, use the sequence variable n instead of a loop index. It takes as much as 0.5 milliseconds less to access (depending on how many other variables are in your VAT).


Mark positions attacked by a queen on a chess board

Your solution is very procedural, and more like how a C program would be written.  I don't consider it to be idiomatic Scala.  You should decompose the problem into functions, such as isQueen and isAttacked in my solution below.

There should be very little code left over in main.  As a shortcut, then, you can just plop the main code directly into the ChessQueenAttack by making it extend App.

object ChessQueenAttack extends App {
  def isQueen(r: Int, c: Int): Boolean = { (r, c) == queenPos }

  def isAttacked(r: Int, c: Int): Boolean = {
    (r == queenPos._1) ||                       // Same row as queen
    (c == queenPos._2) ||                       // Same column as queen
    (r + c == queenPos._1 + queenPos._2) ||     // On / diagonal
    (r - c == queenPos._1 - queenPos._2)        // On \ diagonal
  }

  def board: String = {
    (0 until 8).map { r =>
      (0 until 8).map { c =>
        if (isQueen(r, c))    "Q" else
        if (isAttacked(r, c)) "X" else
                              "0"
      }.mkString(" ")
    }.mkString("\n")
  }

  val queenPos = (args(0).toInt, args(1).toInt)
  println(board)
}


Iterating through nested array of objects

Your method already looks good! I would only make a couple small changes to the logic as follows:

The if (this._children.length > 0) isn't necessary as the for loop
will make the check for you
Instead of using a standard for loop, I would prefer a for..of
loop. Typescript will transpile this so it will work in any
environment
I prefer early returns to nested statements. Because of this, I
would recommend storing the result variable in as small a block as
possible

With these changes:

public findNode = (id: any): TreeNode => {
  if (this._id === id) {
    return this;
  }

  for (const child of this._children) {
    const result = child.findNode(id);
    if (result) {
      return result;
    }
  }

  return null;
}

Also, here's a couple Typescript specific notes:

Avoid any like the plague. When you use any you are telling
typescript to effectively ignore any mistakes in your code. Given
your data structure, it looks like id should be of type string
I highly recommend turning on
strictNullChecks.
This will help prevent a large class of errors
Methods are public by default in Typescript, with this in mind I
recommend dropping the public modifier in most cases as it is redundant. However, this does not apply if you are working on a team with developers who generally work with other languages as it could lead to confusion in the team. For example, in C# the default is
that all methods are private

With these changes:

findNode = (id: string): TreeNode | null => {
  if (this._id === id) {
    return this;
  }

  for (const child of this._children) {
    const result = child.findNode(id);
    if (result) {
      return result;
    }
  }

  return null;
}


Find palindromic substrings as efficiently as possible

You code looks pretty neat, i do not think that using recursion would improve it very much, but i have some minor suggestions;

1) Performance-wise improvements

The only thing that seems odd at first glance is how you reverse the string to compare subString.split('').reverse().join('');

I had to look it up, but i found that the way that you are doing its the right way using In-built functions, and its pretty much good for almost all cases, but if you want to improve a little the performance you could use something like:

function reverse(s) {
  var o = [];
  for (var i = 0, len = s.length; i <= len; i++)
    o.push(s.charAt(len - i));
   return o.join('');
}

Using this function is has an improve in performance over your current implementation.

2) Readability

You could extract your conditional and use it as a function so your intent would be more clear:

let isPalindrome = function (word, words) {
  return word === word.split('').reverse().join('') && !words.includes(word)
}

and use this function in the conditional as:

if(isPalisdrome(subString, subStrings)) {
          subStrings.push(subString);
 }

3) Conclusion

In the end putting all together the code would be something like:

function reverse(s) {
  var o = [];
  for (var i = 0, len = s.length; i <= len; i++)
   o.push(s.charAt(len - i));
   return o.join('');
}

function isPalindrome(word, words) {
  return word === reverse(word) && !words.includes(word)
}

function countPalindromesInString(s) {
    let subStrings = [];
    for (let i = 0; i < s.length; i++) {
      for(let j = 0; j < s.length - i; j++) {
        let subString = s.substring(j, j + i + 1);
        if(isPalindrome(subString, subStrings)) {
          subStrings.push(subString);
        }
    }
  }
  return subStrings.length;
}


I don't think you need a cursor, looks like a simple update:

 WITH cte AS
  ( SELECT -- do all the counts using conditional aggregation
       ModuleID
       ,Count(DISTINCT ID) AS Started
       ,Count(DISTINCT CASE WHEN ModuleDatecomplete <> '' THEN ID END) AS Completed
       ,Count(DISTINCT CASE WHEN Pass = 'Yes' THEN ID END) AS Passed
    FROM TblResults
    GROUP BY ModuleID
  )
 UPDATE TblModules
 FROM cte
 SET
   Started = cte.Started
   ,Completed = cte.Completed
   ,Passed = cte.Passed
   ,PassedPercent = ((cte.Passed * 100.0) / cte.Started)
 WHERE
    ModuleID = cte.ModuleID

Of course this is fully untested, but the syntax should be ok as-is.

Edit:

In 99+% rewriting a cursor with set-based SQL improves performance.
In your case you run three Selects and one Update per row, e.g. for 100 rows returned by the cursor Select the DBMS needs to execute 400 statements sequentially, 300 Selects and 100 Updates. Combining the three SETs into one using conditional aggregation would reduce the amount of work to 100 Selects and 100 Updates and result in approx. half the runtime. But a single Update might run 10 or 100 or 1000 times faster.


Should I hide exceptions or let them propagate? Logging should be redundant in production environment, so I think hiding them would be fine.

Both. I think this should be configurable. During setup / testing exceptions should be thrown for easier debugging (database permission issues etc.) but in production exceptions should not be thrown.

I have been using NLog and at least in my use this way has been working fine.


As you are using Linux, use this in a PHP file:

<?php system('zip -r backup *'); ?>

This will create a ZIP of all files/directories exists in the directory.


If you were not using AutoMapper, your POST method would either have a block of manual mapping, or it would call out to a custom mapper class. In the latter case, you would have a line (or two) calling that helper class instead of a line calling AutoMapper.

Whether returning a PartialView is the best method depends on your UI; if that's what your View needs, then that's what you need to to. (I personally don't use them in my markup.)

I wager the reason you think the mapping doesn't belong in your POST method is because your Controller is not just concerned with Control, but also Persistence and Construction. If the rest of your application is indeed this simple, then you might as well stick with it, but as complexity grows, you should consider hiding the persistence concerns behind an interface.


NASM tutorial (Linux syscalls, 64 bit) code with CI-build and test

When the function has finished it's logic, these registers should have their previous values

The normal x86-64 System V calling convention allows functions to clobber RAX, RCX, RDX, RSI, RDI, and R8-R11.  Most of these registers are also used for passing args to functions, or returning them (RAX and sometimes RDX).
For a more readable guide to calling conventions, see Agner Fog's calling conventions PDF which covers the differences between calling conventions on Windows/non-Windows and how to deal with it.  (His optimization manuals are essential reading, too if you want to write efficient asm.)
Also, the standard calling convention passes the first arg in rdi.  You seem to be using rsi.  This needs to be documented with a comment.  (Your whole code is under-commented, even though most of it is straightforward).
All libc functions like strlen follow the normal calling convention, so writing code that takes advantage of the fact that your functions don't clobber some registers requires remembering the non-standard calling convention they use.
Using a non-standard calling convention that doesn't clobber any registers might be good for some obscure use-cases like optimizing for code-size in a function with many callers, or for a debug-print function.  You're making your functions bloated by forcing them to save/restore all registers.  Also, restoring even rax stops you from returning an error code (possible if stdout is closed).  I think your function is intended for use in toy programs that don't check for errors, though.  But still, allowing your functions to clobber rax is pretty sensible.
BTW, in most stack-args calling conventions (including args that don't fit in registers in the x86-64 System V convention used on Linux), functions are allowed to modify their args on the stack.  So it's not weird that functions are allowed to clobber the registers their args are in.
Also beware that inserting a debug-print function call isn't necessarily safe even if it restores all registers.  x86-64 System V defines a red zone of 128B below rsp that a function can assume isn't clobbered asynchronously (by signal handlers if you have any), so a function might have valuable data stored at [rsp - 8] or something.  Inserting a debug-print function call into a function that was previously a leaf function might break it (because call pushes a return address, overwriting memory below the old rsp).  This is why you should just use a debugger instead of writing debug-print functions.
Anyway, if you insist on save/restoring all registers, don't forget that syscall itself clobbers rcx and r11.  See What are the calling conventions for UNIX & Linux system calls on i386 and x86-64?.  Or maybe you're intentionally not saving r8-r11?  read_input writes r8 without saving it first.  That's fine, you can use whatever non-standard calling convention you want, but document it with comments.
Also, implement it efficiently: in sprint, you push / pop RSI around a mov rax, rsi.  You're only reading it, which doesn't modify rsi.
Also, you should wait until the end of the function to restore RSI.  If you're going to eventually save/restore registers inside your function, you might as well do it early.

Keep read-only string constants in section .rodata
section .data is for modifiable strings that go in read-write memory.  Use section .rodata for your inputTemplate.

Indentation / formatting style:
It's nice to indent the operands to a consistent column, so different length mnemonics don't make your code as ragged.  I've been doing this in code blocks in this answer.
Also don't forget to use : after labels even in .data / .rodata sections.

Make function definitions contiguous and use local labels for function internals.
next_char is not a usable entry-point to your code.  It's part of sprint.  So what you've done is put the first part of sprint early in memory, then code for another function, then the rest of sprint.  This is not efficient for hardware to run (I-cache locality and a jmp instruction to reach the 2nd half of the function), or easy for anyone to read.
Putting a ret after a jmp is particularly silly:
jmp  next_char
ret

because nothing jumps back to execute the ret instruction.  Anyway, much better to just put the next_char code right below the first part of sprint so execution falls into it.
Similarly, sys_exit is guaranteed not to return, so there's no point putting some pop and ret instructions after it.  Or push instructions before it.
If some of the blocks were helper functions, it could make some sense, but they're not.  (Although sprint_linefeed should use kernel_fn_print_string, see below.  Except that you can't really use it because it pops more than it pushes.  Having the save/restore built-in to blocks of code makes it hard to reuse them.)
For labels internal to a function, use .name instead of name to give it local scope.
You don't need to jmp over blank lines in the source
Execution continues to the next instruction on its own.  This is an example:
count_length:
    sub rax, rsi
    mov rdx, rax
    jmp kernel_fn_print_string

kernel_fn_print_string:
    mov rax, 1
    ....

The jmp instruction is completely useless and a waste of space.  You should have done this:
.count_length:
    sub    rax, rsi
    mov    rdx, rax          ; should have used rdx as the loop counter in the first place to save this mov
.kernel_fn_print_string:
    mov    eax, 1
    ....

Use more efficient instructions
mov eax,1 is smaller than mov rax,1, but exactly equivalent.  NASM will actually optimize it to mov eax,1, but the other NASM-syntax assembler (YASM) won't, and will emit the 7-byte mov r/m64, imm32 form of the instruction (with a REX prefix) instead of 5-byte mov eax, imm32.
xor eax,eax is the most efficient way to zero eax.  Use that instead of mov eax, 0.
Use push imm8 for small constants.  mov  rsi, 0Ah / push rsi can be just push 0xa.  (I prefer C-style 0xDEADBEEF hex constants, not MASM-style trailing-h).  sprint_linefeed is a good example of how bloated your calling convention forces your code to be.
sprint_linefeed:
    call   sprint

    push    rsi          ; this and the 2nd pop aren't needed if you can clobber caller's RSI
    push    0Ah
    mov     rsi, rsp
    call   sprint
    pop     rsi          ; clear the newline from the stack
    pop     rsi          ; restore RSI
    ret

Of course, you know you want to sys_write exactly one byte, so could just do that with a few instructions instead of calling sprint on a known-length string.  Or you could push the right registers and jmp to kernel_fn_print_string directly.  But that doesn't work because you need it to return to your code to pop rsi, and you can't call it because it pops more than it pushes before running a ret.
I guess you could make sprint do extra work (like save/restore rsi) so you could use it from other functions that use just the tail of the function to restore rsi and return.  This whole thing is a mess, and without knowing what you're aiming for (simple code, small code-size, fast?) I have no idea what to recommend.
Use do{}while() loop structure in asm whenever possible.
A normal idiomatic asm loop has one taken conditional branch at the bottom instead of a not-taken branch at the top and a jmp at the bottom.  Why are loops always compiled into “do…while” style (tail jump)?.  (Also, prefer calling strlen because it's a lot faster than a naive byte-at-a-time loop for strings more than a few bytes long.  glibc's strlen uses SSE2 pcmpeqb to look for the zero byte, and this)
.next_char:
    inc     rdx
    cmp     byte [rdx], 0
    jnz     .next_char
   dec     rdx       ; un-count the last byte.  Happens once outside the loop.  Or init rdx to -1 instead of 0 to avoid this.

When a loop might need to run zero times, you can put a test/branch outside the loop.  But strlen always looks at at least one byte.

Use global to export functions in the symbol table
global sprint makes it possible to use extern sprint and call sprint from a separately-assembled file.
Align your function entry-points for performance
If you're really going for code-size, then sure leave everything packed.  But normally you want to align 16 before a function so there's a full fetch-block of code to decode.  Some CPUs may do a 16B-aligned fetch that contains the target address when jumping, and if the branch target is near the end of that 16B then there are only a couple bytes to decode in the first cycle.

Comment your code, especially any magic numbers.
mov  eax, 1       ; __NR_write
mov  edi, 1       ; stdout
syscall           ; sys_write(1, buf, len)

You can optimize by using mov edi, eax instead of another mov-immediate for a constant that happens to be the same.
read_input requires a fixed-size 255 byte buffer instead of having the caller pass a size?!?
This is just weird.  Write a function with 2 args: pointer + length, like a normal person.
read_input assumes that it can strlen() the buffer
read_input uses sprint to print the buffer as an implicit-length string.  But sys_read doesn't append a trailing zero, so this is only safe if the caller zeroed the buffer so there's a terminating zero somewhere.
If your intent was to print was you got from sys_read, you should use the length return value in rax instead of examining memory.  If your intent was to print out the buffer as an implicit-length string, then document that carefully (because it's weird).
Things would be simpler if you wrote a wrapper function that printed explicit-length strings.  You could use that here, and from sprint_linefeed.
Return the sys_read result from read_input
Otherwise the caller can't tell how many bytes were read.  The input bytes could be the same as what was already in the buffer.  (Even on an interactive TTY, a user can type ^V to escape any literal byte including a zero byte.)  (See this SO Q&A for example.

sys_write may return early for very large buffers
Nothing guarantees that sys_write will write all of the characters you pass it.  For small strings this is usually fine, but see When does the write() system call write all of the requested buffer versus just doing a partial write?.  e.g. if writing to a pipe, you're unlikely to be able to write more than the size of the kernel's pipe buffer in one system call.
If you want to be robust, check the sys_write return value to see if it's == the length, and if not advance the pointer and decrease the length and try again.  (If the return value wasn't an error code: -4096 to -1).

My version of your code
SECTION .rodata
inputTemplate:  db  "User input: ", 0h

;;maxBytesToRead equ 255

;;; void sprint(char *str) // in RSI
;;; {  sys_write(stdout, str, strlen(buf); }

;;; clobbers RAX and R11, everything else unmodified
;;; doesn't attempt to retry on interrupted or incomplete writes.

;;; returns sys_write return value in RAX unless string length was zero, then leaves RAX unmodified.

ALIGN 16
global sprint
sprint:
    cmp     byte [rsi], 0  ; don't even make a syscall at all with zero length
    jz      .no_print

    push    rdx
    push    rdi
    mov     rdx, rsi
.next_char:              ; first byte already checked earlier
    inc     rdx
    cmp     byte [rdx], 0
    jnz     .next_char

    sub rdx, rsi          ; string length (excluding terminator)

 kernel_fn_print_string:
    push    rcx          ; syscall clobbers RCX and R11.

    mov     eax, 1       ; __NR_write
    mov     edi, eax     ; stdout = 1 as well
    syscall              ; sys_write(stdout, buf, rdx)

     ;; TODO: check return value and retry if not all the bytes were written.

    pop     rcx
    pop     rdi
    pop     rdx
.no_print:
    ret

ALIGN 16
global sprint_linefeed
;;; sprint(rsi);  sprint("\n");
sprint_linefeed:
    call    sprint

    ; calling  kernel_fn_print_string  is inconvenient here because it wants to pop more than it pushes.
    ; could just inline that code
    ; or for small strings, would be more optimal to copy to a local buffer and append the newline to make one sys_write() call
    push    rsi
    push    0xa          ; '\n'
    mov     rsi, rsp
    call sprint
    pop     rsi          ; pop the newline
    pop     rsi          ; restore caller's RSI
    ret

ALIGN 16
global  read_input
;;; size_t read_input(buf=RSI, len=RDX)
;;; { length = sys_read(0, buf, len);
;;;   print it out
;;;   return length;
;;;  }
;;; clobbers RAX, R8-R11
read_input:
    push    rdi
    push    rcx          ; syscall clobbers RCX and R11

    xor     eax, eax     ; __NR_read
    xor     edi, edi     ; stdin = 0
    ; rsi = buf
    ; rdx = len
    syscall              ; Linux syscalls preserve everything but RCX and R11

    ;; TODO: check for error (rax = -1 to -4095)
    mov     r8, rax      ; save write return value
    mov     r9, rsi

    mov     esi,  inputTemplate    ; static data is in the low 32 bits
    call    sprint       ; print constant string (TODO: length is known, don't waste time on strlen)
    mov     rsi, r9
    call    sprint       ; length is known here, too, if buffer was zeroed before.

    pop     rcx
    pop     rdi
    mov     rax, r8
    mov     rsi, r9      ; restore caller's RSI

    ret

ALIGN  8        ; tiny function, almost fits in 8 bytes
global quit
quit:
kernel_fn_quit:
    mov   eax, 60       ; __NR_exit
    xor   edi, edi
    syscall             ; sys_exit(0)

As I said earlier, this is still a mess.  IDK what to recommend because IDK what this code is supposed to be useful for.
This still has some code-paths that save / restore and then save/restore the same register twice, e.g. sprint_newline, because it uses sprint internally multiple times.  If you care more about code-size than speed, then it can make sense to do it that way.


I'd like to focus on two key issues:

Global variables

You should strive to have no global variables in your program, and it is entirely possible to eliminate them from this program.

If your functions only ever use local variables, then you can understand your code by analyzing each function separately.  However, when you use global variables, you will need to analyze the entire program at once, because the values could be affected by code anywhere in the program.

For example, there is no reason why turns needs to be global.  By making it global, you cannot be sure, just by looking at the play() function, that the loop will execute turns number of times, because you have to worry about the possibility that comparison() modifies its value.  Rather, turns should be local to play().  (Actually, it should be a parameter.)

def play(turns):
    # loops for different choices, and calls the comparison function
    while turns > 0:
        try:
            pchoice = int(raw_input("Choose one! \n <1> Scissors \n <2> Paper \n <3> Rock \n"))
            cchoice = randrange(1,4)
            comparison(pchoice, cchoice)
        except KeyError:
            print "an invalid input! Please try again. \n"
            play(turns)     # Problematic.  I'll say more about this later…
            return
        turns -= 1

Use of functions as if they were GOTO labels

Suppose that at the "How many times do you want to play?" prompt, you hit Enter many times, then hit ControlC.  You would get a stack trace like this:

How many times do you want to play? : ^CTraceback (most recent call last):
  File "cr64216.py", line 45, in <module>
    Main()
  File "cr64216.py", line 15, in Main
    Main()
  File "cr64216.py", line 15, in Main
    Main()
  File "cr64216.py", line 15, in Main
    Main()
  File "cr64216.py", line 15, in Main
    Main()
  File "cr64216.py", line 15, in Main
    Main()
  File "cr64216.py", line 15, in Main
    Main()
  File "cr64216.py", line 15, in Main
    Main()
  File "cr64216.py", line 15, in Main
    Main()
  File "cr64216.py", line 15, in Main
    Main()
  File "cr64216.py", line 15, in Main
    Main()
  File "cr64216.py", line 15, in Main
    Main()
  File "cr64216.py", line 7, in Main
    turns = raw_input("How many times do you want to play? : ")
KeyboardInterrupt

That deep stack trace is a sign of improper recursion.  A properly constructed program should only have one frame in the stack at that point, namely Main().

Rather than recursing, you should implement the retry mechanism using a loop.

def Main():
    print "~A game of Scissors, Paper, Rock!~"

    # Ask until a valid number of turns is given by the user
    while True:
        turns = raw_input("How many times do you want to play? : ")
        # tests for int input and restarts if not an int
        try:
            turns = int(turns)
            print "\nYou will play", turns, "turn(s) against the computer! \n"
            break
        except ValueError:
            print "That's not a valid input! Integers only, please! \n"

    play(turns)


Access elements via ID

You can get access to elements directly via their ID, if you ensure that each elements id and or name is unique withing the page and JavaScripts global scope.

var x = parseFloat(document.getElementById("Lang_from").value);

becomes

var x = parseFloat(Lang_from.value);

In the example at the bottom I have removed all the names from the HTML. You have not indicated that this is a submit-able form and thus you can do without the extra markup.

Note that forms do provide additional information for clients with special needs. For content that faces the world (public) always consider Accessibility. Dealing with font end interaction (not using forms) you should be familiar with WAI-ARIA and how it makes content meaningful and accessible to everyone .

Use Number rather than parseFloat

Rather than use parseFloat use Number to convert a string number to a Number type

var x = parseFloat(Lang_from.value);

becomes

var x = Number(Lang_from.value);

or you can coerce a string representing a number using an operator. Commonly + is used

var x = + Lang_from.value;

JavaScripts has automatic type coercion and will force the string to a number, Note that + will not work as  var x = "10" + Lang_from.value; as the type is set by "10" and + can operate on strings (concats)

Define appropriate variable types

The variables you use are never modified. JS has several variable types. var, let, and const. Get in a habit of using the most appropriate type, for variables that do not change or should not change use const

const x = +Lang_from.value;

Naming is an important programming skill to master

Always pay special care to the names you use.

Some of your variable names have absolutely no relationship to their content (eg x, y, and maybe f)

Using abbreviations is OK and can reduce clutter, using the first letter of each word in the ID is OK (BUT DEFINING NAME and USING NAME must be no more than a page of apart, as the need to hunt for meaning is a distraction that aids bugs getting in)

const lf = +Lang_from.value;
const lt = +Lang_to.value;
const q =  +quantity.value;
const s =  +subject.value;
const ft = +file_type.value;

Avoid intermediates if possible

Rather than the many names, calculate the total as you access the data.

var total = (+Lang_from.value) + (+Lang_to.value); // The extra + to coerce to number
total *= quantity.value;  // *= same as total = total * quantity.value;
                          // The extra + not ended if the operation on the value is
                          // not +
total += +subject.value;
total += +file_type.value;

NO! don't do this... <button onclick="functionName()">

Avoid putting code within the markup. The event listener for calculate should be added via JavaScript when the page has loaded. Use "load" or "DOMContentLoaded" events

addEventListener("load", function() {  // waits for the page to load
     calculate.addEventListener("click", calculateTotal);
});

// or using arrow function and a slightly earlier event that fires when
// all the HTML content has loaded and been parsed (image and the like may not be ready)
addEventListener("DOMContentLoaded", () => {  // waits for the page to load
     calculate.addEventListener("click", calculateTotal);
});

// NOTE that the element id is calculate which conflicted with the JavaScript function
// name calculate. I renamed the function to calculateTotal ( which I would have done
// even if there was no name conflict)

Loose ends are bad practice

Keep the code clean and do not include code that has no purpose. You have 5 variables that get the selections yet you don't use them. They should not be in the function. If you put them their because you intend to use them at another time, finish the code or add a comment with that code eg /* Todo: Show selection names */  else the code is considered incomplete (easy to forget or worse)

Use appropriate properties

When adding content to an element and it is just text (no HTML content) use the node property Node.textContent to set the text. (Elements inherit properties from Node so can be used on most elements)

Example

Basic Markup only

I have removed all irrelevant information from the Markup, (forms, styling wrappers, name/id duplicates, property duplicates, class name)

I removed the references to the CSS styles. Looking good is important, but start at the core and work up, don't start with looking good, that is why we have CSS, to seperate the two.

"use strict";
addEventListener("DOMContentLoaded", () => {
  calculate.addEventListener("click", calculateTotal);
});

function calculateTotal() {
  var total = (+Lang_from.value) + (+Lang_to.value);
  total *= quantity.value;
  total += (+subject.value) + (+file_type.value);
  total_price.textContent = "$" + total.toFixed(2);
}

From

<select id="Lang_from">
  <option value="0.025">English</option>
  <option>German</option>
</select>

To

<select id="Lang_to">
  <option value="0.025">German</option>
  <option>English</option>
</select>

File type

<select id="file_type">
  <option value="0">TXT</option>
  <option value="3">MS word</option>
  <option value="5">PDF (+5$)</option>
  <option value="10">Hand Writing</option>
</select>

Subject

<select id="subject">
  <option value="0">General</option>
  <option value="10">Technical / IT</option>
  <option value="15">Medical</option>
  <option value="5">Press</option>
</select>

Word count

<input type="number" id="quantity" min="500" value="1000">
<button id="calculate">Calculate</button>

Total price

Beginners note

You will notice the string "use strict"; at the top of the JavaScript, it is a directive that forces JavaScript to run in strict mode.

The name may suggest this is something for experienced coders, quite the contrary as experienced JS coders seldom make the errors this will trap.

Experienced JS coders always use strict mode because its faster and because everyone make mistakes.

Ergo: Always run your javascript in strict mode using the directive "use strict";

This example has no semantic meaning to some

I have not used ARIA to add semantic meaning to the content as I do not think its applicable in this case and would make for a way too long already too long answer.

Slight change to result

I noted that the quantity input is unconstrained in its precision (Allows fractions). When you output values, especially monetary values, be careful to include the correct rounding and precision. A money value ideally always starts with the currency type (I used $ and the value is written with full precision Dollars.Cents eg $10.00.

JavaScripts Number (floating point double) is only an approximation of numbers, in a few calculation a number can easily gain a rounding error and just display the value raw will end you with displayed values like 10.00000000000003 or 3e-17 both not good things to show when it involves money,

References

The site you used as a reference has a bad wrap, being incomplete and out of date, Though it has been years since I have had a good look, so if this remains true I am unsure.

I better reference site is MDN JavaScript and the main landing MDN it has a mostly complete reference of Web technologies, plenty of learning resources (tutorials, examples and the like), and if you need to get to the definitive resource they do provide links to the all the standards documentation (Very dry and hard to read resource of everything) that is applicable.


If a message is there, but you cannot see it, is it really there?

Coding style looks good except for one thing. You are using a conditional expression where an if statement would do.

encode_and_print_file() if 'en' in choice.lower() \
                        else decode_and_print_file()

As the value of the expression is not used, I would prefer the statement version as it is clearer:

if 'en' in choice.lower():
    encode_and_print_file()
else:
    decode_and_print_file()

I don't see why you use if 'en' in choice.lower() to recognize the word "encode", allowing "en" anywhere. if choice.strip().lower().startswith('en') would be more to the point.


Find all the countries I can visit by just crossing direct borders

You don't need to artificially limit number of iterations, according to PG manual using UNION without ALL is enough:

  Recursive Query Evaluation

  Evaluate the non-recursive term. For UNION (but not UNION ALL), discard duplicate rows. Include all remaining rows in the result of the recursive query, and also place them in a temporary working table.
  So long as the working table is not empty, repeat these steps:

  a) Evaluate the recursive term, substituting the current contents of the working table for the recursive self-reference. For UNION (but not UNION ALL), discard duplicate rows and rows that duplicate any previous result row. Include all remaining rows in the result of the recursive query, and also place them in a temporary intermediate table.

  b) Replace the contents of the working table with the contents of the intermediate table, then empty the intermediate table.

with recursive travel(country) as (
  select 'S'
  union
  select unnest(array[country1, country2]::text[])
    from travel
      join borders on (country = any(array[country1, country2]))
)
select country from travel where country <> 'S';

Btw, the problem is related to calculating transitive closure on a graph.


Finding two indices of numbers which sum to N

You can emplace after testing for the complementary, it simplifies the code and avoids using a multimap:

vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int, int> numbers;
    //removed because can be very inefficient if nums is big or there are a lot of duplicates
    //numbers.reserve(nums.size());

    //a micro optimization could be to loop from the back and compare
    // i to 0 in the test but it doesn't weigh much against container operations
    for(size_t i = 0; i < nums.size(); ++i) {
        int num = nums[i];
        if (num > target) {
            continue; //no need to waste time storing it either, assuming all numbers are unsigned
        }

        auto it = numbers.find(target - num);
        if (it != numbers.end()) {
           return {i, it->second};
        }
        //no need to emplace for integers? actually slower than insert if key is already present
        numbers.insert({num, i});
    }
    return {};
}

If the values are in a range comparable to the size of the vector, you can just create a valarray<int> of size maxValue+1, fill it to -1 on initialization, and use that instead of the map to check if a value is already present.

Another small optimization that can be done would be to have your loop like that:

int i = 0;
for (int num : nums) {
    //...
    //calls to 'continue' can be replaced by goto endloop

endloop:
    i++; //equivalent in performance to ++i for basic types
}

Iterating over the container like this (which is actually moving a pointer forward) is faster than accessing the element of the vector by its index every time. Although it's a relatively small optimization given that there are map operations used in the loop itself.


Overall, very good
I inspected your query closely and did not find anything standing out that could really be improved much. Here are some good points I found:

Your formatting is consistent and the indentation makes it clear how your code is structured.

You used a clear variable for Favorite type instead of magic numbers.

Your aliases are clear and descriptive.

There are no unnecessary operations, joins or sub-queries that I could find.

Here are a few very minor points to consider.

Using AS operator for table aliases/correlation names. Here is an answer on Stack Overflow that covers the topic.

You could use a small query with your variable to make the intent a bit more clear, like DECLARE @FavoriteType TINYINT = (SELECT Id FROM VoteTypes WHERE Name = 'Favorite'); although this could impact performance slightly, if you have a whole bunch of variables like this. With just a few though the performance difference is negligible.

As for the COUNT(1) vs. COUNT(*), honestly there is no difference. Either way the query plan optimizer will execute them identically because they are both non-nullable expressions. See more details on Stack Overflow and a similar answer on Database Administrators which also covers COUNT(some_field) which behaves differently.


Two similar shell functions that run different programs

Two simple bash solutions I can think of are:

Use a shell script and $0/$BASH_SOURCE to determine the calling name and a symlink from one name to the other.
Two small wrapper functions.

h() {
    local DIR=$PWD
    local TARGET="cabal.sandbox.config"
    while [[ ! -e $DIR/$TARGET -a $DIR != "/" ]]; do
        DIR=$(dirname $DIR)
    done
    if [[ $DIR != "/" ]]; then
        local DB=$(sed -ne '/^package-db: */{s///p;q;}' "$DIR/$TARGET")
        set -- "${@:1:1}" -no-user-package-db -package-db="$DB" "${@:2}"
        # or this is the order of original arguments and added arguments don't matter
        set -- "$@" -no-user-package-db -package-db="$DB"
    fi

    "$@"
}

runhaskells() {
    h runhaskell "$@"
}

ghcs() {
    h ghc "$@"
}

Slightly DRYier version of the above which uses bash's FUNCNAME array.

    h() {
        local DIR=$PWD
        local TARGET="cabal.sandbox.config"
        while [[ ! -e $DIR/$TARGET -a $DIR != "/" ]]; do
            DIR=$(dirname $DIR)
        done
        if [[ $DIR != "/" ]]; then
            local DB=$(sed -ne '/^package-db: */{s///p;q;}' "$DIR/$TARGET")
            set -- "${@:1:1}" -no-user-package-db -package-db="$DB" "${@:2}"
            # or this is the order of original arguments and added arguments don't matter
            set -- "$@" -no-user-package-db -package-db="$DB"
        fi

        "${FUNCNAME[1]%s}" "$@"
    }

    runhaskells() {
        h "$@"
    }

    ghcs() {
        h "$@"
    }


Best way to write generic factory in Java

When you see yourself going and editing the same function again and again to extend its functionality then thats a code smell. The problem is that whenever you add a type you have to add an if condition to your converter. So the conversion could be the class responsibility. in Java 8 you can use Suppliers for that and if you don't have Java 8 then Guava is your friend

 Supplier<DBObject> convertToDBObject(){ // java 8 code
   Supplier<DBObject> supplier = ()-> {
     BasicDBObject dbObject = new BasicDBObject();
     dbObject.append("age", this.getAge());
     dbObject.append("id", this.getId());
     return dbObject;
   }
  return supplier;
 }

Or implement Guava suppliers anonymously if you running java 6 or 7.
You can add an interface for convertable things that your classes can implement.

interface DBObjectConvertable{
   Supplier<DBObject> convertToDBObject();
}

and by doing so your types will be responsible for converting to DBObject in their own ways. The code smell in your code is adding ifs to the factory.Suppliers are factories but in a declarative way, so instead of returning converted object immediately, I will return you a function that knows how to convert to MongoDB objects.


Efficiently determine whether two arbitrarily-sized integers share a digit

Edge cases

You don't handle negative integers very well. Specifically, the modulo operator, when performed on a negative integer with a positive divisor, may return a negative value. And when this negative value is something like, say, -2, then you get 1 << -2, which results in setting a high bit instead of the bits for 0-9.

Duplication

You currently have duplicated the code for a and b. By making use of smaller methods, you can get rid of the duplication:

int getBitsFor(long num)
{
    int bits=0;
    if(num==0) bits=1;
    while(num!=0)
    {
        bits |= (1 << (num % 10));
        num/=10;
    }
    return bits;
}

And then use like so:

boolean shareDigits(long a, long b)
{
    return (getBitsFor(a) & getBitsFor(b)) > 0;
}

Readability

It would help if you were to put spaces between operators and the operands. Basically, I find int aBits = 0 more readable than int aBits=0. The less effort I have to spend on interpreting the code, the more effort I can spend actually writing or improving the code.

For reference:

int getBitsFor(long num)
{
    int bits = 0;
    if(num == 0) bits = 1;
    while(num != 0)
    {
        bits |= (1 << (num % 10));
        num /= 10;
    }
    return bits;
}

Compare with the snippet above, see which feels easier to read for you.

Simplification

200_success pointed this out, but they deleted their answer (although I found that it made a good point):

If you wrote do-while loops instead, then you would not need the special case for num == 0:

int getBitsFor(long num)
{
    int bits = 0;
    do
    {
        bits |= (1 << (num % 10));
        num /= 10;
    } while (num != 0)
    return bits;
}

Performance

You want to know if there's a faster way check if integers share a digit.

To be honest, I don't know. Your implementation looks pretty fast. But your implementation also takes a constant amount of calculations related to the size of the input and makes no use of shortcuts.

One shortcut that I can come up with - if a number contains all the digits, then you don't need to continue.

But perhaps checking for this case makes the worst case slower again...

I also checked https://graphics.stanford.edu/~seander/bithacks.html which is a collection of "Bit Twiddling Hacks", but there doesn't seem to be an algorithm for checking for duplicated digits in there.


In your locationIsFine it seems you check for each room in your roomStore if any of its tiles intersect with a tile inside your new/fake room.

It would probably be worth wile to add some basic checks which (the larger your roomStore will grow, the more it) will reduce the number of checks needed.

This is actually a rectangle intersection problem.
Between rectangles, if one isn't completly to the left, right, above or below the other, they will intersect; so checking on that is the fastest way and will save you the check on each and every tile against each and every tile of the other room. This will save you from creating the tilesets for the fake room.

So a start to enhance the algorithm would be this.

var locationIsFine = function(x, y, width, height) {
    //make sure room wont hit any other rooms, we do this by checking if edges of a room collide with an exisiting room
    for (var i = 0; i < roomStore.length; i++) {
        // roomStore[i] completly left or completly right of new room
        if(roomStore[i].X > x+width || roomStore[i].x+roomStore[i].Width < x) continue;
        // roomStore[i] completly above or completly below new room
        if(roomStore[i].Y > y+height || roomStore[i].Y+roomStore[i].Height < y) continue;

        //if a room is neither completely to the right nor completely to the left as well as
        //not completly above nor completely below, it will intersect
        return false;
    }
    return true;
}


If A.ndim is not in 1, 2, 3, your code tries to return a non-existing string s. It would be better to be explicit about what your code supports atm:

def ndtotext(A, w=None, h=None):
    ...
    else:
        raise NotImplementedError("Currently only 1 - 3 dimensions are supported")
    return s

While we are at the point of having your code be clear about what is happening, you should add a docstring explaining what your code does:

def ndtotext(A, w=None, h=None):
    """Returns a string to pretty print the numpy.ndarray `A`.

    Currently supports 1 - 3 dimensions only.
    Raises a NotImplementedError if an array with more dimensions is passed.

    Describe `w` and `h`.
    """
    ...

Next, Python has an official style-guide, PEP8, which programmers are encouraged to follow. One of the things it recommends is surrounding operators with spaces (which I fixed in the rest of the code) and using lower_case for variables and functions (which I left as is for now).

Now, let's come to your actual code:

You calculate some values multiple times (like str(A[0])), save those to a variable.
If you want to compare to None, use is (since it is a singleton).
No else needed after an if...return (this is a matter of personal style, I prefer not having the additional level of indentation).
Use str.rjust to add enough whitespace in front of your strings. You could also use str.format for this, but it looks less nice.
Your w has a weird structure, with the width of the first column being the last entry and the rest starting at zero.
Give the unicode values names. And then add functions to draw a line of specified length.
String addition is costly and slow. Try to consistently use building a list and str.joining it.

UPPER_LEFT = u'\u250c'
UPPER_RIGHT = u'\u2510'
LOWER_LEFT = u'\u2514'
LOWER_RIGHT = u'\u2518'
HORIZONTAL = u'\u2500'
VERTICAL = u'\u2502'

def upper_line(width):
    return UPPER_LEFT + HORIZONTAL * width + UPPER_RIGHT

def lower_line(width):
    return LOWER_LEFT + HORIZONTAL * width + LOWER_RIGHT

def left_line(height):
    return "\n".join([UPPER_LEFT] + [VERTICAL] * height + [LOWER_LEFT])

def right_line(height):
    return "\n".join([UPPER_RIGHT] + [VERTICAL] * height + [LOWER_RIGHT])

def ndtotext(A, w=None, h=None):
    """Returns a string to pretty print the numpy.ndarray `A`.

    Currently supports 1 - 3 dimensions only.
    Raises a NotImplementedError if an array with more dimensions is passed.

    Describe `w` and `h`.
    """
    if A.ndim == 1:
        if w is None:
            return str(A)
        s = " ".join([str(value).rjust(width) for value, width in zip(A, w)])
        return '[{}]'.format(s)
    elif A.ndim == 2:
        widths = [max([len(str(s)) for s in A[:, i]]) for i in range(A.shape[1])]
        s = "".join([' ' + ndtotext(AA, w=widths) + ' \n' for AA in A])
        w0 = sum(widths) + len(widths) - 1 + 2 # spaces between elements and corners
        return upper_line(w0) + '\n'  + s + lower_line(w0)
    elif A.ndim == 3:
        h = A.shape[1]
        strings = [left_line(h)]
        strings.extend(ndtotext(a) + '\n' for a in A)
        strings.append(right_line(h))
        return '\n'.join(''.join(pair) for pair in zip(*map(str.splitlines, strings)))
    raise NotImplementedError("Currently only 1 - 3 dimensions are supported")

This can probably be even more compactified, but I think it is a good start.

Example usage:

x = np.arange(12)

print(ndtotext(x))
[ 0  1  2  3  4  5  6  7  8  9 10 11]

print(ndtotext(x.reshape(3, 4)))
┌───────────┐
 [0 1  2  3]
 [4 5  6  7]
 [8 9 10 11]
└───────────┘

print(ndtotext(x.reshape(3, 2, 2)))
┌┌─────┐┌─────┐┌───────┐┐
│ [0 1]  [4 5]  [ 8  9] │
│ [2 3]  [6 7]  [10 11] │
└└─────┘└─────┘└───────┘┘


Invert the bits of a non-negative integer in Common Lisp (SBCL)

A possible way is to use one of the bitwise logical operators on integers, that treat integers as binary numbers. For instance, by using the logxor operator, we could write:

(defun invert-bits2 (n)
  (if (> n 0)
      (logxor (1- (expt 2 (integer-length n))) n)
      0))

The function integer-length returns the number of bits of the binary representation of an integer, so that (1- (expt 2 (integer-length n))) is a binary number with all ones and the same length as n.

CL-USER> (loop for f in '(identity invert-bits invert-bits2)
            do (format t "~20b~%" (funcall f 300212)))
 1001001010010110100
  110110101101001011
  110110101101001011
NIL


Sorry, but this is simply not a good design.

Your reliance on memory-owning raw pointers means that the library is easy to use wrongly, and that the user will leak memory. This is a big no-no in modern C++. First, because it’s harmful and makes user code brittle and complex; and second, because it is unnecessary. Modern C++ gives you all the tools to avoid manual memory management.

Think carefully about ownership in your component model and choose an appropriate smart pointer. Since you control the object hierarchy, boost::intrusive_ptr may be the best match, but consider other alternatives which are less generic (such as std::unique_ptr).

Finally think about ways to avoid pointer use completely, if possible. In fact, the code you’ve shown doesn’t use runtime polymorphism at all so there is no use of pointers. Just handle objects directly.

Regarding your implementation of RTTI: Without knowing the detailed requirements of your object model it’s hard to comment here; however, you say that you don’t want to get the RTTI overhead. What makes you think C++ RTTI has more overhead than your solution? In fact the implementation you’ve shown is, if anything, less efficient than C++ RTTI because your use-case can be resolved at compile-time.

But let’s assume that you just forgot to make your classes polymorphic, and that the real code cannot resolve the type information at compile time. Then your RTTI mechanism stores redundant information and is still less efficient than C++’ built-in mechanism.

Finally, if you are afraid of RTTI overhead (and have data to back this up) then the real solution is not to roll your own system, it’s to avoid RTTI be redesigning your classes such that they have a uniform interface and don’t need to be distinguished at runtime. In fact, this is the idiomatic solution in C++, and RTTI is the exception rather than the norm.


Looks really good. It's clear and easy to understand. Regarding this specific implementation, a couple of things that came to mind:

In setRemember(), unless you specifically only want to support the values 1 or 0, the code can be changed to:

this.clientStorage = remember ? this.localStorage : this.sessionStorage;

In setRemember(), when switching storage mechanisms it might make sense to copy the values out of the old mechanism into the new one so anything the user has previously set will be preserved. Similary, if the user is changing from localStorage to sessionSorage, would it make sense to also clear the old storage mechanism? If making either of these changes, the method could also first compare the new value against the old value and only continue if there is actually a change.
What is o used for in log() method?
In the log() method, depending on on the utility you're using for logging, you might consider logging the entire object, at once, as many console / logging utilities will allow you to inspect objects. This can sometimes be more informative, although here it's just about whatever would be more convenient because all values will be strings, anyway. If you go this route, you could rename the current function to something like logEach().
In the execution of clear(), should you preseve the h_token key?

Taking a step back, here is an alternate API for the utilitiy. Just thinking out loud.

ssn(key) - Retrieves a value. Synonymous with get()
ssn(key, value) - Sets a value. Synonymous with set()
ssn(obj) - Set all values from obj. Synonymous with setAll()
ssn.clear() - Unchanged.
ssn.clone() - Synonymous with getAll()
ssn.log() - Log the clientStorage object as a whole, as described above.
ssn.logEach() - Log each property and corresponding value, one at a time.
ssn.remember() - Retrieves the current remember setting.
ssn.remember(value) - Sets the remember value. Synonymous with setRemember()

One final thought you may want to implement some sort of 'namespace' type of functionality to be able to differentiate between settings saved for different users. I don't suggest this for security reasons, but more from a user-experience perspective. I think, with the way it's set up, multiple users on the same computer will have their settings merged, which may get confusing.


Computationally efficient way of comparing and merging like object keys

Interesting question,

there is no faster approach that I know of, in essence, your approach mimics jQuery's $.extend() source code. Except that your code does not clone parameters which might bring you trouble.

I think your code might be messed up, or you might not understand what it is doing.

This:

var template = {key1:false, key2:false, key3:false};
var cfg = {key1:true, keyTWO:"puppies", key3:false};

var cfg_obj = mapConfig(template, cfg);
console.log(cfg_obj);

is equivalent to this:

var template = {key1:false, key2:false, key3:false};
var cfg = {key1:true, keyTWO:"puppies", key3:false};

mapConfig(template, cfg);
console.log(template);

because you change the provided object itself, which probably is not right in all circumstances. I assume that is why you have configured_template in there ?

Furthermore, it does not seem to make sense to assign false to properties that you want to discard.. It eats up memory for no good reason.

All in all, I would counter propose

function configureTemplate( template, config) {
    var result = {}, key;
    for (key in config) {
        if( key in template ){
          result[key] = config[key];
        }
    }
    return result;
}

Note that you were polluting the global namespace by not declaring key with var.

Personally, I would drop most of the curly braces:

function configureTemplate( template, config) {
    var result = {}, key;
    for (key in config)
        if( key in template )
          result[key] = config[key];
    return result;
}

var template = {key1:false, key2:false, key3:false};
var cfg = {key1:true, keyTWO:"puppies", key3:false};

var cfg_obj = configureTemplate(template, cfg);
console.log(cfg_obj);

On a final note, try not to disemvowel your variables. It makes grokking code needlessly harder.


Session expiration handler using PHP and jQuery

I don't believe the code works as expected.

One of us for sure made mistake with session_status() == PHP_SESSION_NONE. If is me, comment so I can fix the answer.

Code style

You will have better readability, if you indent everything inside the class.

You need to work on if statement in SESSION_handler::session_expired(). I can not read it at all. I personally would do it on single row, but then many people will not like it at all.

Constructor

self::$cookie_lifetime - I do not see where you need this?

You initializing the static fields every time.

self::$gc_maxlifetime = ini_get('session.gc_maxlifetime');
self::$cookie_lifetime = ini_get('session.cookie_lifetime');

I would suggest something like this:

if (self::$gc_maxlifetime = -1){
   self::$gc_maxlifetime = ini_get('session.gc_maxlifetime');
   self::$cookie_lifetime = ini_get('session.cookie_lifetime');
}

You also might decide to remove them and use ini_get directly. Or you can do static method SESSION_handler::gc_maxlifetime().

Here you create session as well:

if(session_status() == PHP_SESSION_NONE) {
    session_start();
}

Do you really need to check session_status()? My experience is you can use session_start() directly. If there is a session created, statement will do no harm.

I believe you need to initialize $_SESSION['time_at_last_session'], but only if is not set already.

Something like:

if (!isset($_SESSION['time_at_last_session']))
    $_SESSION['time_at_last_session'] = time();

SESSION_handler::get() and SESSION_handler::set()

Why you have this:

if(session_status() == PHP_SESSION_NONE) {
    // ...
}
return undefined;

You probably want to check if everything with the session is correct? to do so, use:

if(session_status() != PHP_SESSION_NONE) {
    // ...
}

You return undefined;. This is first time I see this line in PHP. Just remove the if statement. Session is already made in constructor. If is not undefined will not help at all.

Actually, in constructor, you can save the result of session_start(); into some class property and use it instead of session_status().

SESSION_handler::session_expired()

should be something like this?

public function session_expired(){
    $time = isset($_SESSION['time_at_last_session']) ?
             $_SESSION['time_at_last_session'] : 0;

    // same, but ugly:
    //$time = (int) @$_SESSION['time_at_last_session'];

    if (session_status() == PHP_SESSION_NONE)
        return true; // session problem

    if (time() - $time > self::$gc_maxlifetime)
        return true; // session expired

    // fix $_COOKIE[session_name() thing

    return false; // session is NOT expired
}

is_session_expired.php

All OK if you fix the constructor.


Maximum distance between space stations HackerRank

builting min

minVal = float('inf')
for j in c:
    if abs(i-j) < minVal: minVal = abs(i-j)

can be rewritten using min: min(abs(i-j) for j in c).

Apart from that, placing the code on the same line as the check looks very unreadable to me.

There is also no need to keep the values in a list,

for i in range(n):
    lst = []
    for j in c:
        lst.append(abs(i-j))
        cityDiff[i] = min(lst)

can be

max(min(abs(i - j) for j in c) for i in range(n))

variable names

i and j are useful variable names as counters. Here you use them as citie and space station. The same goes for c, which are the space stations.Then call em like that:

max(
    min(abs(space_station - city) for space_station in space_stations)
    for city in range(n)
)

space stations

A first improvement I would suggest if the city you want to check is a space station or not. In your naive algorithm you do  m x n checks. This will reduce it by m x m. If you use a set for the space stations, this inclusion check will be quick.

space_station_set = set(space_stations)
max(
    min(abs(space_station - city) for space_station in space_stations)
    for city in range(n) if city not in space_station_set
)

sorting space stations

If you sort the space stations, you can use this fact.

space_stations = [1, 4, 7]
space_stations_sorted = (
    [float("-inf")] + sorted(space_stations) + [float("inf")]
)
space_station_pairs = (
    (space_stations_sorted[i], space_stations_sorted[i + 1])
    for i in range(len(space_stations) + 1)
)

This will generate pairs of adjacent space stations. I added the infs to take care of the edges

list(space_station_pairs)

[(-inf, 1), (1, 4), (4, 7), (7, inf)]

Then you loop through the cities like this:

one, two = next(space_station_pairs)
distance_max = float("-inf")
for city in range(n):
    if city == two:
        one, two = next(space_station_pairs)
        continue
    distance = min((city-one), (two-city))
    distance_max = max(distance, distance_max)

This way you only loop once through the cities and twice through the space stations, so you reduced the complexity to O(n).

looping only over the space stations:

The furthest city will always be either in the middle between 2 space stations or at the edges of the map. You can use this fact to

space_stations_sorted = sorted(space_stations)
distance_max = max(
    (two - one) // 2 for one, two in pairwise(space_stations_sorted)
)
distance_max_total = max(
    distance_max, space_stations_sorted[0], n - space_stations_sorted[-1] - 1
)

this loops only once over the space stations, and leaves the cities untouched.


Enforcing numeric inputs and sanitizing different formats for IE11 input fields

Don't guess!
You should not attempt to correct client input unless you make sure that the client knows (via a click) that a change has been made.
Converting a value like 100,1.0 to 1001.0 is a guess. The client may have intended only the 100, or the 1.0 and your guess may not be noticed.
You can vet input as it is entered or on paste, removing non numeric characters (which you don't do) eg "a100a" will become 100, but when there is ambiguity like "a100a00" it should be considered not a number.
If the result is not a number use standard validation warnings rather than guessing.


This seems fine to me: it's nice and simple, and I've seen this pattern used "in the wild" before. One thing you could do is, in the MockUserRepo proxying functions, if the function variable is nil, either execute a default implementation, or return a more specific error (or even panic). For example:
func (m *MockUserRepo) GetUserByEmail(s string) (*user.User, error) {
    if m.GetUserByEmailMock == nil {
        // default implementation: return a dummy user object
        return &user.User{ID: generateID(), Email: s}, nil
    }
    return m.GetUserByEmailMock(s)
}

// or:

func (m *MockUserRepo) GetUserByEmail(s string) (*user.User, error) {
    if m.GetUserByEmailMock == nil {
        // default implementation: panic with a more specific error
        panic("MockUserRepo: GetUserByEmail not set")
    }
    return m.GetUserByEmailMock(s)
}

The reason I'd be okay with a panic here is because not setting GetUserByEmail is almost certainly a coding bug in the test, not really a runtime error condition. This latter approach doesn't gain you much over just letting the nil pointer access panic, except that the error message is a bit more specific.


Looks pretty good.

A couple comments:

Unless this is an assignment to make or use a Stack, a Python list would suffice.

The code checks if a char is in '[{(', then checks if it is in ']})' and the stack is empty, then checks if it is in ']})' (again) and checks if the top of the stack is the matching bracket. All characters go through all those checks.

In general, it is good to make the common case fast and less cases can be slower.

def check_balance(code):
    """Return True if brackets are balanced, False otherwise.
    """

    valid = {']': '[', ')': '(', '}': '{'}

    lefts = []

    for char in code:
        # common case
        if char not in '[](){}':
            continue

        if char in '[({':
            lefts.append(char)

        elif not lefts or lefts.pop() != valid[char]:
            return False

    return lefts == []


Is there any room for "shortening" the code?

Shorthands
Shorthands can simplify the markup. The click handlers already use the shorthand @click instead of v-on:click. The bindings can be simplified as well. For example - instead of:

v-bind:class="..."

the v-bind can be omitted:
:class="..."

Watch out!

Yesterday there was an answer to your TODO app post which suggested using computed properties. With the current architecture using a computed property doesn't seem feasible, but a watcher method could be employed. Instead of setting up a method like doCompleted() that must be called manually, a watcher method can be used to adjust the values whenever that value changes.
watch: {
  stepCounter: function(newValue, oldValue) {
    this.steps.forEach(item => {
      item.completed = item.step < this.stepCounter;
    });
  }
},

Note that newValue could be used instead of this.stepCounter.
While it would occupy the same number of lines as the current code, it takes the burden off the methods doPrev and doNext of having to call the method doCompleted. See the demo below for an illustration of this.

const makeStep = (text, index) => {return {text, step: ++index, completed: false}};
const steps = ['Cart', 'Shipping', 'Payment', 'Confirmation'].map(makeStep);
var app = new Vue({
  el: "#cart",
  data: {
    stepCounter: 1,
    steps
  },
  watch: {
    stepCounter: function(newValue, oldValue) {
      this.steps.forEach(item => {
        item.completed = item.step <  this.stepCounter;
      });
    }
  },
  methods: {
    doPrev: function() {
      if (this.stepCounter > 1) {
        this.stepCounter--;
      }
    },
    doNext: function() {
      if (this.stepCounter <= this.steps.length) {
        this.stepCounter++;
      }
    }
  }
});
* {
  margin: 0;
  padding: 0;
  font-family: "Poppins", sans-serif;
}

.progressbar {
  display: flex;
  list-style-type: none;
  counter-reset: steps;
  padding-top: 50px;
  justify-content: space-between;
}

.progressbar li {
  font-size: 13px;
  text-align: center;
  position: relative;
  flex-grow: 1;
  flex-basis: 0;
  color: rgba(0, 0, 0, 0.5);
  font-weight: 600;
}

.progressbar li.completed {
  color: #ccc;
}

.progressbar li.active {
  color: #4caf50;
}

.progressbar li::after {
  counter-increment: steps;
  content: counter(steps, decimal);
  display: block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  border: 2px solid rgba(0, 0, 0, 0.5);
  background: #fff;
  border-radius: 50%;
  position: absolute;
  left: 50%;
  margin: -60px 0 0 -15px;
}

.progressbar li.active::after,
.progressbar li.completed::after {
  background: #4caf50;
  border-color: rgba(0, 0, 0, 0.15);
  color: #fff;
}

.progressbar li.completed::after {
  content: '\2713';
}

.progressbar li::before {
  content: "";
  position: absolute;
  top: -26px;
  left: -50%;
  width: 100%;
  height: 2px;
  background: rgba(0, 0, 0, 0.5);
  z-index: -1;
}

.progressbar li.active::before,
.progressbar li.completed::before,
.progressbar li.active+li::before {
  background: #4caf50;
}

.progressbar li:first-child::before {
  display: none;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

{{step.text}}

      <button type="button" class="btn btn-sm btn-success" :class="{ disabled : stepCounter === 1}" @click="doPrev()">Prev</button>
      <button type="button" class="btn btn-sm btn-success" :class="{ disabled : stepCounter > steps.length}" @click="doNext()">Next</button>

If the data structure can be modified such that the completed property isn't needed, then the markup could use the condition step.step < stepCounter to determine when the completed class is added to each list item. See the snippet below for a demonstration of this.

const makeStep = (text, index) => {return {text, step: ++index}};
const steps = ['Cart', 'Shipping', 'Payment', 'Confirmation'].map(makeStep);
const app = new Vue({
  el: "#cart",
  data: {
    stepCounter: 1,
    steps
  },
  methods: {
    doPrev: function() {
      if (this.stepCounter > 1) {
        this.stepCounter--;
      }
    },
    doNext: function() {
      if (this.stepCounter <= this.steps.length) {
        this.stepCounter++;
      }
    }
  }
});
* {
  margin: 0;
  padding: 0;
  font-family: "Poppins", sans-serif;
}

.progressbar {
  display: flex;
  list-style-type: none;
  counter-reset: steps;
  padding-top: 50px;
  justify-content: space-between;
}

.progressbar li {
  font-size: 13px;
  text-align: center;
  position: relative;
  flex-grow: 1;
  flex-basis: 0;
  color: rgba(0, 0, 0, 0.5);
  font-weight: 600;
}

.progressbar li.completed {
  color: #ccc;
}

.progressbar li.active {
  color: #4caf50;
}

.progressbar li::after {
  counter-increment: steps;
  content: counter(steps, decimal);
  display: block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  border: 2px solid rgba(0, 0, 0, 0.5);
  background: #fff;
  border-radius: 50%;
  position: absolute;
  left: 50%;
  margin: -60px 0 0 -15px;
}

.progressbar li.active::after,
.progressbar li.completed::after {
  background: #4caf50;
  border-color: rgba(0, 0, 0, 0.15);
  color: #fff;
}

.progressbar li.completed::after {
  content: '\2713';
}

.progressbar li::before {
  content: "";
  position: absolute;
  top: -26px;
  left: -50%;
  width: 100%;
  height: 2px;
  background: rgba(0, 0, 0, 0.5);
  z-index: -1;
}

.progressbar li.active::before,
.progressbar li.completed::before,
.progressbar li.active+li::before {
  background: #4caf50;
}

.progressbar li:first-child::before {
  display: none;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

      <li v-for="(step, index) in steps" v-bind:class="{ active: index + 1 === stepCounter, completed: step.step < stepCounter }">{{step.text}}

      <button type="button" class="btn btn-sm btn-success" v-bind:class="{ disabled : stepCounter === 1}" @click="doPrev()">Prev</button>
      <button type="button" class="btn btn-sm btn-success" v-bind:class="{ disabled : stepCounter > steps.length}" @click="doNext()">Next</button>

CSS: margin rules
The ruleset .progressbar li::after { contains these rules:

margin-left: -15px;
margin-top: -60px;

Presuming there is no margin inherited from other elements for the right and bottom, those can be combined into a single rule:
margin: -60px 0 0 -15px;


Returning JSON depending on the route_id

How about somethink like:

 $allOrders = array();
 foreach($allWayPoints as $allWayPoint)
 {
            $allOrdersInWaypoint = Transaction::where('waypoint_id', "=", $allWayPoint)->where('type', "=", "DD")->get()->lists('order_id');
 //           $allOrders[] = array($allOrdersInWaypoint);
            $allOrders = array_merge($allOrders, $allOrdersInWaypoint);
 }

 foreach($allOrders as $order)
 {
       $otherOrders = Order::find($order);

       if(isset($otherOrders))
       {
            $getOtherOrders[] = array(
                                            'id'             => $otherOrders->id,
                                            'tracking_id'    => $otherOrders->tracking_id,
                                            'shipper_ref_no' => $otherOrders->shipper_ref_no);
       }
 }

Then they wont be nested and $allOrders will simply be a flat array containing the numbers, assuming $allOrdersInWaypoint is a array of numbers.


Creating all possible combinations of points

Google Guava has a cartesianProduct helper method, I would try to use it instead of the nested loops. I don't think that it will be faster but it would be easier to read an maintain.


Well what you are trying to do is not strictly speaking an abstract factory. For it to be an abstract factory the use case should look like this:

UniversalFactory.Factory<IFoo>  // client has no idea about IFactory<IFoo> implementation
                .Create(... parameters ...); // client has no idea about IFoo implementation, returns IFoo

Ideally, you should not even need to pass parameters. That is why you are building factories after all. To delegate object creation.

Other minor remarks:

where T : TF - those are not very descriptive names for generic arguments. Perhaps you can come up with better naming.
var id = Convert.ToInt32(p[0]); - i'm not sure i like Convert here. It might hide bugs and misusages. I think that strong cast is better in that case.
public static IFoo Create(int id) - i don't see any reason to use factory method.

public class FooImpl : IFoo
{
    public int Id { get; private set; }

    public FooImpl(int id)
    {
        Id = id;
    }
}

this looks a lot cleaner. Also i think Id setter should be always private.

Overall, i think unless you are doing it for studying purposes, you should just grab an existing DI library, as you've metioned yourself :)


Validation rules with support for immediate termination of processing

You shouldn't bind the implementation to any particular type in this case the StopProcessingIfInvalidCheckpoint.

I think it would be better to drop this class and instead add a new property IsFinal to the interface. You could check if the validation fails and IsFinal is set to true then you stop processing other rules.

If you want to get rid of the generic argument but at same time you want to keep it for other implementations then add another abstraction layer. Make the interface non-generic and add an abstract class that is derived from the non-generic interface:

interface IValidationRule
{
    ValidationRuleResult Validate(object instance);
    bool IsFinal { get; }
}

abstract class ValidationRule<T> : IValidationRule
{
    public abstract ValidationRuleResult Validate(object instance);
    public bool IsFinal { get; set; }
}

class FooValidationRule : ValidationRule<int>
{
    public override ValidationRuleResult Validate(object instance)
    {
        ... do something with (T)instance;
    }
}

and

foreach (var vr in validationRules)
{
    var result = vr.Validate(instance);
    if (!result.IsValid && vr.IsFinal)
    {
        break;
    }
    validationResults.AddRange(result.ValidationResults);
}

so

Rules =
{
    RuleOne(),
    RuleTwo() { IsFinal = true },
    RuleThree()
}


K&R (C): generate histogram of word-lengths

Initial reaction to your program is that it seems to be good and clean C code. So the overall impression is good, but there are things to review, even though some comments may be a bit of personal reference.

Punctuation char or not – The code includes check against single characters, so the extension to check against the ranges from c > 'a' && c < 'z', should be within reach
Split main method in multiple functions – This might not be covered yet, but I include it as it is good to start doing this as early as possible. However this does introduce the icky subject of passing arrays with/without size. Sorry about that!
Use of state vs simple length of current word – The naming of the states was a little unclear to me, and whilst reviewing the logic it hit me that if you are not counting the length of a word (i.e. the character is a legal word character), you can simply test if the length of the word, len, is larger than 0 to match your current IN_WORD state. As such, the state variable can be replaced with a test len > 0
Make the most common (shortest?) block come first – In your code you start of the input processing by verifying length of something and adding to the histogram. But of what?  Then comes the block actually increasing the length and reading the words. To me, it is more natural to switch these blocks, so that you know why len has a length
Stay consistent with bracing – For most of the code you've chosen to have start braces at preceding line, and that is a style choice. You've also chosen to let one-liners be without braces, this I would advise against. At some point in time this cause you some issue. My strong suggestion is to always enclose for or if (or similar) blocks with braces always. It will save you some grief further down the line.
Include number on both axes – Kind of strange not have numbers on the x-axis. To allow for two digits in the length of word, you can increase width of each column to three characters
Skip empty columns – No need to print the empty columns, is there?
Consider changing columnn marker – To me, the . is a little invisible, and I feel the # or * is more intuitive to use to mark the count
Consider labeling the axes – Consider adding labels like Count or Occurences, and Word length for the axes. It does however impose a smaller problem of where to put them...
Why the putchar, when printf works? – The usage of putchar('\n'); seems unmotivated, when you can do a printf("\n");. Is there a reason behind that?
Comment on comments – You've added suitable comments in most places, and when going to functions this becomes even more importantprocessing

Refactored code

That is enough rambling, and here is my suggestion to refactor code addressing most of the issues I've commented upon:

#include <stdio.h>

#define IN_WORD     1   /* point in word */
#define OUT_WORD    0   /* point out of word */
#define MAX_LEN     20  /* max word length to consider */

/*
 * Reset the histogram to all 0's too clear it out
 */
void init_histogram(int histogram[], size_t histogram_length)
{
    int i;

    for (i = 0; i < histogram_length; ++i) {
        histogram[i] = 0;
    }
}

/*
 * Read input, character by character, and divide into
 * words which are counted the length of (up until the max
 * max length specified in histogram_length). If word is
 * actually longer, the histogram records is at max length.
 *
 * Count characters, a-z and A-Z, and increase length of word,
 * and add to histogram if length>0 when we hit a non-character
 */
void create_histogram_from_input(int histogram[], size_t histogram_length)
{
    int len=0;       /* length of current word */
    int c;           /* current character */

    /* Keep reading character until end of file */
    while ((c = getchar()) != EOF) {

         // Check if it is an character ...
         if ( ( c >= 'a' && c <= 'z') ||
              ( c >= 'A' && c <= 'Z') ||
              c == '-' ) {

            ++len; /* Increase length of current word */

        } else {
            /* ... it was not a character, so check if we have
             * a positive word length
             */
            if (len > 0) {
                /* increment histogram entry for current word length */
                if (len >= histogram_length) {
                    len = histogram_length;
                }

                histogram[len - 1]++;

                len = 0; /* Reset length of current word */
            }
        }
    }
}

/* Pretty print the histogram vertically, with numbered x-
 * and y-axis. Only print as many columns as we have word lengths
 */
void print_histogram(int histogram[], size_t histogram_length)
{
    int i, j, c;
    const int y_axis_width = 4;

    int top_count = 0; /* Highest count of a given length */
    int max_length = 0; /* The longest word in histogram */

    /* Find the highest count, and longest word */
    for (i = histogram_length; i > 0; --i) {

       /* If max_length is not set, and we find a positive length
        * whilst going backwards, it is the longest word
        */
       if (max_length == 0 && histogram[i-1] > 0) {
           max_length = i;
       }

       /* Scan entire histogram to find the highest count of that length */
       if (histogram[i-1] > top_count) {
           top_count = histogram[i-1];
       }
    }

    /* print histogram from top to bottom */
    for (i = top_count; i > 0; i--) {

        /* print Y-axis */
        printf("%3d|", i); /* If this changes, change y_axis_width */

        /* print entries for each word length */
        for (j = 0; j < max_length; j++) {
            if (histogram[j] < i) {
                printf("   ");
            } else {
                printf(" # ");
            }
        }
        printf("\n");
    }

    /* print X-axis separator*/
    printf("%*s", y_axis_width, " ");
    for (i = 0; i < max_length; i++) {
        printf("---");
    }
    printf("\n");

    /* print X-axis numbers */
    printf("%*s", y_axis_width, " ");
    for (i = 0; i < max_length; i++) {
        printf("%2d ", i+1);
    }
    printf("\n");
}

int main()
{
    int histogram[MAX_LEN];

    /* Reset histogram */
    init_histogram(histogram, MAX_LEN);

    /* Read input, and fill out the histogram */
    create_histogram_from_input(histogram, MAX_LEN);

    /* Print out the histogram */
    print_histogram(histogram, MAX_LEN);

    return 0;
}

Some extra comments regarding my refactored code:

Location of top_count in functions – When all is gathered within main() your choice of doing the top_count in the input processing loop is not the worst. However when dividing into functions, it does rather belong in the print_histogram() instead of input processing. This also removes the extra setting of this multiple times during the processing
Size of arrays and functions – One of the major hickups with C is that when an array is sent as an parameter to a function, you loose the size information. It is a best practice to include this as a parameter. For more information see How do I determine the size of my array in C?
Some dislike printf("literal string") – This is sometimes frowned upon, as it is considered to be a security issue, especially in the form char *s; ... ; printf(s). The first parameter of printf is supposed to be a format string, and neither the literal string nor the string pointer are safe in that respect. They could be replaced by using printfs("%s", s), but often this is skipped by most people
The printf width as parameter trick – Using printf("%*d", width, number), i.e. that is including * in the format string, you can specify the width in the parameter. This allows in my code for setting the leading indent before the x-axis text using the constant y_axis_width
Finding number of columns – To ease the logic of finding the longest word, I reversed the scan for top_count and max_length. This allows me to use one single loop, since top_count doesn't care, but for max_length I can there simply test if is set or not, before checking if that histogram column has a length, which indicates that there is a list one word of that length.

A test run against the leading comment of create_histogram_from_input() gave the following output:

 15|       #
 14|       #
 13|       #
 12|    #  #
 11|    #  #
 10|    #  #
  9|    #  #
  8|    #  #        #
  7|    #  #        #
  6|    #  #        #        #
  5|    #  #  #  #  #        #
  4|    #  #  #  #  #        #
  3|    #  #  #  #  #        #
  2|    #  #  #  #  #  #  #  #
  1| #  #  #  #  #  #  #  #  #  #        #
    ---------------------------------------
     1  2  3  4  5  6  7  8  9 10 11 12 13