Code improvements
Going from top to bottom, here are some improvements I would suggest.

If database_path is a constant, it should be named instead DATABASE_PATH, or some other all-caps name, to make it evident that it shouldn't be changed. You may consider storing this outside of the code in some config file, so if it ever changes you only need to change the config file and not the code.

Since you are using Python 3, consider using type hints. This will make your code easier to read, as well as allow static analysis of your code to make sure the correct types are used. For example, here would be your connect function with type hints. Note the added import from typing, which has common types like List, Dict, and Tuple.
from typing import Dict

def connect(database: str) -> Dict:
    """Open a connection and a cursor to the database file provided."""
    conexion = sqlite3.connect(database_path + database + ".db")
    cursor = conexion.cursor()
    return {"conexion":conexion, "cursor":cursor}

Instead of making up a word like conexion, consider just adding an underscore at the end when you are worried about using a reserved keyword, i.e.:
connection_ = sqlite3.connect(database_path + database + ".db")

I would recommend using the string .format() method instead of +'ing strings together. For example:
connection_ = sqlite3.connect("{0}{1}.db".format(database_path, database))

It makes the intention more clear, and makes sure everything is the right type to avoid type errors. You could also split the string building by itself for easier reading:
connection_string = "{0}{1}.db".format(database_path, database)
connection_ = sqlite3.connect(connection_string)

Design improvements
Having worked with SQL databases quite a bit, I personally think it is a bad idea to dynamically build SQL query strings as you are doing. The main reasons are as follows:

They are error-prone
They have potential security risks
They usually have poor performance

To briefly address each:

Imagine that you (or another programmer) makes a typing error, say typing "Usres" instead of "Users", the SQL DB will return an error stating that the "Usres" object doesn't exist. Then you need to build in error handling in your functions to account for misspelled or otherwise non-existent database objects.

Imagine you had some kind of input form where a user types in some information, for example, their user name; then, you put that into your SQL query string and execute it on the DB. It's all well and good, as long as the user types something that could be valid. But there is a risk for what has become jokingly known as a Bobby Tables problem, or SQL injection.

Take this for example: query_built = query_built + " WHERE " + str(sqlquery["where"])
Say I entered this as user name: Phrancis'; DROP TABLE Users;--
Your executable query string would then look something like this:
"SELECT Id FROM Users WHERE Name = 'Phrancis'; DROP TABLE Users;--'"

Notice that trailing single quote at the very end after --, which is now commented out and ignored, and the single quote I put in the user name is used instead.
And if SQL executed that, then, you better have a recent backup of your users table!

For performance, queries that are executed "ad hoc" (or, basically, improvised) on the database usually have a poorer performance than queries that are stored. The SQL database usually has to recalculate execution plans for ad hoc queries each time, as opposed to re-using the execution plan from the last time(s) a similar query was executed. On busy production databases, this can make a significant impact on the database processing load.

Ultimately, for any production code, database queries should each have their own functions/methods, as in this example:
def check_user_exists(user_name: str) -> bool:
    query = "SELECT id FROM users WHERE name = ?"
    cursor.execute(query, user_name)
    # etc.


Best way to avoid users to cancel my routine halfway through while managing other errors

I think I've managed to improve (or clean at least) the code mentioned above:

Private Sub Worksheet_Activate()

Application.EnableCancelKey = xlErrorHandler
On Error GoTo errHandler
Application.ScreenUpdating = False
ActiveWindow.DisplayHeadings = False

ActiveSheet.Unprotect "XXXXX"
ActiveSheet.ShowAllData
ActiveSheet.Range("estimate_table").AutoFilter Field:=59, Criteria1:=">0"
ActiveSheet.Protect "XXXXX"

Application.ScreenUpdating = True
Application.EnableCancelKey = xlInterupt

Exit Sub

exitHandler:
    ActiveSheet.Protect "XXXXX"
    Application.EnableCancelKey = xlInterupt
    Application.ScreenUpdating = True
    Exit Sub
errHandler:
    If Err.Number = 18 Then
    Resume exitHandler
    Else
    Resume Next
    End If

End Sub

What I still don't understand is why it seems like I still can't stop the routine by pressing ESC (90% of the time, the process goes through and once in a while the process is indeed stopped)..


The biggest thing I can say about your code is don't use raw pointers, start getting into the habit of using smart pointers.

  Smart pointers enable automatic, exception-safe, object lifetime management.


Identifying surface events happening at specific time intervals

With the caveat that I am not familiar with either the Mint.com format or Pandas, I can make a few suggestions:

The Python convention is to indent by 4 spaces, and wrap lines at 79 characters. It’s not a hard requirement, but it would be less jarring for me to read your code. And use one space after commas, it’s easier to read.
There aren’t any comments or docstrings to help me understand your code, which will hinder anybody trying to review or understand it.
It’s not clear to me why you define the parse_date() function. It has the same argument signature as datetime.strptime(), but now somebody familiar with the datetime module will find it harder to read your code. It would be better to replace all calls to this function with datetime.strptime().
In the calculate_diff_list function:

Don’t use list as a parameter. Overriding builtins is a bad idea, and can lead to subtle bugs.
You don’t say if you’re using Python 3 or Python 2.x; if the latter, use xrange() instead. It’s faster and more memory efficient.

In the diff_month function, it would be good to provide a docstring explaining exactly what you mean by “difference in months”, and how this function should be used. You should also specify the ordering, because it’s not necessarily obvious.

For example, consider 31 Dec 2014 and 1 Jan 2015. Are they a month apart or not? Your function returns 1 and -1 (!) depending on the ordering.
In unique_merchants(), you could make a couple of tweaks:

Default keyword arguments don’t have spaces around the equals sign.
If you could drop the pandas requirement, this could be reduced to set(df[merch_column]). You only need an iterable, not a list. This goes for the other functions along here (which also need some docstrings and comments, really).

As far as I can tell, the only bit of functionality that relies on pandas is foo = pd.read_csv(csv). (foo and csv are terrible variable names.) Have a look and see if the builtin csv module can be used here, then you might be able to simplify some more of the code.


Writing data to an Excel sheet using openpyxl

Perhaps manipulating data in the spreadsheet is not the most efficient way to do this, could you save the spreadsheet as a csv, and then you could read both spreadsheets into a list structure using the python core csv module.

Alternatively, you might use the Pandas library to import the csv files to a dataframe, do your processing and resave to a csv output.

You can write your results out as csv, open this in excel and resave as an xlxs file.

Both of these approaches should take a few seconds to run


Finding binary combinations based on substitute wildcards

Let's get the obvious out of the way first.
Style.
The first thing that hits me is the indentation being offset here:

