Using/storing server-side data on the client side

Right now, you have two separate AJAX calls: one to determine if a day has bookings, and one to determine whether a specific time slot can be booked.

I would suggest one of two things:

Send a request only once that returns all booking data for the specified date.
Send only a validation request upon clicking Book; don't bother checking if a date has bookings.

Option 1 is the ideal approach, since it minimises requests. However, if for some reason you don't want a user to know when you're booked, you'll need to go with option 2. Whichever option you go with, you should provide feedback on its success (or failure) after submission, in case somebody else booked it sometime between validation and submission.

If you're adamant about continuing with your approach, then instead of using 0 and 1, consider using a salted hash involving the date. For illustrative purposes, I'm only using one round (since this type of thing doesn't need to be cryptographically secure).

define("BOOKING_DATE_SALT", "asprin111")
$flag = md5($clicked_date . ($db->num_rows() ? "yes" : "no") . BOOKING_DATE_SALT);
...

Of course, you won't want to repeat this code in check-slot-availability.php so it would probably belong better as a function in some shared library.


Early-termination foldLeft for Scala Streams

Your foldLeft1 method looks fine.

You don't need asInstanceOf. You pattern match a Stream[A] so the head will always be A and the tail Stream[A].
A case block doesn't need parentheses, but this is mostly a choice of preferred style.

The second case block could then look like :

case h #:: t =>
  val (z1, stop) = f(z, h)
  if (stop) z1 else t.foldLeft1(z1)(f)

If we want to generalize your foldLef1 method, we can see that foldLeft is implemented in TraversableOnce for Stream, List, ... (source on GitHub). So we could create an implicit class for TraversableOnce.

We cannot use pattern matching if we are using TraversableOnce to get the current element and the rest elements. If we look at the implementation of foldLeft for inspiration, we can see that it uses foreach and a mutable variable. That is no good in our case since we don't (necessarily) want to loop over all the elements of our collection (or iterator, ...).

We can use toIterator to get an Iterator to loop over our elements, and with an Iterator we can stop iterating whenever we want, that looks just like we want.

We can adjust the code of your foldLeft1 for Stream to use an Iterator :

implicit class FoldLazy[A](trav: TraversableOnce[A]) {
  def foldLeft1[B](z: B)(f: (B, A) => (B, Boolean)) = {
    def go(it: Iterator[A], z: B): B =
      if (it.hasNext) {
        val (z1, stop) = f(z, it.next)
        if (stop) z1 else go(it, z1)
      } else z
    go(trav.toIterator, z)
  }
}

Which we can use :

Stream(1,2,3).foldLeft1(0)((acc, elem) => (acc + elem, elem % 2 == 0))  // 3
List(1,2,3).foldLeft1(0)((acc, elem) => (acc + elem, elem % 2 == 0))    // 3
Vector(1,2,3).foldLeft1(0)((acc, elem) => (acc + elem, elem % 2 == 0))  // 3

Note that this doesn't work for Array, since Array is only a TraversableOnce through ArrayOps or WrappedArray, and the Scala compiler doesn't apply multiple (nested) implicit conversions.


Function to download anonymous type data into excel

Actually you can have anonymous types as parameters - called dynamics - but IMO it's not pretty (and probably rather slow):

static void ConvertToDatatable(IEnumerable<dynamic> input)
{

  foreach (var i in input)
  {
    Type type = i.GetType();
    if (type.GetProperty("Age") != null)
      Console.WriteLine($"{i.Name}: {i.Age}");
    else
      Console.WriteLine($"{i.Name}: No age");
  }
}

static void DynamicTest()
{
  bool isTrue = true;

  IEnumerable<object> data = null;

  if (isTrue)
  {
    data = Enumerable.Range(1, 5).Select(i => new { Name = "Name " + i, Age = i * 10 });
  }
  else
  {
    data = Enumerable.Range(1, 5).Select(i => new { Name = "Name " + i });
  }

  ConvertToDatatable(data);
}

I think I'd use a classical OOP approach:

class BaseClass
{
  public string Name;
}

class Sub1 : BaseClass
{
  public double Age;
}

class Sub2 : BaseClass
{
  public int Age;
}

static void ConvertToDatatable(IEnumerable<BaseClass> input)
{
  foreach (var i in input)
  {
    if (i is Sub1)
      Console.WriteLine($"{i.Name}: {(i as Sub1).Age}");
    else if (i is Sub2)
      Console.WriteLine($"{i.Name}: {(i as Sub2).Age}");
    else
      Console.WriteLine($"{i.Name}: No age");
  }
}

static void BaseClassTest()
{
  bool isTrue = true;

  IEnumerable<BaseClass> data = null;

  if (isTrue)
  {
    data = Enumerable.Range(1, 5).Select(i => new Sub1 { Name = "Name " + i, Age = i * 10 });
  }
  else
  {
    data = Enumerable.Range(1, 5).Select(i => new BaseClass { Name = "Name " + i });
  }

  ConvertToDatatable(data);
}

Beside that, I think your naming is quite remarkable and rather hard to read because of the length:

For instance it's hard to quickly distinguish between:

vwTransactionInfoItemProcessesInDownloadFormat

transactionInfoItemProcessesInDownloadFormat

vwTransactionInfoItemProcesses


Find all possible interpretations of an array of digits

test4 makes no sense. The question states "Given an array of digits (1 to 9) as input...", yet your test input is {12, 23, 2}.

As the digits are 1-9, there's no way to represent 'j' (10) or 't' (20). I'm guessing that's a mistake in the question.

  I'm also verifying space complexity to be \$O(2^n)\$

\$O(2^n)\$ is certainly an upper bound on the number of valid interpretations, but we can find a tighter bound.

Here's a hint: let's look at the number of interpretations of this sequence of inputs

{ }               1
{ 1 }             1
{ 1, 1 }          2
{ 1, 1, 1 }       3
{ 1, 1, 1, 1 }    5
...

Look familiar? I'm going to re-post part of an another answer of mine.

Suppose our array \$s = s_0 s_1 \ldots s_{n - 1}\$ is of length \$n\$. We define a function \$f\$ such that \$f(i)\$ is the number of ways to interpret the suffix of \$s\$ starting at position \$i\$: \$s_i s_{i + 1} \ldots s_{n - 1}\$. In this way, our final solution will be the value of \$f(0)\$.

How many ways are there to interpret the empty array? Just one, so we can write

\begin{align}
f(n) &= 1.
\end{align}

Now how about the suffix \$s_{n - 1}\$? Well if it's \$0\$, that's invalid; otherwise there's just one way to interpret it.

\begin{align}
f(n - 1) &= \begin{cases}
0 &\mbox{if } s_{n - 1} = 0, \\
1 & \mbox{otherwise}. \end{cases}
\end{align}

Now for the general case, the suffix \$s_i s_{i + 1} \ldots s_{n - 1}\$.

If \$s_i = 0\$, there are no interpretations. Otherwise, we have two cases to deal with.

If \$10 \leq s_i s_{i + 1} \leq 26\$, we can interpret the suffix as

\begin{align}
(s_i s_{i + 1}) \underbrace{s_{i + 2} \ldots s_{n - 1}}_{f(i + 2) \text{ interpretations}} \quad \mbox{ or } \quad
(s_i) \underbrace{s_{i + 1} s_{i + 2} \ldots s_{n - 1}}_{f(i + 1) \text{ interpretations}}.
\end{align}

Otherwise, we can only interpret the suffix as
\begin{align}
&(s_i) \underbrace{s_{i + 1} s_{i + 2} \ldots s_{n - 1}}_{f(i + 1) \text{ interpretations}}.
\end{align}

Putting that all together, we get
\begin{align}
f(i) &= \begin{cases}
0 &\mbox{if } s_{i} = 0, \\
f(i + 1) + f(i + 2) & \mbox{if } s_i = 1 \mbox{ or } (s_i = 2 \mbox{ and } s_{i + 1} \leq 6), \\
f(i + 1) & \mbox{otherwise.}
\end{cases}
\end{align}

So in the worst case, for example { 1, 1, 1, ..., 1 }, this reduces to the \$n\$th Fibonacci number, giving us space complexity \$O(F_n)\$.


Here are some code style and organization notes:

remove unused imports (sys, requests)
import time is also not needed since you are immediately shadowing it after by defining the variable time
missing datetime import
organize imports per PEP8
use consistent 4-space indents
no need for extra space after the function and before the opening parenthesis - e.g. siren() vs siren ()
let's avoid hardcoding the constant values, like the number 7 and define it in a, say, GPIO_PIN "constant"
let's move all the initial setup code to under the "main" block of the program
use print() as a function as opposed to a statement (for Python 3.x compatibility)

Here is the improved initial part of the code without the "scraping" part:

from datetime import datetime
from time import sleep

import RPi.GPIO as GPIO
from clint.textui import puts, colored
from scraper import Scraper

GPIO_PIN = 7

def setup_gpio():
    """Sets GPIO siren is attached too."""
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(GPIO_PIN, GPIO.OUT)

def siren():
    """Make a siren (flash) on a desired output pin."""
    GPIO.output(GPIO_PIN, GPIO.HIGH)
    sleep(30)
    GPIO.output(GPIO_PIN, GPIO.LOW)

if __name__ == "__main__":
    print("Starting")
    print("Monitoring")

    now = datetime.now()

    setup_gpio()

Note that I've renamed time variable to a more readable now.

As far as the rest of the code in the "main" block of the program:

please see if there is a better way to register a handler for the scraper - instead of defining a decorator, define the handler function before the "main" block and call register_handler() passing in the function:

scraper.register_handler(handler)

the time comparisons can be improved by using the .hour attribute of a datetime and short-circuiting:

if 8 < now.hour < 20:

you can omit the last "else" + "return" branch
the prints around the siren() call should probably be put into the siren() function itself to avoid the code duplication


First of all, there is no need to write a generic data access class.  Use the Data Access Application Block.  It gives you everything you need to access a database.  Why reinvent the wheel.  You can even download the source code to this if you want to see how Microsoft does it.

Having said that, if you are doing this just as an exercise then I see a couple things...

I am not a big fan of static classes (except for possibly simple "function" classes, classes which provide generic functions such as a function to convert unix timestamp to datetime).  Making classes static makes it more difficult to unit test.

Along these lines of unit testing I would also recommend you implement an interface so you could can make unit testing easier through IOC / dependency injection

Your methods should only do one thing.  Adding too much functionality into each method limits the flexibility of the caller.  You should have a method that creates a connection, another that creates a command, and another that executes the command.  Example, I would not open and close my connections within the "Execute..." methods because what if the caller wants to open the connection so they can execute multiple commands in the same connection.  If you want to add methods that do multiple things then they should be separate from your generic data access class, and they should call your generic data access methods.

I do not see anything to handle transactions.  This would be something you would want to add.


Remove parameters from string containing URL

The simplest way, a true one-liner, would be to use strtok, an ancient but for some reason obscure function that does exactly what you need:

$url = "http://www.test.com/test.html?parameter=hey&parameter2=ho";
$url = strtok($url, "?");

it will give you the part before the token if it is found, or the whole string otherwise


Optimize jquery plugin "on" method extension

I dont know if there is a better way to do it, but it seems quite smart and minimally intrusive.

From a once over style perspective:

function (key, element) <- since you dont use element, you can remove it from the signature
This

$.each(fctsToObserve, function (key, element) {
  fctsObserveKeys += "hasChanged." + key + " ";
});

would have been better served with Array.reduce, not sure if you want to support browsers that don't have Array.reduce
Naming.. Any code reviewer would be remiss if they did not point that you abbreviate your variables too much which makes the code needlessly harder to understand
In the if in $.fn.on = function () { you should use curly braces or a least a newline.
There is no point in declaring var namespace here:

observeMethods: function (namespace) {
    var namespace = namespace ? "." + namespace : "";

just go for

observeMethods: function (namespace) {
    namespace = namespace ? "." + namespace : "";

Comments, some of the more trickier concepts could have used a line of comment


Project Euler, problem # 9, Pythagorean triplet

Search Space

Your search space is too large.  Since 0 < a < b < c and a + b + c = 1000, you can put hard limits on both a and c.  The maximum a can be is 332, since 333 + 334 + 335 > 1000.  Similarly, the minimum value c can be is 335, since 332 + 333 + 334 < 1000.  As well, the maximum value c can have is 997 (1 + 2 + 997 = 1000).

Based on the above, if you wish your outside loop to loop over c values, your first loop should be:

for c in range(335, 997 + 1):
    # ...

And the inner loop should be over a values:

    for a in range(1, 332 + 1):
        b = 1000 - c - a
        # ...

But now that we’ve selected a c value, can tighten the limits on a even further.  When c is 600, then a+b must be 400, and since a < b must hold, the maximum a can have is 400 / 2.  So:

    for a in range(1, min(332, (1000 - c) // 2) + 1):
        b = 1000 - c - a
        # ...

Moreover, since we’ve selected a c value, we have established a maximum value for b as well, since b < c must hold.  If c is 400, then b can’t be larger than 399, so a must be at least 1000 - 400 - 399 = 201, establishing a lower limit for our inner loop:

    for a in range(max(1, 1000 - c - (c - 1)), min(332, (1000 - c) // 2) + 1):
        b = 1000 - c - a
        # ...

Geometry

As pointed out in a comment by @Peter Taylor below, we can tighten the limits on c much further.

First, triangles must be triangular.  In every triangle, the length of any side must be less than the sum of the lengths of the other two sides.  In particular, \$c < a + b\$ must be true.  Since \$a + b + c = 1000\$, we can conclude \$c < 1000 - c\$, or more simply, \$c < 500\$, establishing a much smaller upper limit.

The smallest value c could obtain would be when a and b are at their largest.  If we relax the conditions slightly, allowing \$a \leq b\$ and \$a, b, c, \in \Re\$; we have an isosceles right-angle triangle, \$a = b = c / \sqrt 2\$.  Then:

\$a + b + c = 1000\$

\$c = 1000 \sqrt 2 / (2 + \sqrt 2) \approx 414.2\$

giving us a larger lower limit.

Thus, the range of the outer loop can be reduced to:

for c in range(413, 500):
    # ...

Repeated Calculations

When searching for the Pythagorean triplet, you are calculating c ** 2 each and every iteration of the inner loop.  The value of c is constant during execution of the inner loop, so c ** 2 is also constant.  Since exponentiation is a relatively expensive operation, you should get a speed improvement by moving this calculation out of the inner loop:

for c in range(413, 500):
    c2 = c ** 2
    for a in range(max(1, 1000 - c - (c - 1)), min(332, (1000 - c) // 2) + 1):
        b = 1000 - c - a
        if a ** 2 + b ** 2 == c2:
            return a, b, c

1000 - c is also repeated in the inner loop, so you could compute this outside the loop also; it should provide a slight performance improvement.

See other answers for important PEP8, f-string, docstring, and return value improvements not duplicated here.


posY += 32;
        }
        posX += 32;

You have your tile sizes hardcoded in the TileMap ... in an obscure place (render code).

Consider placing them as constants in Tile or TileMap. That way, upscaling to 64x64 tiles is a lot easier.

public static BufferedImage getTileImage(int texKey1)
{
    BufferedImage image;
    switch(texKey1)
    {
        case 1:
        {
            image = Grass.texture;
            break;
        }
        case 2:
        {
            image = Dirt.texture;
            break;
        }
        case 3:
        {
            image = Tree.texture;
            break;
        }

        case 36:
        {
            image = Blank.texture;
            break;
        }
        default:
        {
            image = Blank.texture;
            break;
        }
    }
    return image;
}

You could use a Map here. Map<Integer, BufferedImage>, or better, Map<Integer,Tile>. Then you just have to get the Tile from the map, and ask that for the image. And if it's null you can return a blank.


Spam detection in PHP for comment system

Minor (and subjective) remarks:

Function name: The function does not sniff spam but calculate a score for the given content. Therefore I'd rename the function to something like getSpamScore
The variable $matches is not declared. Declaring it before using in in preg_match_all allows IDEs to perform code analysis and other developers don't have a hard time looking for its declaration.
Two empty lines just take up space. Your code should be clear enough from structure not to need any extra indentions (which you don't have) or double blank lines. As the preg_match_all is directly related to the if and only to it, I'd not have any lines at all between the match and the if-statement.  (This applies to all other lines too)
//url is/are present comment: more of a personal thing maybe: I don't like obvious comments. Personally I prefer the if it needs a comment it needs to be refactored way of writing comments (non in about almost every case). Comments need maintenance time (updating comments for changed code). But time should only be spent here if it provides value. Additionally comments tend to loose their relation to the code they originally were attached to (mostly by refactoring). This greatly confuses other developers.
$get_number_of_urls naming: this variable contains a verb. Verbs indicate actions (e.g. a method). In PHP I'd expect this variable to be a closur, not an integer. Yet you don't actually get the number or urls, you already have them. A proper name might be number_of_urls instead.
Stick to one convention of styling code: in your case this especially applies for where to have whitespaces. In your if and foreach lines you mix up foreach( foreach ( and your if conditions sometimes have whitespaces in between and sometimes not. I suppose this is some kind of work-in-progress code. Yet later styling costs time. Code you write always should meet production ready requirements (regarding style). It takes some time at the beginning to stick with someones conventions, but you'll get used to it and do it automatically after some time.
In my opinion this function has too many responsibilities (at least two). I'd suggest splitting this function into two sub-functions. This function itself only calls and sums of the results of the independent tests. When going OO this of course wants a design pattern ;)


HTML and CSS markup to achieve desired result

A few suggestions

You were using this to pass classes to your main logo

.col_left img {
    float:right;
    display: block;
    line-height:40px;
    margin-left: auto;
    margin-right: auto;
}

But that will create problems if you introduce any other images there. So instead try giving that element a class. For example, a class of logo or anything that you want to name it. This way there will not be any unexpected conflicts caused by CSS inheritance

HTML

CSS

.logo {
  float:right;
  display: block;
  line-height:40px;
  margin-left: auto;
  margin-right: auto;
}

In testing, can use image placeholders. In my example, I used Placehold.it which allows you to just give a desired height

All of your
s on the left have the same rules. So you might as well give that
 a class and pass rules that way. However some rules may not apply. Also you gave both an id and class to those
s. this is what I did

HTML

    User

    Vacancies

    Company

CSS

.user, .vacancy, .company {
  background:url('http://www.otlayi.com/web_images/content/free-doc-type-sprite-icons.jpg');
  width: 0px;
  height: 20px;
  padding-left: 30px;
}

.user { background-position: -10px -6px; }
.vacancy { background-position: -48px -6px; }
.company { background-position: -88px -6px; }

I did it that way so that you can choose to add in what you want to accept what CSS rules.

in testing. When you have links, it is common to just use href="#"

Full code available at this CodePen.


Super class knowing the type of its children? Surely there is a better way

First, I get some error messages when I put this in the compiler.
I had to replace the anonymous inner class that is returned by performAnalysis with a helper class. I'm not a fan of helper classes like this, so it would be nice if someone else had a better idea.

Second, I'm thinking generics would solve this quite nicely.
I agree that the parent class should not need to know it's child classes, but it can obtain this data; see the methods that I have commented out. I have commented them out because I don't like them, but still want to show that it's possible. I'll admit that using .class is a bit tricky when using generics, because of type erasure. However, as long as the generic types are known at compile time, this should not be a problem.

interface IDataAnalysis<InputType extends IAnalysisData, OutputType extends IAnalysisData> {

//    public Class<?> getInputDataType( );
//    public Class<?> getOutputDataType( );

    OutputType performAnalysis(InputType inputData);
}

public class DataAnalysisMean implements IDataAnalysis<IAnalysisDataSet, IAnalysisDataScalar> {

//
//    public Class<?> getInputDataType( ) { return IAnalysisDataSet.class; }
//    public Class<?> getOutputDataType( )  { return IAnalysisDataScalar.class; }

public IAnalysisDataScalar performAnalysis(IAnalysisDataSet inputData) {

    IAnalysisDataSet inputDataSet = (IAnalysisDataSet)inputData;
    double sum = 0;

    for (int i = 0; i < inputDataSet.getCount(); i++) {
        IAnalysisData dataItem = inputDataSet.getData(i);
        IAnalysisDataScalar dataItem2 = (IAnalysisDataScalar)dataItem;
        sum += dataItem2.getValue();
    }

    return new HelperClass( inputDataSet, sum );
}

private class HelperClass implements IAnalysisDataScalar
{
    IAnalysisDataSet inputDataSet;
    double sum = 0;

    HelperClass( IAnalysisDataSet inputSet, double sum )
    {
        this.inputDataSet = inputSet;
        this.sum = sum;
    }

    @Override
    public double getValue() {
        return sum / inputDataSet.getCount();
    }

    @Override
    public AnalysisDataType getType() {
        return AnalysisDataType.Scalar;
    }
   }
}


Execute a function n times, where n is known at compile time

Your implementation is fine. But it is a little bit ironic: In your SO answer, you start of with "you can use better functions", yet you rewrite nTimes via go. If this was a real module, you would probably want to export both functions nTimesTH and nTimes, and implement the former via the latter:

{-# LANGUAGE TemplateHaskell #-}
module Times (nTimes, nTimesTH) where

import Control.Monad (when)
import Language.Haskell.TH

-- example implementation
nTimes :: Int -> (a -> a) -> a -> a
nTimes n f x = iterate f x !! max 0 n

nTimesTH :: Int -> Q Exp
nTimesTH n = do
  when (n <= 0)    (reportWarning "nTimesTH: argument non-positive")
  when (n >= 1000) (reportWarning "nTimesTH: argument large, can lead to memory exhaustion")

  f <- newName "f"
  x <- newName "x"

  lamE (map varP [f,x]) $ nTimes n (appE (varE f)) (varE x)

This removes the need for code duplication, and any future optimization you find for nTimes gets automatically applied in nTimesTH, although that only matter during the compile time. After all $(nTimesTH n) is completely evaluated during compilation.

Other than that, I moved the warnings on top of the function, since this brings the names f and x closer to their actual use. I also replaced the data constructors with their respective functions.

Note that for a real module you still want to add documentation:

-- | @'nTimes' n f x@ applies @f@ @n@ times over @x@.
-- It does not apply @f@ if @n@ is negative. In this case @x@ is returned.
--
-- prop> nTimes n f x == iterate f x !! max 0
nTimes :: Int -> (a -> a) -> a -> a

-- | @'nTimesTH' n@ returns a function that applies the first
--   argument @n@ times to the second argument.
--   @n@ must be known at compile time. Needs @-XTemplateHaskell@.
--
-- prop> $(nTimesTH n) f x == nTimes n f x
nTimesTH :: Int -> Q Exp


Efficiently generating HTML CSS table using Java

How about extracting the style=""s into the head?

sb.append("");

You should write helper methods, that do the 'heavy lifting' for you:

void appendTag(StringBuilder sb, String tag, String contents) {
    sb.append('<').append(tag).append('>');
    sb.append(contents);
    sb.append("</").append(tag).append('>');
}
void appendDataCell(StringBuilder sb, String contents) {
    appendTag(sb, "td", contents);
}
void appendHeaderCell(StringBuilder sb, String contents) {
    appendTag(sb, "th", contents);
}

Please note, that if you are using StringBuilder you should not concatenate strings with +.  You want to get rid of string concatenation, not do it.

If you want to get even more expressive you should take a look at existing template engines. They are optimized and mostly easy to use.

Suggesting mustache:

If you are using mustache, you can write a template like this:

    <title>Table</title>

....

    {{#metrics}}

        {{getName}}
        ...

    {{/metrics}}

and then render it via e.g.

public static void main(String[] args) throws IOException {
    HashMap<String, Object> scopes = new HashMap<String, Object>();
    scopes.put("metrics", dataMetricsList);

    Writer writer = new OutputStreamWriter(System.out);
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile(new StringReader(getTemplateCodeFromAbove()), "example");
    mustache.execute(writer, scopes);
    writer.flush();
}

It depends on your use case, of course. If all you ever want is to render a single table, you are fine with StringBuilder. But if you find yourself repeating this, get an external library for it.


Insertion sort implementation adapted from the web

First of all, what you implemented is not insertion sort:

Insertion sort uses one loop to iterate over the array, and for each element uses another loop to move the element to its desired location. This makes its running time \$O(n^2)\$.

Your algorithm iterates over each pair of elements (using the two nested loops in InsertionSort()) and then for each pair, uses a third loop (the one in Insert) to move the one element to the position of the other if necessary. This makes its running time \$O(n^3)\$, which is significantly worse than \$O(n^2)\$.

So that's a problem.

In addition to that there's also a major usability problem with your function:

By making the array and its size a global variable and a constant instead of parameters, you make reuse of your function as good as impossible. If you want to use the function to sort multiple arrays, you have to copy each one into the global variable, call the sort function, and then copy it back from the global variable again. And this only works if all the arrays have the same size. If the arrays have different sizes it's plain impossible to use your InsertionSort function on them.

So passing the array and its size as parameters is clearly preferable.

Lastly, I realize that you're most probably aware of this and this is just a learning exercise, but just in case:

In most real-world applications, quick sort or merge sort are usually preferable to insertion sort, having much better performance characteristics than insertion sort in the majority of cases. So if you want to use this in real code, you should rethink whether you really want to use insertion sort.

Also the standard C library has a sort function built-in, so you don't even have to implement anything yourself.


Updates or creates an entity based on if a value is present in an Optional

Regarding your questions

Is this an inappropriate use of Optional's map method? I'm not mapping
to a new object but rather just returning the same car with some
properties potentially updated.

I think it's appropriate because it might return an updated object. Unfortunately (as you said) Java 8 doesn't have ifPresentOrElse.

The save method is really only required to be called for cars created
in the orElseGet.

You can change the orElseGet with orElseGet(() -> mySpringCarRepo.save(createCar(carInfo))) and remove the final save to the db.
Performances
The complexity of the method is O(c*ci) where c is the number of cars in your DB and ci is the number of CarInfo.
If you store the Cars in a Map instead of a Set you can improve it to O(ci).
void saveCars() {
    // get CarInfo from a webservice
    List<CarInfo> carInfos = getCarInfo();
    // Get cars from DB that correspond to each CarInfo
    Map<Long,Car> cars = mySpringCarRepo
            .findByCarInfoIdIn( getCarInfoIds(carInfos) )
            .stream()
            .collect( Collectors.toMap(Car::getCarInfoId,Function.identity()));

    for (CarInfo carInfo : carInfos) {
        // Returns Optional<Car>
        Optional.ofNullable(cars.get(carInfo.getId()))
        // Update car if already exists
        .map(c -> updateCar(carInfo, c))
        // Save car otherwise
        .orElseGet(() -> mySpringCarRepo.save(createCar(carInfo)));
    }
}

Or if you don't mind to query the db for each CarInfo, than the method is shorter:
void saveCars() {
    getCarInfo().stream()
        .forEach(carInfo ->
                    // returns Optional<Car>
                    mySpringCarRepo.findByCarInfoId(carInfo.getId())
                    // Update car if already exists
                    .map(car -> updateCar(carInfo, car))
                    // Save car otherwise
                    .orElseGet(() -> mySpringCarRepo.save(createCar(carInfo))));
}

Note 1: I haven't fully tested the code, it's just to give you an idea how to improve it.
Note 2: the performance gain might be irrelevant due to the DB and network latency, but with the second approach you should save some memory space.
Naming
The method name saveCars is not very appropriate, a better name might be updateCars or syncCars.


Using enum to create, subscript and loop an array of structs in Swift 5.0

Maybe you should create enum with property? Something like this, I don't know if it is what you want but hope it will be helpful.

enum Ship {

    case first(ShipPropperties), second(ShipPropperties), third(ShipPropperties)

    static let allValues: [Ship] = [first(ShipPropperties()), second(ShipPropperties()), third(ShipPropperties())]

    var properties: ShipPropperties {
        switch self {
        case .first(let properties): return properties
        case .second(let properties): return properties
        case .third(let properties): return properties
        }
    }

    func changeProperties(to: ShipPropperties) {
        properties.changeProperties(name: to.name, fuel: to.fuel, speed: to.speed)
    }

}

class ShipPropperties {

    var name: String = "TBD"
    var fuel: Int = 0
    var speed: Int = 0

    func changeProperties(name: String, fuel: Int, speed: Int) {
        self.name = name
        self.fuel = fuel
        self.speed = speed
    }

}


Send an inbound Enquiry to a Users registered Twitter Account to notify them of its arrival

Context:

  This answer was originally supplied in context as part of a larger
  answer, when the question was split here I've also split the answer here

Updated code

The updated code does create a better signal to the reader of what is going on, I particularly like the variable name coming out one of the operations. You are trying to write Laravel code so I'll skip over framework coupling issues

Had a look at Laravel's docs and there is a filter method on the collection class so we could change the code to this:

filter(function (Enquiry $enquiry) : bool {
  return $enquiry->canTweet() || $enquiry->shouldTweet();
));

The reason to inverse the check from reject to filter is that I find it hard personally to read negative code, With !$something, first your brain has to parse what $something is, and then it has to flip it, I would advise as much as possible to write code that talks about the situation from the "positive" prospective.

I've also added type hinting again, seems like you agree that type hinting is overall good but just not in the habit of doing so? Remember anonymous functions can be type hinted too.

I would also suggest moving that anonymous function out into it's own function not necessarily just for code reuse (although that's a nice side effect) but because it forces you to create a semantic name for what the combination of canTweet() and shouldTweet() is.

I definitely appreciate it doesn't look necessary now to create a new function but if you default to doing so you encourage other developers to not lump all their changes at this particular call point (good if this eventually gets reused elsewhere).

Also you tell them the intent of the code so hopefully they won't dump unrelated stuff into your function, code always grows in active projects, decisions you make now will affect future code more than you know, variable names/function names that you decide now will be replicated in other parts of the code and particularly classes they get sticky to everything because they are a natural clumping mechanism

Alternatively (or additionally) I personally often assign the result of a condition to variable before return to force myself to name it and it also helps when using xdebug, because you can then see the result of the return inside the function itself, this makes stepping over/debugging easier because xdebug cannot go in reverse see: https://bugs.xdebug.org/view.php?id=888 :(

We can also stop our coupling to the structure of NewEnquiryEvent by changing the signature of the handle method to array $enquiry_ids

Feels like the OOP way to do this would be to create a method that does this:

class NewEnquiryEvent
{
  public function getIds() : array
  {
    return $this->body->id;
  }
}

Personally I would prefer to do this:

namespace NewEnquiryEvent;
function getIds(NewEnquiryEvent $event) : array
{
  return $event->body->id;
}

This is because I prefer to take responsibly away from classes they're usually already doing too much

I find OOP developers typically set things to private or protected for one of these reasons:

They think it makes the property immutable
They think know better than the callee about how the object should be used, and they think they can dictate that
They do it because they were taught to do so by default without really questioning why

Let's assume that's happened and we can't edit their class because we don't want to debug their class or its a third party code that we want are not interested in maintaining our own fork of then use the following:

namespace NewEnquriyEvent;
function getIds(NewEnquiryEvent $event) : array
{
  return (function () : array {
    return $this->body->id;
  })->call($event);
}

I imagine this won't be consistent with your current project structure or in particular your autoloader and sometimes consistency should trump logic or programming style, but either way I think it's interesting to explain the train of thought.


Removing duplicates from list and filtering non-letter characters

Think carefully about what data structure you're using, lists aren't always the best choice. In this case you need to do two major things with your words.

Associate words with the line number they first appear on.
Remove words from one group using entries from another.

Right off the bat whenever you need to associate one set of elements with another, you should think of a map. In Haskell, you'll want to look at the documentation for Data.Map.

By reordering and reconsidering the operations you're performing on lists and sets, you should be able to rewrite your code to use maps and significantly cut down the amount of code you have written and end up with something more expressive too.

As it isn't clear that you've actually turned in this assignment I'm afraid I'll have to be coy, but here's the most pointed help I can give you on your specific questions.

Regarding removing duplicate words, the trick is to rely on the fact that maps can only contain a given key once. Pay close attention to the various ways of constructing a list that are specified in the documentation for Data.Map.

Filtering out the non-letters in a string doesn't get much simpler than filter Char.isLetter in your code above. The dissatisfaction you are feeling might be because of the gross duplication between the definitions of word and stopWord, and word' and stopWord'. Any time you have two lines in Haskell that are identical but for the value you're operating on, your code is crying out for a new function definition.

Your code is lingering in IO far more than is necessary, pull the pure data manipulating machinery out into separate functions. To start you off, knowing no more than the type signatures I've given here, what do you think these functions do? What part of your code do they replace? Take a shot at defining them.

normalize :: String -> String
??? :: [a] -> [(a, Int)]
??? :: String -> [([String], Int)]


How May I extract this ternary operator in independent statement

You could do query.GroupBy(MyTernaryWrapperMethod) and declare that method as

string MyTernaryWrapperMethod(xVariableType x)
{
    if(x.ProductStatusId == ProductStatus.Sold || x.ProductStatusId == ProductStatus.OnHold) return "Delivered";

    if(x.ProductStatusId == ProductStatus.Shiped) return "Shiped";

    if(x.ProductStatusId == ProductStatus.NotAvailable) return "NotAvailable";

    if(x.ProductStatusId == ProductStatus.Paid) return "Paid";

    return "New"
}

But, that method seems to return something being an actual property of x. So maybe you should add a new method to x's type. Also it would be better to use swicth/case instead of those ifs:

public string ProductStatusName()
{
    switch (ProductStatusId)
    {
        case ProductStatus.Sold:
        case ProductStatus.OnHold: return "Delivered";
        case ProductStatus.Shiped: return "Shiped";
        case ProductStatus.NotAvailable: return "NotAvailable";
        case ProductStatus.Paid: return "Paid";
        default: return "New"
    }
}

And then you do:

var results = query.GroupBy(x => x.ProductStatusName()).Where(g => g.Key != "New")


Your solution is principally correct. If you want to play nice with potential generic traits (at the cost of a potentially uglier error message), you'd replace the static_assert with SFINAE:

template <
    class UR = T,
    class TypeMustBeT = std::enable_if_t<std::is_same<std::remove_reference_t<UR>, T>::value>
>
void Add(UR&& object)
{
    m_Vector.push_back(std::forward<UR>(object));
}

This way, the function Add will not exist at all when UR is not a forwarding reference for T1.

If you don't like the "template magic" involved in this and/or the compiler errors generated from misuse, you can solve this by providing the two strongly-typed overloads as std does and forward to a common private implementation:

void Add(const T& object)
{
  AddImpl(object);
}

void Add(T&& object)
{
  AddImpl(std::move(object));
}

private:
template <class UR>
void AddImpl(UR&& object)
{
    static_assert(std::is_same<std::remove_cv_t<std::remove_reference_t<UR>>, T>::value, "UR and T should be the same!");
    m_Vector.push_back(std::forward<UR>(object));
}

This way, you can keep the static_assert-using version and keep the static assertion just to check your code's correctness, not the client code's.

Note that the static_assert needs to do std::remove_cv after std::remove_reference, otherwise it will fail for UR = const T&. The same applies to the original code in the question too.

Unrelated to the question at hand, but I assume using namespace std; is for this reduced example only and is not present in your real code. It's very bad practice to put that into header files in real code.

1 Note that "forwarding reference" is the preferred term instead of "universal reference," since it captures the semantics better.


Sending user information to server to track hits / traffic on site

For one, I wouldn't work with that code. I would prefer working on a verbosely written code. If you want to shrink this piece of code, use a minifier before release. But on development, work on the full, verbosely-written code.

That said, variable names could be better. p, u, t, s tell me nothing about what these variables are. Best if you expand the names to ones that mean something.

Also, your variables are in the open, in the global scope. There is a slight chance your code would be clobbered by other code on the page. Wrap it in a closure to avoid collision.

Now for your approach.

XMLHttpRequest which is a bit overkill. It's not cross-browser friendly if you factor in older browsers, and you're using a POST request. If you just want to track hits, a "tracking pixel" is much simpler.

It's the same approach, but instead of XMLHttpRequest, you use an image. You create the object, tack the data as query params, append that image to the page to kick the request. Your server receives the data as a GET request, gathers the data, and have it redirect to a dummy 1x1 image as a response, literally a "pixel".

For your ID logic, you will not have 100% ID'ing with your current approach. Clearing the cache will force your logic to regenerate an ID, a totally different ID from previous sessions. This will disconnect the user from any known previous data, making your data erroneous.

Consider generating a hash from pieces of browser data that almost never change. Examples of which are the browser's name, the OS name, the timezone, the screen resolution, browser settings, and so forth. A good place to start is the browser's navigator object.

The name of the technique is "device fingerprinting". The fun thing about this approach is you never have to store the value. Since the values are always present but never change, generating a hash from the same values will always yield the same value.

;(function(){

  function hashFunction(string){
    // Any will do. See http://stackoverflow.com/a/7616484/575527
  }

  var userId = hashFunction([
    navigator.userAgent,
    navigator.oscpu,
    // Add more...
  ].join(''));

  var image = new Image();
  var path = 'https://example.com/hit';
  var params = [
    'r=' + encodeURIComponent(document.referrer),
    'u=' + encodeURIComponent(userId),
  ].join('&');

  document.body.appendChild(image);
  image.src = encodeURI(path + '?' + params);

}());

Taking this approach further, you won't need JavaScript at all. HTTP requests send in non-changing data via headers. There will also be some form of non-changing data via the network, like the request IP address. You can move all of this logic to the back-end, using that data to construct a hash. The page request is sufficient to get the data even.


So, any tips that reduce lines of code..

As a start you can remove this useless try..catch because you are only rethrowing the exception which is senseless.

Using += with strings in a loop is a bad habit because each time a new string will be created so better use a StringBuilder.
Speeking about the composition of the query variable you don't need to add new lines and tabs in it. You won't show it, you only execute it as a sql query.

In its current state this method is not flexible enough. Each time you want to query different tables or need only specific permissions you need to change this method.

By passing IEnumerable<string> tables and IEnumerable<string> permissionType you can beautify your method and add a lot flexibility to it.

Let us talk about style. If it comes to style one should stick to a choosen style.

If you choose to use braces {} for loops you should always use them. Mixing styles is a bad habit, don't do it.

Method scoped variables should be named using camelCase casing. PascalCase casing is used for class-, method- and propertynames. So Dictionary<string,bool> Permissions -> Dictionary<string,bool> permissions.

EDIT Based on the great comment of @d347hm4n stating

  In the above code, in all cases, there will be a comma on the end that needs to be removed. So removing the last character from the string builder is sufficient. If the sql generated does change in the future, using a TrimEnd instead gives you the extra intelligence to not remove the comma on the end if it's not there.

I changed the former removing of the comma from

sb.Length -= 1;
string query = sb.ToString();

to

string query = sb.ToString().TrimEnd(',');

Applying the mentioned points lead to

public static Dictionary<string, bool> GetPermissions(IEnumerable<string> tables, IEnumerable<string> permissionTypes)
{
    if (!tables.Any() || !permissionTypes.Any())
    {
        return new Dictionary<string, bool>();
    }

    StringBuilder sb = new StringBuilder(1024);
    sb.Append("SELECT ");
    foreach (string table in tables)
    {
        foreach (string perm in permissionTypes)
        {
            sb.AppendFormat("HAS_PERMS_BY_NAME('{0}','OBJECT','{1}') AS {0}_{1},", table, perm);
        }
    }

    string query = sb.ToString().TrimEnd(',');

    Dictionary<string, bool> permissions = new Dictionary<string, bool>();

    using (SqlConnection sql = new SqlConnection(ConnectionString))
    using (SqlCommand cmd = new SqlCommand(query, sql))
    {
        sql.Open();
        using (SqlDataReader data = cmd.ExecuteReader())
        {
            data.Read();
            for (int i = 0; i < data.FieldCount; i++)
            {
                permissions.Add(data.GetName(i), data[i].Equals(1));
            }
        }
    }

    return permissions;
}

and can be then called like this

IEnumerable<string> tables = new string[] { "appearance", "appearanceSpecs", "cutTemplates", "cutVinyl" };
IEnumerable<string> permissionTypes = new string[] { "INSERT", "UPDATE", "DELETE" };
Dictionary<string, bool> permissions = GetPermissions(tables, permissionTypes);


Immutable C++ stack - thoughts and performance

Element mutability

Your stack is not entirely immutable, because peek returns a pointer to a non-const T, which means it's possible to modify the elements of the stack. And given your use of shared_ptr, this may have severe consequences. Consider this code:

using immutable::stack;

void doSomething(stack::StackPtr stack);

int main() {
  auto stack1 = stack<int>::empty()->push(1);
  assert(*stack1->peek() == 1); // succeeds
  doSomething(stack1);
  assert(*stack1->peek() == 1); //FAILS!
}

void doSomething(stack<int>::StackPtr st) {
  *st->peek() = 42;
}

If this is intended behaviour, it should definitely be heavily documented. To me, it looks much more like a bug, however.

One option would be to change headPtr to be a pointer to const:

typedef std::shared_ptr<const T> headPtr;

However, perhaps a more user-friendly solution would be to change peek() to return a const-reference to T instead of a shared pointer. After all, if I put a T on the stack, I would expect to get a T back, not a pointer to T:

const T& peek()
{
    return *this->head;
}

Of course, this would require handling the case of peek-ing an empty stack, or at least documenting that it produces undefined results.
stackBuilder

I understand you're using the stackBuilder class template to be able to use std::make_shared internally, but it opens up a way to bypass your creation mechanism, which is a potential source of bugs. Nothing prevents a user from doing this:

immutable::stackBuilder<int> p(nullptr, nullptr);
p.push(7);

This will fail at runtime because no std::shared_ptr has ever referred to p, so shared_from_this() won't work.

You should make stackBuilder a private member class of stack (it doesn't even have to be a template any more). That way, it's inaccessible from outside, but its constructor can still be public, so std::make_shared works.

If your compiler implements C++11 member access rights correctly, stackBuilder will then no longer have to be declared as friend, because member classes have the same access rights as other members.
Copy constructor

Your class has an inaccessible assignment operator (which is good since it's supposed to be immutable), but the copy constructor is accessible normally. This is again a potential problem, since your class doesn't work if it's not owned by a shared_ptr. So this code will compile, but fail at runtime:

using immutable::stack;

auto stack1 = stack<int>::empty();
auto stack2(*stack1);
stack2.push(7);

You should make the copy constructor inaccessible as well.
Inconsistent capitalisation

StackPtr vs. headPtr, all camelCase member functions vs. Create() etc. You should pick one pattern and stick to it.

Related to this is the fact that your class closely resembles one from the standard library (std::stack), so it might be worthwhile to modify your naming to match the std one. That would mean renaming peek() to top(), and isEmpty() to empty() (and of course renaming your current empty() to something else). But this depends on other parts of your project as well, of course.
Storing non-copyable types

I think push() should take its argument by value, and std::move() it into the new stack; that way, you can store non-copyable types in the stack as well:

StackPtr push(T newHead)
{
    return std::make_shared<stackBuilder<T>>(std::make_shared<T>(std::move(newHead)), shared_from_this());
}

Alternatively, provide two overloads, one taking const T& and one taking T&&. This would potentially be more efficient for types which are expensive to move.

Note that I've renamed the parameter to newHead - when originally reading your code, I was actually confused and though you were pushing this->head. It's best to prevent such naming confusion.
Storing non-movable types

You might also provide an emplace(), which would even allow non-movable types to be stored (especially as the stack is immutable), and be more efficient with types expensive to copy/move:

template <class... Arg>
StackPtr emplace(Arg&&... arg)
{
    return std::make_shared<stackBuilder<T>>(std::make_shared<T>(std::forward<Arg>(arg)...), shared_from_this());
}

Const-correctness

It doesn't matter too much in your case, because access to its instances is stricty via StackPtr, but you might want to mark all the member functions as const to emphasize the fact that the class is immutable. StackPtr would then change like this:

typedef std::shared_ptr<const stack<T>> StackPtr;

This nicely documents that the class is immutable, and allows it to be more easily used inside other const-correct code, mainly const-correct templates.
A note on performance

I can't see any blatant performance issues there. Nevetheless, your users must be aware that the class uses mechanisms which could negatively affect performance-critical code. One is dynamic allocation. The other one are shared pointers, which must internally use atomic operations or synchronisation on their reference counts.

For normal use, this is hardly a problem. If you expect the class to be used in performance-critical code, though, you might want to provide a custom allocator for it which would prevent constant deallocation and re-allocation. Still, I don't think this is worth doing until profiling tells you otherwise.


Find the number of pawns available for a rook to capture

Dimensions

How big is your chess board, and is it square, or at least rectangular?

First, you use range(len(board)) to determine the rows of the chess board, but then you use range(len(board[r])) for the columns, which means you can handle each row having a different number of columns!

(Supporting a non-rectangular chess board would be a challenging challenge, but totally possible, as demonstrated above.)

But then, you use range(r+1, 8) and range(c+1, 8), indicating that you only support square 8x8 chess boards.

Unfortunately, you haven’t posted the challenge problem text, so we can only guess at the actual challenge.  Additional context would go a long way.

Verbosity & Fancyness

In order to be less verbose, we need to do something at least a little bit “fancy”.  With only rook movements, it may seem overly fancy, but if you later support bishops and queens, the additional capability we build in will be leveraged, and very little code need be added.

Additionally, you only need the white bishop blocking the white rook, and only black pawns being captured.  What about white pawns with a black rook and bishop?  This shouldn’t be a special case; it should be generalized.  But again, generalization one one hand will be more verbose, and “fancy”, and the other hand will be leveraged to make the code agnostic to the current player.

First of all, you should have an on_board function, which will return True if a given position is actually on the chess board.  I’ll hard-code the board size, and assume the board is stored in self; the dimensions could be stored in self or derived from self.board on the fly.

def on_board(self, r, c):
    return r in range(8) and c in range(8)

Next, pieces get “blocked” by other pieces.  So let’s formalize that.  Again, I’ll assume the piece is the 'R', so any white (uppercase) piece will block it.   (You should return the appropriate expression based on the colour of piece ... left to student)

def blocked(self, piece, r, c):
    return self.board[r][c].isupper()

A black pawn doesn’t “block” a white rook’s move, but it does terminate it in a “capture” event.  Again, we’ll assume a white piece is moving, so it will “capture” any black (lowercase) piece.  (Again, base actual return value on piece ... left to student)

def capture(self, piece, r, c):
    return self.board[r][c].islower()

Rooks, bishops, and queens can move in a straight line any number of spaces until blocked, or it captures another piece.  Note that a blocked move is not a valid move, but a capture move is a valid move.

def direction_moves(self, piece, r, c, dr, dc):
    r += dr
    c += dc
    while self.on_board(r, c) and not self.blocked(piece, r, c):
        yield r, c
        if self.capture(piece, r, c):
            break
        r += dr
        c += dc

Rooks, bishops and queens can move in more than one direction, so let’s allow multiple directions to be given at once:

def linear_moves(self, piece, r, c, *dirs):
    for dr, dc in dirs:
        yield from self.direction_moves(piece, r, c, dr, dc)

Now that we have the building blocks, getting a rook’s moves from a given position is easy:

def rook_moves(self, piece, r, c):
    yield from self.linear_moves(piece, r, c, (1, 0), (0, 1), (-1, 0), (0, -1))

Moves for the piece at a given position might be:

def moves(self, r, c):
    piece = self.board[r][c]
    if piece in {'R', 'r'}:   # Black or white rook
        yield from self.rook_moves(piece, r, c)
    # ... other types of pieces ...

With this, your find_p becomes trivial:

def find_p(self, r, c):
    return sum(1 for i, j in self.moves(r, c) if self.board[i][j] == 'p')

The above has increased the amount of code, but at the same time it is more generalized.  It has work to be done to generalize it for white -vs- black.  It would be trivial to add movements for bishops and queens to this structure, and that would not be repetitive code, unlike the original structure.

Unfortunately, you may conclude that it has become overly “fancy”.


Security

  Everything is fully encrypted and secure

Oh, really? I hope that you aren't confusing encoding with encryption. I don't see any encryption taking place.

This is a huge topic, so you have some reading to do - but the bar for 'secure password store' is significantly above where this program currently resides.

Class syntax

This:

class user():

should be

class User:

Also, you're currently using it as a struct with no methods. That should change - you should move some of your code to be methods on that class.

Break

This:

loop = True
while loop:

should be reworked. You can use a while True, and replace the loop = False with a break at the end of that if block.

File handles

Rather than explicitly closing your files, you should usually use them in a with block. Also, this:

user_saves.close

doesn't do what you think it does; in fact it does nothing. For the function call to occur, you need to add ().

Redundant else

This:

    return name, password, user
else:

doesn't need an else, because you've returned in the previous block.

Write a main method

...to pull this code out of global scope:

name, password, users = get_user()
data = get_user_data(password)
print(data)
user_stats = user(name, password, data)


The key issue can be that you run the query with the same parameters multiple times. I assume you have quite many records where Articolo/fase/tipo/etc are the same for you are looking for median. You did not state how many records you have but I think you could reduce the number of issued queries. So - without knowing too much details - I would

Collect unique Articolo/fase/tipo/etc values

Issue the queries only once for each combination

Update median values


Instead of letters="abcdefghijklmnopqrstuvwxyz"; use a built-in constant:

letters = string.letters;

The code only inspects first and last character of the word. It means that aaa.bbb will be treated as a single word. Is this an intent?
split(sep) allows a string of separators. Calling it with

raw = self.text.split(string.punctuation + string.whitespace)

eliminates the need to inspect individual words. If you still want to inspect them, a loop for i in range(len(raw)): should be written more idiomatically as

for word in raw:

(you don't really need i anywhere in the loop).


First of all, do not use static variables to store anything that is not directly singleton related. All your variables - min, max, target, isFound, level, nodes - should be handed around in the call, not stored in class static variable. This not only makes the code utterly unreadable, but it will not be possible to make concurrent calls on the BST, even though search should be thread safe operation.

Namely:
target does not need to exist at all and can be replaced by level only, max|min as return value respectively or in some other way, level can be decremented with every found minimum to leave out target, nodes is really clunky way to mark - not found, simply put, if there is k elements in the BST, trere must be k-th minimum or maximum, so before even going into recursion, you can compare target with number of elements in the tree (updated in class variable on every insert/remove)

Adding suffix "Helper" to your methods is redundant with them being private, and it actually makes them bit more obscured.

Avoid using of one letter variable names. Exception would be some math problem where these variables are commented right before use, or indexes in loops.

It is common convention to have names of methods start with lower case letter, while upper case is for classes. this way, you should have kthMax. For class Bst or better, since it is abbreviation, BST or for clarity, since BST can be anything, BinarySearchTree.

It would be really complicated to work around level and isFound being returned. In this case, search state class seems to be a good idea.

private class SearchState{
    public int level;
    public boolean found = false;
    public final boolean isMin;
    public int value = 0;

    public SearchState(boolean isMin, int level){
        this.isMin = isMin;
        this.level = level;
    }

    public Node first(Node in){
        return isMin?in.left:in.right;
    }

    public Node last(Node in){
        return isMin?in.right:in.left;
    }

    public void check(Node in){
        if (this.level == 0) {
            this.value = in.data;
            this.found = true;
        }
        this.level--;
    }
}

As you can see, it contains all necessary information and methods for distinguishing between min and max search.

Unified method for search of kth number would be then

private void kthRecursion(Node node, SearchState state) {
    if (state.found || node==null) {
        return;
    }

    kthRecursion(state.first(node), state);

    state.check(node);

    kthRecursion(state.last(node), state);
}

and its use

public int kthMin(int k){
    return kthInit(k, true);
}

public int kthMax(int k){
    return kthInit(k, false);
}

private int kthInit(int k, boolean isMin){
    if(k>size || k<=0){
        throw new Exception("Invalid argument "+k+"!");
    }

    SearchState state = new SearchState(isMin, k-1);
    kthNumber(root, state);
    return state.value;
}

Do not know whether this code works, since I do not have rest of your class, but it should work. Please let me know if it does not along with remaining parts of your class so I can fix it.

Hope it helps, regards.


Find pairs in binary search tree in which sum of nodes keys is equal key

I just have minor nitpicks.

1

You can simplify the methods for computing a successor/predecessor:

public static Node successor(Node node) {
    if (node.right != null) {
        return min(node.right);
    }

    while (node.parent != null && node.parent.right == node) {
        node = node.parent;
    }

    return node.parent;
}

Also, you compute the min(node.right) above in code; hence, you repeated yourself.

2

I would rip off the implementation of your sum pair algorithm out of main().

3

I would have a class, say, NodePair, which simply stores a pair of nodes.

4

The actual algorithm could just return the list of those NodePair objects.

5

Since you are printing the results, you could override toString() in NodePair and make it return a string in the format that meets your needs.

6

inOrder is not used. In case you don't need it either, consider removing it.

7

You import java.lang, yet you don't need to: it is imported by default. Also, you left hanging around two packages (java.util and java.io), remove them. Finally, I would encourage avoiding wildcard imports: import on individual basis, let people see what classes you use in your source.

Summa summarum

All in all, I had this in mind:

import java.util.ArrayList;
import java.util.List;

class Main {

    static class Node {

        Node(Node left, Node right, Node parent, int key) {
            this.left = left;
            this.right = right;
            this.parent = parent;
            this.key = key;
        }

        public Node left;
        public Node right;
        public Node parent;

        public int key;

        @Override
        public String toString() {
            return new StringBuilder("Node ").append(key).toString();
        }
    }

    public static Node successor(Node node) {
        if (node.right != null) {
            return min(node.right);
        }

        while (node.parent != null && node.parent.right == node) {
            node = node.parent;
        }

        return node.parent;
    }

    public static Node predeccessor(Node node) {
        if (node.left != null) {
            return max(node.left);
        }

        while (node.parent != null && node.parent.left == node) {
            node = node.parent;
        }

        return node.parent;
    }

    public static Node min(Node node) {
        while (node.left != null) {
            node = node.left;
        }

        return node;
    }

    public static Node max(Node node) {
        while (node.right != null) {
            node = node.right;
        }

        return node;
    }

    public static final class NodePair {
        public Node node1;
        public Node node2;

        public NodePair(Node node1, Node node2) {
            this.node1 = node1;
            this.node2 = node2;
        }

        @Override
        public String toString() {
            return new StringBuilder("[").append(node1)
                                         .append(", ")
                                         .append(node2)
                                         .append("]")
                                         .toString();
        }
    }

    public static List<NodePair> findPairsWithSum(Node root, int sum) {
        List<NodePair> nodePairList = new ArrayList<>();
        Node minnode = min(root);
        Node maxnode = max(root);

        while (minnode.key <= maxnode.key && minnode != maxnode) {
            if (minnode.key + maxnode.key == sum) {
                nodePairList.add(new NodePair(minnode, maxnode));
                minnode = successor(minnode);
                maxnode = predeccessor(maxnode);
            } else if (minnode.key + maxnode.key < sum) {
                minnode = successor(minnode);
            } else {
                maxnode = predeccessor(maxnode);
            }
        }

        return nodePairList;
    }

    public static void main(String[] args) throws java.lang.Exception {
        Node root = new Node(null, null, null, 5);//      5
        Node a = new Node(null, null, null, 2);   //     / \
        Node b = new Node(null, null, null, 1);   //    2   8
        Node c = new Node(null, null, null, 3);   //   /\    \
        Node d = new Node(null, null, null, 8);   //  1  3    9
        Node e = new Node(null, null, null, 9);   //

        root.left = a;
        root.right = d;
        a.parent = root;
        d.parent = root;

        a.left = b;
        a.right = c;
        b.parent = a;
        c.parent = a;

        d.right = e;
        e.parent = d;

        // Print all the node pairs summing to 10.
        for (NodePair pair : findPairsWithSum(root, 10)) {
            System.out.println(pair);
        }
    }
}

Hope that helps.

Edit

Actually, what comes to printing the node pairs, I realized that it makes sense to override Node.toString() as well. After that, building a string representation of a NodePair simplifies a bit. Please, for details refer to Node.toString and NodePair.toString.


Suggestions for a Dungeons and Dragons-like game

There are two huge improvements you can make to increase readability of your code:

Choose better names for some variables – skill1 is better than skl1, and strength2 is better than str2 (str usually means “string”, which adds even more confusion). play1 should be play or play_on.
Put whitespace around operators rather than trying to write your code as compact as possible. For example, change

strdif=str1-str2
if strdif<0:
    strdif=str2-str1
strdif=strdif//5

to

strength_difference = strength1 - strength2
if strength_difference < 0:
    strength_difference = strength2 - strength1
strength_difference = strength_difference // 5

Next, there are a number of small issues that could be improved:

while play1 == True could be abbreviated to while play1. However, setting a variable to False in order to exit a loop isn't very elegant: You could break out of the loop instead, or put the loop into a function from which you can return.
When calculating the differences of strength and skill, you could use the abs function instead: strength_difference = abs(strength1 - strength2) // 5.
You roll two random numbers from 1–6, then compare whether they are greater or smaller than each other. Instead, we could directly figure out the probabilities:

2/12: draw
5/12: player 1 deals a blow
5/12: player 2 deals a blow

which means we only have to roll one value from 1–12
Instead of naming our variables foo1 or foo2, let's create dictionaries that hold variables for each player:

player1 = dict()
player1["name"] = "Character 1"
player1["strength"] = ...
player1["skill"] = ...

This looks more verbose, but allows us to remove a lot of duplication in a minute.
We can stuff the character initialization into a function that returns a player dictionary:

def generate_character():
    character = dict()
    character["name"] = raw_input("name: ")
    character["strength"] = int(raw_input("strength: "))
    character["skill"] = int(raw_input("skill: "))

    print("Your character is %s (strength: %d, skill: %d)" % (character["name"], character["strength"], character["skill"]))

    return character

Note that I use raw_input instead of input, as this avoids executing the input as if it were code.

We can then initialize the players like this:

player1 = generate_character()
player2 = generate_character()

Because all info about a player is conveniently bundled, we can do neat stuff like this:

(loser, winner) = sorted((player1, player2), key = lambda player: player["strength"])

which sorts the players by their strength. This simplifies printing out the stats at the end of a round:

for player, status in [(winner, "won"), (loser, "lost")]:
    print("%s %s the encounter, now has %d strength and %d skill" %
          (player["name"], status, player["strength"], player["skill"]))

Using dictionaries for this is easy, but awkward. Instead we could write a class that represents characters, and create one instance of this class for each player:

class Character:
    def __init__(self, name, strength, skill):
        self.name = name
        self.strength = strength
        self.skill = skill

Our generate_character changes to this:

def generate_character():
    name = raw_input("name: ")
    strength = int(raw_input("strength: "))
    skill = int(raw_input("skill: "))

    character = Character(name, strength, skill)

    print("Your character is %s (strength: %d, skill: %d)" % (character.name, character.strength, character.skill))

    return character

If we combine all these points (and a few other minor quibbles), we might end up with something like the following code:

import random

class Character:
    def __init__(self, name, strength, skill):
        self.name = name
        self.strength = strength
        self.skill = skill

    def hit(self, other):
        strength_difference = abs(self.strength - other.strength)
        self.strength += strength_difference
        other.strength = max(0, other.strength - strength_difference)

        skill_difference = abs(self.skill - other.skill)
        self.skill += skill_difference
        other.skill = max(0, other.skill - skill_difference)

def generate_character():
    name = raw_input("name: ")
    strength = int(input("strength: "))
    skill = int(input("skill: "))

    character = Character(name, strength, skill)

    print("Your character is %s (strength: %d, skill: %d)" % (character.name, character.strength, character.skill))

    return character

def run(player1, player2):
    while True:
        print("Encounter!")

        roll = random.randint(1, 12)
        if roll <= 5:
            player1.hit(player2)
        elif roll <= 10:
            player2.hit(player1)
        else:
            pass # draw

        if player1.strength <= 0:
            print("%s won the game" % player1.name)
            return
        if player2.strength <= 0:
            print("%s won the game" % player2.name)
            return

        (loser, winner) = sorted((player1, player2), key = lambda player: player.strength)
        for player, status in [(winner, "won"), (loser, "lost")]:
            print("%s %s the encounter, now has %d strength and %d skill" %
                  (player.name, status, player.strength, player.skill))

if __name__ == "__main__":
    print("Initialize the first character:")
    player1 = generate_character()
    print("Initialize the second character:")
    player2 = generate_character()
    run(player1, player2)


Find first non-repetitive character in a string

Common characteristics

Asymptotic complexity

Both algorithms perform θ(n) operations for strings of length n.  Since the task always requires examining every character of the input, there can be no alternative that provides better asymptotic complexity than these do.  Additionally, each has memory overhead that does not vary with the input, which affords no asymptotically better implementation in that respect either.  Of course, implementations with the same asymptotic complexity are not all equivalent by either measure.

See also below, however: your implementations of these algorithms are potentially flawed and less efficient.

Wrong range for char

Your codes assume that the string elements all have numeric value between 1 and 126, inclusive, but char can be a signed type, and whether signed or unsigned it can have more than 7 value bits.  Also, (char) 127 is always a valid char (from C's perspective).  As a result, on any conforming C implementation there are valid C strings which, if provided as input to either of your functions, will cause that function to exhibit undefined behavior.

To solve this problem I suggest declaring your arrays with dimension UCHAR_MAX + 1, and casting input chars to type unsigned char before using them as indexes.

Failure behavior

Each function exhibits somewhat surprising behavior for non-empty inputs that contain no unrepeated characters.  They return that character among those with the minimum number of repeats whose first appearance is earliest in the string.  It's unclear what the function is supposed to do in that case, but the the actual behavior is potentially misleading.  It would be better to return an error code.

You could use 0 as an error code, as it is the only char value that cannot appear inside a string.  Your functions will already return 0 when presented with an empty string as input, though I'm uncertain whether that's by design.  Alternatively, the functions could return type int, with the result being -1 when there is no unrepeated character, else the first non-repeated one cast to unsigned char.  This is the scheme the getchar() function uses.

Loop termination conditions

Both codes contain loops with i < strlen(string) for their termination condition.  The compiler can lift the evaluation of strlen() out of the loop only if it makes several assumptions about that function.  Inasmuch as that's a standard library function, it is conceivable that that would happen, but by no means certain.  If it doesn't happen then your implementations become θ(n2) instead of θ(n); I therefore recommend lifting the strlen() call out of the loop manually.

Alternatively, consider avoiding strlen() altogether -- since you need to iterate through the whole string anyway, just break the iteration when you reach the terminator.  That should be more efficient.

Using type int for character counters

Each code uses objects of type int as character counters, but

that's a signed type, even though character counts should never be negative, and
its maximum value can be as low as 32767, which is a relatively low limit

I would suggest size_t instead, which should be sufficient for any representable string, but if you prefer something that may be a bit smaller (at the cost of restricting its range) then you could go with uint_least32_t (from stdint.h) for the smallest an unsigned integer type with at least 32 value bits, or uint_fast32_t for the fastest unsigned integer type with at least 32 value bits (these might or might not be the same type).

First implementation

Use of a file-scope variable

This version of the function relies on file-scope variable characters.  Being declared a file scope gets it free initialization, but relying on that makes your function a one-shot.  Even if you reset the contents of this array on each function call, relying on it makes your function non-thread-safe.

I recommend switching to a local (array) variable inside the function.  If (and only if) you continue to use a file-scope variable then at least declare it static to give it internal linkage.

Questionable data structure

The struct ch type on which this version of the function relies seems a bit of a miss to me, for, as it is used, the value of member c is completely determined by the index of a given instance within array characters.  This member is therefore redundant.

See also my previous comments about using type int for your character counters.

Second implementation

Make use of initialization

You declare array cha without an initializer, and then manually loop to set its initial contents.  Given the data type and the initial values you want to set, it would be clearer and potentially more efficient to instead declare it with an initializer:

int cha[NUM_CHARACTERS] = { 0 };

... and skip the initialization loop.  (Elements not explicitly designated in the initializer get initialized to 0.)

Comparative efficiency

It's hard to be sure what to compare here.  The two codes comprise slightly-different versions of the same underlying algorithm.  Implementing fixes for the various shortcomings I discussed would bring them to pretty much the same place, which would look more like the second code than the first.

There are a number of possible variations on this approach, some of which may run slightly faster than others, but I don't see room for anything substantially more efficient.


Looping through nested arrays with creating new array from nested items

You could indeed create a recursive function to collect each level of departments, keeping going as long as there are nested departments:

function indentDepartments(departments, model) {

    model.parentDepartments(doIndentDepartments(departments, 0));

    // called recursively to indent each level of department
    function doIndentDepartments(departments, level) {
        // indent departments at current level
        var departments = _.map(departments, function(department) {
            return buildDepartment(department, level);
        });

        // indent nested departments
        if (typeof departments.NestedDepartments != 'undefined') {
            departments.push.apply(departments, doIndentDepartments(departments.NestedDepartments, level +1));
        }

        return departments;
    }

    function buildDepartment(data, level) {
        department = _.pick(data, 'DepartmentUnitId', 'ParentDepartmentUnitId');
        name = _.times(level, function () { return '-'; }).join('') + data.Name;

        _.extend(department, { Name: name });
        return department;
    }
}


I am happy your problem is solved. All in all, your code looks solid, my review is mostly nitpicking:

I am all for spartan coding, but you have far too many 1 and 2 character variables, you ought to use more meaningful variables.
Try to have 1 var block at the top. More specifically, you declare data0 after declaring the function stream_layers, there is no need for that.
Please use lowerCamelCase coding, so update_layers -> updateLayers
There is no need to call .mouseover(); after setting the listener, especially since you also call .mouseout(); afterwards for which there is also no need as you already set x and y to 1 with var currentMouseCoord = { x: 1, y: 1 };
You can drop curly braces after loops, please don't drop newlines.
vis.selectAll("path").data(data0).attr.... in transition() really should be broken out into multiple lines.


Here's a much faster algorithm:

Create a Person object containing fields like fname, lname, etc and a list of associated Transaction objects.

Then, create a dictionary with "fname,lname" as the key and a list of Person objects as the value. Iterate through your CSV line-by-line, and if that "fname,lname" key isn't in the dictionary, add it along with a Person object that defines the person's details.

However, if the key is in the dictionary then check the other details to make sure it's an actual match. If it is an actual match, add the transaction to that Person's Transaction array. If not, add a new person item to the end of the array.


I'll probably revisit this later, but for now:

The exception catching should be done at either the model or model-using layer.  I would probably let the exceptions bubble up through the model unless you want the model to be fairly high level.

For the sake of abstracting the DB layer away from the model layer, I might consider wrapping the PDOException in some kind of model exception(s).  Exception wrapping is typically an anti-pattern, but it would keep your consuming code from needing to know that the models are all dependent on PDO.  (Thus allowing you to change PDO to something else if you ever wanted to -- basically it's a weird instance of separation of concerns and hiding implementation details.)

I'm starting to ramble, but what I'm trying to convey is that your consuming code needs to know something went wrong.  If you handle the exception in your DB class, you model has no (pleasant) way to know that something went wrong.  If you handle the exception in your model, the level above the model has no (pleasant) way to know something went wrong.  Basically your consuming code needs to know something happened, and for that to be the case, you need exceptions to come out of the model.  (An alternative would of course be returning a Boolean or something along those lines.  That tends to not fit the OO paradigm very well though, and PDO sometimes uses Boolean false when something isn't an error.)

Your pdoDatabase class shouldn't be a singleton.

$this->db = pdoDatabase::getInstance(); you pass the pdoDatabase instance as a parameter instead of coupling your code to this static method.

Dependency Injection

There's a few other things that stuck out to me, but I'm out of time now ;(.  Will come back later.

Exception Catching

It should be extremely rare for an exception to actually happen with your Mobile.

Consider the sources of exceptions: connection drops, invalid syntax, unknown column/table/etc, so on.  Basically there's different layers of exceptions. There's the connection oriented ones, and the SQL oriented ones.  The SQL oriented ones should never happen.  By the time your code goes into production, you should be certain that none of your queries have invalid syntax, reference non-existing entities, so on.

This leaves connection problems as the only source of exceptions (or perhaps MySQL related hiccups, though those should be pretty rare).

Because of this rarity, I would be tempted to basically ignore any exceptions.

Even if you did handle the exceptions, what are you going to do with them?

try {
    $affs = $mobile->findPhoneAffiliate(5);
} catch (SomeExceptionClass $ex) {
    //There's not really a good way to recover from this, so you might as well
    //show some kind of "Oops, something broke." page.
    //You could then log the exception behind the scenes and make sure the end-user
    //sees nothing sensitive.
}

What I would do in this situation is just let the exception bubble up to the very top. I would have a giant try/catch at the top layer though that intercepts any uncaught exceptions and renders some kind of error page.

How you do this will highly depend on the structure of your website, but assuming you're doing something MVC-ish, it should be fairly simple.  In the catch block, just kill the current dispatch, and instead dispatch a request for the exception page.


Find all possible words in a board of characters

If I were you, I  would stop having the tests mixed up with the implementation. It is somehow "smart", and for small projects like this, you can say it doesn't matter. But IMO it does matter because it prevents you from thinking properly about the design of you code.

Your implementation is a nearly one-to-one implementation of the C++ from Geeks and it appears rather C++-ish.

When it comes to naming, you should call your members after what they do or represent, - not after how they do it or is: DFS() as well as _list tell me nothing.

        for (int row = i - 1; row <= i + 1 && row < boggle.GetLength(0); row++)
        {
            for (int col = j - 1; col <= j + 1 && col < boggle.GetLength(1); col++)
            {
                if (col >= 0 && row >= 0 && !visited[row, col])
                {
                    DFS(row, col, boggle, dictionary, str, visited);
                }
            }
        }

IMO this way to determine the boundaries of the loops is hard to follow. The stop conditions are calculated in the for-statements while the start conditions are determined half in the for-statements and half in the if-statement.

A more clean and C#-ish way could be something like:

  int minRow = Math.Max(0, row - 1);
  int maxRow = Math.Min(rows, row + 2);
  int minCol = Math.Max(0, col - 1);
  int maxCol = Math.Min(cols, col + 2);

  for (int r = minRow; r < maxRow; r++)
  {
    for (int c = minCol; c < maxCol; c++)
    {
      if (!visited[r, c])
        Search(r, c);
    }
  }

The conditions are calculated once before the loops and hence separated nicely from the loops,  and the loops are immediately easy to read and understand. For rows and cols see below.

    private bool IsWord(string str, string[] dictionary)
    {
        for (int i = 0; i < dictionary.Length; i++)
        {
            if (string.CompareOrdinal(str, dictionary[i]) == 0)
            {
                return true;
            }
        }
        return false;
    }

In C# this is a one-liner:

    private bool IsWord(string str, string[] dictionary)
    {
        return dictionary.Contains(str);
    }

        str.Remove(str.Length - 1, 1);

On the StringBuilder it is possible to set the length, which might be faster than removing a sequence of the one last character:

str.Length -= 1;

About the overall design:

On the one hand you let _list be a class member, while all other variables are arguments to the methods. I think I would make a statefull object having as many of the variables as possible as members:

  class WordFinder
  {
    private readonly char[,] boggle;
    private readonly bool[,] visited;
    private readonly int rows;
    private readonly int cols;
    private readonly List<string> words = new List<string>();
    private readonly StringBuilder word = new StringBuilder();
    private string[] dictionary;

    public WordFinder(char[,] boggle)
    {
      this.boggle = boggle;
      rows = boggle.GetLength(0);
      cols = boggle.GetLength(1);
      visited = new bool[rows, cols];
    }
    ...

Other than a reduced set of arguments for the methods one benefit is that the calculation of the boggle dimensions is done once here.

The FindWords method could then look like:

public IList<string> FindWords(string[] dictionary)
{
  this.dictionary = dictionary;
  words.Clear();
  word.Clear();

  for (int row = 0; row < rows; row++)
  {
    for (int col = 0; col < cols; col++)
    {
      Search(row, col);
    }
  }

  return words;
}

where the Search() method is:

private void Search(int row, int col)
{
  visited[row, col] = true;

  word.Append(boggle[row, col]);
  AddIfWord(word.ToString());

  int minRow = Math.Max(0, row - 1);
  int maxRow = Math.Min(rows, row + 2);
  int minCol = Math.Max(0, col - 1);
  int maxCol = Math.Min(cols, col + 2);

  for (int r = minRow; r < maxRow; r++)
  {
    for (int c = minCol; c < maxCol; c++)
    {
      if (!visited[r, c])
        Search(r, c);
    }
  }

  word.Length -= 1;
  visited[row, col] = false;
}

and AddIfWord() is

private void AddIfWord(string candidate)
{
  if (dictionary.Contains(candidate))
    words.Add(candidate);
}

Maybe word should be an argument rather than a member, because it is somehow a "local" variable, but on the other hand there is only one word at the time while the process is running, so it's fairly safe to let it be a member.

For convenience you could provide a static member as:

public static IList<string> FindWords(char[,] boggle, string[] dictionary)
{
  WordFinder finder = new WordFinder(boggle);
  return finder.FindWords(dictionary);
}

We could argue about if boggle and dictionary should be arguments to the constructor or FindWords() - that may be a matter of - if the process is about finding words from dictionary in boggle or visa versa and/or a matter of habit and taste.

When it comes to performance, there is not much to say, because the algorithm is "optimized" by its definition - I can't see any other ways to implement this implementation so to speak.


CSS and HTML5 for this fixed header on scroll

HTML

You might want to id that nav. It's because it might not be the only nav on the page, and the JS will pick it up and add .fixed-header to it. Something like:

<nav id="main-navigation">

CSS

On the CSS part, if only the nav gets a the .fixed-header class, you might want to consider declaring the CSS for .fixed-header like:

nav.fixed-header{...}

That way, it only applies to nav with that class. Scenario: You have another header that wants to be fixed at a certain position. It's logical to name it .fixed-header but it's not a nav. If you didn't do it this way, this style will also apply to the sidebar.

JS

It would be better if you cached the value of jQuery DOM pickups, rather than re-fetching them every time the scroll event fires. Additionally, as mentioned in the HTML section, it's better to identify that <nav>. This time, it's for performance.

When you do $('nav'), what jQuery does is pick up all <nav> in the page, and stores them in an array. When you call functions on it, jQuery loops through each one of them, and applies the function. You would want to avoid that looping, and so, you must limit what is being looped by being more specific with your query. Querying an id would be best since id should only happen once on the page.

var $window = $(window);
var nav = $('#main-navigation');
$window.scroll(function(){
    if ($window.scrollTop() >= 300) {
       nav.addClass('fixed-header');
    }
    else {
       nav.removeClass('fixed-header');
    }
});


Rust - Need help making code idiomatic and clean (with lifetimes)

Hello and welcome to the Rust community.
After a single read of your code, I have a couple comments.

your problems with &str as well as keying by block_id would be best remedied by putting interners in SSA. The best interner choice would be string-interner or internment.
in fn new_variable, you have repeated lookups for the same entry of current_def. LLVM will be unable to optimize out repeated accesses to HashMap. This may slow us down by something like 120~200ns per invocation of the function, because one HashMap lookup takes approx. 40~70ns.
you have Vec<Box<...>> and HashMap<Box<...>,Box<...>>. This inclusion of Box within another container immediately raises a flag in the mind of a Rust programmer that the code is not cleaned up. Wrapping in Box does not provide anything over wrapping in Vec, HashMap or any other container. All wraps provide unique ownership with memory indirection. To illustrate with an example, Box<[T]> is almost like Vec in that both are owned dynamic-length slices (indexable memory ranges) except that Box<[T]> does not allow any overprovisioning of memory (Vec can have capacity above length).
the SSA::current_def type expression is basically as long as your average tweet. Break down complex types longer than 30-40 characters into smaller definitions.

We will begin by changing SSA and fn new_variable, with new structure SSADef:
#[derive(Debug)]
struct SSA<'a> {
    content: HashMap<&'a str, SSADef<'a>>,
}

#[derive(Debug)]
struct SSADef<'a> {
    count: u32,
    current_def: HashMap<&'a BasicBlock<'a>, IRCode<'a>>,
}

impl<'a> SSA<'a> {
    fn new() -> SSA<'a> {
        SSA { content: HashMap::new() }
    }

    fn new_variable<'s>(&'s mut self, name: &'a str, block: &'a BasicBlock<'a>) -> &'s IRCode<'a> {
        // If `name` is not in `content`, insert `SSADef::new()`
        let def = self.content.entry(name).or_insert_with(SSADef::new);
        // Increment the count
        def.count += 1;
        def.current_def.entry(block).or_insert(
            IRCode::Basic {
                value: name,
                btype: Type::TVarRef,
                id: def.count,
            }
        )
    }
}

impl<'a> SSADef<'a> {
    fn new() -> SSADef<'a> {
        SSADef {
            count: 0,
            current_def: HashMap::new(),
        }
    }
}

One minor observation: you can derive Default for SSA and SSADef and call default from both news. This will put 0s and empty HashMaps and other default values in the fields of these structures.
We add the StringInterner. I assume the deeper functionality will always have easy access to top level SSA, and consequently easy access to the interner. If not, we can use some other crate such as internment which provides an appropriate API.
Changing the BasicBlocks for interning is left as an exercise for the reader. We arrive at the following code, which has very few 'as left. This is all I can do without knowledge of the algorithm, I believe:
use std::collections::HashMap;
use std::hash::{Hash, Hasher};

use string_interner::{StringInterner, DefaultSymbol as Sym};

#[derive(Debug, PartialEq, Eq)]
struct BasicBlock {
    block_id: u32,
    code: Vec<IRCode>,
    preds: Vec<BasicBlock>,
    succs: Vec<BasicBlock>,
}

#[derive(Debug, PartialEq, Eq)]
enum IRCode {
    Basic {
        value: Sym,
        btype: Type,
        id: u32,
    },
    Quadruple {
        op: Op,
        params: Vec<IRCode>,
        location: Storage,
    },
    // and some more...
}

#[derive(Debug, PartialEq, Eq)]
enum Type {
    TVarRef,
    // and some more...
}

#[derive(Debug, PartialEq, Eq)]
enum Storage {
    Temp { name: Sym },
}

#[derive(Debug, PartialEq, Eq)]
enum Op {
    Add,
    Sub,
}

impl Hash for BasicBlock {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.block_id.hash(state);
    }
}

#[derive(Debug, Default)]
struct SSA<'a> {
    content: HashMap<Sym, SSADef<'a>>,
    interner: StringInterner,
}

#[derive(Debug, Default)]
struct SSADef<'a> {
    count: u32,
    current_def: HashMap<&'a BasicBlock, IRCode>,
}

impl<'a> SSA<'a> {
    fn new() -> SSA<'a> {
        SSA::default()
    }

    fn new_variable<'s>(&'s mut self, name: &'a str, block: &'a BasicBlock) -> &'s IRCode {
        let name_sym = self.interner.get_or_intern(name);
        // If `name` is not in `content`, insert `SSADef::new()`
        let def = self.content.entry(name_sym).or_insert_with(SSADef::new);
        // Increment the count
        def.count += 1;
        def.current_def.entry(block).or_insert(
            IRCode::Basic {
                value: name_sym,
                btype: Type::TVarRef,
                id: def.count,
            }
        )
    }
}

impl<'a> SSADef<'a> {
    fn new() -> SSADef<'a> {
        SSADef::default()
    }
}

fn main() {
    // very simple test case
    let mut ssa = SSA::new();
    let bb0 = BasicBlock {
        block_id: 0,
        code: vec![],
        preds: vec![],
        succs: vec![],
    };
    println!("{:?}", ssa.new_variable("foo", &bb0));
    println!("{:?}", ssa);
}
```


Password Generator, generate password of desired length

Note: The 65 comes from the CHARACTER_SET length, which I have found out before.

It's 65 at the moment. But what if you want to support more or less characters? A different character set? You'd have to change those hard-coded values every time.

CHARACTER_SET.charAt(random.nextInt(65)

Can be replaced by:

CHARACTER_SET.charAt(random.nextInt(CHARACTER_SET.length())

There is one more hard-coded value in your code.

System.out.println(generatePassword(20));

Extract the 20 to it's own variable. This allows you to extend your program to, for example, ask for user input and use that value instead. Perhaps the user prefers 16 or 28.


Loop for inserting a node into a binary search tree

(Just checking - you want your BST to be allowed to contain duplicates? That's what your current code does.)

Edit: After fixing some mistakes kindly pointed out by @vnp, here is an implementation of insert:

    public void insert(int n) {
        final boolean RIGHT = true;
        final boolean LEFT = false;

        node previousNode = null;
        boolean previousDirection = LEFT; // arbitrary
        node currentNode = head;

        while (currentNode != null) {
            previousNode = currentNode;
            if (n > currentNode.data) {
                currentNode = currentNode.right;
                previousDirection = RIGHT;
            } else {
                currentNode = currentNode.left;
                previousDirection = LEFT;
            }
        }

        if (previousNode == null) {
            head = new node(n);
        } else if (previousDirection == LEFT) {
            previousNode.left = new node(n);
        } else {
            previousNode.right = new node(n);
        }
    }

This avoids using while(true) and break; and uses more shallow if statements, which I think makes it marginally easier to follow.


The solution depends on your exact requirements and the context.
In your case, you could simplify the if-condition like below. If all fit into one if, you can write your code block there only once. If you need it and can't unify your condition, make it a function.

Here, I'm using a combined approach. I put the code from your if into a function, jQuery objects are cached and don't have to be recreated (but are still protected from outside modification because they only exist inside the scope of that function). And I combined all the conditions I could see in your example.

var indicateBadPassword = (function() {
        var $passwordStrength = $('.passwordStrength'),
            $password = $('#password'),
            $passwordStrengthInfo = $('.passwordStrenghtInfo');
        return function() {
            $passwordStrength.
                animate({width:'75px',height:'5px'},200).
                show().
                css('background-color',red);
            $password.css('border-color',green);
            $passwordStrengthInfo.text(weak).show();
            passwordErrors = true;

        }
    })();
if (lessThan12Password && (passwordLC || passwordUC || passwordN)) {
    indicateBadPassword();
}


For a simple domain like that, wouldn't it be simpler to define the data like this?

type Expression =
| IntExpr of int
| AddExpr of Expression * Expression
| SubtractExpr of Expression * Expression
| NegationExpr of Expression

This would mean that you can implement the eval function like this:

let rec eval = function
| IntExpr i -> i
| AddExpr (x, y) -> eval x + eval y
| SubtractExpr (x, y) -> eval x - eval y
| NegationExpr x -> -(eval x)

Here are some FSI examples:

> let x1 = IntExpr 42 |> eval;;
val x1 : int = 42

> let x2 = AddExpr (IntExpr 1, IntExpr 32) |> eval;;
val x2 : int = 33

> let x3 = NegationExpr (SubtractExpr (NegationExpr (IntExpr 3), (AddExpr (IntExpr 4, IntExpr 7)))) |> eval;;
val x3 : int = 14


You should probably store the numeric values also as numbers and not as strings. This makes data retrieval and manipulation easier. Also have a look here for the coordinates. Date and time should be one field and conform to the ISO date format so you can easily parse it with JS and all other programming languages.