As far as method chaining goes, this is neatly implemented.

You've swapped To and From, the method names are inverted. I assume that's just a typo.

public MailManager To(string address)
{
    _mail.From = new MailAddress(address);
    return this;
}

public MailManager From(string address)
{
    _mail.To.Add(new MailAddress(address));
    return this;
}

As it currently stands, I don't think method chaining is really needed here. Every method operates as a basic property setter, which can be handled by using public properties.

This is a matter of preference; but in C# I'd be more inclined to use public properties as opposed to methods.
In the past, all we had was fields and methods. When the tiniest amount of logic was needed to set a field value, we had to rely on methods. Properties were added as a compromise: they are used for setting field values, but you're able to add some minor logic (within reason).

Simple string values can be handled by basic properties:

public string Subject
{
    get { return _mail.Subject; }
    set { _mail.Subject = value; }
}

Note: This example directly sets the value of _mail.Subject. Personally, I'd prefer to not use _mail until the Send() was triggered (and store the values in properties until then), but that may be too subjective for a review.

Your current To() method somewhat conceals the fact that you can add more than one recipient. It doesn't suggest that you're adding to a list. Using a property, this is slightly easier to understand:

public List<string> To { get; set; }

You can cast these into the appropriate MailAddress object and add it to _mail inside the Send() method:

_mail.To.AddRange(this.To.Select(s => new MailAddress(s));

An example of how you'd use a property-based approach:

var mailManager = new MailManager() {
    From = _emailSettings.Email,
    To = new List<string>() { item.Email },
    Subject = string.Format(_emailSettings.Subject, item.Name),
    Body = body,
    IsBodyHtml = true,
    Host = _emailSettings.Domain,
    Port = _emailSettings.Port,
    Credentials =new NetworkCredential(_emailSettings.Email, _emailSettings.Password),
    EnableSsl = true
};

mailManager.Send();

Note: You can also inline everything, i.e; (new MailManager() { ... }).Send();.

Note: I set the property values in the property initializer. You're not required to do so, you can also just store the MailManager in a variable and set its properties when you want to at a later stage (but obviously before calling Send()).

  Should you avoid method chaining?
  No. You wanted to use it, and you used it in a good way. I'm just trying to offer you an alternative which requires less code to achieve the same result.

  If you were implementing method chaining in a class where there is a lot of business logic involved when a method gets calls, then method chaining becomes the preferred approach.
  For the current MailManager class, I find that it doesn't have enough business logic to warrant method chaining just yet. But it's not particularly wrong to do so, just a bit more cumbersome (in my opinion).

Some minor nitpicks:

If you're going to use method chaining to simplify the syntax, it seems consistent to change the Credentials method to take two strings (email,password) instead of a NetworkCredential, or at least create two overloaded methods to allow for either option. Credentials(_emailSettings.Email, _emailSettings.Password) is nicer to read than Credentials(new NetworkCredential(_emailSettings.Email, _emailSettings.Password))
IsBodyHtml() Based on its name, this should be a method that returns a boolean, instead of setting a boolean. A better name would be SetBodyHtml()
AlternateViews(AlternateView alternateView) should really be called AddAlternateView(AlternateView alternateView)
Similarly, To really should be called AddRecipient, since calling the method adds a second value instead of overwriting the first value.

I chose AddRecipient instead of AddTo to avoid semantical confusion between "Add a To-recipient" and "Add this to that".

I would personally change EnableSsl(bool enableSsl = true), though I can see argument for why you used your version.

UseSsl(bool useSsl = true)
EnableSsl() and DisableSsl()


Naming

Java has a Naming Conventions that you currently don't follow.

int Capacity = 10;
int Volume = 0;

You should have : Capacity -> capacity and Volume -> volume. I really suggest you to read the convention when you learn a language. It helps readers to quickly scan your code.

Visibility

Currently, your fields in your class are package private, which mean that every class in your package can access your fields. I recommend to use private for fields in your classes, until you determine that you need something else.

You really want to have the minimum scope for you variable.

Initialization

You're doing your initalization two times. First when you declare Book[] storage = new Book[10]; you create an array of 10 books with it. Next in your constructor, you do: this.storage = new Book[10];. This does the same thing as previously so you should delete one of them.

Magic values

Magic values are constant that are not named but used directly in the code. In your case you have a default size for your library, but it's hard-coded. You could have a : private static final int DEFAULT_SIZE = 10. That would make it make clear what it used for.

Brackets and code block

I prefer to always use bracket in code block, I find it easier to read, less prone to bugs when you change add lines of code and there is less changes when you actually change it (think for source control like Git).

} else if (this.Volume >= this.Capacity) System.out.println("The library is full!");

Should be

} else if (this.Volume >= this.Capacity) {
    System.out.println("The library is full!");
}

For each loops

This is something you really want to use a lot. They exist in a lot of language and will make it easier to read when you loop over a collection and want to access each object. When you don't need to know where in the collection your are (the index), prefer using for-each.

So instead of :

for (int i = 0; i < this.Volume; i++) {
            if (title.equals(this.storage[i].toString())) {
                System.out.println("The book with the title " + title + " exists in the library!");
                return this.storage[i];
            }
        }

You would have :

for (Book book : this.storage) {
   if( book == null) {
        System.out.println("The book with the title " + title + " does not exist in the library!");
        return null;
   }
   if (title.equals(book.toString())) {
      System.out.println("The book with the title " + title + " exists in the library!");
      return book;
   }
}

Someone point me out in comments that there was a bug with my original for-each loop. Now that I fixed it, it is really less elegant. There will be duplication and a new corner case added to the method. This stuff make the method more complicated than not. This is partly because you have an array[] instead of something like and ArrayList (always use List the interface if you use ArrayList). This has already been covered in other answers, so if you change to a more dynamic structure use for-each, if not then continue using your for loop but keep in mind that for-each exist.


A few changes:

Strings shouldn't be used here for keeping track of comparison results. Strings are prone to being typo'd, and may lead to unexpected results (like indexing result causing KeyErrors at runtime). I'd take a page from Java (and other languages) and use -1, 0 and 1 to indicate the results of a comparison. You can see it being used in an answer here. I'd make the following changes:

result = {1: [], # Increasing
          0: [], # Equal
          -1: [] # Decreasing
          }

def two_item_relation(prev, curr):
    if prev < curr:
        return 1
    elif prev == curr:
        return 0
    else:
        return -1

It's much harder to mistype -1 than it is, for example, "decreasing".

If you really wanted Strings for pretty printing purposes (like for your output at the bottom), you could maintain a dictionary mapping comparison numbers to strings:

pp_result = {1: "Increasing",
             0: "Equal",
             -1: "Decreasing"
            }

The point is that you shouldn't use easily mistyped things as keys unless necessary.

Strings also may be slower to compare, and may take more memory, but hash caching and String interning may negate those problems in some cases.

You could also write that function as something like:

def two_item_relation(prev, curr):
    return 1 if prev < curr else \
                0 if prev == curr else \
                    -1

But I'm probably going to get yelled at for even bringing that up. Conditional expressions/ternaries are nice in many cases when you want to conditionally return one or another thing, but they get a little murky as soon as you're using them to decide between three different things. It's especially bad here because this pretty much needs to be split over a few lines, which necessitates the use of line continuation characters, which are a little noisy.

I'm bringing it up in case you're unaware of conditional expressions, not because I'm necessarily suggesting their use here.

You could use enums as well:

from enum import Enum

class Compare_Result(Enum):
    INCREASING = 1
    EQUAL = 0
    DECREASING = -1

def two_item_relation(prev, curr):
    if prev < curr:
        return Compare_Result.INCREASING
    elif prev == curr:
        return Compare_Result.EQUAL
    else:
        return Compare_Result.DECREASING

This has the benefit that it makes it obvious what each result actually means. They also prints out semi-nicely, so the "pretty-printing map" may not be as necessary:

>>> str(Compare_Result.INCREASING)
'Compare_Result.INCREASING'

>>> repr(Compare_Result.INCREASING)
'<Compare_Result.INCREASING: 1>'

And, if you do typo a name (which is harder to do since IDEs can autocomplete Compare_Result.), it will fail outright with an error:

>>> Compare_Result.INCRESING

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    Compare_Result.INCRESING
  File "C:\Users\slomi\AppData\Local\Programs\Python\Python36-32\lib\enum.py", line 324, in __getattr__
    raise AttributeError(name) from None
AttributeError: INCRESING

Unfortunately though, this error does not happen immediately like it does in other languages. The faulty code needs to actually be interpreted before the error is caught. This seems to make enums less useful in Python than in languages like Java or C++, but it's still less error-prone than using Strings or Numbers.

Honestly, I'm too tired right now to comment on the algorithm, but hopefully this was helpful.


The biggest problem with this code is that you are using functions as glorified GOTO labels, when choice() is called from within choice, when choice() is called from play, and when choice() is called initially.  If you hit CtrlC after a few rounds, you'll see that the call stack is inappropriately deep.  The remedy is to use functions, return values, and loops properly.

The other change I would suggest is removing the redundancy between the choices list and the win_table.

import random

MOVES = {
    'rock': {'rock':'It was a Tie', 'paper':'You Lose', 'scissors':'You Win'},
    'paper': {'rock':'You Win', 'paper':'It was a Tie', 'scissors':'You Lose'},
    'scissors': {'rock':'You Lose', 'paper':'You Win', 'scissors':'It was a Tie'},
}

def choices():
    """Produce a tuple of the player's choice and the computer's choice."""
    while True:
        player_choice = raw_input('Choose rock, paper or scissors: ')
        if player_choice.lower() in MOVES:
            computer_choice = random.choice(MOVES.keys())
            return player_choice, computer_choice

def reveal(p_choice, c_choice):
    """Print both players' choices and the result of the game."""
    print 'Computer chose', c_choice
    print MOVES[p_choice][c_choice]

def play():
    """Play a round of rock-paper-scissors, then repeat if desired."""
    while True:
        reveal(*choices())
        if raw_input('Play again? (Y/N):  ').lower() != 'y':
            break
    print 'Have a nice day!'

play()

There isn't much benefit to having choices() produce both the player's choice and the computer's choice, though.  You should break that up into two functions.


Schema design for user profile management

Is this a good design?

No, not really.
Some of the tables are not well designed.
Take a look at the responsibilities of the users table and the media table.

The media table has one clear responsibility:
store the attributes of media items.
Every record is self-contained, complete.
You will probably never update the records in this table:
you will only insert or delete. That's nice and simple
The users table has two responsibilities:

Store the attributes of users
Store the relationship of users and other objects