class MainClass
    {

Should be:
class MainClass
{

The next thing that hits me (in the same millisecond, really), is the inconsistent braces. You have them next-line-style at class level, and anything under class scope has them same-line-style. It's.... annoying to read. C# typically uses next-line braces:
if (count == 0)
{
    Console.WriteLine (word);
}
else
{
    ...
}

Also, it seems like you're fighting your IDE here:

char[] bi = binary.ToCharArray ();

And here:

if (bi [i].Equals ('?'))

These spaces feel very awkward. C# reads better like this:
char[] bi = binary.ToCharArray();

if (bi[i].Equals('?'))

The last thing, and perhaps the most important one, is about method ordering: code should read like a book, and unveil like a story. Just like you wouldn't start reading a story at the end, a class' code shouldn't start with its implementation details - I expect void Main to be the first thing: that's where everything starts, after all.

Abstractions & Responsibilities.
Programming is about making abstractions - the abstraction level of Main is too low, it's not clear what that loop is there for and what's being counted: count isn't exactly the most meaningful name to use here. You're counting question marks, and question marks are a thing in the context of this app. Why isn't there a concept of wildcard anywhere?
private static readonly char Wildcard = '?';

You have a loop in Main, that's counting the wildcards. You could extract a method to better express that intent, but it's probably simpler to inline a bit of LINQ there - note that ToCharArray() is completely useless, since a string can already be iterated as an IEnumerable<char> in C#:
var wildcardCount = binary.Count(c => c.Equals(Wildcard));

Notice how much easier it is to figure out exactly what's going on - and why.
Now, looking at the BinaryString method (bad name, methods should start with a verb, they're actions), I'm questioning why you would need to pass in the wildcardCount as a parameter, when all it's used for is really to exit the looping/recursion logic - you already have that information in the character array itself:
if (!word.Any(c => c.Equals(Wildcard)))
{
    Console.WriteLine(word);
}

Ah.. and now I see why ToCharArray was used - the method returning void, your entire logic depends on the ability to mutate array elements! That smells funky, because parameters are passed by value. A much more idiomatic way, in my opinion, would be to take a string input, and return a new string after processing.
That would make it easier to leave the console output out of the function's logic, too - I don't like that the function is responsible for producing/computing the string (/mutating the character array) and producing the output. It just feels wrong, clearly it breaks the Single Responsibility Principle.


Reverse Polish Notation calculator in Scala

Operator

The main issue about this implementation is that Operator is declared as Enumeration, but indeed does not represent an enum: all the vals are String constants, but not instances of the enumerated type. And this usage is not very appropriate.

Well, enums in Scala are rather different from Java and we cannot easily associate items of an enum with methods: that is what you are trying to do with stringToOperator Map. Generally, it's OK, it works, it remains readable, but the Operator type somehow disappears in the code. If you comment out some lines like this

//  private object Operator extends Enumeration {
val Divides = "/"
val Times = "*"
val Plus = "+"
val Minus = "-"
//  }

//  import Operator._

the code will still compile and work: looks like Operator is not really meaningful in this implementation.

I suggest to create a dedicated type that will provide a means of evaluation of expressions expecting two Double args:

abstract class Operator(operation: (Double, Double) => Double) {
  def eval(left: Double, right: Double): Double = operation.apply(left, right)
}

This type is instantiated with target arithmetic operations, each in a dedicated object:

case object Divides extends Operator({ _ / _ })
case object Times extends Operator({ _ * _ })
case object Plus extends Operator({ _ + _ })
case object Minus extends Operator({ _ - _ })

Now we need to parse a raw token, represented initially as a String. A token can correspond to a numeric value or to an operator. We can use Scala's Either construct to represent this choice:

private def parseToken(tok: String): Either[Double, Operator] = tok match {
  case "/" => Right(Divides)
  case "*" => Right(Times)
  case "+" => Right(Plus)
  case "-" => Right(Minus)
  case _ => Left(tok.toDouble)
}

Consequently, the foldFunc is reduced to one-level matcher for cases from this Either reference:

private def foldFunc(acc: List[Double], tok: String) = parseToken(tok) match {
  case Left(num) => acc :+ num
  case Right(op) => op.eval(acc.head, acc.tail.head) :: acc.tail.tail
}

Exceptions

Exception type is too general and is discouraged to be thrown from any method. Try to find semantically more appropriate existing types. For example, in solve function, if the stack is empty or contains more than two elements, it is in an invalid state. There exists IllegalStateException for that and it might be used.

I'd also suggest more informative messages in the exceptions and probably add more checks for the cases when numbers or operators appear in unexpected positions.


Is it a good practice to use only one database instance?

In this situation, I would say to prefer dependency injection. The reasons being:

You may not only ever run your code against a single database. For example, if your project grows large, you may have separate databases for different regions about the world (North America, Europe, etc). You could also easily have a test database, or a stable-test and an experimental-test, etc., etc. All of this can be controlled by configuration. Of course, you could put this configuration-based logic inside your Database class, but..
You may want different types of databases. Right now you might be using MySQL; later you may use Oracle, or PostgreSQL, or an in-memory database, or a mock database that has no backing store. Using dependency injection lets you very easily switch between these, provided you adhere to the same interface for all of them. You may even start in one region where MySQL is readily available, then expand to another where you can only get Oracle hosts. Changing types is useful for easily changing technologies later, but also because..
Using dependency injection makes it easier to test. You can test against an in-memory database for your unit tests, and against an actual remote database during integration testing.

Of course, dependency injection isn't a cure-all and has its own problems, such as:

Dependency injection is infectious. Somebody somewhere has to know how to construct your object. If your object has its dependencies injected, then it has to know how to construct the dependencies. If it doesn't know that, then the next level up has to know, or the next level from there, or.. etc, etc. The result of this is that..
Your classes become more tightly coupled. Some of your classes become aware of the dependencies of their other classes, by virtue of having to inject their dependencies. A good dependency injection framework can help with this. I don't use PHP much so I'm not aware of any.

This is Code Review, of course, and I'd be remiss if I didn't comment on your code itself:

<?php
    $user = new User();
    $user->update($id,$data);

    $emp = new Employee();
    $emp->delete($id);
?>

To me (admittedly a non-PHP guy) this is an extremely strange pattern. A User and an Employee would seem to be model classes, but here you have them making database calls - you're mixing concerns for these objects. This is a great situation to use the data access object, or DAO, pattern:

<?php
    class User {
        private $data;

        public function __construct() {
            $data = "some_data";
        }
    }

    interface UserDao {
        public function saveUser(User $user);
    }

    // A DAO implementation which knows how to communicate using
    // PDO objects. Can be injected with a PDO object configured
    // to connect to any host, DBMS, etc.
    class PDOUserDao implements UserDao {
        private $pdo;

        public function __construct(PDO $pdo) {
            $this->pdo = $pdo;
        }

        public function saveUser(User $user) {
            // insert pdo insert/update logic here
        }
    }

    class InMemoryUserDao implements UserDao {
        // in-memory implementation here..
    }
?>


Minesweeper grid representation + calculating neighbor-sums

One idea ... in your getSummedMap function, you could put all the +1, -1, 0's in a list of 2-tuples and get the Sum with one for loop, e.g. ...

neighbor_incs = [(-1, 0), (1, 0), (0, 1), (0, -1),  # Top + Bottom + Left + right
                 (-1, -1), (1, -1), (1, 1), (-1, 1), ] # diagonals

for x_inc, y_inc in neighbor_incs:
    Sum += paddedGrid[xIter + x_inc][yIter + y_inc]


if (empty($video['itunes']) && !empty($itunecheck) && $video['itunes'] != "gol") {

If $video['itunes'] is empty, then you already know that it does not equal "gol".  So you could just say

if (empty($video['itunes']) && !empty($itunecheck)) {

And you would get the same effect.

Similarly, we could rewrite the whole thing as

if (empty($video['itunes'])) {
    //if mysql row $video['itunes'] is empty check the function ituneslink
    $itunecheck = ituneslink($mystrings);
    //ituneslink is a function that searches the itunes library for Movies/Music
    if (empty($itunecheck)) {
        //if ituneslink function is empty trigger the empty string itunesgol and
        $itunesgol = '';
        $smarty->assign('itunesgol', $itunesgol);
        itunes_add_item('gol', $video['uniq_id']);
        //add in mysql 'gol' that the itunescheck didn't find anything on itunes
        //search api, this will be useful for future rechecks
    } else {
        //NOW here I check if itunes is empty and itunescheck not empty and row
        //itunes not 'gol'. If all of them comply it will be added in the database
        itunes_add_item($itunecheck, $video['uniq_id']);
    }
} elseif($video['itunes'] == 'gol') {
    $itunesgol = '';
    $smarty->assign('itunesgol', $itunesgol);
    //because itunes search api has a limit of 20 req per minute I had to recheck
    //for this string if available because maybe the first search got 403
    //forbidden because of too many queries
    $itunecheck = ituneslink($mystrings);
    itunes_add_item($itunecheck, $video['uniq_id']);
} else {
    // if row itunes is not 'gol' it means that itunescheck got the itunes link
    //and successfully added in database
    $itunecheck = $video['itunes'];
}

This gets rid of the redundant if statements, adding to the original blocks instead.

Or

if (empty($video['itunes']) || ($video['itunes'] == 'gol')) {
    // if no cached result, or cached as `gol`
    // fetch new results from iTunes
    $itunecheck = ituneslink($mystrings);
    if (empty($itunecheck)) {
        $itunesgol = '';
        $smarty->assign('itunesgol', $itunesgol);
        itunes_add_item('gol', $video['uniq_id']);
    } else {
        itunes_add_item($itunecheck, $video['uniq_id']);
    }
} else {
    // otherwise use cached result
    $itunecheck = $video['itunes'];
}

This changes the behavior slightly.  It doesn't assume that a second iTunes search will always return results.  Instead, it treats a cached failure the same as no result in cache.

But if we do that, we can go ahead and just say

if (empty($video['itunes'])) {
    // if no cached result
    // fetch new results from iTunes
    $itunecheck = ituneslink($mystrings);
    if (empty($itunecheck)) {
        $itunesgol = '';
        $smarty->assign('itunesgol', $itunesgol);
    } else {
        itunes_add_item($itunecheck, $video['uniq_id']);
    }
} else {
    // otherwise use cached result
    $itunecheck = $video['itunes'];
}

This removes the concept of caching failures.  Instead, we'll just generate a cache miss next time.

You could also go the other direction and add more complexity such that you sometimes redo a 'gol' and sometimes don't.  Or whatever.  But as things are written, there doesn't seem to be any reason to have two cases with mostly the same behavior.

It is of course possible that I'm missing something.  You don't include definitions for ituneslink, itunes_add_item, and $smarty->assign, so there could be special stuff happening there.  Or prior to this code in setting $video['itunes'].  Or after this code that uses $itunesgol or $itunecheck.  But from what I see of this code, this seems to do mostly the same thing as the original.


Test to see if installed and if not, install it

Overall it's fine. My suggestions would be:

Fix the indenting.
If you find the comments helpful, great. Otherwise, consider saying "why" and not "what", e.g. # set the var SUDO to "" (blank) -> # This will be used as a prefix to run a command as root
You can alternatively consider checking if the command exists by running it: if htop --version > /dev/null 2>&1. This does not discriminate against aliases, functions and builtins.
Prefer user lowercase variable names to avoid conflicting with existing environment variables. SUDO="sudo" is ok since SUDO isn't in use, but if you had tried the same with PWD="pwd" or SHELL="sh" you could have gotten some odd side effects.
Use echo 'Error: htop is not installed.' >&2 to write the error message to stderr
The >&1 aka 1>&1 is redundant: it just redirects the FD to where it's already going.
It's generally considered rude to install packages without asking the user. A more canonical approach is to simply exit with an error saying that htop is missing and leave it to the user to install it (this also avoids tying the script to Ubuntu/Mint).
If you continue when htop exists, why is the script exiting after installing htop? If it's to handle installation failures due to bad password or full disk, you should probably handle that explicitly.
You can use exit aka exit $? to exit with the status of the previous command, so that if the installation failed, you don't claim that the script ran successfully.


It looks like you are trying to calculate the Wilson Score lower confidence bound for ranking as described here: http://www.evanmiller.org/how-not-to-sort-by-average-rating.html

There are a couple issues with the code. The main one that jumps out is that only some of the needed variables (n) are passed into the function and the other simply read from the module namespace (ups, downs). Encapsulating into functions can help. Another issue is where i and j are not actually used within the loop and are bad variable names anyway.

The following code also generates synthetic data so I could test the full code.

from math import sqrt
import numpy as np

def generate_data(filename):
    """ Generate synthetic data for StackExchange example """
    ratings_per_example = 10
    ratings = np.random.binomial(ratings_per_example,0.4,100)
    fake_ups = ratings
    fake_downs = ratings_per_example-ratings
    fake_ids = np.arange(len(ratings))
    merged = np.asarray(zip(fake_ids, fake_downs, fake_ups))
    np.savetxt(filename, merged, fmt='%d', delimiter=",", header='Fake Header')

def confidence(filename):
    """ Returns an array of lower confidence bounds from up/down rankings in file """
    downs = np.genfromtxt(filename, dtype=long, delimiter=',', skip_header=1, usecols=(1,))
    ups = np.genfromtxt(filename, dtype=long, delimiter=',', skip_header=1, usecols=(2,))

    lower_bound_ranks = [wilson_lower_bound(up, down) for up, down in zip(ups, downs)]

    return lower_bound_ranks

def wilson_lower_bound(up, down, z=1.0):
    """ http://www.evanmiller.org/how-not-to-sort-by-average-rating.html """
    n = up + down
    if n == 0:
        return 0.0
    else:
        phat = float(up) / n
        return ((phat + z*z/(2*n) - z * sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n))

generate_data('foo.csv')
confidence('foo.csv')


Check if a given linked list is palindrome

More tests

Having a test suite is nice.
It would be even nicer to make it more comprehensive by adding:

edge cases (empty list for instance)
inputs with an even number of elements
negative test cases : input is not a palindrome.

Here is a suggestion, I took this chance to remove the duplicated logic by extracting the data into a proper data structure:

# Test Cases
tests = [
    ([], True),
    ([1], True),
    ([1, 1], True),
    ([1, 2], False),
    ([3, 7, 3], True),
    ([3, 7, 4], False),
    ([6, 3, 7, 3, 6], True),
    ([7, 8, 6, 3, 7, 3, 6, 8, 7], True),
    ([7, 8, 6, 3, 7, 4, 6, 8, 7], False),
]
for inp, expected in tests:
    res = Solution(inp).list_palin()
    if res != expected:
        print("%s: %d != %d" % (inp, res, expected))

Using the boolean type

The bool type is expected for this type of situation (even if in Python, booleans are also integers equal to 0 or 1).

Many things can be simplified then:

    if ispal :
        return 1
    else :
        return 0

becomes:

    return ispal

Also, you can return False directly in the else block of the while loop.
Then, it becomes more obvious that you never assign False to ispal. You can get rid of it and all the logic around it.

def list_palin(self):
    """ Check if linked list is palindrome and return True/False."""
    node = self.head
    fast = node
    prev = None

    # prev approaches to middle of list till fast reaches end or None
    while fast and fast.next:
        fast = fast.next.next
        temp = node.next   #reverse elemets of first half of list
        node.next = prev
        prev = node
        node = temp

    if fast:  # in case of odd num elements
        tail = node.next
    else:    # in case of even num elements
        tail = node

    while prev:
        # compare reverse element and next half elements
        if prev.val == tail.val:
            tail = tail.next
            prev = prev.next
        else:
            return False
    return True

Do we need that much code?

Depending on what you are trying to achieve personally, you may or may not need to re-implement a linked list.

Also, having a class named Solution seems a bit awkward here.

Function/method to compare list

The final block of the function compares 2 lists. It may be worth moving this to a function on its own.

Even better, you could define an __eq__ method in the ListNode class:

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

    def __eq__(self, other):
        return isinstance(other, ListNode) and self.val == other.val and self.next == other.next

and then just write:

    if fast:  # in case of odd num elements
        tail = node.next
    else:    # in case of even num elements
        tail = node

    return prev == tail


There are two aspects to HTTP Strict Transport Security (HSTS):

Implementing HSTS on your site.
Submitting your already HSTS enabled site to the HSTS preload list. This is where the "list of HSTS sites" are compiled directly into the browser, which avoids the first request ever being over HTTP (where the request is potentially vulnerable to MITM attacks).

You seem to be going straight for #2. This is not necessarily recommended. Think of the "preload list" as a one-way trip. Technically it's possible to be removed from the preload list; realistically that's not something you want to even be thinking about. (It's hard - slow - enough stepping back from HSTS-only.)
The preload list submission page itself does not recommend going straight to "preload list submission". The recommendation is to increase the max-age parameter over a period of time (months), before taking the final step to submitting to the preload list. Test test test in the meantime to ensure SSL certs are reliably renewed, no mixed content warnings etc. etc.
I would also be wary about HSTS preload list submission (or even HSTS itself to some degree) on a shared server, where you don't have full control over the SSL configuration. You don't actually state whether you are on a shared server or not, but since you are doing all this config in .htaccess, I assume that you are. If you have your own server and access to the server config then most of this should be configured in the server/virtualhost config (and it is arguably easier and more reliable to do so).
Remember, that once you have gone the HSTS route (and users have accessed the HTTPS site or you are on the "preload list") then your site can only be accessed over HTTPS. This doesn't just apply to your site, but also to any 3rd party services you might be using (mixed content browser warnings etc.).

#IMPLEMENT HSTS
<IfModule mod_headers.c>
Header set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
</IfModule>

This sets the required HSTS HTTP response header on "most"*1 responses (but note the preload parameter, which should probably be omitted initially).
*1 However, this directive does not necessarily set the required header on all responses. A requirement of HSTS is that you also set the header on "redirect" responses (eg. www to non-www on HTTPS). Currently the above does not do this. You should be using the always condition on the Header directive to set the header on responses other than 200 OK. For example:
# Use "always" condition to set on "redirects" as well.
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains"

(I've also removed the preload parameter for now.)
You do not need the <IfModule> wrapper and should be removed. mod_headers should be enabled by default. This is your server, you know whether mod_headers is enabled or not. mod_headers must be enabled for this to work. You don't want this to silently fail should mod_headers not be available - you need notification as soon as this fails with an error in your logs.
Many articles state that you should only set the Strict-Transport-Security header on secure (HTTPS) responses. And the "preload list submission" does indeed issue a "warning" (not strictly an "error" I believe) if you send the header over HTTP as well. However, whilst it only needs to be set on the HTTPS response, compliant browsers ignore this header when sent over an unencrypted HTTP connection (to prevent MITM attacks) so it should not matter whether the header is "unnecessarily" sent over HTTP as well. This would be easier to manage in the appropriate <VirtualHost> containers in the main server config. Sending this header only on HTTPS responses in .htaccess is more complex (and hence more prone to error). You would need to employ an additional environment variable that you can use to set the HSTS response header conditionally.
For example:
# Set environment var "HSTS" if accessed over HTTPS connection
RewriteCond %{HTTPS} on
RewriteRule ^ - [E=HSTS:1]

# Conditionally set only on HTTPS connections (ie. when "HSTS" env var is set)
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains" env=HSTS

Otherwise, I believe your remaining directives are OK with regards to HSTS. But as always, test test test.

Resolve multiple (unnecessary) redirects

#FORCE WWW TO NON-WWW
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]

#URL EXTENSION REMOVAL
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]

A potential issue here (with the 2nd and 3rd canonical redirects above, after the HTTP to HTTPS redirect) is that this potentially results in two additional redirects if www + .html is requested. This could be resolved by simply reversing the two redirects and including the canonical hostname in the "URL EXTENSION REMOVAL" redirect (as mentioned in my answer to your earlier question).
For example:
#URL EXTENSION REMOVAL
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ https://example.com/%1 [R=301,L]

#FORCE WWW TO NON-WWW
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule (.*) https://example.com/$1 [R=301,L]

See my previous answer for an alternative approach to the "URL EXTENSION REMOVAL" redirect that addresses some potential issues.
If you are not using the www subdomain on other hostnames (eg. www.subdomain.example.com) then you could simplify the CondPattern on the www to non-www redirect to simply ^www\., ie. any requested hostname that simply starts www., rather than checking the entire hostname.

Additional Fixes
URL Extension Removal / Rewrite Loop (500 Internal Server Error)
There are a couple of other issues that I did not get round to addressing in your earlier question, not relating to HSTS, which I'll cover below...

#URL EXTENSION REMOVAL
:
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]

This (and similar) is one of those code snippets that is "blindly" copy/pasted everywhere (and I mean everywhere) as the "standard" way to append (URL-rewrite) the file-extension when using extensionless URLs. However, whilst it probably "works" for your valid-URLs, it has a serious flaw when requesting invalid-URLs...
If /about.html is a valid file that you wish to serve when requesting the extensionless URL /about then it works OK. However, if I (maliciously) requested /about/ or /about/<anything> it will send your server into a spiralling rewrite-loop, resulting in 500 Internal Server Error response. The end-user should not be able to invoke such a response (potentially more vulnerable to DDOS attacks and other hostile behaviour).
This is because REQUEST_FILENAME (the mapped filesystem path) does not necessarily refer to the same public URL-path as the REQUEST_URI (requested URL-path) variable.
To resolve this, use REQUEST_URI throughout. For example:
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.html -f
RewriteRule ^ %{REQUEST_URI}.html [L]

(The NC flag is superfluous on the RewriteRule directive here.)
See my answer to the following ServerFault question for more detail on this.
Hotlink Protection - Simplify Condition

#HOTLINKING PROTECTION
RewriteCond %{HTTP_REFERER} !^https://(www\.)?example\.com(/.*)*$ [NC]

This is relatively minor. The regex in the above condition can be simplified. At this point in the .htaccess file, the hostname has already been canonicalised to remove the www the subdomain, so the (www\.)? subpattern in the above is superfluous. As is the trailing (/.*)*$ subpattern, which simply matches everything else. You don't need to actually match anything here, you just need to assert that the Referer header starts with the appropriate (scheme+)hostname.
For example:
RewriteCond %{HTTP_REFERER} !^https://example\.com

The NC flag is also superfluous here. Forcing a case-insensitive match when it's not required just creates (a tiny bit) more work for your server and in some cases can open you up to vulnerabilities ("duplicate content" being a common one - although that is not an issue here).
Enabling unnecessary Options

#PREVENT DIRECTORY BROWSING
Options All -Indexes

This doesn't only prevent "directory browsing". The All argument enables a bunch of other stuff that you probably don't need, such as server-side includes (Includes) and the ability to execute CGI scripts (ExecCGI). (Incidentally, this is the only time when you can mix arguments with a + or - with those without.) To only prevent directory browsing (ie. the auto generating of directory indexes by mod_autoindex) then remove the All argument.
However, you probably only need FollowSymLinks (which might already be set in the server config), so you could set the following instead:
Options FollowSymLinks

Note the absence of + or -. This only sets FollowSymLinks, so disabling Indexes ("directory browsing") if it was already set.


Given a path to a directory, print the path to the biggest file in it

I find it weird that your function accepts a File but returns a String.  I would choose to return a File.

According to the JavaDoc for listFiles(),

  If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of File objects is returned, one for each file or directory in the directory.

Based on the documented behaviour, I would say that your if (current.isDirectory()) and if (files != null) checks are redundant, and I would eliminate the current.isDirectory() check.

It might be a good idea to do something about the possible SecurityException if you don't have permission to list a directory.

The throw new AssertionError() in the private constructor is an interesting idea that I haven't seen before.  Perhaps it would be better written as assert false;.


Elegant way for parsing birthday from rodne cislo (czech republic ID)

In addition to Doi9t's answer, which gives good advice, I'll add that your function name, extractBirthdayFromRodneCislo, is wrong, as it merely prints the birthday instead extracting it.

The easy fix is to rename the function extractBirthdayFromRodneCislo, which may fit you case, but doesn't allow you to do anything more fancy than that.

The better way to do things would be to return the date, allowing you to do anything with it after calling the method.

I'm completely new to Java, so I might miss something here, but it seems that the java.time.LocalDate datatype is a good fit for the job.

So your function becomes something like this:

public static LocalDate extractBirthdayFromRodneCislo(String rodneCislo) {

    // your logic here

    return LocalDate.of(year, month, day);
}

This approach has the added advantage that, should there be a mistake in the input string leading to an invalid date, it will throw an exception instead of silently accepting an invalid date – if you pass 622754/1234 to your function or Doi9t's, it will not care that 1962 -23 54 is not an acceptable output and print it just like any other date.

This illustrates to another problem: input validation. Your code doens't care if the input is indeed a Rodne Cislo. It will take any string as input. It may fail if Integer.parseInt encounter non-digit characters, but will accept strings that are too long, too short, has a properly placed / character or not (comments pointed out that Czech people don't always include the /, any other character in this place, etc., leading to a big risk of improperly parsing the string.

One possible tool for validating strings are regular expressions (regex). A lot of different patterns can be used to validate the input string, a simple one would be:

^[0-9]{6}\/[0-9]{3}[0-9]?$

If you are unfamiliar with regex, here is a breakdown of this expression:

^[0-9]{6}\/?[0-9]{3}[0-9]?$

^                                 # start with (no leading characater)
 [0-9]{6}                         # 6 digits
         \/?                      # may or may not include a "/" character
            [0-9]{3}              # 3 additional digits
                    [0-9]?        # 1 optional additional digit
                          $       # ends here (no trailing character)

Checking if the input string matches this pattern will call out a lot of invalid input strings, although it doesn't check if the month and day numbers are within valid ranges – it is definitely possible, but will get nasty quite quickly, and the LocalDate.of() method already takes care of it.

Another nice thing about regex is that you can extract specific ranges within the expression easily with capture groups. A little modifications on the previous expression gives (with explanation):

^([0-9]{2})([0-9]{2})([0-9]{2})\/?[0-9]{3}[0-9]?$

^                                                     # starts with (no leading characater)
 ([0-9]{2})                                           # 2 digits, capture them in group 1
           ([0-9]{2})                                 # 2 digits, capture them in group 2
                     ([0-9]{2})                       # 2 digits, capture them in group 3
                               \/?                    # an optional "/" character
                                  [0-9]{3}            # 3 digits
                                          ([0-9]?)    # 1 optional digit, capture it in group 4
                                                  $   # ends here (no trailing character)

You can then used the captured strings to parse the numbers (groups 1 to 3), or identify if the birth year is before or after 1954 (group 4).

My final take on the problem is this code:

import java.time.LocalDate;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

class Main {
    public static void main(String[] args) {
        System.out.println(extractBirthdayFromRodneCislo("535223/1234"))
        // > 2053-02-23
        System.out.println(extractBirthdayFromRodneCislo("530223/123"))
        // > 1953-02-23
        System.out.println(extractBirthdayFromRodneCislo("7503121234"))
        // > 1975-03-12
        System.out.println(extractBirthdayFromRodneCislo("753312/1234"))
        // > Throws an exception (invalid month)
        System.out.println(extractBirthdayFromRodneCislo("753312/12345"))
        // > Throws an exception (doesn't match pattern)
    }

    public static LocalDate extractBirthdayFromRodneCislo(String rodneCislo){
        Pattern p = Pattern.compile("^([0-9]{2})([0-9]{2})([0-9]{2})\\/?[0-9]{3}[0-9]?$");

        Matcher m = p.matcher(rodneCislo);

        if (!m.matches()){
            // Input doesn't match the pattern
            // throw a relevant exception
            // although I can't seem to do that propely with Java
        }

        int year = Integer.parseInt(m.group(1));
        if (year < 54 && !m.group(4).isEmpty()){
          year += 2000;
        }else{
          year += 1900;
        }

        int month = Integer.parseInt(m.group(2));
        if (month > 12){month -= 50;}

        int day = Integer.parseInt(m.group(3));

        return LocalDate.of(year, month, day); // will throw an exception if month or day ends up invalid
    }
}


Equivalent of Python's dict.update for STL maps in C++

You're not thinking laterally here.  If you std::swap() your two inputs, then you can merge() the original into the new, and the contents of the new map will prevail.

Here's what I mean:

namespace codereview
{
    template <typename DictT>
    void update(DictT& dst, DictT src)
    {
        std::swap(dst, src);
        dst.merge(src);
    }

}  // namespace codereview

// Test
#include <iostream>
#include <map>

template<typename Map>
void print(const Map& x)
{
    for (auto const& i: x)
        std::cout << i.first << "=" << i.second << " ";
    std::cout << std::endl;
}

int main()
{
    using Map = std::map<int, const char*>;
    Map a { {0, "zero"}, {1, "one"} };
    const Map b { {0, "nothing"}, {2, "two"}};

    print(a);

    // test lvalue argument
    codereview::update(a, b);
    print(a);

    // test rvalue argument
    codereview::update(a, Map{{3, "three"}, {0, "nada"}});
    print(a);
}

Output

0=zero 1=one
0=nothing 1=one 2=two
0=nada 1=one 2=two 3=three

Note that I changed the method signature to accept src by copy - the compiler will move-construct into src if it can, but if not, we'll need a copy so that we don't perturb the caller's version when we swap.


for loops

You are doing the same thing over and over again in many places in the code.

For example,

for (u64 k = start; (lcm*k) < limit; k++){
    u64 K = lcm*k;
    if ((primes[k] & (ONE << 0)) && (K+F30[0]) % num == 0)
        primes[k] &= ~(ONE << 0);
        ......
        if ((primes[k] & (ONE << 7)) && (K+F30[7]) % num == 0)
            primes[k] &= ~(ONE << 7);
}

could become

for(u64 k = start; lcm*k < limit; k++)
{
    u64 K = lcm*k;
    for(int i = 0; i < 8; i++)
    {
        if ((primes[k] & (ONE << i)) && (K+F30[i]) % num == 0)
            primes[k] &= ~(ONE << i);
    }
}

There are many other places you could do this as well. Also, the while loop near the bottom could be transformed into a for loop, as you are basically doing a for loop with while.
u64 vs int

Don't use a u64 when you don't need them; ints save on storage. You can replace the bottom two loops with regular ints.
Comments

Your code is somewhat confusing when you look at it on first glance. Maybe you should add some comments for the reader to see what is happening in your MarkNonPrimes function. Also, in the variable count (why declare it to 3-1 instead of 2?), and how you got that magic constant 0.26 in your vector declaration. The naming of F30 is pretty cryptic too.
Conventions

If you are going to use a convention then stick with it. Don't use ONE << 0 then ONE<<0 later.
Global variables

See here. Pass the variables as a parameter instead of declaring them globally, because as the project grows in size, then it will become harder to not have an ambiguous match for your global names. However, the constant ONE is fine, because not many variables will have the name one, but you should rename it u8_ONE instead because you may be declaring a u16_ONE or something of the sort.

Here is the code with all the modifications (except comments and naming):

#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>

typedef uint64_t u64;
const uint8_t u8_ONE = 1;
void markNonPrimes(const u64 start, const u64 num, const u64 lcm, const u64 limit, std::vector<uint8_t> &primes, u64 F30[])
{
    for(u64 k = start; lcm*k < limit; k++)
    {
        u64 K = lcm*k;
        for(int i = 0; i < 8; i++)
        {
            if ((primes[k] & (u8_ONE << i)) && (K + F30[i]) % num == 0)
                primes[k] &= ~(u8_ONE << i);
        }
    }
}

void getPrimesUpto(u64 limit)
{
   const u64 F30[] = {1,7,11,13,17,19,23,29};

   const u64 lcm = 30;
   std::vector<uint8_t> primes(limit*0.26 + 1,0xff);
   u64 n = 0;
   u64 count = 2;
   for(int i = 1; i < 8; i++)
   {
       markNonPrimes(1, F30[i], lcm, limit, primes, F30);
   }
   for(int k = 1; lcm * k * lcm * k < limit; k++)
   {
      const u64 K = lcm * k;
      for(int i = 0; i < 8; i++)
          if(primes[k] & (u8_ONE << i))
              markNonPrimes(k+1, K+F30[i], lcm, limit, primes, F30);
   }

   for(int k=0; lcm*k < limit; k++)
   {
      for(int i = 0; i < 8; i++)
         if(primes[k] & u8_ONE << i && lcm * k + F30[i] < limit)
         {
             count++;
             /*std::cout << lcm*k+F30[i] << " ";*/
         }
   }

   std::cout  << "\n======\n"<< count << "\n";
}

int main()
{
   clock_t start = clock();
   getPrimesUpto(100);
   std::cout << "\nTime: "<< clock() - start << std::endl;
}


Perl code that breaks a line after fixed number of columns

I am not sure it can be optimized in a sense of better performance. It could be streamlined though. The initial test for length($line) <= $LINE_LENGTH is just redundant. Compare:

    while (length ($line) > LINE_LENGTH) {
        $prefix = substr($line, 0, $LINE_LENGTH - 1 );
        $line = substr($line, $LINE_LENGTH - 1);
        printf("%s\n", $prefix);
    }
    printf("%s",$line );

PS: I am not familiar with perl enough. If there is a split at position function, you may use it instead of calling substr twice.


This post has been around for too long and I don't want it to be a zombie any longer... You haven't replied to our questions in comments but we see you have been on SE sites lately so I am going to go ahead with the code as is.

As was pointed out in comments there appears to be some type of rendering (perhaps server-side) that is mixed in with the JavaScript code, which is not declared, so I wouldn't really be able to try running the code even if I wanted to :/ I could try to dig through your StackOverflow posts to find relevant code but I don't have time for that.

For the code you posted, it doesn't really seem like "a lot" but that depends on perspective... if you really wanted, you could abstract the code in the v-if (i.e. v-if="date.datestamp==conflict.datestamp") to a method and call it instead of having the logic in the markup.

I question whether <template> is the best tag to use in the for loops...While there are no restrictions on permitted content within a <template> tag, it seems odd to have one nested inside the other. Would a simple <div> suffice for one or both?


You can accomplish this using Java 8 streams.

public List<Object> fetchMultiFieldsList() {
    return multiFieldMap.entrySet().stream()
      .flatMap(e -> {
          String entityName = e.getKey();
          List<Object> ids = e.getValue();
          return ids.stream()
            .map(id -> queryService.query(entityName, queryService.property("id").eq(id)));
      }).collect(Collectors.toList());
}

I think the code itself is relatively self-explanatory. The important bit is the usage of flatMap instead of map for the first mapping operation so that the resulting streams are concatenated, ending up with a flat list of objects rather than a list of lists.

It is unfortunate that Java does not support destructuring assignment, which would allow the first lambda expression to be a single expression of the form (k, v) -> ..., but it does not, so I've left the statements in for clarity.

If you are willing to omit the inner declarations, the above code can be simplified further.

public List<Object> fetchMultiFieldsList() {
    return multiFieldMap.entrySet().stream()
      .flatMap(e -> e.getValue().stream()
          .map(id -> queryService.query(e.getKey(), queryService.property("id").eq(id)))
      ).collect(Collectors.toList());
}

Whichever one you prefer is a matter of personal preference. The former has more descriptive variable names, while the latter is simpler and more functional.


Filter for reading data over a serial connection

class Filter(object) :
    """Return x if x is greater than min and less than max - else return None.

How about "if x is between min and mix"?

    Keyword arguments:
    min -- the minimum (default 0)
    max -- the maximum (default 0)

    Notes:
    Accepts integers and integer strings
    """
    def __init__(self, min=0, max=0) :

min and max are builtin python functions. I suggest not using the same names if you can help it.

        self.min = min
        self.max = max
    def __call__(self, input) :
        try :
            if int(input) <= self.max and int(input) >= self.min :

In python you can do: if self.min < int(input) <= self.max

                return int(input)

        except : pass

Don't ever do this. DON'T EVER DO THIS! ARE YOU LISTENING TO ME? DON'T EVER DO THIS.

You catch and ignore any possible exception. But in python everything raises exceptions, and you'll not be notified if something goes wrong. Instead, catch only the specific exceptions you are interested in, in this, case ValueError.

Futhermore, having a filter that tries to accept string or integers like this just a bad idea. Convert your input to integers before you use this function, not afterwards.

The interface you provide doesn't seem all that helpful. The calling code is going to have to deal with None which will be a pain. Usually in python we'd do something operating on a list or as a generator.

Perhaps you want something like this:

return [int(text) for text in input if min < int(text) < max]


I've finally found a satisfactory way to create classes on JavaScript. Are there any cons to it?

What about regular inheritance? Is extend supposed to be the superclass?

foo = { foo: "bar" };

a = my_class(foo);
b = my_class(foo);

a.foo = "baz";
console.log(b.foo);

--> "baz";

I would expect a and b to have their own state, yet they share a single foo property.


Calling API (with rate of 5 calls/second) using Jersey client

I'm not familiar with Jersey at all, so just two generic notes:

You might want/could use HEAD instead GET which does not download the message body.
I don't know what is logging framework but if it's SLF4J you should use the {} pattern instead of string concatenation.

logger.debug("Session URL is {}", sessionURL);


I can pass the initializer a negative size. Or a non-numeric size. I won't get any complaints until I try to use the buffer.
If I use write! exclusively, the buffer will always be empty. You're always shifting an element off of the array - even if it's the one you just added.
It's impossible to write nil or false to the buffer, though either of those are values someone might legitimately want to write.
But even if you manage to write a false'y value, you can't get it back; you'll just get a BufferEmptyException even if the buffer's not empty. Raise if the array's truly empty, and do so before you shift; not if the value you already shifted off is false'y. And, worse yet, the value is just gone forever. You shifted it off the array, so it's just disappeared. Since you can just use the array's length to tell you the state of the buffer, it's no problem to store false'y values.
It's generally good practice to define a non-bang method in terms of its bang counterpart. Right now you have 2 separate places where things are added to the buffer, instead of having one method call the other, just with an extra check.
Speaking of, it'd be nice to have a bang version of read that doesn't raise exceptions.
It'd be nice to have an attr_reader for the size, and a to_a for the items.
It'd also be nice to have a full? method. Otherwise you'll always have to either rescue an exception from write, or exclusively use write!. Besides, you could use the same full? method within the class too.
Likewise, an empty? method would be nice to complement the full? method. While you're at it, you might even add a method that returns the number of slots left in the buffer, and/or one that that returns the number of slots occupied.

Of course, it's not quite a circular buffer since, for one, it's not a perfectly fixed size. If write! worked as intended, and only shifted off items when necessary, it'd still (in it's current form) shift them off only after the buffer's "overflowed".

For another, it's not actually circular. You don't end up overwriting previously set slots. Instead you push and shift and array that expands up to a certain size. From the outside, it might well look like a circular buffer, but none of its internals match that description.

What you have is a general (almost) fixed-length (or rather "limited-length") FIFO buffer, but I wouldn't call it circular. But then again, implementing a strictly circular buffer in Ruby isn't really that useful. A FIFO buffer has its uses, sure, but a strictly circular one seems like trying to do low-level programming in a very high-level language. It's a technique that's useful when you have to allocate memory, and it's cool when you can do pointer arithmetic. But you don't allocate memory in Ruby, and you can't do pointer manipulation, so the arguments and tools for creating efficient buffers aren't really there.

It's like camping in you own back yard. It's fun to try, but it's not survivalism (and it'd probably be kinda dangerous to make a campfire).

But hey, it is fun

class FixedLengthFIFOBuffer
  class BufferEmptyException < StandardError;  end;
  class BufferFullException < StandardError;   end;

  attr_reader :size

  def initialize(size)
    @size = size.to_i # still lacking a check for values below 1
    @buffer = []
  end

  def full?
    @buffer.size >= size
  end

  def empty?
    @buffer.empty?
  end

  def write(data)
    raise CircularBuffer::BufferFullException if full?
    write! data
  end

  def write!(data)
    @buffer.shift if full? # maybe use read! instead and return the value?
    @buffer << data
  end

  def clear
    @buffer.clear
  end

  def read
    raise CircularBuffer::BufferEmptyException if empty?
    read!
  end

  def read!
    @buffer.shift
  end

  def to_a
    @buffer.dup
  end
end


As Phrancis noted, there's no way for us to tell what an interviewer might want to learn from this. So this is just based on my impressions.

I don't know why this is wrapped in a main function. The code appears written to run once, and take its input from the command line. But in that case, there's no reason to wrap it at all, really.
Conversely, if you do wrap it in a function, something has to actually call that function, but I don't see that anywhere.

So the code looks like it's supposed to be a standalone example that you just run - but it won't do anything unless you call main() yourself. However, if the point is to make a function that can be used with other code, then:

Don't call your function main, because that makes no sense
Don't take over input and output. If I call a function to rotate an array, I'd expect to pass in the array to rotate, and get an array back. I don't expect to have to enter stuff manually, and just have the results printed back at me.

It'd make more sense if your code only handled the rotation itself, returned the rotated array, and left everything else to other code. Rotating the array is the core task here; not input handling or printing. That's just scaffolding to prove it works - you can still add all that, and make a self-contained little test script, but again, that's not the point of implementing array rotation.

So I'd focus on the rotation itself, put that in a function. Something like rotateArray(array, steps).

Now, for your actual implementation:

There's a straight-up bug: If the array is empty to begin with, shift() will return undefined which then that gets pushed back to the array n times. So for n rotations of an empty array, you'll get an array back with n values in it (which are all undefined).
I wonder what'll happen if I try to rotate an array, say, 9,007,199,254,740,990 times. I'm betting it'd take a while (code's \$O(n)\$). And in the end, the rotated array might be back where it started, making all those trillions of shifts and pushes pointless. So that seems like there are optimizations that can be made.
Using shift and push is a valid solution, just not a very efficient one. Rotating an array is the same as chopping it into two pieces and putting them together "backwards". That is what shift and push does too, they just can't do more than one element at a time.
Why can't I pass a negative rotation-count to rotate right instead?

