Using Parsec for simple arithmetic language

Where you used case you could have used pattern matching. This yields more idiomatic code in many cases.

isNumerical :: Term -> Bool
isNumerical TmZero = True
isNumerical (TmSucc subterm) = isNumerical subterm
isNumerical (TmPred subterm) = isNumerical subterm
isNumerical _ = False

eval :: Term -> Term
eval TmTrue  = TmTrue
eval TmFalse = TmFalse
eval TmZero  = TmZero
eval (TmIf term1 term2 term3) = evalIf (eval term1) term2 term3
eval (TmIsZero subterm) = evalIsZero $ eval subterm
eval (TmPred subterm) = evalPred $ eval subterm
eval (TmSucc subterm) = evalSucc $ eval subterm
eval TmError = TmError

evalIf :: Term -> Term -> Term -> Term
evalIf TmTrue a  _ = eval a
evalIf TmFalse _ b = eval b
evalIf _ _ _  = TmError

evalIsZero :: Term -> Term
evalIsZero TmZero = TmTrue
evalIsZero term
    | isNumerical term = TmFalse
    | otherwise        = TmError

evalPred :: Term -> Term
evalPred TmZero = TmZero
evalPred t@(TmSucc subterm) = t
evalPred _ = TmError

evalSucc :: Term -> Term
evalSucc term
    | isNumerical term = TmSucc term
    | otherwise        = TmError

Note the complex terms are farmed off to their own functions. This makes testing easier. Especially as the runtime gets more complex.

You asked about main's type. If you use forM_ you can define it as main :: IO ().

As for Applicative:

functionParser :: String -> (Term -> Term) -> GenParser Char st Term
functionParser name funcTerm = funcTerm <$> (string (name ++ "(")
                                             *> arithParser
                                             <* char ')')
ifParser :: GenParser Char st Term
ifParser = TmIf <$> (string "if" *> spaces *> arithParser)
                <*> (spaces *> string "then" *> spaces *> arithParser)
                <*> (spaces *> string "else" *> spaces *> arithParser)

Also, the last 'try' should not be used. 'try' means to attempt a parse and do not consume the input if it failed. The last parse action is the end of the parse so there is no need to leave the input in the parser.


Aggregate cost for a directed graph in Prolog

Using global variables is a sure sign that you are not working within the declarative paradigm. A declarative way to solve this is to keep track of the already visited variables via an argument of your predicate.

Also, please_use_a_readable_naming_convention insteadOfMakingEverythingHardToReadAsInJava.

For example, suppose you have a relation visited_and_move(Vs0, Vs, Vertex0, Vertex), where:

Vs0 is the list of vertices that are already visited
Vs is the next list of such vertices
Vertex0 is the previous vertex
Vertex is the next vertex.

This is only an example; you may not need all arguments. However, the general approach should be clear: Think in terms of relations between entities, such as the relation between a previous list and the next one.

Such pure predicates can be used in all directions, and tested in isolation without needing to store an implicit global state.


There's a couple of nice alternatives for you.

Extensions

If you don't need to encapsulate the XmlNodeList instances, you could make your methods extensions for XmlDocument or whatever you've extended:

public static class TemplateExtensions
{
    public static XmlNodeList GetTemplates(this XmlDocument document)
    {
        return document.GetElementsByTagName("Templates");
    }

    public static UITemplateAssoc GetTemplate(this XmlNodeList list, string name)
    {
        foreach(var nd in list)
        {
            if (nd.Name == name) return nd;
        }
    }

    // ...
}

// ...
var templates = yourDocument.GetTemplates();
var template = templates.GetTemplate("abc");

More on extensions methods here:
http://msdn.microsoft.com/en-us/library/bb383977.aspx

Inheritance

Put these methods in a base class and have the behavior that differs in inherited classes.

[edit]Updated to show how the base class can be generic[/edit]

public abstract class TemplateListBase<T>
    where T : XmlNode
{
    private XmlNodeList templates;

    public XmlNodeList Templates
    {
        get
        {
            return templates.GetElementsByTagName( "Templates" );
        }
    }

    protected TemplateListBase(XmlNodeList initialList)
    {
        templates = initialList;
    }

    public void AddRange(XmlNodeList list)
    {
        foreach( T nd in list )
        {
            AddTemplate( nd );
        }
    }

    public T GetTemplate (string name)
    {
        foreach( T nd in templates )
        {
            if( nd.Name == name ) return nd;
        }
        return null;
    }

    public void AddTemplate ( T val )
    {
        for( int i = templates.Count - 1 ; i >= 0 ; i-- )
        {
            if( templates[i].Name == val.Name )
            {
                templates.ReplaceChild( val , templates[i] );
                return;
            }
        }
        templates.AppendChild( val );
    }
}

public class UITemplateAssocList : TemplateListBase<UITemplateAssoc>
{
    public UITemplateAssocList(XmlNodeList listOfUITemplates)
        : base(listOfUITemplates)
    {
    }

    public void FancyLogicA(string data)
    {
        foreach(var node in Templates)
        {
            // differing logic
        }
    }
}

public class ConcreteTemplateB : TemplateListBase<SomeOtherKindOfNode>
{
    // ..

    public void FancyLogicB(XmlNodeList list)
    {
        for (var node in list)
        {
            if (LikeThisNode(node)) AddTemplate(node);
        }
    }
}

Notice that I replaced your setter with an AddRange method.
It's ususally good practice not to replace an entire encapsulated collection using a setter.
Although you can validate the entries in the setter, a property should not do much logic other than returning or setting privates.
If you have a look at the collections in the BCL, they all expose an AddRange method and a method Clear to empty the collection. The AddRange method also gives you the option of adding multiple sets in turn.

If you need different logic when stuff is added etc, have a look at the template method pattern:
http://en.wikipedia.org/wiki/Template_method_pattern

If you need multiple base classes with differing logic, you could combine the inheritance with the extension methods, or another base class. :)


Upload an image to a folder through a form

You should invert the order of your PHP processing and your HTML output.  When working in PHP, always strive to adhere to this approach, as it will help you as you start working on more complex logic.  You will inevitably find yourself needing to set HTTP response readers, cookie values, etc. in your responses.  You need to do this work BEFORE sending any output to the browser - either that or use a hacky output buffering approach.

If you need to set conditional output (i.e. success/error messages, dynamic content, variable output, etc.), consider setting these values into variables and having only basic PHP insertions in the HTML portion of the code.  You should avoid any complex PHP calculations or logic once output to browser has started.

Other thoughts:

You need work on your coding style. Primarily in your case that is in the area of using indentations in your code (both HTML and PHP) to better convey nesting of code blocks.
Don't output system-generated error messages directly to the user.  You may want to log these, but you should always consider end user error messages separately from system errors.  Oftentimes, that may require mapping of PHP-generated errors to user-friendly error messaging. Here is good example: echo "Error: " . $_FILES["photo"]["error"] . "<br>";
Things like file size that are too large may best end up with server responding with 400 or 413 HTTP response code in response header rather than just simple error message. You should actually not handle this at all in your PHP code, but rather in your PHP configuration, so that file upload limits are applied at PHP level, not in your code logic.  If for some reason you need to change the file size limit for a particular script, you could make runtime change to configuration.  There is no reason to defer this file size check into your code. The PHP file upload common pitfalls page has some good additional info in this area - http://php.net/manual/en/features.file-upload.common-pitfalls.php
From a security standpoint, you are doing nothing to prevent against cross-site request forgery (CSRF) attacks.  Typically, this is handled with comparison of hidden form input field with value in session. This really should be a standard part of any form your create in any web application.
You are doing nothing to validate $_FILES and some of the values it holds before operating against the information.  The file name, in particular is something you might want to validate, to make sure the user isn't passing a filenames like ../../index.php which could end up writing files in arbitrary locations in your web directory.


Bash Code to backup the history file in Linux

First, logrotate is a tool built to do exactly this sort of thing. I would recommend using that to achieve the effectively the same extremely reliably and with lots of configuration options. That said, some suggestions on the code as written:

ShellCheck is great; I would recommend following its recommendation to use (( i++ )).
wc -l counts the number of lines, not bytes or kilobytes, which seems to be what you want.
old, minus and i are not helpful names; I have to read and understand all the code in the context in order to understand what they mean.
It looks like you only ever replace the last of the 20 files once you have 20 backups.
You have five instances of ~/.bash_history, even though one of them is the value of a variable. I would pull that variable out and reuse it everywhere.
Use More Quotes™ - it's good for you and the code.
Rather than a special unnumbered backup file (~/.bash_history.old), why not just start numbering the backups immediately? That way you can get rid of at least two checks for whether that file exists ([[ ! -e ~/.bash_history.old ]] and its inverse, [[ -e $name$old ]]).


Good way to write extend method of a contructor?

I think you cannot move parent constructor call out of child constructor. At least because you have different parameters, extend function cannot guess what kind of parameters it should pass.

But even if you standardize all constructors, you will have to make a "smart" constructor in Base class, that know about possible "sub-constructors". I don't think its a good idea ))

But what i would do - remove any mention of parent-class from children constructors'.

var Base = function(name){
    this.name = name;
}
Base.prototype.extend = function(new_constructor){
    //new_constructor.prototype = new this.constructor();
    new_constructor.prototype = Object.create(this.constructor.prototype);
    new_constructor.prototype.constructor = new_constructor;
    new_constructor.prototype.parentConstructor = this.constructor;

    return new_constructor;
}

var Robot = Base.prototype.extend(function(name, material){
    Robot.prototype.parentConstructor.call(this, name)
    this.material = material
    this.type = 'robot';
});

var T1000 = Robot.prototype.extend(function(options){
    T1000.prototype.parentConstructor.call(this, options.name, options.material)
    this.guns = options.guns;
    this.type = 'killer robot';
});

robot = new Robot("Boutros", "metal");
t1000 = new T1000({name: "Arnie", material:"flesh/metal", guns:3});

console.log(robot)
console.log(t1000)


Custom exit with only some exceptions in Python

You can use a tuple of exception types with except, so your except clause could be simplified to:

except tuple(exit_codes) as exit_err:
    exit_code = int(exit_codes[type(exit_err)])
    sys.exit(exit_code)


Some observations. The space between #! and the path to binary is not needed. (It used to be for some arcane versions of Unix but not anymore AFAIK)

Secondly, I prefer to let env find ruby for portability.

#!/usr/bin/env ruby

require 'optparse'
require 'pp'
require 'fileutils'