Every record is only half-complete (user attributes),
to get the full picture you need to follow the references to other tables.
You will probably never update the records very frequently,
for setting the last status and location ids

It would be better to make the users table in charge of user attributes only.
You could add additional tables to track the relations with other objects.

The circular dependencies are especially ugly:

users depends on status for the last status, and status depends on users to associate all statuses with a user
Same for locations

I recommend this kind of structure:

user - in charge of user attributes (name, registered date)
status - in charge of status attributes (message, date)
user_status - in charge of linking user and status
user_last_status - in charge of linking user and last status, with unique key on user

And similarly for locations.
It's more work, but the end result will be more robust and flexible.

A reasonable compromise can be to not create user_status,
but include user_id in the status table (with a similar treatment for locations too).

  Select all users who belong to group and all groups created after that group.

To find users by a given group id fast,
you need an index on the group id column in the users table.
Below I explain how to create foreign keys.
When you make user.group_id a foreign key referencing group.group_id,
creating such index is one of the steps,
and will ensure fast lookups.

In addition,
you might also find a group fast by name.
In that case you might want to create an index on group.name column.
However, if you won't have many groups than that would be overkill,
and not recommended by the documentation.

  Select all users with last message, status, location and media URLs included.

Generally speaking, For good performance of queries like this,
you want to make sure that all fields used in the WHERE and JOIN clauses are indexed.
If you follow my suggestions,
this will be automatically the case for most of these elements you mention,
and for the rest you can probably figure out yourself.

Another issue with the design is that some of the fields are not clear enough, for example:

users

userid: it would be good to know if this will be a technical id or a something like a UNIX username. If the latter, I'd rename to username
name: NULL is allowed, but why?
lmessage: an integer field, but not clear which other table it will reference
registered: I suppose the date when the user was created. I recommend using the type datetime, even if internally it might be just an integer

locations

serial: technical id I suppose?
locationid: text? That's a bit surprising. How is it different from serial?
time: perhaps there can be a better name for this. And again, I recommend using the type datetime

status: similar objections as with locations
messages

sno: technical id I suppose? I recommend to standardize the name of technical ids in all tables
sender, receiver: I'm wondering if these have any relation to other tables

media: this is good and clear. The UNIQUE keyword on mediaid is pointless when you add a PRIMARY KEY constraint on the same column

The answers to the questions I raised would be good in comments.
Some example values for the columns would be useful too,
especially for the ones where the meaning and motivation is not obvious.

Declare PRIMARY KEY on the field's line

Instead of declaring PRIMARY KEY at the end,
it's more compact to declare it on the field itself, like this:

CREATE TABLE IF NOT EXISTS locations
  (
     serial INTEGER NOT NULL PRIMARY KEY,
     -- ...
  );

I also added NOT NULL for the field, though it's not strictly necessary.
When a field is primary key in sqlite,
it's treated as auto-incrementing,
so even if you try to explicitly insert NULL into it,
it will actually use max(col) + 1 instead.
But I like to write it this way anyway to make it explicit:
looking at this schema there will be no doubt that the field will never contain NULL.

Pointless unique indexes

Many of the indexes you're adding seem completely pointless:

CREATE UNIQUE INDEX IF NOT EXISTS id_unique ON users (userid ASC);

CREATE UNIQUE INDEX IF NOT EXISTS serial_unique ON status (serial ASC);

CREATE UNIQUE INDEX IF NOT EXISTS id_unique ON messages (sno ASC);

CREATE UNIQUE INDEX IF NOT EXISTS mediaid_unique ON media (mediaid ASC);

In all these commands, the target fields are already marked as PRIMARY KEY,
so adding a unique index will do absolutely nothing.

From the docs:

  In most cases, UNIQUE and PRIMARY KEY constraints are implemented by
  creating a unique index in the database. (The exceptions are INTEGER
  PRIMARY KEY and PRIMARY KEYs on WITHOUT ROWID tables.) Hence, the
  following schemas are logically equivalent:

CREATE TABLE t1(a, b UNIQUE);

CREATE TABLE t1(a, b PRIMARY KEY);

CREATE TABLE t1(a, b);
CREATE UNIQUE INDEX t1b ON t1(b);

There is one more unique index in your post:

CREATE UNIQUE INDEX IF NOT EXISTS serial_unique ON patterns (serial DESC);

But the schema of the patterns table is not in your post.
Curiously, this unique index uses the DESC keyword,
which would set it apart from the other examples which all used the default ASC.
In this case, I'm wondering what difference this will make on a table where the target column is already a primary key.
That might be an interesting question on stackoverflow.com

Although in this case it seems the unique indexes are redundant and can be removed,
if ever you need to make a column unique,
I recommend declaring UNIQUE on the column's line when creating the table,
like this:

CREATE TABLE IF NOT EXISTS status
  (
     serial INTEGER NOT NULL PRIMARY KEY,
     userid TEXT NULL UNIQUE,
     -- ...
  );

Or else,
if you really want to use a unique index with DESC sorting order,
then create the index right after creating the table.
It's not a good idea to separate the declarations of tables and indexes like in your post. The indexes are closely tied to their tables,
and the code is most readable when dependent elements are closed to each other.

Also keep in mind that only versions of SQLite 3.3.0 understand indexes with descending sorting order.

Use foreign keys

It seems you wanted to use foreign keys just didn't know how :)
Here's an example:

CREATE TABLE IF NOT EXISTS users
  (
     userid     TEXT NOT NULL PRIMARY KEY,
     locationid INTEGER NULL REFERENCES locations (locationid)
  );

CREATE TABLE IF NOT EXISTS locations
  (
     serial INTEGER NOT NULL PRIMARY KEY,
     locationid TEXT NOT NULL UNIQUE,
  );

CREATE INDEX users_location_index ON users(locationid);

Notice the UNIQUE constraint on the referenced column:
this is a requirement of foreign keys.
(For more details, see the docs.)

Lastly, notice the index on users.locationid.
Although not required, this is recommended by the docs.

Indicate the column sizes

Although SQLite understands and ignores VARCHAR(N),
treating it as TEXT,
I recommend to use VARCHAR(N) anyway for non-text fields.
This is to indicate your design intentions.
It will also make it easier to port your schema to other databases in the future.
To be safe, add a comment to remind that SQLite doesn't enforce the specified sizes.

Naming and style

I recommend using id column names like user_id, status_id instead of userid and statusid because this seems a common practice.

I would borrow some ideas from Django:

Use singular instead of plural for table names: for example user instead of users
Use id as the auto-incrementing technical id field consistently in all tables
Very cosmetic thing but anyway: write SQL types like INTEGER and TEXT using lowercase letters


Redefining \v and \i is a bad thing. Don't, you'll regret it as soon as you want to need to cite a paper by Eduard Čech or by Erdal Arıkan.

You also have quite an inefficient usage of xstring and no error checking if a _ is forgotten.

Here's a complete implementation with xparse:

\documentclass{article}

\usepackage{xparse}