Here's what I'd do:

function rotateArray(array, steps) {
  // check if there's even something to rotate
  if(array.length < 2) {
    return array.slice(0); // always return a copy
  }

  // get the number of actual rotations to perform
  var n = steps % array.length;

  // check if there's any need to rotate
  if(n === 0) {
    return array.slice(0); // always return a copy
  }

  // slice and concat
  if(n < 0) {
    return array.slice(n).concat(array.slice(0, array.length+n));
  } else {
    return array.slice(n).concat(array.slice(0, n));
  }
}

This code does a few simple checks to see if there's any reason to rotate the array at all, and, if there is, it does by concatenating two slices (code's \$O(1)\$), rather than going steps number of iterations with shift and push.
And in case there's no reason to rotate anything, it just returns a copy of the input array (so that the output is always a new array, even if nothing needed to be rotated).


Function for adding a tag to the first row of a table is running slowly

As far as I understand, you just want to wrap the first as <thead> and the rest in <tbody>. Why it's slow:

html() is one possible cause. That's because you're reconstructing the DOM rather than reusing what's there already.
find() is a descendant lookup function. It looks for elements deep into the tree. If  you know that the element is a few levels down, then use multiple children() calls instead which only searches one level deep.
Just to add, attribute selectors like [id*="gvCategories"] are very slow. Better to use multiple classes instead, like class="MainContent gvCategories". That way, you can do $('.gvCategories'), which is faster.