The options are globals. So perhaps it is better to specify that explicitly.
This will help in modularization later.

$options = {:sub => "", :downcase => nil}

In the interests of people who have to use 80 char width terminals, I advice
an 80 cols limit (or near abouts) for lines :) .
I would also advice on verbose and dryrun flags to tell the user what is going to happen, and what is happening.

The stdlib example is to just call .parse! directly and I think that that style
is more rubyish than creating a new variable optparse.

OptionParser.new do |opts|
  opts.on('-r', '--regex REGEX', String,
     'Specify the regular expression to replace'){|$options[:regex]|}
  opts.on('-s', '--sub SUBSTITUTE', String,
     'Specify what to replace the match with. By default, the \
      empty string (so the matched patterns are \
      stripped).'){|$options[:sub]|}
  opts.on('-d', '--downcase', 'If passed, all filenames will be \
      downcased.'){|$options[:downcase]|}
end.parse!

I like programs to give me the usage if they are invoked with no input values.

usage unless ARGV.length > 0

I also think that the transformation of old name to new name should be a
separate method. And why embed a string inside a string and then transform
to a regular expression when you can directly transform that string to a regexp?

def transform(str)
  ($options[:downcase] ?
      str.downcase : str).gsub(Regexp.new $options[:regex], $options[:sub])
end

And given all these, I prefer a little more functional way of processing
The advantage is that you are restricting the IO to a very small portion.

ARGV.map{|target| [target, transform(target)]}.each do |old,new|
  File.rename(old, new)
end

Now, these comments are highly subjective. But given the length of
your snippet, I suppose that is justified? Because it obviously works as given.


Retrieve Father and Child structure in a Database Table

Firstly, you use both the

SELECT [XYZ]
INTO [ABC]

and the

INSERT INTO [ABC]
SELECT [XYZ]

syntax in the same query, using one would make the query much more consistent and easier to read. Personally, I prefer using INSERT INTO [ABC] SELECT [XYZ], you do have to explicitly create the temporary table though, but that makes it usually clearer what is happening.

If you'd prefer, you can change

DECLARE @ID CHAR(11)
SET @ID = 13192

to

DECLARE @ID CHAR(11) = 13192

And you should really explicitly drop the #MyTempTable at the end of the query.

Lastly, the biggest change I would suggest is to completely remove the selects from outside of the while, they are completely redundant. If you remove those selects from outside the while loop, then the first iteration of the while does exactly the same as the selects on the outside would have done.

Here is what we end up with:

IF OBJECT_ID('tempdb..#MyTempTable') IS NOT NULL DROP TABLE #MyTempTable

DECLARE @ID CHAR(11) = 13192

CREATE TABLE #MyTempTable(ID INT, FatherID INT)

WHILE @ID <> 0
BEGIN
    INSERT INTO #MyTempTable
    SELECT *
    FROM [MyTable]
    WHERE [ID] = @ID

    SELECT @ID = [FatherID]
    FROM #MyTempTable
    WHERE [ID] = @ID
END

SELECT *

FROM #MyTempTable
ORDER BY [ID]

DROP TABLE #MyTempTable

Here is an SQL Fiddle.


Testing an implementation of ports-and-adaptors for tkinter

I prefer Option A over Option B. While you do then end up resting both the port and the adapter in one go, the port and adapter together constitute the unit you are trying to test: the piece of code that allows you to manipulate the widget in question.

Option B, in my opinion, is perhaps a tad too granular.


I've never seen GetList() method on SqlConnection so I'm assuming this is your own class?

If that were the case would it not be best to have IDataContext abstract the Connection details away and return an IConnection contract.

public interface IDatabaseContext : IDisposable
{
    IConnection Connection { get; }
}

Doing this you can ensure your calling classes are completely decoupled from the implementation details of a connection.  Otherwise any implementation of IDataContext would have been coupled to a SQLConnection and you lose the benefit of the initial abstraction.


The timeout is caused by a bug is in the ms method.  ms(0,mid)  should be ms(l, mid).

A few comments on the code itself:

Don't use lower case L as a variable name.  It looks too similar to the digit 1.
Don't use static variables to communicate between your methods.  It makes the code harder to test and you risk bugs due to crosstalk between different invocations of the method.  In this case, for example, ms and merge should just return the number of shifts instead of incrementing static counter noi
Better separation of input parsing from actual computation.  You should have a method long countingMergeSort(int[] ary).  That would make it easier for you to test your code.


There are lot of ways to organize an architecture. I will explain how do I understand some of them. Read about MVC and MVVC patterns.

First of all, it would be better do divide all code related to requests and code responsible for UI.
Creating a model class is a good way. Model can only keep and parse data. It shouldn't contain any business logic.
You can create one more type class. Such as presenter or viewModel. This class would manage all contains in this module. Contains the cars array in your case. And here you can ask the ServerInteractor class to run the requests.
All code related to requests would be better to keep in ServerInteractor (or LocalInteractor).
It is a good practice to write methods smaller if it is possible. For example in your cellForRowAt method you can divide all code such as "cell.date.text = entry.date" to the separate method

I wish  it would be useful )


Pandas - 3 iterations per second on simple conditional