\NewDocumentCommand{\ind}{me{_}}{%
  \IfNoValueTF{#2}{\doind{#1}{???}}{\doind{#1}{#2}}
}

\ExplSyntaxOn
\NewDocumentCommand{\doind}{mm}
 {
  \tl_if_single:nTF { #1 }
   {% a single character
    \str_if_eq_x:nnTF { #1 } { \str_upper_case:n { #1 } }
     {% upper case, assume matrix
      \lyndon_index_matrix:nn { #1 } { #2 }
     }
     {
      \lyndon_index_do:nn { #1 } { #2 }
     }
   }
   {% not a single character
    \lyndon_index_do:nn { #1 } { #2 }
   }
 }

\cs_new_protected:Nn \lyndon_index_matrix:nn
 {
  \int_compare:nTF { \clist_count:n { #2 } > 1 }
   {% Got multiple indexes so all good
    \lyndon_index_do:nn { #1 } { #2 }
   }
   {% Only one index so grab the column
    \lyndon_index_do:nn { #1 } { {:},#2 }
   }
 }
\cs_new_protected:Nn \lyndon_index_do:nn
 {
  #1\sb{#2}
 }
\ExplSyntaxOff

% Example document
\begin{document}

\begin{tabular}{r l}
$\ind{A}$           & missing subscript\\
$\ind{\tilde{x}}_i$ & the $i$th element of the vector $\tilde{x}$\\
$\ind{X}_{i,j}$     & the row $i$ and column $j$ element of the matrix $X$\\
$\ind{X}_i$         & the $i$th column vector of the matrix $X$\\
$\ind{X}_{i,:}$     & the $i$th row vector of the matrix $X$\\
\end{tabular}

\end{document}

On the other hand, I see no much gain in using _ and also in doing checks for uppercase letters, which is quite limiting. I'd prefer a * version for vectors.

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand{\ind}{smm}
 {
  \IfBooleanTF{#1}
   {% *, a vector
    \lyndon_index_do:nn { #2 } { #3 }
   }
   {% normal, a matrix
    \lyndon_index_matrix:nn { #2 } { #3 }
   }
 }
\cs_new_protected:Nn \lyndon_index_matrix:nn
 {
  \int_compare:nTF { \clist_count:n { #2 } > 1 }
   {% Got multiple indexes so all good
    \lyndon_index_do:nn { #1 } { #2 }
   }
   {% Only one index so grab the column
    \lyndon_index_do:nn { #1 } { {:},#2 }
   }
 }
\cs_new_protected:Nn \lyndon_index_do:nn
 {
  #1\sb{#2}
 }

\ExplSyntaxOff

% Example document
\begin{document}

\begin{tabular}{r l}
$\ind*{\tilde{x}}{i}$ & the $i$th element of the vector $\tilde{x}$\\
$\ind{X}{i,j}$        & the row $i$ and column $j$ element of the matrix $X$\\
$\ind{X}{i}$          & the $i$th column vector of the matrix $X$\\
$\ind{X}{i,:}$        & the $i$th row vector of the matrix $X$\\
$\ind{\Gamma}{j}$     & Greek matrix
\end{tabular}

\end{document}


Build List from unshared items from two other Lists

The operation is called the symmetric difference of List1 and List2.  You can write

return list1.Except(list2).Union(list2.Except(list1)).ToList<string>();


Shuffling and hiding views specified by parameters

A few things that could be improved:

You have quite a lot of empty white lines, and extraneous space:

return {

    galleryVideoShow : function () {

        //closing others
        $scope.contractorShow = false;
        $scope.galleryPhotoShow = false;
    },

    contractorShow : function () {

    // ...

This block, for example, without extraneous whitespace, would look like:

return {
    galleryVideoShow: function(){
        $scope.contractorShow,
        $scope.galleryPhotoShow = false;
    },
    contractorShow: function(){

    //...

        var hideGallery = (function (type) {

            return {

                galleryVideoShow : function () {

                    //closing others
                    $scope.contractorShow = false;
                    $scope.galleryPhotoShow = false;
                },

                contractorShow : function () {
                    //closing others
                    $scope.galleryPhotoShow = false;
                    $scope.galleryVideoShow = false;

                },

                galleryPhotoShow : function () {

                   //closing others
                    $scope.contractorShow = false;
                    $scope.galleryVideoShow = false;

                }

            }

        })();

There's no reason to assign hideGallery like that.

It'd be better as a plain object.

var hideGallery = {
        galleryVideoShow: function(){
            //closing others
            $scope.contractorShow,
            $scope.galleryPhotoShow = false;
        },
        contractorShow: function(){
            $scope.galleryPhotoShow,
            $scope.galleryVideoShow = false;
        },
        galleryPhotoShow: function(){
            $scope.contractorShow,
            $scope.galleryVideoShow = false;
        }
}

Which would be better called something like GALLERY_EFFECTS, and kept as a constant.

Also note that for each function in hideGallery, the comment //closing others was present, it's only part of what the functions do, and would be better off at the root of hideGallery in a more expanded version.

       $scope.$watch('viewProjectInfo', function ( newValue, oldValue ) {

            if(!newValue) return;

            $scope.photos = $scope.viewProjectInfo.ImagePaths;

            $scope[GalleryType] = !$scope[GalleryType];
            $scope.shownGallery =  GalleryType;

            hideGallery[GalleryType](); //manually close other open gallery

            $('html, body').animate({scrollTop:$(document).height()}, 'slow');

        });

    };

Why are there so many empty lines at the bottom? (six, I counted) They just look poorly formatted, or like missing code.
You should wrap your conditionals in brackets, because untold circumstances can happen.
You should spread the .animate call over a multiple lines, as you're building an object inside the function call.

   $scope.$watch('viewProjectInfo', function(newValue, oldValue){
       if (!newValue){ return };
       $scope.photos = $scope.viewProjectInfo.ImagePaths;

       $scope[GalleryType] = !$scope[GalleryType];
       $scope.shownGallery = GalleryType;

       hideGallery[GalleryType]();

       $('html, body').animate({
           scrollTop: $(document).height()
       }, 'slow');
   });


Function that strips trailing '0's from a float

My thoughts are as follows:

Since you are leveraging snprintf, you have already limited the string size to buffer_size, so the additional condition in the while loop should not be needed.
Since there is no validation, I'm assuming the data has been validated before and that the value will never exceed buffer_size with, which allows for the following simplification:

int float_to_str(float f, char *output, int buffer_size)
{
    int buf_len = snprintf(output, buffer_size, "%0.5f", f);
    if(buf_len>buffer_size) return -1 ; // updated to add validation
    //Strip trailing '0's from response
    while (buf_len>0)
    {
        if (output[buf_len-1] == '0') // is the last char a zero?
        {
            output[buf_len-1]=0;  // null terminate the string
            buf_len--;
        }
        else break;  // if this is not a zero, we are either at the . or a non zero digit
    }
    return buf_len;
}

I'm not sure your code will return the correct result if the input is 300.00014, my initial thought is your output would be 300.00.


I'm not familiar with MR best practices, but here are some JS-specific comments.

Key Points

DRY - that emit code is repeated all over the place and has only slight changes - parameterize what varies and put it all in a function
You are repeating your loops - either do everything in one loop for better performance (and keep in mind that for is faster than forEach, or go fully functional (see next)
You are essentially doing a filter within your loop - use filter to remove the if logic from within the loop (or see previous). If you want to go even more functional, maybe you should use underscorejs or lo-dash, which both have a unique function already.
Never change the prototype of a builtin unless you have already checked if the method exists (like a polyfill) and/or you have a really, really good reason to do so. Mostly, just don't.
Declare functions so that they are not re-created (unless necessary)
You should probably close your db connection ASAP
Oh, and name your inline functions to provide better documentation

A simple refactoring hosted as a gist for easy forking

function getUnique() {
    var u = {}, a = [];
    for (var i = 0, l = this.length; i < l; ++i) {
        if (u.hasOwnProperty(this[i])) {
            continue;
        }
        a.push(this[i]);
        u[this[i]] = 1;
    }
    return a;
};
function emitHelper(kind, shop, tag) {
    emit(shop, {
        "kind": kind,
        "tag": tag,
    });
};
db.customers.mapReduce(
    function mapCustomerToShopWithKindAndTag() {
        var customer = this;
        var kind;
        getUnique(this.tags).forEach(function(tag) {
            kind = customer.status ? "unique_customers_submitted" : "unique_customers_withheld";
            emitHelper(kind, customer.shop, tag.tag);
            emitHelper("unique_customers_total", customer.shop, tag.tag);
        });
        this.tags.forEach(function(tag) {
            kind = customer.status ? "total_customers_submitted" : "total_customers_withheld";
            emitHelper(kind, customer.shop, tag.tag);
            emitHelper("total_customers_total", customer.shop, tag.tag);
        });
    },
    function reduceToCountOfKindsPerTag(key, sets) {
        var forms = {};
        sets.forEach(function(set) {
            if (typeof forms[set.tag] == "undefined") forms[set.tag] = {};
            if (typeof forms[set.tag][set.kind] == "undefined") forms[set.tag][set.kind] = 0;
            forms[set.tag][set.kind] += 1;
        });
        return forms;
    }, {
        out: "form_numbers",
    },
    function(err, results) {
        console.log(err);
        //console.log(results);
        results.find().toArray(function(err, numbers) {
            db.server.close(); // Maybe wrap in a try/catch too
            console.log(err);
            console.log(JSON.stringify(numbers));
        });
    }
);


mIRC scripting like string token manipulation in Lua

You don't need to use tostring inside string.match or other methods provided by string meta-table.
I'd suggest allowing users to pass the character as well as ASCII-code for the separator. This is of course, you own choice and nothing needs to be done in the code to enforce this.
The following loop:

for i = 1, #tokens do
    if (i == n) then result = tokens[i] end
end

is entirely useless and can be replaced with result = tokens[n].
I do not understand your reasons behind the following conversion:

w = tonumber(w) or tostring(w)

w will be type string by default.
You can use table.concat effectively; instead of creating string buffers.
Instead of writing long winded if-else blocks, put the smaller blocks forward and return results as soon as you arrive at one.
In lua, you do not necessarily need to put the if-conditions inside parentheses.
What does a negative range imply? I tested your function with gettok(text, -3, 46, -2) expecting cherry.grape as output, instead; I received banana.cherry.
For your start and stop values, use math.max and math.min.

The rewritten code follows. Please note that I've used my own convention of variable naming.

local function Tokenize( sChar, sInput )
    local tReturn = {}
    for sWord in string.gmatch( sInput, "[^"..sChar.."]+" ) do
        table.insert( tReturn, tonumber(sWord) or sWord )
    end
    return tReturn
end

local function GetTok( sInput, iPosition, Separator, iRange )
    local Separator = string.format( '%c', Separator )
    local tTokens = Tokenize( Separator, sInput )
    if iPosition == 0 then
        return sInput
    end
    local iStart, iStop = ( iPosition > 0 ) and iPosition or ( #tTokens + iPosition + 1 )
    if not iRange or iPosition == iRange then
        return tTokens[ iStart ]
    end
    if iRange > 0 then
        iStop = iRange
    elseif iRange == 0 or ( iStart + iRange ) > #tTokens then
        iStop = #tTokens
    else
        iStop = iStart + iRange + 1
    end
    if iStart == iStop then
        return tTokens[ iStart ]
    end
    if iStart > iStop then
        iStart, iStop = iStop, iStart
    end
    return table.concat( tTokens, Separator, iStart, iStop )
end


Add 100 to all values in nested dictionary

If you're using both keys and values from a dictionary, then using the items method:

... for key, val in dct.items() ...

is neater than iterating over the keys and including dct[key] everywhere. In Python 2.7+, you can use a dictionary comprehension (see e.g. the tutorial) rather than pass a list comprehension to dict:

dict_data = {key: {key_: val_+100 for key_, val_ in val.items()}
             for key, val in dict_data.items()}

Note that using key, val and the _ versions also makes it clearer what's happening than x and y.


More elegant Sass @mixin to create pseudo-element shapes

Refactoring

You can DRY this up a bit by taking advantage of lists and the zip function.

@mixin triangle($dir, $color, $size, $leg1: $size, $leg2: $leg1) {
    $sides:
        0,
        $leg1 solid transparent,
        $size solid $color,
        $leg2 solid transparent;

    $order:
        ( top: top right bottom left
        , right: right bottom left top
        , bottom: bottom right top left
        , left: left bottom right top);

    $x: zip(map-get($order, $dir), $sides);

    border: {
        @each $p, $s in $x {
            #{$p}: $s;
        }
    }
}

Misc.

Avoid using abbreviated variable names like $clr.  It might seem obvious to you that it's short for color, but I have a product sitting under my sink called CLR.  I had to read the mixin's code in order for me to discern what it was supposed to be for.

I've modified the argument order here and added some defaults so that you only have to give 1 piece of size information if you want an equilateral triangle, 2 pieces will give you an isosceles.  You probably don't really need that last argument, but I threw it in anyway.

Improving further

I don't have time at the moment to go into this, but things could further be improved by doing the following:

Specifying height/width rather than the desired border width
Using shorthand

You can see what I mean by looking over the results from a CSS triangle generator


Simple React component to show sorted articles

Date sorting Your dates are of the format YYYY-MM-DD. You currently sort them with:
(a, b) => b.date > a.date ? 1 : b.date === a.date ? 0 : -1

When you want to lexiographically compare strings to determine which comes first in the alphabet for sorting, you can do it more concisely with localeCompare, which returns a number indicating whether one string comes before, is the same as, or after another. You can use:
(a, b) => b.date.localeCompare(a.date);

articlesOrder's state relies on, essentially, magic strings:
const [articlesOrder, setArticlesOrder] = useState('byUpvotesDesc')

Since there are only two possible sorting methods, you might consider using a boolean instead:
const [orderByUpvotes, setOrderByUpvotes] = useState(true)

If there were more sorting methods, I would feel a bit more comfortable using an enum of sorts (or TypeScript to enforce string comparison safety) than comparing strings like articlesOrder === 'byUpvotesDesc' that need to match across multiple places in the code. For example:
const SORTING_OPTIONS = {
  byUpvotesDesc: 0,
  byDatesDesc: 1,
  // ...
};
// ...
const [articlesOrder, setArticlesOrder] = useState(SORTING_OPTIONS.byUpvotesDesc);

Another option would be to omit the articlesOrder variable entirely, and instead only sort the articles when a button is clicked (see below) - but if you want to expand on the component, keeping an articlesOrder variable will probably be useful to indicate to the user what the current sorting order is (for example, to give the top container a visual indicator of what option is currently selected).
Mutation You are mutating the prop when you do:
<Articles articles={articles.sort(articlesOrder === 'byUpvotesDesc' ? sortByUpvotesDesc : sortByDateDesc)} />

because .sort sorts in-place. Put the prop into state instead, and when a new sort order needs to occur, copy the array before sorting it so as not to mutate. Also, rather than .sorting every time the component is rendered, it would be better to sort only when the sort order changes. Here's one possible approach:
const sortByUpvotesDesc = (a, b) => b.upvotes - a.upvotes
const sortByDateDesc = (a, b) => b.date.localeCompare(a.date);

function App({ articles: articlesProp }) {
    const [articles, setArticles] = useState(articlesProp);
    const [articlesOrder, setArticlesOrder] = useState();

    const sortArticles = (callback) => {
        setArticles(
            articles => articles.slice().sort(callback)
        );
    };
    // The below could be made more abstract and DRY if there were more options
    // but with only two, it would probably be more confusing than useful
    const mostUpvotedClickHandler = () => {
        sortArticles(sortByUpvotesDesc);
        setArticlesOrder(SORTING_OPTIONS.byUpvotesDesc);
    };
    const mostRecentClickHandler = () => {
        sortArticles(sortByDateDesc);
        setArticlesOrder(SORTING_OPTIONS.byDatesDesc);
    };
    // Sort articles on initial mount, before they're rendered, to avoid reflow:
    useLayoutEffect(mostUpvotedClickHandler, []);

    return (

                Sort By
                <button onClick={mostUpvotedClickHandler} >Most Upvoted</button>
                <button onClick={mostRecentClickHandler} >Most Recent</button>

            <Articles articles={articles} />

    );
}

Semicolons Best to be consistent; either use semicolons or don't. If you're skilled and confident that you won't be bitten by the rules of ASI, you can omit them. Use a linter to enforce your desired style across your codebase.


Without changing your time too much I got these results:

Original run:

>>>
200 375 425
Product: 31875000
Time: 8.19322 seconds
>>>

New code:

>>>
200 375 425
Product: 31875000
Time: 0.28517 seconds
>>>

What I changed:

I moved the timing to completely surround the code, instead of when it hit the triplet.
I inlined the check for the triplet, as functions are slow in Python
Instead of generating a list for num, I used a range object straight up to generate them as needed
I eliminated the i loop and condition by using the fact that i will need to be 1000 - num - dig.

Resulting code:

import time

start = time.time()

for num in range(1, 1000):
    for dig in range(num, 1000 - num):
        i = 1000 - num - dig
        if num * num + dig * dig == i * i
            print(num, dig, i)
            print("Product: {}".format(num * dig * i))

elapsed = time.time() - start
print("Time: {:.5f} seconds".format(elapsed))

Fun fact: the check for a triplet in this case can be reduced to:

num * dig + 1000 * i == 500000

Where did I get these magic numbers you ask? Math. Check it out:

$$(\text{num}+ \text{dig}+ i)^2 = 1000^2$$
Expand:
$$\text{num}^2 + \text{dig}^2 + i^2 + 2 \; \text{num}  \; \text{dig}+ 2  \; \text{num}  \; i + 2  \; \text{dig}  \; i = 1000000$$
Use triplet equality:
$$2 i^2 + 2  \; \text{num}  \;  \text{dig}+ 2  \; \text{num}  \; i + 2  \; \text{dig}  \; i = 1000000$$

Factor:

$$i(\text{num}+ \text{dig}+ i) + \text{num} \; \text{dig}= 500000$$

Use fact that \$\text{num}+ \text{dig}+ i = 1000\$ in our case:

$$\text{num} \; \text{dig}+ 1000 i = 500000$$


Finding time complexity of my solution to the 'longest palindrome' problem in Python

Some thoughts on the long version only:

Use at least one linter like pycodestyle on your code to learn to write more idiomatic Python. This makes the code easier to read for other Python developers.
Most of the names are good (longestPalindrome), but

index, i and findcharIndex in a single method is very confusing,
the semantics of A, oList, j and Solution all have to be inferred from context which is mentally taxing, and
type suffixes like in remString are generally discouraged.

if foo then return true else return false should be replaced with simply return foo in any language.
Ideally your algorithm should not need the if(longestPalindrome == ""): check at the end - longestPalindrome should contain the longest palindrome by then.
Many @staticmethods is a common anti-pattern indicating that the code is really imperative rather than object oriented. This code might work better as a @property of str, since semantically that is what it is.


Moving repeated files from one folder to another

Maybe you try with this pseudocode:

get files list from directory
declare array for crc
for each file in directory
check if the mime content type is correct
get crc for file
check if this crc is in array for crc
if is in array move it
else push crc into array

Thanks Pimgd. You are right. I should write it on the beginning. First of all there is only one loop, so if you have a lot of files, it will be faster. Second, it checks content file, so you will not touch not image files. Third, the code will be more clear.


You can replace all of the

if(x.match(...))
    return true;
else
    return false;

with:

return x.match(...) !== null;

or if you're content with returning a truthy/falsy value instead of proper booleans you can even simplify it to:

return x.match(...)

IsEnoughLength is ungrammatical. I'd use IsLongEnough
You're mixing the password strength estimation with presentation logic. You should have one function which returns a value indicating the strength of the password and another which manipulates the DOM.
Use CSS classes to format the text instead of <b> and <font style=
Personally I wouldn't bother with argument checking in such a simple internal function. But if you do, throw an exception on programmer error, don't just return false.

if ((str == null) || isNaN(length))
    return false;

should be something like

if (str == null)
    throw new Error("str must not be null");
if(isNaN(length))
    throw new Error("length must be a number");

(or a fancier exception class if you want)


Since Smalltalk is super interactive also try browsing through the methods of e.g. ByteString and other classes and the different ways to search for methods and their implementors:

You can actually run do: and at:put: on it directly, but there's also doWithIndex: for example, which looks like it will make your second bit even simpler:

string := 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'.
string doWithIndex: [ :char :i | (char = $T) ifTrue: [ string at: i put: $U ] ].

Now, in terms of readability, the first one is of course much easier to understand.  It's to the point and obvious even for readers with no knowledge of Smalltalk.  The second one and the example I posted aren't (or are less so at least) - they use more complex syntax and several new concepts.

If you restrict yourself to just String I think your second approach is fine though.


Add Default Rubberduck VBA Folder Annotation to VBProject.VBComponents

HasFolder = InStr(.Lines(1, .CountOfLines), Chr(39) & "@Folder")

That condition can technically be True in modules that don't actually have the annotation; a @Folder Rubberduck annotation is only valid in a module's declarations section, so there's no need to grab the module content any further than .CountOfDeclarationLines - if the module is nearing the 10K lines capacity, using this instead of .CountOfLines could make a significant difference in the size of the string being passed to the InStr function.

Select Case Component.Type
    Case vbext_ComponentType.vbext_ct_StdModule
        FolderName = Project.Name & ".Modules"
    Case vbext_ComponentType.vbext_ct_ClassModule
        FolderName = Project.Name & ".Classes"
    Case vbext_ComponentType.vbext_ct_MSForm
        FolderName = Project.Name & ".Forms"
    Case vbext_ComponentType.vbext_ct_ActiveXDesigner
        FolderName = Project.Name & ".Designers"
    Case vbext_ComponentType.vbext_ct_Document
        FolderName = Project.Name & ".Documents"
End Select

I wouldn't repeat the concatenation here - just work out the last part of the name per the component type, and then concatenate with Project.Name & "." (I'd pull the separator dot out of the Case blocks as well) - and then I might give it a bit of breathing room, but that's more subjective:
    Select Case Component.Type
        Case vbext_ComponentType.vbext_ct_StdModule
            ChildFolderName = "Modules"

        Case vbext_ComponentType.vbext_ct_ClassModule
            ChildFolderName = "Classes"

        Case vbext_ComponentType.vbext_ct_MSForm
            ChildFolderName = "Forms"

        Case vbext_ComponentType.vbext_ct_ActiveXDesigner
            ChildFolderName = "Designers" 'note: not supported in VBA

        Case vbext_ComponentType.vbext_ct_Document
            ChildFolderName = "Documents"

    End Select
    FolderName = Project.Name & "." & ChildFolderName

I like the @Folder("Parent.Child") syntax and I see that's what you're generating here:

Component.CodeModule.InsertLines 1, Chr(39) & "@Folder(""" & FolderName & """)"

Note that this would also be legal... and simpler to generate:
Component.CodeModule.InsertLines 1, "'@Folder " & FolderName

Obviously if you prefer the parenthesized syntax (either works, it's really just down to personal preference) like I do then by all means keep it, but Rubberduck's new Move to Folder command doesn't put the parentheses in. I'd probably have the single-quote ' character spelled out, too, but I can see how a ' might be harder than necessary to read in the middle of a bunch of " double quotes. On the other hand, defining a constant for it would remove the need to have the "@Folder string literal defined in multiple places:
Private Const RD_FOLDER_ANNOTATION As String = "'@Folder "

...

Component.CodeModule.InsertLines 1, RD_FOLDER_ANNOTATION & FolderName

I have to mention that Rubberduck deliberately shoves all modules under the same default named-after-the-project folder (they can easily be sorted by component type in the Code Explorer), because we strongly believe grouping modules by component type is utterly useless and counter-productive: when I look at the code for a given functionality, I want to see all the code related to that functionality - and I couldn't care less about the component type of the code I'm looking at... it's mostly all class modules anyway.
A sane way to organize the modules in a project, is by functionality: you want your ThingView user form in the same place as your ThingModel class and your ThingPresenter and the Things custom collection - that way when you're working on that Thing, you don't have to dig up the various pieces in an ever-growing list of components under some useless "Class Modules" folder.


PHP strpos() as a way to implement an swear word filter

Two things I have noticed:

You remove all non-alpha-numeric characters, apart from the dash and space characters. I don't see what this adds to your filter? Clearly all the other characters are never part of your swear words, so why bother to remove them? It could, in theory, have unpredictable consequences, because formerly separated characters might form new words. Instead of removing you could replace the characters with a space, but my suggestion is to just don't do this step at all.

strpos() is case sensitive, that would mean your function won't find "BadWord" or "BADWORD" unless you add all these variants to your array. Better use stripos() which is case-insensitive.


you can just use an XML serializer?

var s = new XmlSerializer(typeof(FormLink));
TextWriter w = new StreamWriter("settings.xml");
s.Serialize(w, form);
w.Close();


Watch log dir for new file, automatically tail to slack

This seems quite fine. Given your circumstances, I don't see how this can be done simpler.

The script could use a bit of tidying up though. The indentation of watchlogdir.sh is haphazard, it would be more readable to make it consistent. Oh I see now. It's the $$ that messes things up, your formatting is fine.

In the other script, this line could be written better:

FILETOWATCH=`ls -t /var/log/xxx/*.log | head -1`

By using $(...) instead of `...` for command substitution, and using the canonical option -n1 instead of -1 with head:

FILETOWATCH=$(ls -t /var/log/xxx/*.log | head -n1)


Some suggestions:

There’s a lot of repetition in the code for generating each of the rows. Repetition is generally a bit of a code smell; you could improve this by using a list comprehension for each row, for example:

row1 = [round(random.uniform(0, 1)) for _ in range(3)]
row2 = [round(random.uniform(0, 1)) for _ in range(3)]
row3 = [round(random.uniform(0, 1)) for _ in range(3)]

By nesting the list comprehension and using tuple unpacking, we can reduce repetition further:

row1, row2, row3 = [
    [round(random.uniform(0, 1)) for _ in range(3)]
    for _ in range(3)
]

Your code uses 1.0 and 0.0 for the two values, whereas convention is usually to use O and X. If you use random.choice instead of random.uniform, you can get this instead:

row1, row2, row3 = [
    [random.choice(['O', 'X']) for _ in range(3)]
    for _ in range(3)
]

It’s good that the rest of your code copes with this gracefully – it doesn’t actually care what values you’re putting in the cells.

Once you’ve done that, you can tidy up the printing of the rows so you don't see the square brackets/commas from Python’s list syntax.
There are lots of if statements with multiple conditions and repetition, which is a bit messy. It would be cleaner if you defined a function that checks if a group of values are all equal. Then you could write:

if all_equal(row1[0], row2[0], row3[0]):
    print("All %s's in top row!" % row1[0])

That makes the conditions both shorter and easier to read.
Your script says “All X's in diagonal”, regardless of which diagonal it actually is. That’s less clear than it could be, and means it could potentially print the same sentence twice. I’d recommend using different terms to describe each diagonal – perhaps primary and secondary diagonal?


Welcome to Code Review!
PEP-8
In python, it is common (and recommended) to follow the PEP-8 style guide for writing clean, maintainable and consistent code.
Functions and variables should be named in a lower_snake_case, classes as UpperCamelCase, and constants as UPPER_SNAKE_CASE.
Type hinting
With newer python versions, you can make use of type hinting to give a brief overview of the type of variables and function parameters.
Counting letters
Python provides an inbuilt collections.Counter for you to make use of.
Comments
The comments don't really help here. Also, prefer writing docstring over comments for functions.
Variable names
You open a file, and name its pointer as words, whereas the function is returning a list of words; called reader, which in turn is stored in a variable called words?
Weird conversions
You generate a mapping of letters to their respective counts, as a dictionary (hash-map/table/lookup), then convert it to list of 2-valued tuple, sort that, and convert back to dictionary. Why? dict has \$ O(1) \$ lookup and sorting makes no sense in your case.
Iteration with index
You use the following loop structure:
for i in range(len(words)):

where, i in itself is serving no purpose. Every occurrence of usage of i is of the form words[i]. You can just iterate over the values of words list itself:
for word in words:


I'd suggest that you do:

Print all items

where print_frame.html is a simple page that displays an animated loading gif, and contains js that makes an ajax call to printallthisstuff.php.  The success callback for that ajax call will then replace the body content (which currently displays loading.gif) with the html returned from printallthisstuff.php, and call print, as you are doing now.


Firstly, the biggest problem is that ReaderWriterLockSlim implements IDisposable so your DeviceLocator class should too as it holds a reference at the class level.

You could make better use of the locks if you moved things round a bit:

public void AddLocators(IEnumerable<DeviceLocator> locators)
{
    cacheLock.EnterWriteLock();
    foreach (DeviceLocator locator in locators)
    {
        AddLocatorUnsafe(locator);
    }
    cacheLock.ExitWriteLock();
}

private void AddLocatorUnsafe(DeviceLocator locator)
{
    m_deviceList.RemoveWhere(x => x.CompanyID == locator.CompanyID
            && x.SerialNumber == locator.SerialNumber);

    m_deviceList.Add(locator);
}

Now you only acquire the lock once and do everything while holding that lock instead of having to keep acquiring and releasing between items.

Don't do this:

try
{
    // ...
}
catch
{
   throw;
}
finally
{
    // ...
}

That catch block is entirely redundant - remove it.

Some people would probably tell you off for using regions. I'm not really that fussed about it but you should be aware that a lot of C# developers don't like using regions for splitting up classes.


First off, congrats on making your own, that's the best way to learn and usually you don't need all the added overhead that a prefab provides.

In the implementation of MVC I like to use, there is a router between the view and controller, so its more of a MVRC rather than MVC. Just another level of abstraction, but I like it. It seems like what you are trying to do here is similar. So maybe my experience will help. My routers are typically classes, but that's a preference. Here are some suggestions on your code, along with a possible solution to your problem.

Error Reporting

When you set error reporting, make sure you don't do the same thing twice, such as setting the same reporting level, it should always be the same, so just declare it before the if statement. This actually holds true for anything. This is called the DRY principle (Don't Repeat Yourself). Also, you might want to consider logging errors even while in the development environment. This ensures that you don't miss those "silent" errors and allows you to ensure that the logs are working correctly. So a possible rewrite of your setReporting() function.

function setReporting() {
    error_reporting(E_ALL);

    ini_set( 'display_errors', DEVELOPMENT_ENVIRONMENT );
    ini_set('log_errors', 'On');
    ini_set('error_log', ROOT.DS.'tmp'.DS.'logs'.DS.'error.log');
}

Would change DEVELOPMENT_ENVIRONMENT to just DEVELOPMENT or my preferred STAGING.

Edit Above I meant to say ENVIRONMENT instead of DEVELOPMENT. This is because you are no longer using this constant to check the development environment, you are using it to set an environment.

You might actually want to set up your error reporting and db connection using a config file of some sort and then just reference it in the router. Another level of abstraction, but a very common one.

Development Tools

Don't use die(), var_dump(), print_r(), etc... outside of you development environment. There are better, more elegant, ways of displaying data to the customer.

Unnecessary Work

Instead of using "REQUEST_URI" and removing "QUERY_STRING" from it, why not just use "SCRIPT_NAME"? It does the same thing.

$_SERVER[ 'SCRIPT_NAME' ];

You don't have to define $urlArray as an array if you are immediately going to assign an array to it. Essentially you are assigning it a value and then never using it, which is bad and confusing. This isn't Java or C, you don't have to type hint a variable before using it.

Always check to see if the language you are working in provides a way for you to do something easier than you could do it yourself.

Defining a Default Value

This is a stylistic choice, but instead of using else statements to define default values, just define the default values first. If those values need to change, then change them.

$route[ 'view' ] = 'index';
if (isset($urlArray[3]) & !empty($urlArray[3])) {
    $route['view'] = $urlArray[3];
}

Distinguishing Between isset() and empty()

isset() returns TRUE only if a variable is set, and its value is not NULL.

empty() returns FALSE only if a variable is not FALSE, NULL, an empty string, any form of zero, or an empty array.

Unless you explicitly need to distinguish between a variable not being set, or empty, then I would suggest only using  isset(), not both.

list()

A better way to assign array values to specific variables is to use a list(). You'll need to use array_pad() to ensure the array is the proper length first, but don't worry, it won't add anything if its already past that length. Also, I don't know why you are passing these variables to an array and then never using that array. It's unnecessary. However, I do show how to pass these variables back to an array in case you are planning on expanding upon that function.

$urlArray = array_pad( $urlArray, 4, NULL );
list( , , $controller, $view ) = $urlArray;
$route = compact( 'controller', 'view' );

Your Problem

Your array, at least in the examples you provided, is not four fields long, its three. You've skipped the first empty field, but then, instead of using "1" as your index, you use two. Arrays start indexing their fields at zero. So When you call for the indices at "2" and "3", you are actually calling for the third and fourth elements. This is why your example will work for one level, but not another. I'm surprised your examples aren't throwing out of bounds errors.

Anyways, a better way to write your hook.

function hook() {
    $params = parse_params();

    $url = $_SERVER[ 'SCRIPT_NAME' ];
    $url = trim( $url, '/' );//remove forward slash from beginning and end of $url

    $urlArray = explode( '/', $url );
    $urlArray = array_pad( $urlArray, 2, NULL );
    list( $controller, $view ) = $urlArray;

    if( ! $controller ) { $controller = 'front'; }
    if( ! $view ) { $view = 'index'; }

    $route = compact( 'controller', 'view' );
}

Now if you want to extend to another level you would just adjust the padding, add to the list, add a default, and then add it to the compact.

Custom URLs

These are done through the htaccess file with mod_rewrite. At least, I think that's right. I haven't tried figuring this out yet, so I can't give you details, but it is well documented on the internet, just google it.

UPDATE

Looks good. I put an edit in one of the above sections because of a typo. You followed most of my previous advice, so there's not much I can add. I did just notice a couple of things though.

It looks as if you are passing your post and get data directly to your PHP scripts. This is bad. You should always validate and sanitize them. If your PHP version is >= 5.2 you can use a helpful PHP function called filter_input_array(), or filter_input().

It is best to only use the concatenate . operator if you are adding variables to a string. Even though it doesn't look like much, it is still an operator and takes processing power. Admitedly not much, but you should still code so that you aren't blattantly ignoring such minor inefficiencies. Not to say that you need to go out of your way to make your script as quick as possible. Far from it. But if its a quick fix that doesn't hurt anything, why not. It may not present much improvement now, but say you find yourself working on a script with a massive array that you need to loop over. At such a point every little efficiency matters. If you are already taking care of some of the easier stuff automatically it won't be as difficult to refactor the rest.

require( $_SERVER[ 'DOCUMENT_ROOT' ] . '/' . APP . '/models/general.php' );

Last but not least, don't just copy-paste suggestions into your code. I notice my coding style made it into your code. Take time to understand suggestions and write them yourself. As you found out, my answer was not 100% operational and you had to adjust it. Even if all you are doing is manually typing out these suggestions, without any change, you will find you will remember it a little better for the next time you need it and something might even click so that you understand it better.

Hope this helps!


Extracting a column

It's a lot easier to extract columns from text using awk.
Instead of this:

grep "cpu MHz" /proc/cpuinfo | sed 's/[\t ]*//g; s/cpuMHz://g'

This is shorter, and uses a single awk process instead of grep + sed:

awk '/cpu MHz/ {print $4}' /proc/cpuinfo

Extracting a line

This is a really awkward method to extract the 4th line:

echo $cpu_freq | head -n 4 | tail -n 1

This is simpler and better:

sed -ne 4p <<< "$cpu_freq"

Using arrays

Instead of getting the values of cpu0..cpu3 one by one by running separate command(s) for each, you can get it in one go:

cpus=($({ echo scale=2; awk '/cpu MHz/ {print $4 " / 1000"}' /proc/cpuinfo; } | bc))

Explanation:

The awk command appends the " / 1000" to the CPU frequency, so it's ready for piping to bc
Pipe all lines (commands) to bc at once, and get all the output at once
Group the echo scale=2 and the awk for bc by enclosing in { ...; }
Store the output of bc in an array

From this array, you can extract the individual CPU values

cpu0=${cpus[0]}
cpu1=${cpus[1]}
cpu2=${cpus[2]}
cpu3=${cpus[3]}

Next steps

I don't want to spoil all the fun for you :-)
Following the techniques above,
you should be able to extract the other values more efficiently (using fewer processes) in a similar fashion.


Factory pattern along with DI using Unity container

The following code should tell a story as it is reviewed. There are not many comments as the code has been simplified to be easy to understand as it speaks for itself. I suggest comparing it to what you had before and observe the difference in strategy taken to achieve the factory pattern with DI.

Apart from the composition root, note the separation of concerns and loose coupling of all members involved. The factory in the original post was tightly coupled to the UnityContainer and was also creating an instance every time the factory method was called. The container should only be created once in the composition root of the application.

public interface IPaymentGateway {
    void Invoke();
}

public class WellsFargoGateway : IPaymentGateway {
    public void Invoke() {
        Console.WriteLine("Implement Wells Fargo logic");
    }
}

public class SHIFT4Gateway : IPaymentGateway {
    public void Invoke() {
        Console.WriteLine("Implement SHIFT4 logic");
    }
}

public class ProtobaseGateway : IPaymentGateway {
    public void Invoke() {
        Console.WriteLine("Implement Protobase logic");
    }
}

internal class NullGateway : IPaymentGateway {

    static Lazy<IPaymentGateway> nullObject = new Lazy<IPaymentGateway>(() => new NullGateway());

    public static IPaymentGateway Empty {
        get { return nullObject.Value; }
    }

    private NullGateway() {

    }

    public void Invoke() {
        //No-op
    }
}

public enum GateWay {
    PROTOBASE = 1,
    SHIFT4 = 2,
    WELLSFARGO = 3
}

public interface IPaymentGatewayFactory {
    IPaymentGateway Create(GateWay GateWayType);
}

public class DefaultPaymentGatewayFactory : IPaymentGatewayFactory {

    readonly Func<GateWay, IPaymentGateway> factoryFactory;

    public DefaultPaymentGatewayFactory(Func<GateWay, IPaymentGateway> factoryFactory) {
        this.factoryFactory = factoryFactory;
    }

    public IPaymentGateway Create(GateWay GateWayType) {
        return factoryFactory(GateWayType);
    }
}

public static class CompositionRoot {
    public static IUnitContainer Configure() {
        //Dependency injection using unity container
        var container = new UnityContainer();
        //Register the gateways using named mappings
        container.RegisterType<IPaymentGateway, WellsFargoGateway>(GateWay.WELLSFARGO.ToString());
        container.RegisterType<IPaymentGateway, SHIFT4Gateway>(GateWay.SHIFT4.ToString());
        container.RegisterType<IPaymentGateway, ProtobaseGateway>(GateWay.PROTOBASE.ToString());
        //create the strategy
        Func<GateWay, IPaymentGateway> factoryFactory = (gatewayType) =>
            container.Resolve<IPaymentGateway>(gatewayType.ToString()) ?? NullGateway.Empty;
        //register factory
        var factory = new DefaultPaymentGatewayFactory(factoryFactory);
        container.RegisterInstance<IPaymentGatewayFactory>(factory);

        return container;
    }

}

class Program {
    static void Main(string[] args) {
        var container = CompositionRoot.Configure();
        var factory = container.Resolve<IPaymentGatewayFactory>();
        IPaymentGateway gateway = factory.Create(GateWay.SHIFT4);
        gateway.Invoke();
        gateway = factory.Create(GateWay.WELLSFARGO);
        gateway.Invoke();
        gateway = factory.Create(GateWay.PROTOBASE);
        gateway.Invoke();
        Console.ReadLine();
    }
}


Multiple forms for accessing records in database

Learn about Data Binding

Here is one tutorial.  My main point is that with the Visual Studio designer linking  back end data and the UI is pretty straight forward. And you can get navigation automagically; and along with "master / detail" synchronization it is so "thank goodness I didn't have to write this."

Separate UI from Data Fetching

I would pass in a MyClass object to the Form. This dependency injection is generally superior to "newing up" objects internally; making the design far more flexible and testable. I.E. we can inject mock (fake) stuff for the sake of testing.

One Form

Once the data fetching is factored out of frmTest then it becomes clear that a second Form is not needed. However, if you want that child form look/feel/behavior, then the data binding above makes it easy peasy.

Code Convention for Data Fetching

Don't leave open / unused connections lying about
Always wrap DB calls in try/catch. There's so much that can go wrong.

Here is a generally accepted good way of writing the code, taken right out of MSDN.

public void GetPeopleData() {
    // I put these outside of "using" because they are class variables.
     myClass.myConn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\Testing\TestDatabase.accdb";
 myDS = new DataSet();

    // everything created in "using" gets destroyed/goes out of scope at end
    // of "using" block. And in particular "myConn" gets disposed / destroyed
    // at the end because it is the "using" parameter. We really want to make
    // sure all the resources - and in particular the OleDbConnection - go
    // away.
    using (OleDbConnection myConn= new OleDbConnection(connectionString))
        {
            string SQL = "SELECT * From Test";
            OleDbDataAdapter myDA = new OleDbDataAdapter(SQL, myConn);

            // Open the connection and execute the insert command.
            try
            {
                connection.Open();
                myDA.Fill(myDS, "People");
                NavigateRecords();
                MaxRows = myDS.Tables["People"].Rows.Count;
            } catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
      } //using

        // The connection is automatically closed when the
        // code exits the using block.
} //GetPeopleData()

Rename GetConnection()

This method gets the data. "Getting the connection" is merely a detail in that process.

EDIT

Changed the general example to be specific to the question code.

Renamed GetConnection() to GetPeopleData()

Refactor GetPeopleData()

GetPeopleData() should do that and only that. I do not understand NavigateRecords() in there. I should think navigating records is done in the child form ... or does NavigateRecoreds() even navigate the records?


Push Notifications - save token id into a database using Asynchronous Request

First of all I think you could improve indenting (use Xcode built-in tool) and spaces.

Second thing you had 2 useless local variables.

And, most important, IMO you should create a struct or a class as your API client wrapper. Even if you have one simple method for now.

Here is a very simplified example.

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

    var userId = "001" //I just use it as USER number 1
    let token = deviceToken.hexString()

    let apiClient = MyRESTAPI(userId: "001")
    apiClient.setUserToken(token) {
        result in
        switch result {
        case .Ok(let response):
            println("data: \(response)")
        case .Error(let error):
            println("failed: \(error.localizedDescription)")
        }
    }
}

    struct MyRESTAPI {
        enum Result {
            case Error(NSError)
            case Ok(NSURLResponse)
        }

        let userId:String

        func setUserToken(token:String, completion:(Result -> Void)) {
            var postBody = NSString(format: "user=%@&token=%@", self.userId, token)
            var endBody = NSURL(string: "http://www.myServer.com/api/v1.0/register.php")
            var request = NSMutableURLRequest(URL: endBody!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30.0)

            request.HTTPMethod = "POST";
            request.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding)
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
                (response, data, error) -> Void in

                if data != nil {
                    completion(MyRESTAPI.Result.Ok(response))
                } else {
                    completion(MyRESTAPI.Result.Error(error))
                }
            }
        }
    }

    extension NSData {
        func hexString() -> String {
            // "Array" of all bytes:
            let bytes = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes), count:self.length)
            // Array of hex strings, one for each byte:
            let hexBytes = map(bytes) { String(format: "%02hhx", $0) }
            // Concatenate all hex strings:
            return "".join(hexBytes)
        }
    }


A simple jQuery function that removes empty or tags containing just ' '

"This isn't exactly DRY" is pretty much what I think about

$(this).text().trim() == '&nbsp;' || $(this).text().trim() === ''

text() can be a very expensive call: I would refactor to only do $(this).text().trim() once.

As a minor concern, the use of trim() suggests that you want to remove nodes whose text is purely whitespace. So shouldn't a node whose text is &nsbp; &nbsp; be removed? Perhaps you should be using a regex match instead of trim()? Something like (warning: untested) $(this).text().match(/^(\s|&nbsp;)*$/).

And then you could take it further: &nbsp; isn't the only way of escaping U+00a0, and the other whitespace characters can also be escaped in various ways...


Strip all comments and create a new file with only (JS) code

To handle codes, use a parser. Build an AST from parser (maybe comments are already removed there). And then convert it to codes. A FSM implementation may work. (I'm not sure). But I believe your current RegExp approach are far from working.
Anyway,
1. Line break
JavaScript support 5 different line terminator sequence. Your code only support one or two of them.
2. Single line comment
Line end no need to have ;.
var a = 42// comment

3. Multi line comment
Start / end of multi line comment no need to take a single line. They may appear on the same line.
var a = 42; /* comment */

var a = 42; /*
*/ var b = 42;

3. Some more complex comments
After you fix above issues, you are ready to handle more complex situations:
var a = 3
/*
*// 3;
/*/ /*/
/* // */
// /*
var b = 4;
// */

4. String and RegExp
Text in strings / regular expressions are not comments.
var a = '; // ';

var a = '\
// ';

var a = `
// `;

var a = /[; //]/;

This would be more complex if mix them up.
var c = `; // ${function () {
    a =  '}';
    // Wow, SO failed to use correct syntax highlight for this too!
}}`

5. HTML like comments
This could be optional. Most browsers supports HTML like comments. But this is not required to every JavaScript engine.
var a = 42;
--> this is comment
<!-- this is comment too

6. Shebang
It is up to you if you want to handle shebang as comments. They work on some browsers.
#!/usr/bin/node

var a = 42;


In order to get the output that you wanted, using array_combine will most likely be your best bet. You can simplify your statements pretty easily because variables are you friends:

$current_year = date('Y');
$date_range = range($current_year, $current_year+10);

form_dropdown('year', array_combine($date_range, $date_range), set_value('year'));

Addendum by @brettsantore

I think this solves what I thought to be a problem, the combining of so many functions. I ended up simplifying it a little more.

$current_year = date('Y');
$range = range($current_year, $current_year+10);
$years = array_combine($range, $range);


Reading file and writing to output file with line numbers

Here are my comments:

1) File handling

Your file handling logic is in the right direction:

the File handlers (goThrough and print) are defined outside of the try block,
are opened at the beginning inside the block
are closed in the finally clause.

However, you forget to protect the code from NPE (NullPointerException):
at the beginning inside the try block, both handlers contain null.  You first open print the output handler, and then goThrough.  However, in the finally clause, the order is reversed. So, if an exception is thrown while opening print, goThrough is never initialized and you might encounter NPE in the finally clause. it is absolutely essential to ask separately about each file handler before closing it:

if (goThrough != null) goThrough.close();
if (print != null) print.close();

Note: the best practice rule dictates that you first open the input handler, then the output one, and closes them in the reverse order.

As you can see, proper file handling is a delicate process that requires careful attention to details at different points in the code.  Since many errors were made by many a good developers in many production programs, Java 7 added a feature that automatically handles this logic for you.  it is called try-with-resources and it means that you declare and open the handlers at the point of the try block and the compiler adds the correct finally clause. I leave to you as study exercise to go though the tutorial and implement the feature into your code.

2) Exception handling

Exception handling in writeToLine() is incorrect:

The method is declared with throws FileNotFoundException clause.  However, the code is surrounded with try-catch that catches  all exceptions, including the supposedly thrown one.
The catch block contains what looks like a statement fragment that does nothing (but passes compilation).  perhaps you meant to throw an Exception?

3) Design

This last comment falls into "best practice" category: the main() method does too many unrelated tasks: receive input from user, file handling and main loop. if, for example, you have a separate method that is responsible for communicating with the user, receiving user input and validating it, then perhaps you would be able to check for existence of input file as part of validation... then again, one method for receiving user input and validating it? hmm maybe we can design further break down ...


You should use try-with-resources when you create a Scanner, and should only ever open a Scanner on System.in in your main program.  If you do this, you can pass the required size as an argument to the MagicSquare constructor:

public static void main(String[] args) {
    try(Scanner sc = new Scanner(System.in)) {
        byte size = sc.nextByte();
        MagicSquare m = new MagicSquare(size);
        m.printSquare();
    }
}

I’ve left construction of the magic square in the constructor (seems appropriate), but moved printing of the square to the main program.  After all, you might not always want to print the magic square.

You have numerous inefficiencies in your implementation:

You use square.length and (worse!) square[0].length when you could simply use size if you stored the magic square’s size as a size member.

You are testing x < square.length && y < square.length before resetting square[x][y] = 0;.  The x and y values should always be valid if you reach this step of the solve() method.  But there is one small possibility of them becoming invalid.  After filling in the last square...:

if (x == square.length && y == square.length-1 && isMagic()) {
    return true;
}

If it turns out isMagic() returns false, the method continues, loops over all values looking for an unused one (there aren’t any), and exits the method, returning false, but only after resetting square[x][y] = 0; which is why the check for invalid coordinates is required.  If instead you used:

if (x == square.length && y == square.length-1) {
    return isMagic();
}

... then the method always returns immediately, whether or not the completely filled in square is magic or not.  Now, the if guarding square[x][y] = 0; becomes unnecessary.

But the real issue comes from your algorithm as a whole.  You loop over \$N^2\$ squares, and for each square try each of the \$N^2\$ values, and for each value check each of the \$N^2\$ squares to see if the value is already used.  This is an \$O(N^6)\$ algorithm!

The usage check can be reduced to \$O(1)\$ by storing a “used” flag for each number:

boolean used[] = new boolean[size*size+1];

or

BitSet used = new BitSet(size*size + 1);

Then, simply checking used[value] or used.get(value) will return whether the value has been used or not.  Set the flag for the value when you store it in the square[][], and clear it when you replace the value.  That one change will reduce your time complexity from \$O(N^6)\$ to \$O(N^4)\$.

The next speed up can come from the observation that, if you take a solved NxN magic square, and erased one row and one column, you could trivially recreate the erased values.  If you know N-1 values in a row or column, the remaining value must be the desired total less the sum of the filled in values.  1 + 8 + ? = 15 ... the missing value is 15-(1+8)=6!  Of course, since you are generating candidate values, you need to ensure the computed value is (a) possible, and (b) unused.

Adding up numbers takes time.  Why keep adding the values?  You could keep a running total for each row and column:

square[x][y] = value;
row_sum[x] += value;
col_sum[y] += value;

... of course, you need to subtract the value out when backtracking, or replacing with a different candidate value.

Magic Squares are horizontally, vertically, and rotationally symmetric.  In a 4x4 magic square, there are only 3 unique locations the number “1” may appear in.  The remaining 13 locations would all correspond to simple rotations or mirroring of the square.  This would reduce the possible 4x4 squares from 16! permutations down to 3*15! ... an 81% reduction.  However, you are not finding all permutations; you stop once the first magic square is found, so this reduction in search space likely won’t produce much savings, if any.

While an 8x8 magic square seems huge, it is still within the realm of possibility.  The magicNumber, however, would be 260 which is too large for a byte.   Limiting the values themselves to a byte restricts the square to 15x15, and may be reasonable, but the sum should probably be an int.

This code ordering seems reversed!

    if (isValidRow(x) && isValidCol(y)) {
            square[x][y] = i;

square[x][y] should be filled in before the isValid checks are done.  Otherwise, an invalid state will prevent updating the square to a valid value.

“Invalid”, in this case, only happens if the sum becomes too large, and subsequent values will only make matters worse, but if the code is relying on that, it should break out of the candidate values loop once an invalid state is reached, instead of continuing with the next value.


java.sql.Timestamps: There's gotta be an easier way

Bug

gc.set(Calendar.HOUR, 59);

I suppose you mean gc.set(Calendar.HOUR, 23); here?

Potential Bug

while (rs.next()) {
    ard = new AssistReportData();
    // ...
}

I suppose this works currently because you only get a single result row, but please be aware that if you have multiple rows, you will simply be re-referencing until the last row of your ResultSet.

Getting dates

All you need is a nice method that converts Date to Timestamp:

// using shortened variable names for brevity
private static Timestamp convertAndReset(Date date, int hr, int min, int sec, int nano) {
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR, hr);
    calendar.set(Calendar.MINUTE, min);
    calendar.set(Calendar.SECOND, sec);
    Timestamp result = new Timestamp(calendar.getTimeInMillis());
    result.setNanos(nano);
    return result;
}

You can them call it as such:

ps.setInt(1, teamId);
ps.setTimestamp(2, convertAndReset(date, 0, 0, 0, 0));
ps.setTimestamp(3, convertAndReset(date, 23, 59, 59, 0));

Java 8?

If you happen to be on Java 8, then congratulations: the new java.time.* classes ('Time APIs') are much better for chronological representations.

You can then consider rewriting the same method as such:

private static Timestamp convertAndReset(Date date, int hr, int min, int sec, int nano) {
    return Timestamp.valueOf(date.toInstant().atZone(ZoneId.systemDefault())
                                    .toLocalDate().atTime(hr, min, sec, nano));
}

Convert Date to Instant via Date.toInstant().
Convert to ZonedDateTime via Instant.atZone(ZoneId).
Convert to either a LocalDate or LocalDateTime. Using the former because...
Setting the time via LocalDate.atTime() is arguably more fluent, which gives us a LocalDateTime instance with the desired time in another 'step'.
Finally, call Timestamp.valueOf(LocalDateTime) to get the Timestamp instance.


You're right, it can be turned into one line using comprehension syntax which would be your best option of you're looking for a slightly more efficient code.

isdecimal() is better to use in this case than isnumeric() because the isnumeric() accepts types like ½ and ¼ and n² which might produce some side effects you don't want if you're using this function for some real application. Apart from this the code looks good, can be improved using the comprehension syntax which is more efficient and shorter.

Improved version:

def sum_digits(chars: str) -> int:
    """Return sum of numbers in chars"""
    return sum(int(char) for char in chars if char.isdecimal())

if __name__ == '__main__':
    print(sum_digits('abcd173fg'))
    print(sum_digits('abcd'))
    print(sum_digits('173678'))


Solving the knapsack problem with user provided input

General

You don't have any comments. I recommend you document what basic blocks of code are doing
I recommend factoring out the parsing and algorithm parts of your code into different functions.
Why prompt the user for the number of input items? You can trivially detect it from the second line input, unless this specifies a different value.
Non-descriptive variable names: What does s contain? What does ans mean?
The itertools crate is super helpful whenever iterators are involved

Input Capture / Parsing

Read in both lines at once: let lines = io::stdin().lock().lines().take(2);
Map over those lines, parsing the integers:

let mut numbers = lines.map(|line| {
    line
    .trim()
    .split(' ')
    .map(|s| s.parse::<i32>().unwrap())
});

Split the first line:

let first_line = numbers.next().unwrap().take(2).collect::<Vec<_>>();
assert_eq!(first_line.len(), 2);

let num_items = first_line[0];
let max_weights = first_line[1];

And grab the items from the second line: let items = numbers.next().unwrap().collect::<Vec<_>>();

Algorithm Part 1 (s)

I'd specify the range as 1..(1 << num_items) to really make clear that second 1 is being shifted, not the whole range.
Personally, I prefer my tuples to be easily spotted. I'd set the iteration result a variable then use that in the tuple:

.map(|i| {
    let sum = items
        .iter()
        .enumerate()
        .filter(|&(t, _)| (i >> t & 1 == 1))
        .map(|(_, elem)| elem.clone())
        .sum::<i32>();
    (sum, i)
})

It's unclear what .filter(|&(t, _)| (i >> t & 1 == 1)) is doing here, but usually bitwise comparisons can be expressed more clearly with other operations.
Additionally, i and t should probably be renamed to be more clear.
Also, those extra parenthesis around the closure return value should instead be used to group whichever operation takes precedence for clarity of the expression
.map(|(_, elem)| elem.clone()) I think can be replaced with .map(|(_, &elem)| elem)
Recommend returning (i, sum) instead of (sum, i) to better match the pattern of enumerate
Extra parenthesis around the return value in .filter(|&(elem, _)| (elem >= 0))
I think .min_by(|(a, _), (b, _)| a.cmp(&b)) can be replaced with .min_by_key(|(x, _)| x)
Doesn't look like you ever use s.0 so you can ignore it with let (_, s): (i32, i32) = ...
In fact, it doesn't look like you use the i index at all after the first .map(|i| { so you don't need to pass it through the rest of the chain.

Algorithm Part 2 (ans)

You repeat (x >> t & 1 == 1) twice: here and above. Perhaps move it to a clearly-named function?
I'd store the ans.iter().fold(...) in a variable before printing the result. Makes the eventual format string output easier to predict.
Suggest using format! in the fold:

.fold(|out, &num| format!("{}{} ", out, num))

Alternatively, you could use join instead of the fold:

ans.into_iter().map(|x| x.to_string()).collect::<Vec<_>>().join(" ")


Correct practice for Python properties that depend on other attributes

I vote the first method (with the change of having () as the default argument instead of None, because it's simpler).

If you don't absolutely need code introspection, don't use it. In my mind it's more cluttered and risks confusing editors such as PyCharm, as well as human beings, about the composition of a class. To take this idea a little further, there's no need for "pinned" to accept a tuple in the constructor. Give it the same contract as pin_corner; that is, accept both arguments and default them both to None. There's less validation required - when accepting a tuple you would need to check its length as well as the validity of its members.


Parsing and summarizing an aviation METAR (US) report

A question before

It is not clear to me how yor code works, but could as I'm not an expert of this METAR format.

The weather you find is just the last you get from the input string.

If you have, for example, an Heavy show you will miss it as you could even have a Overcast.

This part is much a question, than an answer, sorry.

Assuming your code is correct and the input string contains only one weather condition, here are my considerations.

Advise 1

You should use a for loop with the keys of SearchActivity.conditions, and break as soon as you find the conditions, avoiding matching all others.

So for example:

String weather = SearchActivity.conditions.get("CLR");

for (String condition : SearchActivity.conditions.keySet()) {
   if (d.getRawData().contains(condition)) {
       weather = SearchActivity.conditions.get(condition);
       break;
   }
}

Of course if you really need the last match, than you could not use this loop, as the Set don't preserve the order of the keys.

In this case, if you still want to have a loop, you should create an array with the conditions keys.

Advise 2

You should use constant for the condition labels:

final String CLR = "CLR";
final String FOG = "Fog";
... so on...

And use those constants in your code.

EDIT

For example in your if else:

if (d.getRawData().contains(FOG)) {
    wCode = FOG;
} else if (...
} else {
    wCode = CLR;
}

A review on the code

Your if else statement is not correct, as the last check could be just an else:

....
} else if (d.getRawData().contains("NSC")) {
  wCode = "NSC";
} else {
  wCode = "CLR";
}

As after you check if the wCode variable is empty and the you force CLR, that is the last condition.

if (TextUtils.isEmpty(wCode)) {
  wCode = "CLR";
}


Improving my solution to the Quiz project from Gophercises in Golang

from what I saw there are a few changes that could be done to the program

while parsing command-line arguments I think it's better to put them inside a function cause it makes the code look clean and simple and as it is returned as a pointer you would have to keep getting the value as * but you could return it as the specific type and have a simpler handling
 csvFile, timeLimit, isShuffle := parseCMD()

 func parseCMD() (string, int, bool) {
 csvFile := flag.String("csv", "problems.csv", "a csv file in the format of 'question,answer'")
 timeLimit := flag.Int("limit", 3, "the time limit for the quiz in seconds")
 isShuffle := flag.Bool("shuffle", false, "shuffle the quiz order each time it is run")
 flag.Parse()
 return *csvFile, *timeLimit, *isShuffle

}

var (
csvFile = flag.String("csv", "problems.csv", "a csv file in the format of 'question,answer'")
timeLimit = flag.Int("limit", 3, "the time limit for the quiz in seconds")
isShuffle = flag.Bool("shuffle", false, "shuffle the quiz order each time it is run")
)
var can be used on a variable that doesn't have any initialization or if it's gonna be a global score or... if in a case outside an if statement or a for loop (a situation where:= won't work)..  as these are being declared inside a function and have a default value a short variable declaration would be a more golang kinda way. (there is not a lot of difference between using var and:= in your code but in a situation like this:= would be more golang-ish)
https://stackoverflow.com/questions/53404305/when-to-use-var-or-in-go/53404332
https://stackoverflow.com/questions/21657446/var-vs-in-go

 timer := time.NewTimer(time.Duration(*timeLimit) * time.Second)

while defining a ticker add a "defer ticker.stop()" to release any resource related to as it wont be garbage collected (https://golang.org/src/time/tick.go)

if isTimerDone {
select {
case <-ch:
if recipientAnswer == quiz.answer {
score += 1
}
case <-timer.C:
isTimerDone = false
fmt.Println()
return
}
} else {
break
}

In the above case the if check (isTimerDone) won't actually hit as by flow you always go into the select case and if you get an answer you continue the loop and if the timer hits you return.. so a better way to write it would be to remove the IF-ELSE check..
from what I understand yours is a score counting program so assuming you don't answer and the timer hit.. you could continue the loop and score based on the total answer or break the loop if he doesn't answer (this is just a suggestion :) )


Finding the intersection of two sets of integers

Let's look at these two nested loops. How many times does the loop body need to be executed?

for(x = 0; x < n; x++)
{
    for(i = 0; i < m; i++)
    {
        /* loop body ... */
    }
}

The loop body gets executed \$ nm \$ times. But the problem statement says that we have \$ 1 \le n, m \le 10^6 \$, so in the worst case \$ n = m = 10^6 \$ and so the loop body gets executed \$ 10^{12} \$ times. There's no way to do that in just 3 seconds!

So you need to find a different algorithm, one that doesn't try to examine every pair of elements.

How might you do that? Well, here are two ideas:

Sort the two arrays, and then output the intersection by merging the sorted arrays.
Store the first input set in a data structure that has efficient lookup, for example a hash table or a radix tree, and then look up the numbers in the second input set.


Well for starters bind the event using the jQuery standard

var $win = $(window).bind('orientationchange', function(){
    // math.abs to reduce logical operators
    $('body').removeClass('landscape portrait') // reset
        .addClass(Math.abs(this.orientation) === 90 ? "landscape" : "portrait");
});

// now you can trigger the orientation manually on doc ready to set the class
$win.trigger('orientationchange');

var num = 400,
    $body = $('body'),
    $example = $('.example');

if($body.hasClass("landscape"))
    $example.animate({'bottom', 0});
else
    $example.animate({'bottom', num});


Design Pattern - Strategy Pattern in PHP

I think there might be room for improvement.

First of all, Strategy pattern relies on interfaces / common classes and you are combining Shape with concrete Strategy passing it to the constructor.

To be more specific, here you bound Square with ConsoleDraw and WebDraw:

$shape[] = new Square( 10, new ConsoleDraw );
$shape[] = new Square( 10, new WebDraw );

The question is, what if I passed any DrawStrategy to the Square object? Should it work? Everytime? This is my point. I think you should hide allowed strategies on list behind the concrete Shapes and pass context.

Based on context, pick the right strategy (let's say, we are in Console Context - pick the ConsoleDraw. If we were on DesktopAppliction context - throw Exception "Unsupported" or don't draw at all).


It's good to have 2 methods.
For the reason that @britishtea said in a comment,
which is so spot-on I'm just going to quote it verbatim:

  A method that takes a boolean value as a parameter and behaves differently depending on that value is not one method, but two methods! You should keep them separated. You couldc of coursec implement them using shared functionality, but your public API should offer two methods. :) – @britishtea

And indeed, this is how the .NET framework does it too
(See StandardDeviation() and StandardDeviationP(), thanks @200_success).

At the same time, of course don't repeat yourself.
Extract the common logic to a private helper method,
and rewrite your public methods in terms of the private one:

private static double StandardDeviation(List<double> numberSet, double divisor)
{
    double mean = numberSet.Average();
    return Math.Sqrt(numberSet.Sum(x => Math.Pow(x - mean, 2)) / divisor);
}

static double PopulationStandardDeviation(List<double> numberSet)
{
    return StandardDeviation(numberSet, numberSet.Count);
}

static double SampleStandardDeviation(List<double> numberSet)
{
    return StandardDeviation(numberSet, numberSet.Count - 1);
}

Lastly, the parameter name "numberSet" is a misnomer,
suggesting a Set, when it's really a List.


Calculating sum of multiple columns in pandas

You can do the whole filtering and sum using pandas' builtins:

for group, individuals in Compare_Buckets.items():
    DemoDF[group] = DemoDF.filter(items=individuals).sum(axis=0)


Your code is not a replacement for replace (pun intended).  Its type signature is wrong.  Your code has type Eq b => b -> b -> [b] -> [b], but replace should have type Eq a => [a] -> [a] -> [a] -> [a].

<$> and <*> are infix, not prefix.

I'd prefer this to your implementation:

replace' :: Eq b => b -> b -> [b] -> [b]
replace' a b = map (\x -> if (a == x) then b else x)

It does the exact same thing in the exact same way, but is simpler and more readable (even a novice Haskell programmer who has never heard of bool or <$> or <*> can read it).  Even more important: it has a type signature.

If you'd decided to cut-and-paste the type signature of the function you wanted to replicate before starting, you would have found out that your version doesn't work as a replacement at compile time -- and if you'd looked at and thought about the type signature, you probably would have wondered why the extra []s were there, and figured it out even earlier.


What is the purpose of the IMapper interface and Mapper class?  It looks to me that they are just wrapping the IMappingEngine interface and MappingEngine class.  While this is a good method when you have a third party class that doesn't have an interface, I think it is overkill here.  Why don't you just use the IMappingEngine where you need that functionality?

If you are going to keep your Mapper class, I would rename it, having two Mapper classes is confusing.

As for where it is, I don't have a problem with doing it this way.  All the wire-up is done in one place, and its easy to find and add to as needed.


You could write it in 1 loop but you'll still need separation of logic for each type of Control:

foreach(Control c in panel1.Controls)
{
    if(c is TextBox)
    {
        var tb = c as TextBox;
        if(!String.IsNullOrEmpty(tb.Text))
            tb.Text = "";
    }

    if(c is Label)
    {
        var l = c as Label;
        if(l.Tag != null && l.Tag.ToString() == "Clearable")
            l.Text = "";
    }
}