The fastest and most painless fix is to just write the HTML with the first row in a <thead>. Plain and simple.

If you really want to go with JS, then here's my take on it and the performance test to prove it

jQuery.fn.fixGridView = function () {
    "use strict";

    // A jQuery object may be more than one element. Operate on each  using each()
    // Additionally, return the result to allow chainability.
    return this.each(function () {
        // Cache the element to avoid doing DOM refetch
        var element = $(this);
        if (!element.is('table')) return;

        // No need for tbody, since the browser automatically adds it
        // http://stackoverflow.com/a/938143/575527

        // Now we avoid using find() since it looks for all descendants.
        // Instead, we use children() to limit our search to 2 levels of children
        var rows = element.children('tbody').children('tr');
        var thead = element.children('thead').length;

        // Get the first row, wrap it in <thead>, and prepend it to the table
        if(!thead) rows.eq(0).wrap('<thead/>').parent().prependTo(element);

    });

};

$(document).ready(function () {
    $('.gvCategories').fixGridView();
});


If you want code readability, check the escape-string-regexp solution from @CoolAJ86

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , =
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());


Finding the tallest and find the index number of the next taller guy in a circular queue

I think you can write a linear time solution borrowing ideas from this. The idea is to keep a stack of decreasing maxima (SDM). Let's consider first the problem without taking into account the circularity...