I don't really know the libraries that you're using, but maybe the overhead of dropping rows from the CSV one by one is significant?  You could try batching the drop (it looks like that drop function takes a list of indices but you're only passing it one at a time) and see if that speeds things up:

from pandas import DataFrame
from typing import List

def remove_rows_that_dont_have_important_1_in_important_2(df: DataFrame) -> DataFrame:
    """
    Removes all rows of the dataframe that do not have important_1 inside of important_2.
    Note: All rows have the same value for important_1.
    Note: Every row can have a different value for important_2.
    Note: There are unrelated columns in the df that cannot be dropped from the df. But rows still can.
    """
    important_1 = df.at[0, 'important_1']  # get the icao fro the df from the first ob
    important_2_col = df.columns.get_loc('important_2')  # column order won't always be the same, so find the right column first

    indices_to_drop: List[int] = []

    for i in range(len(df), 0, -1):
        print(i)  # DEBUG printing

        important_2  = df.iat[i, important_2_col]
        if important_2 == np.NaN or important_1 not in important_2:
            indices_to_drop.append(i)

    df.drop(indices_to_drop, inplace=True)
    return df


As you and I both know, what follows is the answer I posted to your question at Unix and Linux. I'm not sure if this might be considered in bad taste or not - and if so, I'll happily delete it - but at the other site the question was apparently closed as a cross-post in favor of this. And so I thought - maybe it belonged? Anyway, here goes:

What you're really doing wrong is duplicating your effort - basically every hardcoded occurrence of _agent or _server appears to be completely redundant.

For example, if this is being run on a linux system, you can completely drop the grep_...() functions, and consolidate both check_...s into a single entity which might work like:

email(){
    mutt -s "Zabbix Auto-restart Script Just Ran" \<user email\>
}
prlog(){
    date +"%x %X:%tservice $1${2+%n************************}"
}
chk_run()
    while  [ "$#" -gt 0 ]
    do     if     ps -C zabbix_"$1"
           then   : "$(($1=1))"
           else   set zabbix_"$@"
                  service "$1" start || eval >&2 '
                  prlog   "$1 restart failed."  +; exit '"$?"
                  prlog   "$1 restarted."       +  >&2
                  prlog   "$1 restarted from $0." |email
           fi;    shift
    done

The key to that is you would just call chk_run with an argument list each member of which would indicate to it what it should be checking each iteration.

loop()
    until [ "$(($1&&$2))" -eq 1 ]
    do    chk_run "$@"
          sleep 2
    done  >/dev/null 2>>"$log"
agentd=0 server=0 loop agentd server

POSIXly the only thing that should need altering there is the ps command - because POSIX doesn't specify the -C switch. And so you could just change the if line to look like:

if    ps -eocomm= |
      grep -xqF zabbix_"$1"

Aside from mutt, service, and the ps optimization, it should all be standard command language. At least one advantage to that is the #!/bin/bash hash-bang is completely unnecessary - there is no anchor here to some shell-specific extension, and so it should work pretty much exactly the same in all shells which strive for POSIX-compliance. That means that #!/bin/dash is a very simple optimization in this case.


C# based IRC application (with WPF as UI)

One thing I noticed at a glance is that the main window code-behind is doing a lot of work that isn't really UI-focused.  For example, the code to handle loading plugins from external DLLs is not something I would expect a Window subclass to do. I would highly recommend restructuring the application to utilize pattern that helps you to break things up into more single-purpose classes.

A good example of a pattern that I use often is Model-View-Presenter, or MVP.  A more common pattern in WPF projects is Model-View-ViewModel, or MVVM.

The separation of view logic from business logic makes the application more modular, allowing you to swap out components more easily.  For example, if you decide later that a different UI technology (e.g., HTML/Javascript Metro) is more to your liking, you just need to swap out the view.


Project Euler problems 1 and 2 in python

Problem 1 is probably better and more pythonic when written as a list comprehension:

x = sum(i for i in range(1000) if i % 3 == 0 or i % 5 == 0)
print(x)

For the second problem I would recommend a generator and to use sum again:

def fibonacci(max_n):
    n, prev = 1, 1
    while n <= max_n:
        yield n
        n, prev = n + prev, n

total = sum(n for n in fibonacci(4000000) if n % 2 == 0)
print(total)

This way only two ints are ever in memory (well three if you count max_n). In comparison, your code has a list of possibly large size.


QuickSort C++ Implmentation using Iterators #2

You still have the same UB as in the original question. An unpleasant (i + 1) suggests the fix: first swap, then advance:

        itr i=left;
        itr it=left;

        while(it<right)
        {
            if(*it<*right)
            {
                using std::swap;

                swap(*i,*it);
                std::advance(i,1);
            }
            std::advance(it,1);
        }

        using std::swap;

        swap(*i,*right);
        return i;


LeetCode #1120 Maximum Average Subtree (Python)

Non-Local Variables

ans is visible (for reading) inside of helper.  It just can't be changed, although its contents can be modified.

So yes,  ans = [0] is an ugly hack.  You don't need it.  What you need in its place is nonlocal.

def maximumAverageSubtree(self, root: TreeNode) -> float:
    ans = 0

    def helper(node):
        nonlocal ans     # <--- Refer to ans in outer (but not global) scope

        if not node:
            return 0, 0

        left_sum, left_count = helper(node.left)
        right_sum, right_count = helper(node.right)

        ans = max(ans, (left_sum + right_sum + node.val) / (left_count + right_count + 1))

        return left_sum + right_sum + node.val, left_count + right_count + 1

    helper(root)

    return ans

Arbitrary-named, narrowly-scoped recursive function

In this case, you're going to need to get used to it.

Instead of creating a new function, which is visible outside the maximumAverageSubtree function, this helper is only useful to this function.  It does not need to exposed to the outside, so it makes sense to hide it inside.

This is a common paradigm in Python.  Decorators use this all the time.  For example, a @timed decorator has an internal wrapper() function.

def timed(func):

    def wrapper(*argv, **kwargs):
        start_time = time.perf_counter()
        result = func(*argv, **kwargs)
        end_time = time.perf_counter()
        print(func.__name__, "took", end_time - start_time, "seconds")
        return result

    return wrapper

The function shouldn't be arbitrarily named; its name should reflect its purpose.  Here, we are wrapping a call to another function, so wrapper() makes sense.

Above, you have a helper() function.  That probably could be named better.  Maybe process_subtree(node).  But it is "scoped" inside maximumAverageSubtree(), so its name doesn't need to repeat that level of detail.


PDO - configuration, database connection & and using

Ok there are three distinct parts I'll discuss, but the most important one is the last one (the User class).

Config constants:

defined('DB_DNS') ? null : define("DB_DNS", "mysql:host=localhost;dbname=photo_gallery");
defined('DB_USER')   ? null : define("DB_USER", "root");

Things like this are sadly quite common. The problem with this setup is that things like username, password and even the default DB name (owing to it being part of the DSN) are all hard-coded in your project. The chances of these credentials being tracked by a SVC system like git are really quite high. As are the chances that the credentials may vary depending on the environment the code runs on (local/develop/testing/production). These are configuration parameters that you really shouldn't keep hard-coded in the code base

All things aside, it's also a lot shorter to write:

defined('SOME_CONSTANT') || define('SOME_CONSTANT', 'define here');

You're using a ternary to set a given value to null. Now a DSN can't be null, nor can the DB username. You should error in those cases, instead of setting the values to null.

try-catch-die

Code like this:

try {
    $connection= new PDO(DB_DNS, DB_USER, DB_PASS);
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e) {
    echo "Error: ".$e->getMessage();
    die();
}

is again all too common. But it's smelly for a number of reasons:

Exception's indicate something Exceptional has happened, and requires special attention by a piece of code written especially for such an event, often this is an Exception-handler. A basic handler will check some parameters to see if it can/should output details about the error, or hide them from the client, and will almost always write the full stack trace to some log, so you can diagnose the problem later on. What you're doing here is squelching that information, echo an often cryptic error message and then die. That's not handling the exception, that's giving up
PDO never throws a "regular" Exception instance, it throws PDOExceptions, your catch block should reflect this. This becomes especially useful when you're working on larger projects where a single method call can throw any number of different exceptions, and your calling it from a place where you can handle some of these exceptions, but can't handle others. In that case, you'll write something like catch (ExceptionICanHandle $e) {} and let other exceptions propagate to code that can handle it
Your DSN string is missing the ;charset=utf8 bit at the end (required to protect against injection)
You're calling setAttribute after constructing the instance. You needn't do that, the PDO constructor takes a fourth argument (array of attributes).

In short, here's what I'd write:

//parse or "obtain" config in some way
$dsn .= ';charset=utf8';//in case the charset is still missing, fix the config. I'm adding it here as a reminder
$connection = new PDO($dsn, $user, $pass, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

No try-catch nonsense, no die and no setAttribute. Just 1 line that does it all.

The User class

Your class suffers from a number of issues. The short list:

global is code-smell, a sign of bad design. Don't use it unless you really have to. And you really never need to use it (I've not seen a valid use case in 10 years +)
Again: try-catch-die, I've explained what is wrong with this
echo in a method is code-smell: SRP (Single Responsability Principle) is one of the core principles to follow if you want to write good code: A class should have only one job. User is a data object, it represents a DB record that represents a user of sorts. That's its job, nothing more, nothing less. Taking care of output is the job of a template/view.
Coding standards are important. Your class does not conform to the most widely adopted standard: PHP-FIG (PSR)
This is perhaps personal, but for the same reasons (SRP), I don't like data models to have find or save methods defined. That's the job of a DB mapper, or in doctrine-speak, an entity manager. Still, it's not unheard of to have data models with DB connections, so this is just a matter of opinion

In short, and assuming you're to keep the find_by_id method, here's what I'd have the User class look like:

class User
{//next line <-- PSR
    /**
     * @var PDO
     */
    protected $connection = null;

    /**
     * @var array
     */
    protected $statments = [];

    /**
     * @param PDO $connection
     */
    public function __construct(PDO $connection)
    {
        $this->connection = $connection;
    }

    /**
     * @param int $id
     */
    public function findById($id)
    {
        if (!is_numeric($id) || $id < 1) {
            throw new InvalidArgumentException('ID must be positive integer');
        }
        $method = __METHOD__;
        if (!isset($this->statements[$method])) {
            $this->statements[$method] = $this->connection->prepare('SELECT * FROM user WHERE id = :id');
        }
        $stmt = $this->statements[$method];
        $stmt->execute([':id' => $id]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        $stmt->closeCursor();
        if (!$data) {
            return null;
        }
        $found = new User($this->connection);//pass connection
        //load data model
        $found->setId($data['id'])
            ->setName($data['name']);
        return $found;
    }
}

The other method, I'd write in the same way, but I'll leave that for you to write. I'll have a look to previous reviews I've posted here that do roughly the same thing (query the DB, setup a data model etc...), because this review was written in a hurry, the code is not tested, and I might have left some things out

related review - links to 4 other reviews


Initialize a gitlab project both locally and remotely with a single command

Welcome to CodeReview.SE and thanks for submitting your script for a code review!
Good points

Good output conveying how progress is being made.
Clear variable names

Suggestions

Are there limitations for what characters can be in a repo name?  If so, you might want to check that before sending it to the API.  It is good that you're checking to make sure they passed something in.
Aside from making sure $1 is set, there is no error checking.  If the curl fails do you want to continue with the git commands?
It isn't clear if you want this to run in bash or POSIX sh.  The question is tagged for bash, but your sh-bang line points at POSIX shell.  But yay for including the sh-bang line.
One shell best practice is putting your variable substitutions in double quotes.  git remote add origin "https://gitlab.com/$username/$repo.git" shows how to change one of your lines of code.  You want the variables inside of double quotes so that spaces in a variable name don't cause the shell to split what you think is one argument into multiple arguments to the command.

Ideas

Do you really want the token stored in the source code?  Can you pull this from a secrets vault or store it in a separate file?  If you want to commit your source code to a code repository (like git) it would be much better if it didn't include secret tokens.
I'd try seeing if I could get this to work as a git subcommand.  Here is a medium article on writing your own git subcommands.
Use shellcheck to get automated best practice suggestions for your shell code.  It can also be run locally on the command line.


Your update status method does too much. It has to decide which panel to use, which string to create and even how to create it.

If you separated them you could focus on exacly one task at a time:

The entry method should just decide which specialized update method to use.

It passes the required parameters to them and lets them do the job.

After reciving the result it passes it to the SetText method.

private void UpdateStatusLabels(PanelType panelType)
{
    var playerStats = Player.BaseStats;
    var values = Enum.GetValues(typeof(StatsOrders));
    var names = from object value in values select value.ToString();

    switch (panelType)
    {
        case PanelType.Stats:
            var playerStatsText = CreateStatsPanelText(playerStats, names);
            SetText(panelStats, "EditorOnly", playerStatsText);
        break;

        case PanelType.Points:
            // ...
        break;
    }

}

Everything the specialized methods do is to create the new string. (this is an example for one of them).

You don't need to use arrays and indexes. As you are looping over both collections synchronously you can make your life easier and use the Zip extension to iterate over both of them at the same time.

For creating the status text you should use the StringBuilder which makes the string creation cleaner.

private void CreateStatsPanelText(IEnumerable<Stats.Stats> playerStats, IEnumerable<string> names)
{
    var playerStatsText = new StringBuilder();

    foreach (playerStats.Zip(names, (playerStat, name) => new { playerStat, name }))
    {
        playerStatsText
            .Append(name.SplitOnCapitalLetters())
            .Append(" : ")
            .Append(playerStat.Increase(playerStat.PointsInStats))
            .AppendLine();
    }

    return playerStatsText.ToString();
}


Compute all valid configuration of eight queens on a 8x8 chess board

Coding style

Don't put a space between a function name and the opening bracket for its parameters. You should also consistently have a space after the comma between parameters in a function, iterable, etc. So, that should have been range(0, stop). Incidentally, if your starting value is 0, you can simply use range(stop).

When you need to do

for i in range(stop):
    value = seq[i]
    # do stuff

you should use enumerate().

for i, value in enumerate(seq):
    # do stuff

Obviously you can also enumerate only a part of your iterable and if the starting index isn't 0, you can specify that as well, i.e., enumerate(seq[start:stop], start).

When you want to initialise a list with the same immutable object, you can do

[value] * n

instead of

[value for i in range(stop)]

Care must be taken here, because if you tried to do [[]] * n, you would create n references of the same empty list and when it is modified, it changes for each index in your list. In such a case, you would have to fall back to initialising your iterable the way you did it. Also, while it's a matter of preference, I find it more natural to initialise the queen positions to None than some arbitrary value.

Your main function is simply a wrapper for get_arrangements(), where you simply initialise some objects. You can make get_arrangements() your main function and simply check whether you're currently at row 0 so you can initialise said objects.

def eight_queen(grid_size, row=0, already_placed_queen_cols=None):
    if not row:
        already_placed_queen_cols = [None] * grid_size

    if row == grid_size:
        yield already_placed_queen_cols
    # ...

This way you also solve the problem of the global variable, which is indeed ugly. I don't understand why it shouldn't be a parameter of your main function. The say I see it, I'm tasked with finding the solution to the n-queens puzzle, so the one thing I need to define is the board size. If I'm only interested in the solution for size 8, I can give it a default value in the parameters, so to call the function with no inputs, but that still allows me to generalise the solution should I feel like it later on.

The is_valid() function is only supposed to be called by your main function, and someone has no use for it unless he can replicate an intermediate state of its input parameters. As such, you can add a leading underscore to its name to indicate the user has no interest in calling it directly.

Naming style

I would call the main function solve_queens_puzzle() as that's what you're doing.

is_valid() correctly describes that it returns a boolean, but it's somewhat vague about the validity of what it tests. is_valid_placement() should suffice.

already_placed_queen_cols does feel a bit awkward indeed. queens_coords sounds equally descriptive and less verbose. Following on that, already_placed_queen_col is deceptive for having only a letter different in such a long name. I wouldn't complicate things here, from a glance at the code it's obvious the rows/columns iterated are up to proposed_row. I would simplify that to

for row, col in enumerate(queen_coords[:proposed_row]):
    if col == proposed_col:
        return False
    # ...

This one is entirely subjective, but you can either stick with a row/column convention, since mathematically speaking you're dealing with a 2D array, or you can use rank/file, which are the respective chess terms.

Performance

In the context of the backtracking algorithm you've implemented, there is one inefficiency. For each new row, you iterate over all 8 squares and check whether there are any conflicts. However, you repeat a lot of the same computations for each square, e.g., the proposed row against all the earlier rows, etc. Instead, you should go over the earlier rows once, while calculating any restrictions for the current row along the way. Specifically, for the current row you can't use the column of any previous row, or the diagonals that result from them. That way in one pass you can collect the available squares and return that from the function for iteration. This yields an exponential improvement for grid sizes over 10, when the solutions aren't computed almost instantly. Obviously, this changes the intent of the function, so its naming has to follow accordingly.

Overall, this is what I got.

def _get_possible_squares(size, current_rank, queen_coords):
    # no restrictions for the first row
    if not current_rank:
        return range(size)

    restrictions = set()
    for rank, square in enumerate(queen_coords[:current_rank]):
        restrictions.add(square)
        diff = current_rank - rank
        left_diagonal = square - diff
        right_diagonal = square + diff
        if left_diagonal >= 0:
            restrictions.add(left_diagonal)
        if right_diagonal < size:
            restrictions.add(right_diagonal)
    return (square for square in range(size) if square not in restrictions)

def solve_queens_puzzle(size, rank=0, queen_coords=None):
    if not rank:
        queen_coords = [None] * size

    if rank == size:
        yield tuple(queen_coords)
        return

    for square in _get_possible_squares(size, rank, queen_coords):
        queen_coords[rank] = square
        for solution in solve_queens_puzzle(size, rank+1, queen_coords):
            yield solution

for solution in solve_queens_puzzle(8):
    print(solution)


Portability
There is no guarantee that this code will be using ASCII so it would be better to use '0' rather than 48 which is something of a magic number. Using '0' makes it more readable and easier to understand.
lc_atof Doesn't Handle String Termination or End Of Line Correctly
This code doesn't handle a NULL terminated string or an end of line character. The function isspace() returns true for end of line so the code will walk right past it.
    while (isspace(**str))
        (*str)++;
    if (**str == '+' || **str == '-')
    {
        if (**str == '-')
            sign = -1.0;
        (*str)++;
    }
    if (!isdigit(**str))
    {
        errno = EIO;
        return (-1);
    }

Complexity
I reaize that you didn't ask for this to be review, but the complexity of each if statement in the example call function is too much and caused me to make an error in my review previously:
int a_parsing(char* str, t_pars* data)
{
    if (*(str++) == 'A')
    {
        if (((data->a_ratio = lc_atof(&str)) >= 0.0) && data->a_ratio <= 1.0 && errno == 0)
            //
            if (((data->a_R = lc_atoi(&str)) >= 0) && data->a_R <= 255 && errno == 0)
                if (*(str++) = ',' && ((data->a_G = lc_atoi(&str)) >= 0) && data->a_G <= 255 && errno == 0)
                    if (*(str++) = ',' && ((data->a_B = lc_atoi(&str)) >= 0) && data->a_B <= 255 && errno == 0)
                        return (skip_space(&str));
    }
    return (0);
}

I would rewrite the code as :
#define MAX_COLOR   0xFF
int a_parsing_prime(char* str, t_pars* data)
{
    if (*(str++) == 'A')
    {
        data->a_ratio = lc_atof(&str);
        if (!errno && data->a_R <= MAX_COLOR)
        {
            if (*(str++) = ',')
            {
                data->a_G = lc_atoi(&str);
                if (!errno && data->a_G <= MAX_COLOR)
                {
                    if (*(str++) = ',')
                    {
                        data->a_B = lc_atoi(&str);
                        if (!errno && data->a_B <= MAX_COLOR)
                        {
                            return (skip_space(&str));
                        }
                    }
                }
            }
        }
    }
    return (0);
}

which truely shows the complexity of the function.


Cleanest way to get list of Django objects that have same foreign key and display them in a view

However, I am not sure if passing the interviews QuerySet like that is a good practice or not.

This is good practice, known as dependency injection. If someone asks for your business card, you wouldn't give them your wallet and let them fish it out - you can think of passing objects to the template renderer the same way. Passing only the company object would mean there would have to be more logic in your detail.html template to fish out the interviews, which is less than ideal. The way you currently do it serves as documentation as to what objects are required by the detail.html template.

  In general, is there a better way to get a list of objects that have the same foreign key?

You can specify a related_name for the company foreign key on your Interview model like so.

class Company(models.Model):
    name = models.CharField(max_length=200)

class Interview(models.Model):
    company = models.ForeignKey(Company, related_name='interviews', on_delete=models.CASCADE)
    position = models.CharField(max_length=200)

Then you can access all interviews for a company like company.interviews.all()


Calculating Standard Deviation using SQL

Assuming you want to reinvent the wheel…

You really shouldn't be using a data table as scratch space for calculations, even if it is a temporary table.  You should also not need to rely on variables either — that is not idiomatic SQL.  A Common Table Expression would solve both problems.

CREATE TABLE #Numbers
(
  Number DECIMAL(10,4)
);

INSERT …;

WITH Mean AS (
    SELECT SUM(Number) / COUNT(Number) AS Mean
        FROM #Numbers
), Deviation AS (
    SELECT Mean, POWER(Number - Mean, 2) AS Error
        FROM #Numbers CROSS JOIN Mean
)
SELECT Mean, SQRT(SUM(Error) / COUNT(Error)) AS [Standard Deviation]
    FROM Deviation
    GROUP BY Mean;


First of all, it seems like you're reinventing the wheel here. You didn't provide any context for what this is for so I'll try to cover all bases.

If you are using this as part of a bigger project, I'd recommend abandoning this approach and picking up something like Prototype.js or maybe Ember.js if you're ambitious. Alternatively, take a look at how CoffeeScript does it. CoffeeScript's underlying JS is pretty messy but it's significantly simpler than yours AND supports inheritance.

If this is just an educational exercise, I can point out a few problems with your code that I see.

extend_obj(Extended.prototype, constructor);

This seems to be copying the instance's properties onto the class prototype. This doesn't make much sense as the instance's properties should be separate.

var instance = new SubClass({ name: "custom name" })

This actually instantiates an Extended (aka SubClass) object with no instance properties and modifies the Extended prototype to have a name property of "custom name". This is very strange behavior.

In general, when trying to emulate Classes in JS, the prototype is where instance methods go or, possibly, default values for properties. However, an instance (created with new) should have no effect on it.


Calculate class to practice encapsulation

On Formatting

You can format your output using System.out.printf , or String.format()

For example, if you wanted your division test result to only include 2 digits after the decimal you could instead call System.out.printf("Division: %.2f%n", calc.divide());

The % is a special character; when the printf method reaches it it replaces that location with the specified formatted version of the proceeding arguments (You can have several in one line as long as they are in order). The '.2' that proceeds is what enforces only 2 digits after the decimal. The %n that immediately follows is so you can still have a new line after calling printf. You can read more about formatting and find some additional examples here.

On Exception Handling

I'll also echo the previous answer in saying that handling edge cases would do you some good, this could be done with a simple conditional within the method to ensure the divisor is not 0, which would otherwise cause an error or report NaN/infinity when it is undefined.

You could throw an exception if the divisor is 0 within the divide method itself, like so:

public double divide() {
        if (num2 == 0) {
            throw new ArithmeticException("Dividing by 0 is undefined");
        }

        return num1 / num2;
    }

The message could be  a simple "Cannot divide by 0." Which, if you catch it, would allow a 0 divisor to exist, and you don't have to constrict the possible num2 values and calculations possible.

On Java Convention & Readability

variables and methods are camelCase
Class and interface name are PascalCase
CONSTANTS are UNDERSCORE_CAPITALIZED

Also, try to have a line break between your methods, it'll aid in readability once method body increases. Though I personally omit this when the methods are closely linked, like getters and setters for the same value, as @Rhuarc13 suggest you have.

Although I disagree with adding anything not explicitly necessary(any user trying to pass a no arg constructor would encounter a compilation error) since this is an exercise on encapsulation I think a getter has some merit. Setters don't make sense in this case given your variables' final state, but if you instantiated several of these Calculate objects with different values it would be helpful to have a method to keep track of them without providing users with access to the variable itself, which would break encapsulation*.

Access to the variable directly is arguably inconsequential since it's final, but the point of encapsulation is that the external users should not concern themselves with the fields or implementation.

If you go in your calculate and added methods like so:

public double getNum1() {
    return this.num1;
}

public double getNum2() {
    return this.num2; // this keyword refers to that particular object
}

Then when you're interested in what value is actually contained within the object for example in your test case you could call

System.out.println("Number 1: " + calc.getNum1());
System.out.println("Number 2: " + calc.getNum2());

Alternative Implementation

If you were interested in setters as well, if you had private instead of final values you could use something like this:

public class Calculator {
    private double num1;
    private double num2;

    public Calculator setNum1(double num1) {
        this.num1 = num1;
        return this;
    }

    public Calculator setNum2(double num2) {
        this.num2 = num2;
        return this; // return the current state of Calculator to allow for chaining
    }

    public double divide() {
        return num1 / num2;
    }

    public double add() {
        return num1 + num2;
    }

    public static void main(String[] args) {
        // You can chain call them
        Calculator example = new Calculator().setNum1(3).setNum2(5);

        System.out.println(example.add());
        // Or use it separately.
        example.setNum1(45);
        System.out.println(example.divide());
    }
}

On User Input + Further input validation

Your revision seems concerned with user input, if you actually want to get and use input, a simple way to do that is to make use of Scanner.

Make sure to retrieve the resource at the top: import java.util.Scanner and then declare an instance: Scanner input = new Scanner(System.in)

The nice thing about that is you could ensure a non-0 divisor with a while loop.

for instance if in your main method you did:

System.out.print("Enter second value: ");
double val2 = input.nextDouble();

You could proceed with this:

while (val2 == 0) {
    System.out.print(
        "Second value cannot be 0" +
        "\nEnter a non-0 value: ");

    val2 = input.nextDouble();
}

and that would make sure that your user provided a non 0 divisor.


Retrieving font preference setting in Eclipse JDT plugin

I'm not familiar with Eclipse plugin development, so just two minor notes after going through javadoc of the relevant APIs:

FontRegistry has an addListener method which you might want and/or need to listen to and change the font of the textControl when the user changes their font settings.
The comment could be a great method name here (retrieveFontPreference, for example):

// retrieve the font preference from the theme manager
IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager();
ITheme currentTheme = themeManager.getCurrentTheme();
FontRegistry fontRegistry = currentTheme.getFontRegistry();
Font font = fontRegistry.get(PreferenceConstants.EDITOR_TEXT_FONT);

See also: Clean Code by Robert C. Martin, Bad Comments, p67: Don’t Use a Comment When You Can Use a Function or a Variable


Comparing objects in a list against each other

I find the problem you are trying to solve to be as hard to grasp from the code presented as from the description:
- document your code, using the conventions of the language (&environment) of choice.
- use telling names

In the for-loop, you don't use i: don't use enumerate().
I think the first comprehension easier to understand with reading (? "r") mentioned first:
measurement = (y for y in self.records if reading.<predicate>(y))
I think it confusing to use the same identifier for unrelated objects in one and the same statement - suggesting if not any(reading in n for n in new):
instead of if <condition>: <pass> else: <act> do
if not <condition>: <act>
compare_record_same_name() is a horrible name, as it mentions only half of what the function checks. It seems it is there to check whether the other record belongs to the same "measurement" - name it for that: same_measurement().
instead of converting duration to seconds each and very time, make TIME_SEPARATOR a timedelta

I'd try a different approach:

readings with different instrument names do not belong to the same measurement, anyway:
use a separate collection for each name
sort each collection by time (hoping the method used makes good use of what order is bound to exist in input)
any gaps exceeding TIME_SEPARATOR separate measurements
if the time covered by any group g is too big for one measurement, split at large internal gaps or evenly by number of readings or time range or …


If all your queries are similar to the example, you would obviously benefit from storing the data in a dict where a tuple of two values is the key, and the value is a list of ints -- all of the third items that share the same key.

from collections import defaultdict

stuff_dict = defaultdict(list)
for t in stuff_tuple:
    stuff_dict[t[:2]].append(t[2])

for item in stuff_dict['hello', 241]:
    print item


I don't like either of them because they look like multiple numbers could be assigned to multiple persons which is obviously wrong.

You can get only one result for a search because you are not searching with wildcards so consider this. A person can have multiple numbers so for a person you can have a single hit. If you search for an exact number you'll also get a single hit. This can be made clear by naming the method appropriately: FindExact. Later you can add another one that can search with wildcards (patterns).

class Phonebook
{
    private readonly Dictionary<string, List<string>> _entries =
        new Dictionary<string, List<string>>();

    public void Add(string person, string number)
    {
        List<string> numbers;
        if (_entries.TryGetValue(person, out numbers))
        {
            numbers.Add(number);
        }
        else
        {
            _entries[person] = new List<string> { number };
        }
    }

    public KeyValuePair<string, List<string>> FindExact(string personOrNumber)
    {
        List<string> numbers;
        return
            _entries.TryGetValue(personOrNumber, out numbers)
            ? new KeyValuePair<string, List<string>>(personOrNumber, numbers)
            : _entries.FirstOrDefault(x => x.Value.Contains(personOrNumber));
    }
}

Currently searching for a persons would be faster because it is a key in the dictionary. You could add another dictionary that maps numbers to persons and make the number search as fast as person search by looking at the key instead of searching all values:

private readonly Dictionary<NUMBER, PERSON> _numberPerson...

In your second solution you don't need a dictionary at all because use don't use it like it should be used. You loop twice over it to find either value. In this case you can also use a list.

If you want to use a dictionary then use it appropriately otherwise it doesn't make any sense.

Use two dictionaries to make the exact search even faster but don't loop twice over it.

You can also replace both queries with a single one:

var query =
    from x in myPhonebook
    where x.Key == input || x.Value == input
    select x;

Even better like so:

var result = myPhonebook.FirstOrDefault(x => x.Key == input || x.Value == input);


Mapping Many Parameters Programmatically

I think the solution for this case maybe is more painful than a long code of config, and this code looks like test data.

A possible workaround could be match the label string with the same property of printTestData. and then call it by reflection. But i prefer have the long config. instead of a hackish-call-property.


Mutual recursion - Naming the opponent serve - pingpong

From the problem statement:

Implement a function pingpong that returns the nth element of the
ping-pong sequence without using any assignment statements.
You may use the function num_sevens, which you defined in the previous
question.
Use recursion - the tests will fail if you use any assignment
statements.
Hint: If you're stuck, first try implementing pingpong using
assignment statements and a while statement. Then, to convert this
into a recursive solution, write a helper function that has a
parameter for each variable that changes values in the body of the
while loop.

Code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable.

Your first solution makes far too much of a simple switch in the increment value with duplicated functions differing merely in the literal integer values 1 and -1. It requires a diff comparison to find the small, obscure differences between the largely duplicate player1 and player2 functions. Duplication of code hurts maintainability. The solution introduces an obscure player abstraction which is not part of the problem statement. It is not readable. Also, the solution uses multiple assignment statements for the player function variables: "the tests will fail if you use any assignment statements."

While the problem statement did say you may use num_sevens, this problem asks "if k contains the digit 7". To count all occurences of digit 7 when we only care about the first occurence is inefficient.

Your second solution, "code written without using mutual recursion", which you added later, is clearly incorrect. It uses multiple assignment statements: "the tests will fail if you use any assignment statements." For no apparent reason, you use the name toogle instead of switch and you complicate things by introducing a toggleValue variable.
toggleValue := 1 ^ -1
increment := 1
. . .
        increment ^= toggleValue

The toggleValue variable is unnecessary and the toggle algorithm is obscure. Simplicity is a virtue.
increment := 1
. . .
        increment *= -1 // switch

The Problem Statement is an academic problem designed to discover if you have learned some fundamental programming concepts: recursion and no assignment statements. The Hint gives a detailed road-map to a solution. You did not answer the problem as stated so you get an F.

Here is an example of the sort of solution that the problem statement likely expected:

Use recursion. First try implementing pingpong using assignment
statements and a while statement. Then, to convert this into a
recursive solution, write a helper function that has a parameter for
each variable that changes values in the body of the while loop.

package main

import "fmt"

func digitSeven(x int) bool {
    if x <= 0 {
        return false
    }
    if x%10 == 7 {
        return true
    }
    return digitSeven(x / 10)
}

func increment(incr int, x int) int {
    if x%7 == 0 || digitSeven(x) {
        return incr * -1
    }
    return incr
}

func pingpong(n int, i int, v int, incr int) int {
    if i > n {
        return v
    }
    return pingpong(n, i+1, v+incr, increment(incr, i))
}

func PingPong(n int) int {
    return pingpong(n, 1, 0, 1)
}

func main() {
    for n := 1; n <= 30; n++ {
        fmt.Println(n, PingPong(n))
    }
}

Playground: https://play.golang.org/p/8H6l-CpLlye
Output:
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 6
9 5
10 4
11 3
12 2
13 1
14 0
15 1
16 2
17 3
18 2
19 1
20 0
21 -1
22 0
23 1
24 2
25 3
26 4
27 5
28 4
29 5
30 6


Human-readable number of bytes in Haskell

We begin with the "loop". map ((size'/).(1024^)) [0..] is iterate (/1024) size. This has not necessarily the same effect, since (x/y)/y is not the same as x/y² when using floating point arithmetic, but it's fine for our cause. It also works like the Python code, which was your original intention.

We now have

humanReadableBytes :: Integer -> String
humanReadableBytes size | null pairs = printf "%.0fZiB" (size'/1024^7)
                        | otherwise  = if unit=="" then printf "%dB" size
                                       else printf "%.1f%sB" n unit
where
    (n, unit) = head pairs
    pairs = zip (iterate (/1024) 'size)) units
    size' = fromIntegral size :: Double
    units = ["","Ki","Mi","Gi","Ti","Pi","Ei","Zi"]

And that's all we can improve in terms of terseness at that point without changing your code fundamentally. The main difference between the Python and the Haskell implementation is the mutation of the original num and the early exit from the function.

I would recommend to check the "B" case earlier by the way:

humanReadableBytes :: Integer -> String
humanReadableBytes size
  | abs size < 1024 = printf "%dB" size
  | null pairs      = printf "%.0fZiB" (size'/1024^7)
  | otherwise       = printf "%.1f%sB" n unit
where
  ...


List with object and index filtering out the object depends upon the index present at list

It seems to me that your solution is basically O(n*m),the size of the unfiltered list times the number of filter indexes.  I think you can get O(n+mlogm),the size of the unfiltered list plus sorting the filtered indexes, by using a combination of indexes and iterators and iterating through both lists at the same time.  It could look something like this:

public static List<Test> getFilteredList(Collection<Test> unfilteredList, List<Integer> filterIndexes) {
    if(filterIndexes == null || filterIndexes.size() == 0){
        return new ArrayList<Test>(unfilteredList);
    }
    Collections.sort(filterIndexes);
    List<Test> newTestList = new ArrayList<>();
    Iterator uIterator = unfilteredList.iterator();
    Iterator fIterator = filterIndexes.iterator();
    Integer fIndex = (Integer)fIterator.next();
    for (Integer uIndex = 0;uIterator.hasNext();++uIndex) {
        Test nextTest = (Test)uIterator.next();
        if (uIndex == fIndex) {
            newTestList.add(nextTest);
            if(!fIterator.hasNext()){
               break;
            }else{
                fIndex = (Integer)fIterator.next();
                if(fIndex >= unfilteredList.size()){
                    break;
                }
            }
        }
    }
    return newTestList;
}


int input = Integer.parseInt(rawInput);

This can throw an exception if rawInput isn't a number.

    else if(input < 10)
    {
        output += ones(0);
    }
    else if(input < 20)
    {
        output += teens(0);
    }
    else if(input < 100)
    {
        output += tens(0);
        output += ones(1);
    }
    else if(input < 1000)
    {
        output += hundreds(0);
        int temp = Integer.parseInt(rawInput.substring(1,3));
        if(temp > 10 && temp < 20)
        {
            output += teens(2);
        }
        else
        {
            output += tens(1);
            output += ones(2);
        }

    }

Code (subroutine calls) are duplicated in the above:

If the number is less than 1000 then you call tens, teens, and ones
If the number is greater than 1000 then you call tens, teens, and ones

There would be less code if you processed it from left to right, like you do when you read and say a number:

if (input > 1000)
{
    output += thousands;
    subtract thousands from input;
}
if (input > 100)
{
    output += hundreds;
    subtract hundreds from input;
}
if (10 < input < 20)
{
    output += teens;
}
else
{
    if (input >= 20)
    {
        output += tens;
        subtract tens from input;
    }
    output += ones;
}
if (output is empty)
    output = "Zero";

int temp = Integer.parseInt(rawInput.substring(1,3));

This is a complicated way to remove the thousands from the input.

A simpler way to subtract thousands from the input is:

input = input - ((input / 1000) * 1000);

main(args);

This is a strange way to loop forever.

Better would be:

public static void main(String[] args)
{
    while (true)
        run();
}

static void run()
{
    rawInput = JOptionPane.showInputDialog("Enter a number between 0 and 9999.");
    ... etc ...
}

Perhaps only the first letter should be capitalized; perhaps with hyphens; and the word "and"; for example "Four hundred and forty-three" not "Four Hundred Forty Three".


Reactive operator for distinct values that must change by amount

DistinctUntilChangedBy()
This method is public and therefore should do proper argument validation. Since this method is an extension-method, it could be called like:
ObservableExtensions.DistinctUntilChangedBy(someObservable, someDecimal);

If someObservableis null, your method would throw a NullReferenceException where an ArgumentNullException would be a better fit.
Equals(decimal, decimal)
Instead of returning diff <= Math.Abs(amount) you could set the class variable amount in the constructor directly to the Abs(amount) of the passed argument:
this.amount = Math.Abs(amount)

That could speed it up if the Equals() method is called often.
GetHashCode(decimal)
Only if you are 100% sure that this method won't ever be called should you throw a NotSupportedException. See What's the role of GetHashCode in the IEqualityComparer<T> in .NET?


How to add forms dynamically in javascript?

To create dynamic forms and elements in javascript is easy.

var newdiv = document.createElement('div'); // Creates the div
document.body.appendChild(newdiv);          // Adds the div to body

After that, you can access newdiv and change attributes of it, such as

newdiv.className = "helloworld";


Print length of longest sequence of consecutive numbers

Using static for the consecutive() function is appropriate.  However, the omission of braces, the inconsistent indentation, and lack of spaces between operators is just as bad as before.

Your function crashes on arrays of length 0 or 1.

The variable names f and counter could be improved.  I think that a different looping structure would be clearer as well.

public static int consecutive(int[] array) {
    if (array.length <= 1) {
        return array.length;
    }

    int maxRun = 0;
    for (int i = 1; i < array.length; i++) {
        int thisRun = 1;
        while (i < array.length && array[i - 1] + 1 == array[i]) {
            thisRun++;
            i++;
        }
        if (maxRun < thisRun) {
            maxRun = thisRun;
        }
    }
    return maxRun;
}


Playing sound in JavaFX when button is pressed, window pops up

It's generally more standard to hide as many fields of your class as possible. I'd recommend making  file, sound and player in Sound as well as path and sound in MusicPane private.

Additionally you're not using file in Sound, so you can remove it. Furthermore your class' bodies are not indented by one level (contrary to usual conventions).

Aside from that there's not much to say about Sound the only thing that may be improved is using Paths.get instead of new File when you create your sound.

The MusicPane has a bit more to talk about. For one I don't quite understand why you're not using an fxml to specify the components. Additionally conventional wisdom suggests to use composition over inheritance. Instead of subclassing Pane into a MusicPane, you should use the Pane as a Member of the "GUI" you expose to your program.

This allows you to better share behaviour between components you create by subclassing Components instead of Pane.

The comments in the code aren't really useful... // if this button is pressed, it plays the sound can be completely removed, especially when you rename the button to play.
//first stop a playing sound, then start the sound  can be completely removed. It adds no information whatsoever to the code.
//Slider to adjust the volume becomes completely superfluous as soon as you rename slider to volumeSlider.


Martix of Counts of Regex Hits Over a List of Strings

An idiomatic approach would be to put MyText in a dataframe (if not already) and assign() the results of str.count().
I'd also suggest using an actual dict for the regex mapping. It's not strictly necessary, but the syntax is just cleaner given that this use case aligns with dict. (Here I created terms from MyDictionary just for continuity with the existing code.)
terms = dict(zip(MyDictionary.TermId, MyDictionary.SearchTerm))
df = pd.DataFrame({'MyText': MyText})

df = df.assign(**{key: df.MyText.str.count(val) for key, val in terms.items()})

#                          MyText  SK_0  SK_1  SK_2  SK_3  SK_4  SK_5
# 0   I saw xx.yy and also xx.yyy     2     0     0     0     0     0
# 1  FireFly* this is xx_yy there     0     0     0     1     0     0
# 2                       I xx$YY     0     0     0     0     0     0
# 3           I see x.yy now .NET     0     1     0     0     0     0
# 4           now xx.yyxx.yyxx.yy     3     0     0     0     0     0
```


Django Custom Decorator for user group check

As an alternative to the answer given by jcollado, Django has some built in decorators to help.

From the docs:

from django.contrib.auth.decorators import user_passes_test

def email_check(user):
    return '@example.com' in user.email

@user_passes_test(email_check)
def my_view(request):

https://docs.djangoproject.com/en/1.6/topics/auth/default/#limiting-access-to-logged-in-users-that-pass-a-test

This could be modified to something like:

from django.contrib.auth.decorators import user_passes_test

def group_check(user):
    return user.groups.filter(name__in=['assignment_collector',
                                        'fund_collector'
                                        'labsheet_collector'])

@user_passes_test(group_check)
def my_view(request):
    ...

If they are not in these groups it will redirect by default to the login page.


You could use find to get the object which includes the given task in its initialTasks array. This also uses 2 loops. But, it returns when the match is found and is less verbose.

const stagesTasks=[{dataTestID:"stage-0",headerText:"Backlog",initialTasks:["task 1","task 2","task 3"]},{dataTestID:"stage-1",headerText:"To Do",initialTasks:["task 4","task 5","task 6"]},{dataTestID:"stage-2",headerText:"Ongoing",initialTasks:["task 7","task 8"]},{dataTestID:"stage-3",headerText:"Done",initialTasks:["task 9"]}];

function getStageName(task) {
  return stagesTasks.find(s => s.initialTasks.includes(task))?.dataTestID
}

console.log(getStageName("task 2"))
console.log(getStageName("task 7"))
console.log(getStageName("doesn't exist"))

If you call this function repeatedly, then you could create a mapper object which maps each task to it's dataTestID. You can just use mapper[task] to obtain the dataTestID. Since you are returning early, I'm assuming the tasks are unique.

const stagesTasks=[{dataTestID:"stage-0",headerText:"Backlog",initialTasks:["task 1","task 2","task 3"]},{dataTestID:"stage-1",headerText:"To Do",initialTasks:["task 4","task 5","task 6"]},{dataTestID:"stage-2",headerText:"Ongoing",initialTasks:["task 7","task 8"]},{dataTestID:"stage-3",headerText:"Done",initialTasks:["task 9"]}];

const mapper = stagesTasks.reduce((acc, o) => {
  o.initialTasks.forEach(t => acc[t] = o.dataTestID)
  return acc
}, {})

function getStageName(task) {
  return mapper[task]
}

console.log(getStageName("task 2"))
console.log(getStageName("task 7"))
console.log(getStageName("task 9"))


Print a word with numbers substituted for characters

Think about the problem as a repeated Cartesian product. It allows us
to use the very useful product function from the itertools module:

>>> list(product('ab', 'AB', 'xy'))
[('a', 'A', 'x'), ('a', 'A', 'y'), ('a', 'B', 'x'),
('a', 'B', 'y'), ('b', 'A', 'x'), ('b', 'A', 'y'),
('b', 'B', 'x'), ('b', 'B', 'y')]

So your problem can be solved by replacing each character in the
string with its possible replacemnets and running product on the
result:

import itertools
import sys

def alternatives(ch, repls):
    key = ch.lower()
    if key in repls:
        return [ch, repls[key]]
    return [ch]

def main(argv):
    if len(argv) != 2:
        print(f"USAGE: {argv[0]} [word]")
        return

    # Populate the known replacements
    replacements = {'a' : '4', 'e' : '3', 'i' : '1',
                    'm' : '/v\\', 'o' : '0', 'r' : '2'}

    s = [alternatives(ch, replacements) for ch in argv[1]]
    for it in itertools.product(*s):
        print(''.join(it))

if __name__ == '__main__':
    main(sys.argv)

Note that this version is not exactly identical to your original. If
you enter "mondoman" the program will output "mondoman" as one
combination.


Concept Review
There are a number of purpose built tools to do this job already. The one that comes to mind first is 'shred'. shred is installed by default on all Redhat and Ubuntu systems (in coreutils package on both systems). It is also installed on my RaspberryPi, so, it is ubiquitous.
Shred does similar things to what your script does, but it will be faster, and more secure, presumably. Running:
shred -u file

will repeatedly overwrite, and then delete the file.
Note that shred itself contains in the documentation:
   CAUTION: Note that shred relies on a very important assumption: that the file
            system overwrites data in place.  This is the traditional way to do
            things, but many modern file system  designs  do  not
            satisfy this assumption.  The following are examples of file systems
            on which shred is not effective, or is not guaranteed to be effective
            in all file system modes:

   * log-structured or journaled file systems, such as those supplied with AIX and
     Solaris (and JFS, ReiserFS, XFS, Ext3, etc.)

   * file systems that write redundant data and carry on even if some writes fail,
     such as RAID-based file systems

   * file systems that make snapshots, such as Network Appliance's NFS server

   * file systems that cache in temporary locations, such as NFS version 3 clients

   * compressed file systems

These same cautions apply to your code.
There is really only one way to manage content that you need to securely erase later, and that is to encrypt the data before you store it, or to store it in an encrypted filesystem.
Deleting the file then is as simple as 'forgetting' the key, or corrupting critical/small parts of it.
The bottom line is that since almost all Linux implementations now use ext3 or some other Journaled file system, that your secure erase is not likely going to be secure enough.
Code Review
Assuming the process would actually work in your setup....
As for your actual script, the code is neat enough, and the command-line arguments are handled OK. There are still a number of problems though:
you have no error-handling for any of your dd commands. if all the dd commands fail (perhaps someone is running in a chroot jail and /dev/zero and /dev/urandom are not accessible), but the rm works, it will seem like the process succeeded, but you have not actually changed any bytes on disk... which is bad.
A user who runs your command as:
securedelete "My Document"

would expect "My Document" file to be overwritten, but you have not quoted the $1 in any of the use-cases, so the dd and rm commands will fail with things like:
dd if=/dev/zero of=My Document bs=$filesize count=1

Actually, that's a good example of a bad failure. All the dd commands will fail, doing nothing, and then, at the end, you will have:
rm -f -- My Document

which will force-delete two files, one called My the other called Document.


Reverse multiple strings separated by comma

Upon learning more brainfuck, I've learned that my loop that subtracts 44 could be improved:

Before

>> tmp2=0 ++++[< tmp1=0 +++++ +++++ + >-] tmp1 is 44
<[<->-] subtract tmp1 from ptr

After

>  tmp1=0 ++++[< ptr    ----- ----- - >-]

This prevents actually creating the value 44 and performing an additional ~44 operations.


Using a like with a leading wild card will likely be very slow as no indexes can be used. As such they should be avoided, which should be easy to do when the string you are checking it a concatenation of values from a table.

I would suggest you do another join from the blog table to the blog tag relationship table, and from that another join to the blog tag table but specifying that the tag is php . This should mean any blog with a php tag will be brought back (complete with all its tags concatenated together) while any blog without that tag will be ignored.

Not tested, but something like the following

SELECT T2.blog_id, T2.title, T2.url, T2.summary, T2.article, GROUP_CONCAT(T3.tag SEPARATOR ':') AS tags
FROM  lm_blog_tag_relationships AS T1
INNER JOIN lm_blog AS T2 ON T1.blog_id = T2.blog_id
INNER JOIN lm_blog_tags AS T3 ON T1.tag_id = T3.tag_id
INNER JOIN lm_blog_tag_relationships T4 ON T2.blog_id = T4.blog_id
INNER JOIN lm_blog_tags AS T5 ON T4.tag_id = T5.tag_id AND T5.tag SEPARATOR = 'PHP'
GROUP BY T2.blog_id
ORDER BY T2.blog_id DESC


Coffee machine that adds condiments dynamically

I would remove the name field entirely, and instead inline it into the getName() method.
That way you can implement the getName() similar to how you implemented getCost().

Concretely this means your getName() method from Beverage becomes abstract just like the other abstract classes.

public abstract String getName();

The base beverage (HouseBlend) then implements the method as:

public String getName() {
    return "HouseBlend";
}

And similarly the decorator classes implement it as such:

public String getName() {
    return "Milk-flavored " + beverage.getName();
}

You can fill in the implementation for the other decorators.


SQL statement construction

Your third-party library do support bindings, so instead of .where("id = " + lineItemId.trim()), you should consider:

//  .where("id = " + lineItemId.trim())
    .where("id = :lineItem")
    .withBindVariableValue("lineItem", lineItemId.trim());

Early variable assignment

LineItem lineItem = null;
// ...
if (/* ... */) {
    lineItem = /* ... */;
}
return lineItem;

You usually should not need to declare the return result right at the start, perform the optional assignment, and then return from the method. You should just return below, without needing the lineItem variable:

// ...
if (/* ... */ ) {
    return /* ... */;
}
return null;


Pandas merge a "%Y%M%D" date column with a "%H:%M:%S" time column

We can let pandas handle this for us and use DataFrame.apply and datetime.datetime.combine like this:
df["TimeMerge"] = df.apply(lambda row: datetime.datetime.combine(row.date1, row.time1), axis=1)

Although the following approach is more explicit and might therefore be more readable if you're not familiar with DataFrame.apply, I would strongly recommend the first approach.
You could also manually map datetime.datetime.combine over a zip object of date1 and time1:
def combine_date_time(d_t: tuple) -> datetime.datetime:
    return datetime.datetime.combine(*d_t)

df["TimeMerge"] = pd.Series(map(combine_date_time, zip(df.date1, df.time1)))

You can also inline it as an anonymous lambda function:
df["TimeMerge"] = pd.Series(map(lambda d_t: datetime.datetime.combine(*d_t), zip(df.date1, df.time1)))

This is handy for simple operations, but I would advise against this one-liner in this case.

By the way, the answer your were looking for can also be found under the question you linked.


Static ConcurrentDictionary to maintain static objects

public List<InstanceField> GeKeysFromCache(string cacheKey)
{
    var resultSet = m_InstancesCached.GetOrAdd(cacheKey, (key) =>
   {
       return new List<InstanceField>();
   });

    return resultSet.ToList();
}

Why so many returns and when you can simply do this with only one return and without the lambda:

return m_InstancesCached.GetOrAdd(cacheKey, new List<string>()).ToList();


Simplify the logic

It seems like:

if planet == "mercury":
    return number_of_days / days_in_year["mercury"]
elif planet == "venus":
    return number_of_days / days_in_year["venus"]
elif planet == "earth":
    return number_of_days / days_in_year["earth"]
elif planet == "mars":
    return number_of_days / days_in_year["mars"]
elif planet == "jupiter":
    return number_of_days / days_in_year["jupiter"]
elif planet == "saturn":
    return number_of_days / days_in_year["saturn"]
elif planet == "uranus":
    return number_of_days / days_in_year["uranus"]
elif planet == "neptune":
    return number_of_days / days_in_year["neptune"]

can be easily rewritten:

if planet in days_in_year:
    return number_of_days / days_in_year[planet]
raise Exception("Unknown Planet! Are you sure you've enter a planet?")

Also, one could consider keeping it even more simple and use the fact that:

return number_of_days / days_in_year[planet]

will throw the relevant exception for an invalid value.

Do not repeat yourself

You can try to avoid duplicated values and have a single source of information. In your case, the list of planet is indirectly hardcoded twice :

days_in_year = {"mercury": 88, "venus": 224, "earth": 365, "mars": 687, "jupiter": 4332, "saturn": 10759, "uranus": 30688,
                "neptune": 60182} #days in each planet's year

and

planets = ["mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune"]

Maybe you could define a constant like DAYS_IN_YEAR_PER_PLANET (corresponding to your actual days_in_year dictionnary) and use it where you are using the list of the planets (for planet in DAYS_IN_YEAR_PER_PLANET: for instance).

Do not perform more operations than required

number_of_days = calculate_days(age) is computed for every planet in the list. It would be better from a performance point of view to feed the function a number of days.

Useless list (or useless test)

You are creating a list with values divisible by 4. Then you iterate over it and check if the value is divisible by 4. It seems like a waste of effort. Let's get rid of the list creation. Code is based on the initial version of your code.

def calculate_days(age):
    leap_days = 0 #holds number of leap days

    for j in range(age):
        if j % 4 == 0 and j % 100 != 0:
            leap_days += 1 #if leap years are divisible by four and not divisible by a hundred, add to leap days

    return (age * 365) - leap_days

Also, this can somehow be written by abusing the generator expression and the sum builtin:

def calculate_days(age):
    leap_days = sum(1
                    for j in range(age)
                    if j % 4 == 0 and j % 100 != 0)
    return (age * 365) - leap_days

Also, you could find mathematical expressions to compute the number of leap days in a more efficient way (constant time instead of linear time) but I'll keep this out of the review.


std::vector composition with self populating super-powers

I think it is overkill to write an own class. This gives you many issues because you have to reimplement vector's interface.

In the current state I don't see any advantage over having just a function that returns a vector that is filled randomly:

#include <vector>
#include <random>
#include <chrono>
#include <algorithm>
#include <iterator>

std::vector<uint32_t> generateRandomVector(std::size_t size) {
    static std::mt19937 gen(
            std::chrono::system_clock::now().time_since_epoch()
                    / std::chrono::milliseconds(1));
    static std::uniform_int_distribution<uint32_t> uint_dist99(0, 99);
    std::vector<uint32_t> result;
    result.reserve(size);
    std::generate_n(std::back_inserter(result), size,
            [&] {return uint_dist99(gen);});
    return result;
}

Use it like this:

#include <iostream>

int main() {
    for (auto a : generateRandomVector(20)) {
        std::cout << a << std::endl;
    }
}

This approach has the advantage of cleanly separating the functionality of the vector (which is to store data) from the functionality of the random generation (which just manipulates a vector).

Of course this interface looses some flexibility but if you need it then you should write a class that allows to create random vectors and not a vector class that happens to fill itself with random numbers.

Your Approaches

Using iota and shuffle does not really shorten the code of populate and somewhat "obfuscates" the thing that is going on there (so you would have to add additional comments to state what you want to achieve and why you restrict yourself to permutations).
The seeding of the random number generator can be done during construction which means during static initialization in the implementation file:

std::size_t getSeedFromCurrentTime() {
    return std::chrono::system_clock::now().time_since_epoch() /
           std::chrono::milliseconds(1);
}

std::mt19937 algorithmicVec::gen(getSeedFromCurrentTime);

About obtaining the seeding from the time I have no experience and cannot help you there.


Helper utilities for easier benchmarking in C

Nice bit of code!  Here are a few suggestions:

Initialize your variables when you declare them.  This helps shorten the code a bit and reduce possible bugs.
You need documenting comments within your code.  Especially since you are considering this as a library.
I would remove the NULL check on code in your execTime method, and document that a valid function pointer should be passed in.  I would expect the code to break if I tried to time NULL, not NULL to be returned back.  The standard library does this same thing with a few of their functions, like strlen().
Good job checking the return from malloc().
I would use the C11 standard function timespec_get() for your timing code.  It's a C standard (important!) function that has nanosecond precision.
If you want a better Fibonacci algorithm, here is an answer I wrote up a while ago on it.
Good job using puts() in place of printf() when you can.
You don't have to return 0 at the end of main(). The C standard  knows how frequently this is used, and lets us omit it.

  C99 & C11 §5.1.2.2(3)

  ...reaching the } that terminates the main() function returns a
  value of 0.


The optimization you made manually is most likely already noticed and implemented by the compiler.

Instead, you should notice that \$\cos\frac{2\pi k}{N} - i \sin\frac{2\pi k}{N} = e^{-\frac{2\pi i}{N}k}\$, and replace multiple invocations of sin and cos with multiplications. Naively:

    complex base = { cos(2.0 * PI / N), -sin(2.0 * PI / N) };
    twiddle_table[0] = { 1.0, 0.0 };
    for (i = 1; i < N; ++i) {
        twiddle_table[i] = twiddle_table[i - 1] * base;
    }

In the production code you need to pay attention to the accumulation of numerical errors, and once in a while fall back to direct computation of sin and cos (or cexp).

Of course, if your compiler doesn't support complex type, you's have to implement complex multiplication manually.

Another optimization comes from the inherent symmetry of the table, e.g. \$cos\frac{2\pi k}{N} = \cos\frac{2\pi (N - k)}{N}\$, so you only need to compute half of the table; there are more symmetries you may exploit.

PS: That said, I strongly recommend to precompute it once for largest possible N. Notice that it can be reused for any power of 2.


Correctness of a minimal parallel workers queue in Ruby

Like @Victor Moroz, I'm also a fan of Queue.  I also prefer to keep the threads around: it's a bit more efficient, but more important, the code is simpler:

require 'thread'

class ParallelWorkersQueue

  def initialize(slots)
    @work = Queue.new
    @threads = slots.times.map do
      Thread.new do
        while (work = @work.deq) != :stop
          work[]
        end
      end
    end
  end

  def join
    @threads.each do
      @work.enq(:stop)
    end
    @threads.each(&:join)
  end

  def push(&task)
    @work.enq(task)
  end

end

Example of its use:

pwq = ParallelWorkersQueue.new(2)
5.times do |i|
  pwq.push do
    puts i
  end
end
pwq.join

# => 0
# => 1
# => 2
# => 3
# => 4

Replace Queue with SizedQueue if you wish to limit the amount of work that can be awaiting a worker thread.


PHP test isset and instantiate in one shot. Possible in PHP?

By reading the manual:

  Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

So in short:

$nid = $_GET['nid'] ?: 0;

Would work, but PHP will trigger a notice if $_GET['nid'] is not set. The logic || operator won't help, either. The closest you can get is:

(($nid = $_GET['nid']) || ($nid = o));

But that's not exactly shorter, nor does it solve the Notice issue.
The "best" as in shortest, moste un-maintainable and horrible looking code I can think of is this:

$nid = 0;//default
foreach($_GET as $name => $val)
{
    $$name = $val;
}
var_dump($nid);

This turns all keys that were present in the $_GET array into var names. If you simply declare the vars you're after (names must be identical to keys, though) and assign them a default value, this loop takes care of the rest.
To map certain keys to another variable name, you could use another array:

$nid = 0;
$map = array('new_id' => 'nid');
foreach($_GET as $k => $v)
{
    if (isset($map[$k]))
    {
        $k = $map[$k];
    }
    $$k = $v;
}

But honestly, maintaining code like this is going to be a nightmare. Though request objects add a lot of overhead for a task as simple as this, their get methods make it all worth while:

public function get($name, $default = null)
{
    if (!isset($_GET[$name]))
    {
        return $default;
    }
    return $_GET[$name];
}

This is easy to read/understand and easy to use:

$nid = $getInstance->get('nid', 0);

Assignes the GET param, or 0 to $nid... which makes your code tidier, easier to maintain and a lot easier to understand. Based on the use-case you posted, I take it you're not using the ternary on just request variables. Well, in that case: use objects with getters/setters that define a default return value (or allow for one to be specified @call-time). If needs must, implement the ArrayAccess or some Traversable interface, so you can use it as an array, too.
Granted, it'll take some time/effort to do this, but once you've done that, any new code you write will be cleaner (no ternaries), debugging will be a doddle and type-hinting will become your best friend. check this answer for some examples and considerations on getters and setters, along with this answer on the importance of pre-declaring properties (and thus implementing getters/setters).

If you're still up for it after that, refer to this answer to see why and how you should avoid object overloading (in PHP, at least) as much as possible.


Data Handling & Security

You use prepared statements, which protects you from SQL injection, which is good. However, the way you handle passwords could be improved to increase security.

It's not a good idea to semi-randomly apply sanitation functions to user input as it results in dirty data.

stripslashes for example really only makes sense when magic quotes is enabled, so you should check that first (and then only strip the slashes in some init file, not every time you access GET). For example, if a user has a password like this: a\'b\\c\'d, stripping slashes reduces the password length from 9 to 6 characters.

Same problem with strip_tags, only much worse. If my password is a<super$secure!password, now my password is a.

You also don't need strip_tags. As XSS protection it's not sufficient anyways (and definitely not needed for passwords, which aren't echoed); You should HTML-encode data when echoing it instead.

There's also really no need to have a length restriction on the password, especially not one that is shorter than what your hashing algorithm allows.

Hashing

Simple sha is really not good enough anymore, as it's too fast. Use bcrypt instead.

Error Handling

Don't echo database error messages directly to the enduser. They won't know what to do with it, and it may provide attackers with information or enable some forms of attacks (such as error based SQL injection).

It's also not a good idea to echo anything in a function, as side-effects like that make it harder to reuse.

Structure

I think your structure is pretty clean, and your code easy to read. Just a couple of small points:

storeFormValues doesn't seem to have any purpose. I wouldn't call the constructor inside a function of the same class, but just use it directly.

I would also not pass a magic array to the constructor, as it's hard to use and reuse (I have to guess how the array must be build and what it must contain, and I have to use the pre-defined array keys).

Instead, just change your constructor to __construct($username, $password). This increases clarity and reduces future bugs.

Misc

remove unused variables such as $correct.
comments such as //store the parameters are not really needed as they don't add any information.
same things should be named in the same way to avoid confusion. For example, registering and logging in are quite similar. But the names userLogin and register are constructed differently. Just use login and register.


Optimal way of skipping certain values in a for loop

Tests across various browser has shown a reverse while loop is fastest.
Accessing array.length is slower than storing it in a variable to iterate on.
You can just "push" to an array by storing the value in the last element which is conveniently at .length
A switch may not be much faster in this case (though it can be with other data) than a bunch of &&s and ||s, but its much easier to read and the fallthrough characteristic allows you to write like code in groupings.  In this case we only have 2 groups: do nothing (break;) and the default "push"

For example:

var i=arr.length;
var newarr=[];
while (i--){
  switch (arr[i].key){
    case 'ContentType' :
    case 'FileRef' :
    case (other) :
    case (cases) :
    case (here) :
    break;
    default: newarr[newarr.length]=arr[i];
  }
}

On a few newer browsers (Chrome for one), push is faster than direct assignment.  Note that this will be reversed from the original array, but if you need to keep them in the same order using for(var i=0,len=arr.length;i<len;i++), I caution you not to be tempted to use newarr[i]=arr[i] or you will get empty slots where your keys match your blacklist.


You are trying to iterate over all numbers and check if each is prime which you do in O(n sqrt n) time. This might be feasible if you switch to a more efficient primality check, such as the Miller-Rabin primality test, as it is deterministic within certain limits depending on the probes.

A simpler way to do this is to generate primes until you are done. This can easily be done by the Sieve of Eratosthenes in roughly O(n log log n) time.

You can run the sieve once, get all the primes up to 175000 (15000th prime is 163841 according to a bit of googling) and then answer all the queries in constant time by dumping all the primes into an ArrayList (in order of course).

If those methods aren't fast enough, look into even faster sieving algorithms such as Sieve of Sundaram and Sieve of Atkin.


Project Euler #4 in C++: largest palindrome product of two 3-digit numbers

Excessive spacing and main()

To start with, 4-space tabs please. 8 is tooooo much, you're using up all the horizontal space!

Additionally, return 0; from main() is optional. If you omit it, the compiler will provide it for you - so you don't have to write it.

isPalindrome()

This function doesn't modify its input - you take a copy, reverse it, and then compare the two. But actually you're making two copies of the input - one into num and the other into oldnum. If you took the argument by reference-to-const, you save yourself a copy for free:

bool isPalindrome(std::string const& num) { .. }

Additionally, the argument should probably be named oldnum - since that's the one that doesn't change.

Avoid code that looks like: if (expr) return true; else return false; That's an extremely verbose way of writing return expr; Altogether, this becomes:

bool isPalindrome(std::string const& oldnum) {
    std::string revnum = oldnum;
    std::reverse(revnum.begin(), revnum.end());
    return oldnum == revnum;
}

However, this is pretty inefficient - we have to make another copy of oldnum just to check if it's reversible? We can do that directly in one go. Just compare the ith element to the N-ith element and make sure they all line up:

bool isPalindrome(std::string const& num) {
    for (size_t i = 0; i < num.size()/2; ++i) {
        if (num[i] != num[num.size()-i-1]) {
            return false;
        }
    }

    // still here? must be a palindrome
    return true;
}

This saves you a copy, so will be quite a bit faster.

findLargestProduct()

There is undefined behavior here. When you write:

int largest, prod = 0;

That isn't initializing largest, only prod. Which is unfortunate since it's only largest that needs to be initialized. Avoid this kind of multiple initialization, and simply do:

int largest = 0;

prod you can simply declare inside the inner-most loop.

Now, the slowest part of this function is isPalindrome(). That's an expensive operation to do - so we want to do it as rarely as possible! As an optimization, we can check if prod > largest first - so you avoid the expensive logic in all the cases where the outcome doesn't matter. If the product isn't the new max, who cares, right? That is:

int prod = i*j;
if (prod > largest && isPalindrome(std::to_string(prod))) {
    largest = prod;
}

Once we're there, let's really make sure we never have to do it by iterating in the opposite order:

for (int i=999; i>=100; --i) {
    for (int j=999; j>=100; --j) {
        ...
    }
}

Math is cool

Assuming the answer will be 6 digits (seems safe), we know it's divisible by 11. We know this because the digits of the number will be \$abccba\$, and the handy rule for checking divisibility by 11 is to sum the even digits and the odd digits and check if the difference is divisible by 11 - and both the even digits (\$b+c+a\$) and the odd digits (\$a+c+b\$) have the same sum. Since we know it's divisible by 11, we know one of the factors must be divisible by 11. Let's pick j. This let's us reduce the loop to:

for (int i=999; i>=100; --i) {
    for (int j=990; j>=100; j-=11) { // largest 3-digit multiple of 11
       ...
    }
}

Breakdown of timing

Here's a breakdown of all the things I just suggested:

as-is                  171.5ms
better isPalindrome    138.0ms
flip ordering            9.9ms
iterate backwards        4.8ms
count by 11s             0.2ms