Say your input was [7, 4, 5, 3]. When you are processing the third item (5), you want your SDM to be [(7, 1), (4, 2)], where he second item in the tuple is the 1-based index of that item in the original array, as per your problem's description. You search the SDM for the last entry larger than the item being processed, which in this case is (7, 1), so the index of the first item larger than 5 to its left is 1. You then discard all items in the SDM to the right of this one, and insert the current value in it's position, so the SDM now becomes [(7, 1), (5, 2)]. Rinse, repeat, and you have all your first items larger than to the left. For the symmetric item to the right, do the same scanning from right to left.

At first this may seem as an \$O(n^2)\$ algorithm, since you have to search a list that could potentially be as large as the array (e.g. if the input is monotonically decreasing) for every item. Because the SDM is sorted, you could try to use binary search to make that bound \$O(n\log n)\$, but that would actually slow down the process!

You have to keep in mind that, as the stack is being searched sequentially, entries that aren't larger than the one being processed are being removed from the stack! So the more work an item requires to find it's answer, the easier it makes it for the ones remaining. A careful analysis of this shows that, on average, each item takes constant time to process, so the resulting time complexity is \$O(n)\$, which is basically as good as it gets.

You can factor in the circularity of the problem into the above approach, by first finding the maximum, and always starting your circular iteration, whether to the left or right, from it, so that you will always have the maximum in your SDM.

But enough talking, here's an implementation:

def taller_to_the_sides(list_):
    max_index = list_.index(max(list_))
    sdm = []
    left = []
    for index in range(len(list_)):
        index += max_index
        index %= len(list_)
        item = list_[index]
        while sdm and sdm[-1][0] <= item:
            sdm.pop()
        if sdm:
            left.append(sdm[-1][1] + 1)
        else:
            left.append(-1)
        sdm.append((item, index))
    if max_index > 0:
        left = left[-max_index:]+left[:-max_index]
    sdm = []
    right = []
    for index in range(len(list_)):
        index = max_index - index
        index %= len(list_)
        item = list_[index]
        while sdm and sdm[-1][0] <= item:
            sdm.pop()
        if sdm:
            right.append(sdm[-1][1] + 1)
        else:
            right.append(-1)
        sdm.append((item, index))
    right = right[max_index::-1] + right[:max_index:-1]
    return zip(left, right)

There are two almost identical blocks in that function that should probably be refactored into a common external function, but I felt it would better show what was going on to keep them separated.

Anyway, when you run this you get the expected output:

>>> list(taller_to_the_sides([172, 170, 168, 171, 169]))
[(-1, -1), (1, 4), (2, 4), (1, 1), (4, 1)]
>>> list(taller_to_the_sides([169, 172, 170, 168, 171]))
[(5, 2), (-1, -1), (2, 5), (3, 5), (2, 2)]

The second example is the first one shifted one item to the right, to show that maxima not in the first position also work. And since the algorithm is linear, it handles large inputs reasonably fast:

a = [random.random() for _ in range(100)]
>>> %timeit taller_to_the_sides(a)
10000 loops, best of 3: 172 µs per loop
a = [random.random() for _ in range(1000)]
>>> %timeit taller_to_the_sides(a)
1000 loops, best of 3: 1.78 ms per loop
a = [random.random() for _ in range(10000)]
>>> %timeit taller_to_the_sides(a)
100 loops, best of 3: 18.3 ms per loop

To be honest, I was expecting it to be faster, but do notice also how the time scaling is roughly linear, as expected.


Good

You are following the .NET Naming Guidelines
The variables are in the correct scope

Review
Omitting braces {} although they might be optional can lead to hidden and therfore hard to track down bugs. I would like to encourage you to always use them.

Regarding public string PrintElements() I would suggest to simply override ToString() which is more idiomatic.

If we take a closer look at the Enqueue(int n) method we notice that the difference between the if and the else part is simply the value of next. We can remove this code duplication by adding a variable Node node and assign head like so
public void Enqueue(int n)
{
    Node node = head;
    head = new Node
    {
        value = n,
        next = node
    };

    size++;
}

much better, isn't it ?

A C# developer would expect from a Queue that if the Queue is empty (in your case if size == 0) a call to Dequeue() would throw an InvalidOperationException.


I have created generic repositories many times and what I found was that you're going to need to create interfaces for each entity typed repository.
So IUserRepository that implements IGenericRepository<User>, this way you'll be able to

Inject the repository easier with Inversion Of Control
Create extra methods for each entity type as and when
Test your controller easier

Update
I realise this update comes a long time after the question, but time has past and experience has been gained.
You don't necessarily need a new interface for entity type. IoC containers can inject a specific implementation based on the generic parameter of the IGenericRepositoy interface. You will need an interface however for each implementation that has specific methods for that type, such as GetExpiredProducts() as mentioned in the initial question.
You could also remove the generic parameter from the interface and move the where clause to each method:
public interface IGenericRepository : IDisposable
{
    IEnumerable<T> SelectAll() where T : class;
    T SelectByID(object id) where T : class;
    void Insert(T obj) where T : class;
    void Update(T obj) where T : class;
    void Delete(object id);
    void Save();
}

then implement a GenericRepository class:
public class GenericRepository : IGenericRepository
{
    public GenericRepository()
    {
        blah...
    }
    public GenericRepository(ModelDBEntities dataContext)
    {
        blah...
    }

    public IEnumerable<T> SelectAll() where T : class
    {
        blah...
    }
    public T SelectByID(object argId) where T : class
    {
        blah...
    }
    public void Insert(T obj) where T : class
    {
       blah...
    }
    public void Update(T obj) where T : class
    {
        blah...
    }
    public void Delete(object argId)
    {
        blah...
    }
    public void Save()
    {
        blah...
    }
}

this would mean that any implementation of a type specific repository could just inherit this saving you some work
public interface IUserRepository : IGenericRepository
{
    int CountUsers();
}

public class UserRepository : GenericRepository, IUserRepository
{
    public UserRepository()
    {
        blah...
    }
    public UserRepository(ModelDBEntities dataContext)
        : base(dataContext)
    {
        blah...
    }

    public int CountUsers()
    {
        blah...
    }
}

You can then decide on what you want to inject into your controller, if you just want the base CRUD methods then you will only need to pass in the implementation of IGenericRepository and use for several types.


Efficiently determine every factor of a given natural number

def primeFactor(n):
    ''' Generates prime factors of n'''
    if n <= 1: return
    prime = next((x for x in range(2, math.ceil(math.sqrt(n))+1) if n%x == 0), n)
    yield prime
    yield from primeFactor(n//prime)

For a start, consider that after yielding prime this can never yield a number less than prime, but the recursive call still starts again from 2. So one optimisation would be

def primeFactor(n):
    ''' Generates prime factors of n'''
    return primeFactorInner(n, 2)

def primeFactorInner(n, min):
    if n < min: return
    prime = next((x for x in range(min, math.ceil(math.sqrt(n))+1) if n%x == 0), n)
    yield prime
    yield from primeFactorInner(n//prime, prime)

Next, that range with an implicit step of 1 is a bit overkill. Once you've finished returning 2s you could just step through odd numbers. At this point I'm tempted to say that it would be convenient to change the return value to already do the grouping, and have an auxiliary method to get the power of a prime in n.

def primePower(n, p): return 0 if n%p > 0 else 1 + primePower(n//p, p)

Then we can write

def primeFactorInner(n, min):
    if n < min: return
    if min == 2:
        a = primePower(n, 2)
        if a > 0:
            yield (2, a)
            yield from primeFactorInner(n // (2 ** a), 3)
            return
    prime = next((x for x in range(min, math.ceil(math.sqrt(n))+1, 2) if n%x == 0), n)
    a = primePower(n, prime)
    yield (prime, a)
    yield from primeFactorInner(n // (prime ** a), prime + 2)

Now, if we carry that argument to extremes we would only want to loop over primes. So we could split into two phases:

for p in enumeratePrimes(math.floor(sqrt(n)) + 1):
    a = primePower(n, p)
    if (a > 0):
        yield (p, a)
        n = n // (p ** a)
        if n == 1:
            # Early abort
            return
if n > 1:
    yield (n, 1)

enumeratePrimes would probably best be implemented with a simple sieve.

  I want it to return the factors in ascending order, without
  duplicates. Originally, I was hoping I'd be able to have the entire
  thing be a lazy function (no eager evaluation at all). Unfortunately,
  I haven't been able to figure out a good way to do this.

The short answer is a priority queue. Initially you insert 1. When you pop and yield a factor, you push certain multiples of the factor. The mildly interesting part is ensuring that you only push each number once. I've found the Java code where I did a variant on this, and ported it to Python:

import heapq

def divisors(n):
    primes = [(1, 1)] + list(primeFactors(n))
    q = [(1, 0, 1)]
    while len(q) > 0:
        # d is the divisor
        # i is the index of its largest "prime" in primes
        # a is the exponent of that "prime"
        (d, i, a) = heapq.heappop(q)
        yield d
        if a < primes[i][1]:
            heapq.heappush(q, (d * primes[i][0], i, a + 1))
        if i + 1 < len(primes):
            heapq.heappush(q, (d * primes[i + 1][0], i + 1, 1))
            # The condition i > 0 is to avoid duplicates arising because
            # d == d // primes[0][0]
            if i > 0 and a == 1:
                heapq.heappush(q, (d // primes[i][0] * primes[i + 1][0], i + 1, 1))

I'm not really a Pythonista, so although I suspect that you can make this even lazier by avoiding the list(), I'll leave that to someone who knows the language better than me.


Here are some things that may help you improve your code.
Use include guards
There should be an include guard in each .h file.  That is, start the file with:
#ifndef EXPRESSION_H
#define EXPRESSION_H
// file contents go here
#endif // EXPRESSION_H

The use of #pragma once is a common extension, but it's not in the standard and thus represents at least a potential portability problem.  See SF.8
Consider using standard routines
C++ provides a great number of useful utilites such as std::remove that you could use instead of your own hand-written function to remove whitespace.  They're almost always faster and less buggy and by using library software, you can develop your own code more quickly and accurately.  So instead of this:
//Remove whitespace
std::string output;
for (auto &i : s)
{
    if (i != ' ')
        output += i;
}
return parseRec(output);

One could use this:
s.erase(std::remove(s.begin(), s.end(), ' '), s.end());
return parseRec(s);

Note that this uses s rather than output per the next suggestion.
Understand pass-by-value
One thing that is quite different about C++ as compared with Java is how parameter passing is done.  In general, there is pass-by-value and pass-by-reference.  The pass-by-value is what we get when we write things like this:
static Expression parse(std::string s);

The gives parse its own copy of s.  If we use pass-by-reference, it would generally look something like this:
static Expression parse(const std::string& s);

Now we are giving parse a reference (indicated by &) rather than copying it.  In this example, we use the very common idiom of passing a const reference.  This indicates that the called function parse may examine but not alter the value.  Unlike Java, there is no automatic garbage collector in C++, so it's up to you to manage memory.  Generally, passing by reference is faster and uses less memory, but in cases where we would be making a copy anyway, passing by value makes sense.
Prefer private to public where practical
The Expression class has its only data members as public members.  Rather than do it that way, it would be better to keep them private. See C.9 for details.
Eliminate redundant functions
When a non-static member function is called in a C++ class, *this is implicitly passed.  So the result is that this function is entirely useless:
float Expression::eval()
{
    return Expression::evalRec(*this);
}

Instead, just rename evalRec as eval and write it as a member function:
float Expression::eval()
{
    switch (symbol[0])
    {
    case '+':
        return left->eval() + right->eval();
    case '-':
        return left->eval() - right->eval();
    case '*':
        return left->eval() * right->eval();
    case '/':
        return left->eval() / right->eval();
    default:
        return std::stoi(symbol);
    }
}

Simplify your code by making full use of standard library structures
The parseRec routine uses a std::ordered_map and also a switch to find the operator with the lowest precedence.  I suggest that when you see that you have repeated the operators in multiple places, this is a hint that perhaps you could use a different approach to avoid this duplication.  In this case, my inclination would be to use std::min_element.  This requires beginning and ending iterators and a comparison operation.  First, let's write a comparison operation:
enum class op_precedence { LOW, MED, NON_OP };

static constexpr op_precedence precedence(char ch) {
    op_precedence val{op_precedence::NON_OP};
    switch (ch) {
        case '+':
        case '-':
            val = op_precedence::LOW;
            break;
        case '*':
        case '/':
            val = op_precedence::MED;
            break;
        default:
            break;
    }
    return val;
}

Now we can use std::min_element:
std::string::iterator lowest{std::min_element(s.begin(), s.end(),
    [](const char &a, const char &b){
        return precedence(a) < precedence(b);
    })
};

This uses a lambda to actually effect the comparison.  So now the whole function looks like this:
Expression Expression::parseRec(std::string s) {
    std::string::iterator lowest{std::min_element(s.begin(), s.end(),
        [](const char &a, const char &b){
            return precedence(a) < precedence(b);
        })
    if (precedence(*lowest) == op_precedence::NON_OP) {
        return Expression(s, nullptr, nullptr);
    } else {
        return Expression(std::string(1, *lowest),
                          new Expression(parseRec(s.substr(0, lowest-s.begin()))),
                          new Expression(parseRec(s.substr(lowest-s.begin() + 1)))
                          );
    }
}

Note, too, that this uses the modern nullptr rather than the old C-style NULL.
Dive deeper into C++
I know you're just beginning with C++ (and it looks like a promising beginning!) but to whet your appetite for more, we can actually go a little further with the concept mentioned above.  Specifically, we have a similar duplication in eval, so we could further consolidate information.  Here's one way to do it:
enum class op_precedence { LOW, MED, NON_OP };
struct op {
    op_precedence precedence;
    float (*operation)(float, float);
};

static const std::unordered_map<char, op> operation = {
    { '+', { op_precedence::LOW, [](float a, float b){return a+b;}} },
    { '-', { op_precedence::LOW, [](float a, float b){return a-b;}} },
    { '*', { op_precedence::MED, [](float a, float b){return a*b;}} },
    { '/', { op_precedence::MED, [](float a, float b){return a/b;}} },
};

static op_precedence precedence(char ch) {
    auto myop{operation.find(ch)};
    return myop == operation.end() ? op_precedence::NON_OP : myop->second.precedence;
}

Now the rest of the program gets shorter and more concise:
float Expression::eval()
{
    auto myop{operation.find(symbol[0])};
    if (myop == operation.end()) {
        return std::stoi(symbol);
    }
    return myop->second.operation(left->eval(), right->eval());
}

Expression Expression::parse(std::string s)
{
    s.erase(std::remove(s.begin(), s.end(), ' '), s.end());
    return parseRec(s);
}

Expression Expression::parseRec(std::string s)
{
    std::string::iterator lowest{std::min_element(s.begin(), s.end(), [](const char &a, const char &b){
        return precedence(a) < precedence(b); })};
    if (precedence(*lowest) == op_precedence::NON_OP)
    {
        return Expression(s, nullptr, nullptr);
    }
    else
    {
        return Expression(std::string(1, *lowest),
                          new Expression(parseRec(s.substr(0, lowest-s.begin()))),
                          new Expression(parseRec(s.substr(lowest-s.begin() + 1)))
                          );
    }
}

Don't use std::endl if you don't really need it
The difference betweeen std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream.  This can be time-consuming in a program with a lot of I/O and is rarely actually needed.  It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one.  Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.
About return 0;
All compliant compilers will generate the equivalent of return 0 at the end of main, so I generally omit that.  Others prefer to write it explicitly for stylistic reasons.  Whichever you choose, it's useful to know.
Use the appropriate smart pointer type
The code, as written, abuses std::shared_ptr because no two objects should ever actually share the same Expression.  For that reason, what you really should use instead is std::unique_ptr, but that makes things a bit more complex.  In particular, we can no longer freely make copies (or they wouldn't be unique!) so we must use C++ move semantics.  It's all perhaps a bit much for a beginner, but here's how one would rewrite the relevant portions of the class declaration.
std::unique_ptr<Expression> left;
std::unique_ptr<Expression> right;
Expression(std::string symbol, std::unique_ptr<Expression> &&left, std::unique_ptr<Expression> &&right);

Now the constructor looks like this:
Expression::Expression(std::string symbol, std::unique_ptr<Expression> &&left, std::unique_ptr<Expression> &&right)
    : symbol(symbol), left(std::move(left)), right(std::move(right)) {}

And instead of using new (which is rather rare in modern C++), we use std::make_unique instead:
return Expression(std::string(1, *lowest),
                  std::make_unique<Expression>(parseRec(s.substr(0, lowest-s.begin()))),
                  std::make_unique<Expression>(parseRec(s.substr(lowest-s.begin() + 1)))
                  );


Template for PHP service (/etc/init.d) script

from stop:

        if (service::is_running())
        {
            writeln('Not stopped; may still be shutting down or shutdown may have failed.');
            return false;
        }

        service::status();

        return !service::is_running();

from start:

        service::status();

        return service::is_running();

Hmm, looks like a similar pattern... Can we combine this in a separate function?

What does service::status do?

    public static function status()
    {
        $running=service::is_running();
        if ($running) writeln(NAME.' start/running, process '.service::get_pid()); else writeln(NAME.' stop/waiting');
        return $running;
    }

... Wait, it prints a few things and then returns whether it's running.

So why the double is_running call?

I'd just return the result of service::status in these cases. It'd be more correct too; what if a service stops between your logging and the return statement? You'd log that it's running and then return that it's ... not running. Good way to have logs showing "everything is fine" whilst things aren't doing what they're supposed to do.


Emptying and populating an element in jQuery

Your code isn't bad, but there are some aspects that tick me a bit.

Lets start with the generateRandom()

You currently have the following:

var objCount = Object.keys(cards).length - 1;
var number   = Math.floor(Math.random() * (objCount - 0 + 1)) + 0;

return number;

And I ask:

Why + 0 or - 0?
Why Object.keys(cards).length - 1; for an array?
Why take 1 to sum it again?
Why that bloat?

Here's how I would write it:

function generateRandom()
{
    return Math.floor(Math.random() * cards.length);
}

Since the length is 1-based and the indexes are 0-based and Math.random() returns numbers between 0 and 1 (excluding the 1), you don't need more than this.
And now, the drawHumanCard()

You have the following code:

var random = generateRandom();

var humanEl = $('#human');

humanEl.find('#human-name').empty().text(cards[random]['name']);
humanEl.find('#human-job').empty().text(cards[random]['job']);
humanEl.find('#human-image').attr('src', 'img\/trumps\/' + cards[random]['image']);

You can store cards[random] inside a variable, like this:

var card = cards[random];

And to improve performance, you don't need the .empty(). It's a waste of time and CPU power.

Also, why humanEl.find('#human-name') instead of $('#human-name')? And why not an array with these objects?

I would rewrite the whole thing as this:

var human;

//it must run after the elements exist in the DOM
$(document).ready(function(){
    human = {
        name: $('#human-name'),
        job: $('#human-job'),
        image: $('#human-image')
    };
});

function drawHumanCard()
{
    var random = generateRandom();

    var card = cards[random];

    human.name.text(card['name']);
    human.job.text(card['job']);
    human.image.attr('src', 'img/trumps/' + card['image']);
}

So, the final code would be like this:

var human;

$(document).ready(function(){
    human = {
        name: $('#human-name'),
        job: $('#human-job'),
        image: $('#human-image')
    };
});

var cards = [
    new TopTrumpCard('Name 1', 'designer', 'image1.jpg'),
    new TopTrumpCard('Name 2', 'designer', 'image2.jpg'),
    new TopTrumpCard('Name 3', 'designer', 'image3.jpg')
];

function TopTrumpCard(name, job, image)
{
    this.name = name;
    this.job = job;
    this.image = image;
}

function drawHumanCard()
{
    var random = generateRandom();

    var card = cards[random];

    human.name.text(card['name']);
    human.job.text(card['job']);
    human.image.attr('src', 'img/trumps/' + card['image']);
}

function generateRandom()
{
    return Math.floor(Math.random() * cards.length);
}

This can and should be written as vanilla Javascript. The use of jQuery isn't justifiable here but that is an exercise for the O.P. to try.


I think one of the reason why functional programming is usually easier is its natural modularity. Consider to design your solution in a more layered way. I.e. separate parser and invocations. Avoid callbacks in favor of lazy stream of events (see unsafeInterleaveIO) or borrow ideas from reactive frameworks. Also see Data.Binary.Get module or parsec package for implementing parser.


Algorithm

The time and space complexity of the current algorithm depends on the length of intervals in the input. This is very inefficient for inputs with long intervals, even when there are only few intervals.

The problem can be reworded as: merge the intervals and calculate their total length.
This should be fairly simple to implement efficiently:

Sort the intervals by start position ascending, and end position descending. That is, (5, 10) should come before (5, 8).
Initialize the previous interval = the first, and total = 0
Iterate from the second interval until the end, at each step:

If the current interval is fully included in previous, then skip it
If the current interval overlaps with previous, then update or replace previous to fully include both the previous and the current
If the current interval doesn't overlap with previous, then add the length of previous to total, and replace previous with the current

At the end, add the length of previous to total

Readability

There are serious readability concerns with this code.
This writing style is error-prone and confusing:

var slot=i+e.Desde-min;
if(slot<cantidad)
if(!bA.Get(slot))
{
   bA.Set(slot,true);
  recorrido++;
}
slot=e.Hasta-i-min-1;

The above should have been written like this:

var slot = i + e.Desde - min;
if (slot < cantidad)
{
    if (!bA.Get(slot))
    {
        bA.Set(slot, true);
        recorrido++;
    }
}
slot = e.Hasta - i - min - 1;

This way the scope of the if statements is perfectly clear.

I also added spaces around operators and after commas as per the convention.

As a side note, in your algorithm the slot < cantidad condition is always true, so in this example the first if statement had no effect,
as if it wasn't even there.


Your code is fine, an equivalent method in Swift 3 would be

let floatArr = numArr.map { $0.map { Float($0) } }

You get the same result with less code by using the
bridging cast from NSNumber to Float, which works for (nested)
arrays as well:

if let floatArr = numArr as [[Float]] { ... }

Actually I don't know of any case (in Swift 3) where this cast can fail.

Things change a bit in Swift 4, as a consequence of
SE 0170 - NSNumber bridging and Numeric types. Your code still works fine, and is equivalent
to

let floatArr = numArr.map { $0.map { Float(truncating: $0) } }

The truncating initializers where introduced because not every
Number can be converted to a scalar value without loosing information,
there are also failable init?(exactly:) initializers.

Now the bridged cast can fail

for numbers which are not exactly representable as a Float,
such as Double(1.1),
for numbers which exceed the range of Float.

(The first case is currently discussed at https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170612/037499.html and may change in the future.)

Example:

let numArr = [
    [ NSNumber(value: 1.1), NSNumber(value: 2.0) ],
    [ NSNumber(value: Double.greatestFiniteMagnitude) ],
]

if let floatArr = numArr as? [[Float]] {
    print(floatArr)
} else {
    print("failed")
}

This produces [[1.10000002, 2.0], [inf]] in Swift 3, but fails
in Swift 4.

To summarize: Your code is fine.

If you don't care about "loosing
precision" or overflows then there is no need to change anything. In Swift 4
you can write it as Float(truncating: $0) to emphasize
that the result might not be exactly identical to the given
numbers.
If you care then you can use the new "exactly" initializers,
or the bridged cast as? [[Float]] in Swift 4.


Finding optimal mapping patterns that transform relational data into a linear format

Some slight improvements:

You could do without the result array (less state ).
I think using vanilla object destructuring is more clear than the lowdash reduce method which is confusing to me (unless I still don't understand it and my code actually is not equivalent to yours ).

const allNodes = [
];

const rootNode = {
};

function initializeNodeMapper(nodes) {
  return function mapNodes(node) {
    const propertyIds = node.properties.map(({ id }) => id);
    const currentNode = nodes.find(({ id }) => id === node.id);
    const nodeWithFilteredProperties = {
      ...currentNode,
      properties: currentNode.properties.filter(({ id }) =>
        propertyIds.includes(id)
      )
    };

    return node.children
      ? [nodeWithFilteredProperties].concat(node.children.map(mapNodes))
      : [nodeWithFilteredProperties];
  };
}

const mappedData = initializeNodeMapper(allNodes)(rootNode);

Update:

Are you looking for something like this?

const nodes = [
];

const rootNode = {
};

const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);

const getFlattenedNodes = node =>
  node.children
    ? [node].concat(
        node.children.reduce(
          (acc, val) => acc.concat(getFlattenedNodes(val)),
          []
        )
      )
    : [node];

const getPropertyIds = node => node.properties.map(({ id }) => id);

const getNodeWithProperties = nodesWithProperties => node =>
  nodesWithProperties.find(({ id }) => id === node.id);

const getNodesWithFilteredProperties = propertyIdsAndNodesToBeFiltered =>
  propertyIdsAndNodesToBeFiltered.map(([propertyIds, nodeWithProperties]) => ({
    ...nodeWithProperties,
    properties: nodeWithProperties.properties.filter(({ id }) =>
      propertyIds.includes(id)
    )
  }));

const getPropertyIdsAndNodes = nodesWithProperties => flattenNodes =>
  flattenNodes.map(node => [
    getPropertyIds(node),
    getNodeWithProperties(nodesWithProperties)(node)
  ]);

const mappedData = pipe(
  getFlattenedNodes,
  getPropertyIdsAndNodes(nodes),
  getNodesWithFilteredProperties
)(rootNode);


Test that all Python keywords are mentioned in a dictionary's values

I'd personally use a generic function to flatten your datatype.

If an item in your collection in collections.Iterable then you will want to recurse through it.
If it's not you will want to yield it.
If it's a str or bytes you'll want to yield it, however this can change. And so you'll want to pass a tuple of these wanted types.
You probably want to only go through dictionary values as opposed to keys. And so you should pass a function to handle dictionaries.

And so I'd make:

def flatten(obj, dict_handle=dict.keys, wanted=(str, bytes)):
    def inner(obj):
        if isinstance(obj, dict):
            obj = dict_handle(obj)
        for el in obj:
            if isinstance(el, collections.Iterable) and not isinstance(el, wanted):
                yield from inner(el)
            else:
                yield el
    return inner(obj)

From this your code becomes:

from keyword import kwlist
import collections

unknown = set(kwlist) - set(flatten(Keywords_33, dict_handle=dict.values))
print(unknown)

If you don't want to remove 'File_2' from kwlist, then you can always change Keywords_33 to a dictionary:

unknown = set(kwlist) - set(flatten(dict(Keywords_33), dict_handle=dict.values))
print(unknown)


String checking functions in functional JavaScript

I think these are rather readable, actually more so than the original ones. You've condensed the functions considerably!

Going pointfree

One further possibility would be to go more "pointfree", which you find a lot of in Haskell, for example. Define or in terms of functions (so its arguments can be evaluated lazily), then you can work at a higher level of abstraction:

const or = (f, g) => (...args) => f.apply(f, args) || g.apply(g, args)

const alpha        = or(lowerAlpha, upperAlpha)
const alphaNumeric = or(numeric, alpha)
const printable    = or(space, inBetween(32, 127))

And then you can configure inBetween to accept the variable parameter separately:

const inBetween  = (a, b) => x => a <= x && x <= b

const space      = x => [9, 10, 12, 13, 32].includes(x)
const numeric    = inBetween(48, 57)
const lowerAlpha = inBetween(97, 122)
const upperAlpha = inBetween(65, 90)

I find this a bit more readable, since it removes the repetition of the parameter code. The resulting code is denser and reads nicely: "alpha means either lowerAlpha or upperAlpha", etc.

But really this comes down to your preferences. As far as

  do these functions satisfy what said as functional?

that depends on your definitions/requirements. I'd say they're certainly functional in the sense of avoiding mutability, except for every, and in the philosophy of composing together small functions.

every

A more functional every might recurse while fn(x) is truthy and elements remain in the list, something like this:

const every = (pred, [head, ...tail]) =>
    pred(head) && (tail.length ? every(pred, tail) : true)

but this won't behave nicely in current JS engines. One modification you could do now, though, is to use for...of in every, so that it also works on Sets, ES7 generators, and other iterables that might not be indexable:

const every = pred => list => {
    for (let x of list) {
        if (!pred(x)) return false
    }
    return true
}


How to simplify the record syntax with pattern matching?

First, when you are not using fields in a record, you don't have to use _ to mark that they should be ignored;  you only need to include the fields in the pattern that you are actually using.

Second, it is possible to update a couple of fields in a record without respecifying the whole thing from scratch.  If x is the name of the old record and you want to set the field a to 42 and b to 24, then the expression x { a = 42, b = 24 } is equal to the record x with a set to 42 and b set to 24.

Putting these ideas together, autoAttack could be rewritten like so:

autoAttack :: Actor -> Actor -> Actor
autoAttack actor@(Actor {stats = stats@(StatsSystem {physicalDamage = p, health = h}})) =
    actor {stats = stats { health = h - p } }

Where we have used the syntax actor@(Actor ..) to bind the Actor to the name actor, which is a useful pattern for when you want to both pattern match on an argument and also have access to its value.

Just to be clear, it is worth mentioning that, because data is immutable, changing a couple of fields involves making a full copy of the data structure.  (Thanks to Daniel Wagner for bringing this up).


Readability concerns with literal dictionary lookup vs if-else

Since you mention maintainability I think that the consideration can be taken in terms of what next changes may look like. If further changes will take more statements to be executed with the result of one of those specific options, or if more options will be added, I would stick to the dictionary approach.

Looking into the future can certainly be tricky, but you need to also think how much will the code need to be change to assert a specific new need. If you need to add a new level of reporting, would you prefer to add a new else if or just a value in a dictionary?

Readability then starts to backfire, since if ... else is quite common. What happens when you arrive at 3, 4 or 5 branches?