PEP 8
You are violating several Style Guide for Python Code rules:

commas should be followed by a space,
variables should be snake_case,
always surround binary operators with one space

Never called
ex1() is never called by your mainline.
Declare variables closer to where they are used
subsequences is declared 7 lines earlier than it needs to be.
Separate I/O from processing
ex1() cannot be called with test data, unless that test data is in a file.  Use two functions.  One that solves the problem with an in-memory string, and a second that reads the string from a file for processing.
Avoid dict.setdefault(...)
subsequences.setdefault(v, []).append(k) will create a new list ([]) every time it is executed.  Many times this default will never be used, and must be garbage collected.  This is just wasting time.
Instead, use collections.defaultdict.  Note that collections is not an external library; it is internal, built into Python.
Counter
Similarly, use collections.Counter for counting objects.  Again, built into Python; not an external library.
Reworked Code

from collections import Counter, defaultdict

def binary_sequence_counts(sequence, shortest, longest, limit):
    n = len(sequence)

    sequence_counter = Counter()
    for i in range(n + 1):
        for j in range(i + 1, n + 1):
            if shortest <= len(sequence[i:j]) <= longest:
                sequence_counter[sequence[i:j]] += 1

    subsequences = defaultdict(list)
    for subsequence, count in sequence_counter.items():
        subsequences[count].append(subsequence)

    result = sorted((count, sorted(subseqs)) for count, subseqs in subsequences.items())
    return result[:limit]

def ex1(ftesto, a, b, n):
    with open(ftesto, encoding='utf8') as f:
        sequence = f.read().replace('\n', '')

    return binary_sequence_counts(sequence, a, b, n)

def testcase():
    seq = "01010010010001000111101100001010011001111000010010011110010000000"
    result = binary_sequence_counts(seq, 2, 4, 20)
    # print result, or
    # check if result is correct

The above code is way more readable than the original.
Efficiency
This code is just plain awful:
    for i in range(n + 1):
        for j in range(i + 1, n + 1):
            if shortest <= len(sequence[i:j]) <= longest:
                ...

If your sequence is 100,000 digits long, the inner loop will execute about 5,000,000,000 times!  That's a lot!  Especially if you're only concerned with subsequences between 2 and 4 digits long, in which case you only need about 300,000 iterations.
A simple modification of the range(...) limits would dramatically improve your speed.  If you do it correctly, you can even get rid of the a <= len(...) <= b test, because with the correct ranges you will not be able to generate sequences that are the incorrect length.
In fact, with the correct limits, you could even use the counter to do the counting entirely for you:
sequence_counts = Counter(sequence[i:j]
                          for i in range(...)
                          for j in range(...))

Proper range limits left as exercise to student.
min heap
You are sorting a potentially huge list of values, and then returning only the n-smallest results.  sorted(iterable)[:n]  This can be a potentially huge waste of time!
Using the heapq.nsmallest(n, iterable) (again, built-in, not an external library), you can reduce the amount of space used, and possibly the amount of time.  Note that this is faster only for smaller values of n.  If n is big, it can be faster to use sorted(iterable)[:n].  Always profile!
Roll Your Own
The question has been updated to disallow any imports.  No problem.  We'll just have to implement our own defaultdict and Counter.
Assuming your are allowed to create your own class ...
object.__missing__
When a dict.__getitem__ is called, but the dictionary does not contain that key, object.__missing__(self, key) is called.  We can use this method to change the behaviour.
Counter
To implement a simple "counter" dictionary, we just need 0 to be returned for any missing key.
class Counter(dict):
    def __missing__(self, key):
        return 0

If the key is missing, 0 is returned.  If you "add 1" to a missing key, 0 is returned, 1 is added to the returned value, and the resulting 1 is stored back under that key:
>>> c = Counter()
>>> c['foo']
0
>>> c['bar'] += 1
>>> c['bar'] += 1
>>> c
{'bar': 2}

Notice that the 'foo' key still does not exist; only the 'bar' key exists because values were actually written to it.
defaultdict
You don't actually need a full defaultdict here.  You just need a dictionary which returns an empty list when an unknown key is retrieved.  Unlike the Counter class above, we need to remember the list that was returned for the key, because we'll be appending items to the list, which (unlike the += operator) won't write the result back into the dictionary.
class DictOfLists(dict):
    def __missing__(self, key):
        self[key] = []
        return self[key]

Unlike the Counter, referencing an unknown key will create the key in the dictionary, filling it with an empty list:
>>> dol = DictOfLists()
>>> dol['foo']
[]
>>> dol['bar'].append("baz")
>>> dol
{'foo': [], 'bar': ['baz']}
>>>

The actual defaultdict allows you to specify a factory function in the constructor, to create values for the missing keys.  That isn't too much more complicated.  Feel free to research this.


Git hook to detect existing tag case insensitive

Finding existing Git tags

The files in a Git repository's meta storage,
such as the content of ./refs/tags, ./packed-refs,
are not API.
It's best to interact with Git through commands.

You can get the list of tags with the git tag -l command.
This will include packed refs as well.

Use early returns

The hook collects counts of matching tags, then matching packed refs,
and finally it decides if it should fail based on the collected counts,
and if the operation is not a delete.
It's usually better to not delay actions when you have enough information to take them.

For example,
very early in the process_ref function you can already know if it's a delete operation.
It would be better to return 0 right there,
to avoid any further unnecessary processing.

The same goes for checking the counts.
If the first count in tags is non-zero,
you can already fail without further processing.

Use grep -q instead of grep -c and checking for non-zero

When grep -q finds a match,
it stops further processing.
grep -c continues until the end of the input to collect all counts.
That's not necessary in your example.

Use more strict pattern matching

Using grep -ic $refname to find a matching ref in the list of refs may leave room for false positives.
For example if there is a tag v1.1,
and then you try to push v1, it will fail.
This is a bit tortured example,
because obviously you won't release v1 after v1.1,
but it's good to be aware of this point.

You could make the matching more strict by adding a $ to anchor the end.
If both the beginning and the end can be anchored,
then you could use the -x flag of grep to match entire lines.
Now that would be rock-solid strict.

Always quote parameters

Even though you know that $refname will never contain unsafe characters,
it's a good habit to always surround with double-quotes when used as command arguments, for example in grep -ic "$refname".

Use $(...) instead of `...`

`...` is obsolete, use $(...) instead.

Alternative implementation

Putting the above together (and some more),
I'd implement the hook like this:

#!/bin/sh

is_delete() {
    [ "$1" = "0000000000000000000000000000000000000000" ]
}

tag_exists() {
    git tag -l | grep -qix "$1"
}

fail() {
    echo "push failed"
    echo "tag already exists: $1"
    echo "please contact dev team"
    exit 1
}

process_ref() {
    target="$2"   # target hash. all 0s for a delete command
    refname="$3"  # the full ref name

    is_delete "$target" && return

    case $refname in
        refs/tags/*)
            tagname=${refname#refs/tags/}
            tag_exists "$tagname" && fail "$refname"
    esac

    return 0
}

while read REF; do process_ref $REF; done


JavaScript

var field, theDivTNR, theDivA;

Why are these in a global scope? It's a good habit to always create your own scope so that you don't have unwanted clashes between scripts which use the same names.

  console.log("page loaded and DOM is ready");

This is debug code, and should be deleted before the code is ready for review.

// The next function is called each type a key has been
// typed in the input field
function showWhatITyped() {
  // fill the div with the content of the input field
  theDivTNR.innerHTML = field.value;
  theDivA.innerHTML = field.value;
}

What if field.value is not valid HTML? I think this should set textContent instead of innerHTML.

HTML

If you have src you don't need type, because the type can be determined from the HTTP headers.

This is quite ugly and very old-fashioned. See e.g. https://stackoverflow.com/q/799981/573420

Type text here: <input type="text" oninput= "showWhatITyped();" id="inputField" >

That oninput is even more ugly, and wholly unnecessary. Just refactor the init method to say

  document.querySelector("#inputField").oninput = showWhatITyped;

You may notice that this eliminates field. It's not necessary to store it, provided that you refactor the listener to handle the event which is passed to it. And, in fact, you can also refactor it to be an anonymous function.

TimesNewRoman

Arial

You asked how to expand to more fonts etc. The simple answer is to use a loop rather than implementing it by hand. Add class="preview" to each of the preview divs, and then use document.querySelectorAll('.preview') to get hold of them.


Atomically incrementing a value in a map in Clojure

Don't always create new atoms

My first comment is that your use of atom seems quite wrong to me: atoms are mutable entities which you're supposed to mutate via e.g. swap! or reset!, which alter the value the atom points to without changing the atom reference itself. What your code is doing is to create new atoms at every call, i.e. you change the atom reference completely. A more proper approach would be:

(defn increment-key [ref key]
  (dosync
    (if-let [current (@ref key)]        ; maps are functions of their keys, no need for 'get'
      (do (swap! current inc) @ref)     ; 'do' here is only used to return the current map
      (alter ref assoc key (atom 1))))) ; change the atom in place

Do you need an atom?

My second comment is that you most likely don't need atom at all, unless you want to also use it directly as shared state among different threads. If you only plan to use the ref map as the shared state, you can just drop the atom and make your code easier to handle. One of the benefits of Clojure immutable data structures is that values are inherently thread safe. The following code would be perfectly thread safe:

(defn increment-key [ref key]
    (dosync
        (if-let [current (@ref key)]
            (alter ref assoc key (inc current))
            (alter ref assoc key 1))))

Do you need a ref?

A last comment is about choosing the right tool for the job: ref is intended for coordinated state change. This means that it helps you in case you have several mutable state references that need to mutate all in a single transaction, which you create with dosync. Your code doesn't seem to need transactions at all, it just needs a single mutable state reference to change atomically, i.e. in a thread safe manner. This is better achieved with a straight atom, which relieves you from the need to establish a transaction:

(defn increment-key [atm key]
  (if-let [current (@atm key)]
    (swap! atm update key inc)
    (swap! atm assoc key 1)))

A next step might be to let the change to be asynchronous by using an agent instead of an atom, but that's slightly beyond the scope here IMO.


I think this question is half-way between Stack Overflow and Code Review anyway...

Start() is running on a standalone thread however it uses _tcpClient. Assuming things are properly done you dispose _tcpClient in container class Dispose() method. When it happens your reader will access (indirectly, through sr of type StreamReader) a disposed object (_tcpClient, from which underlying stream comes from).

You may transfer ownership of _tcpClient to your secondary thread.

void Start() {
    try {
        // All the code you already have in-place
    }
    finally {
        _tcpClient.Dispose();
    }
}

However you already have a flag in-place (_requestStop). Hard to say (without surrounding code) what's wrong but you first should check if you set flag _requestStop and immediately exit (even if reading is in progress). You'd better set that flag and then wait until thread completes its work (for an example see How to wait for thread to finish with .NET?).

Few more considerations more on-topic on Code Review.

1) You're not using using statement:

using (var sr = new StreamReader(_tcpClient.GetStream())) {
    // You don't need to explicitly call sr.Close();
}

Do the same for your XmlReader variable xr.

2) XML deserialization isn't as quick as you may wish. If speed is a measured issue then you may consider to manually parse XML fragment (using XmlReader you have) to build your objects.

3) You should avoid to catch a generic Exception. You should know what may go wrong in your code, catch errors you expect and leave to a more generic error handler to catch the others (for example, no matters how many times you retry because of while() but if _tcpClient has been closed then it won't recover its connection and you'll keep generating exceptions).

4) In your big try/catch you also catch exceptions generated by code called in events. Also some exceptions may leave XmlReader in an inconsistent state and you may want to re-create it.

5) You do not need to cache XmlReader.LocalName property value. It won't perform any parsing for each access and call to property getter may be optimized away (inlined) by JIT compiler. It's such micro-optimization that you won't notice any difference even if you read its value Int32.MaxValue times (do not forget you're also working with network data).

6) XmlReader.LocalName type is string, no reason to loose its type assigning to an object variable. The same is true for NameTable.Add() return type: it's a string, don't assign it to an untyped object variable.

7) You compare strings (localName with watchdog and the others) but you do not explicitly say which type of comparison you want. Is it case-sensitive or case-insensitive? Is current culture aware? Make it explicit according to what you want or you may have surprises when current culture has unexpected text comparison rules (see also this post). Change your code to:

if (String.Equals(xr.LocalName, watchdog, StringComparison.InvariantCulture)) {
}


You probably intended to write

typedef struct {
    int (*pFn)(int)
} Interface;

Use member names which are more descriptive than pFn. I hope that this was just as an example to post here.
Yes this approach can work well. I have worked on a bigger project where we used this OO-light approach for C by having an interface struct and each backend would fill it with it's own implementation.


C# + Linq - grouping objects by frames of time found in the data

This

private static Func<ArticleEmail, DateTime> GetGroupingFunction()
    {
        // I am curious of other dev's opinion on this method :)

        TimeSpan maxMailingTime = TimeSpan.FromMinutes(30);
        DateTime lastDate = DateTime.MinValue;

        return delegate (ArticleEmail email)
        {
            if (email.DateCreated - lastDate > maxMailingTime)
            {
                // the mailing was not sent within maxMailingTime from the start of first email in series
                // we will update the lastDate and this will group the emails into a separate group
                lastDate = email.DateCreated;
            }

            // now we return the value which groups our emails
            return lastDate;
        };
    }

I would just write as:

 private static readonly TimeSpan maxMailingTime = TimeSpan.FromMinutes(30);
 private static readonly DateTime lastDate = DateTime.MinValue;
 private static readonly Func<ArticleEmail, DateTime> GroupingFunction =
    email => (email.DateCreated - lastDate > maxMailingTime) ? email.DateCreated : lastDate;

To initialize a constant TimeSpan you can just use

new TimeSpan(30, 0, 0, 0);

that is a constant of 30 days. Your way with FromMinutes is intended to compute an floating point, like 3.76 days into a TimeSpan and is much slower and inaccurate, since it's floating point operations, not integer.

While I'm not sure what you want with subtracting DateTime.MinValue, which is actually 0 or 1/1/1.
Do you just want to convert a DateTime to a TimeSpan by computing the TimeSpan from 1/1/1 up to the Date ? Creative, but actually useless.

You can get the same with

  const long maxMailingTicks = 30*60*1000000L; // 30minutes
  if (email.DateCreated.Ticks > maxMailingTicks)

Let's think on.
How can a Date ever be smaller than 30minutes ? Do you really want to deal or Check on Dates in the first 30minutes of the life of Jesus Christ ?

So where do we end up ?

 private static readonly Func<ArticleEmail, DateTime> = email => email.DateCreated;

If we assume, the email was not send to notify of the birth of Jesus, there is nothing left to do.

But if you want to keep your test:

 private static readonly Func<ArticleEmail, DateTime> GroupingFunction = email =>
    email.DateCreated.Ticks > maxMailingTicks ? email.DateCreated : DateTime.MinValue;

To Have this possibly working on Linq to SQL also, you rather use
Expression<Func<ArticleEMail, DateTime>> as the Type of the function. There is nothing else to do than exchanging the return type/type of my field. When dealing with Dates and SQL you have to use some special functions sometimes, there could be a revision necessary, but with just "Func", its definitly impossible ever to become SQL at all.
This would definitly work on SQL:

 private static readonly Expression<Func<ArticleEmail, DateTime>> = email => email.DateCreated;

Actually your code was too long. I just dealed with the last 10 lines.


Step 1: Fix your markup. You have the "plants"-list nested inside the link, which is invalid

Step 2: Fix your JS. You correctly add the click handler after the document's ready, but you set the folderToggle variable when the script's run, regardless of whether the document's been loaded. It still works because you have the script at the end of your page, but still. Keep everything inside the $(...) - it'll also keep the folderToggle var out of the global scope.

Step 2: Cache jQuery objects. Don't write $(this) twice.

Step 3: Don't use find() for this. While I can't speak to an exact performance difference, it's more precise to use next(), as the nested list will be the next element/sibling relative to the link.

$(function () {
    $(".tree li > a").click(function(e) {
        var link = $(this);
        e.preventDefault();
        link.next().toggle("slow");
        link.toggleClass("active");
    });
});

Step 4: If you're going to be adding more stuff to the tree via ajax or something, you'll probably want to rewrite the click handler to handle clicks for links added later:

$(".tree").on("click", "li > a", function (event) {
    ...
});

Step 5: You'll probably want to add a class to the "branch" links in the tree. Otherwise "leaf" links will also attempt to open a nested list, which doesn't make much sense, as there won't be one.

Step 6: Use OL (ordered list) unless your lists are actually "unordered". But if they're file lists, they're probably ordered somehow. Minor thing, but semantics matter.

All that said, there's nothing terribly inefficient in your code. If anything's going to lag, it's the toggle animation, but that can't really be sped up, as it's a single function call to jQuery. It's either there or not there.


Styles: "object initializer" vs "constructor" object creation

These are both techniques born of different goals.

The constructor style is something you will design your classes for when you want them to be faux-immutable, that is, you do not want them changed after construction so you make the setters on your properties protected or private.

The initializer style comes from you ceding control of the object's data members to the object's consumer, which you will do when you do not care about the order or timeliness of them being filled in.

One of the largest decision making factors here is this: Is the object safely usable if the properties are null?

If not, the constructor format allows you to ensure they will never be null by requiring them be set at construction by parameter and disallowing them to be set by the consumer.

Example of this would be a connection string object, without a database catalog it cannot be safely used as anything that attempted to use it would try to use the database catalog and may throw an exception if it is null.

The other reason for the constructor format vs. initialization is dependencies, this falls into the same question as null safety but can be thought about a little differently: If an object is useless without a particular dependency object or piece of data, then there is little reason to allow its construction without that parameter.

Example of this would be a file stream, if you do not give it a path or some way of knowing about a file, it becomes a useless object.

Edit:
All that said, as far as using initializer syntax when available, it's really just sugar and I think everyone can agree that you should use it if you know a number of values at construction time.


Combine a set of “ranges” to find least number of ranges

The program is NOT working as expected. You can see the bug if you give it the following input

    int[][] zipRanges1 = new int[][] {
            new int[] { 1, 5 },
            new int[] { 2, 6 },
            new int[] { 3, 4 }
    };

The problem is that you compare ranges from the input only. The correct logic is that for each input range, you should iterate over newZipRanges and "insert" the current input in the correct place. You sohuld make the Logic to normalize the zipcode range piece of code into a method that compares and possibly merges two ranges.

However, the story does not end here. after the above processing is done (after you finish iterating over the input), you will need to iterate over the newZipRanges and normalize it. consider the following case:

newZipRanges contains {1, 4}, {7, 9}
and now the input range you're processing is {1, 8} you will merge it into the first new range and produce newZipRanges == {1, 8}, {7, 9} which obviously needs normalizing.  I think after any modification to newZipRanges (after merging an input range into it) you need to iterate over the newZipRanges and see if any merging needs to be done (perhaps sorting every time? not sure)

one last advice, to merge overlapping ranges, use Math.min on the lower bounds and Math.max on the upper bounds. its nicer than the if question you have.


From a short review;

patient is a global variable, global variables are bad
var patient = [] is more idiomatic than var patient = new Array();
Comments should be all German or all English (I would go for all English, its the common language of the developers)
You can group switch labels, this is valid JavaScript:

        switch(key){
            case "id":
            case "kundennr":
            case "termart":
            case "userId":
                res[i][key] = parseInt(value);
                break;
            case "client":
            case "title":
            case "description":
                res[i][key] = value;
                break;
            case "start":
            case "end":
                res[i][key] = new Date(value);
                break;
            default:
                console.log("unbekannter Datentyp " + key);

Your data fields should be either all English or all German (you have userId, but also kundennr), here as well I would go for all English
Since value already contains res[i][key] for "client", "title", etc., you should probably comment on that
Since this is real, you should not log to console for an unknown data type, you should call a REST service that will log this entry in a database table, and even possibly send out an email to developers
var key in Object.keys(res[i]) is safer than var key in res[i], you never know when someone decides to extend Object
Your indenting is off, consider using a beautifier


I would suggest that you create some intermediate methods instead of doing everything in one method. For example the task of restoring a database is comprised of these subtasks:

Select database file
Create copy
Restore database

var pickedFile = default(StorageFile);

It's a rather convoluted way to say IStorageFile pickedFile = null, don't you think? Personally I don't see many people use default() for this purpose so I would stick with the more common way of initializing.

await _currentFolder.GetFileAsync("MyMoney.sqlite");

Why are you hardcoding the filenames? This limits your re-use in case you want to expand it to other databases as well.

currentDatabase.CopyAsync(ApplicationData.Current.RoamingFolder, "MyMoney.bak", NameCollisionOption.ReplaceExisting);

This call is not awaited!

public async void RestoreDatabase()

Always avoid async void. From a recent answer of mine:

Asynchronous methods should return Task or Task<T>, the former being for traditional void methods and the latter being for methods with T return type.
The reason for this is that a void method cannot be awaited (since it doesn't return a Task) and will in effect be a fire-and-forget kind of thing: it will start executing your asynchronous code on a separate thread and continue doing business as normal. However once the main thread reaches its end, the application will exit regardless of whether or not your asynchronous code has finished as well. This obviously leads to nasty bugs.
In case you ever want to re-use this code for a console application or just in a class library where you don't know the client, I would suggest making it async Task just for good measure.
The only exception to this are asynchronous event handlers since they have to adhere to the convention that event handlers return void. This also explains why events are "dangerous" to use in asynchronous code.

RestoreDatabase()

Convention dictates that asynchronous methods should have the Async suffix.


Extra parenthesis in if-clause vs. readability

Compare this:

if ( ( bIsPaused ) || ( runState != LnrState_Running ) )

And this:

if ( [ bIsPaused ] || [ runState != LnrState_Running ] )

You'll find, I think, that the second is much easier to read. This is because I'm using multiple types of braces (illegal, but bear me with here). As humans we can identify the different symbols very quickly, but we can't really line up matching symbols all that quickly.

This technique:

if ( ( bIsPaused ) || ( runState != LnrState_Running ) )

Depends on pairing up symbols, something we aren't actually all that good at.

However, this technique:

if ( bIsPaused || runState != LnrState_Running )

Depends on our ability to distinguish symbols, which is really good, and not on pairing symbols. It does also depend on our ability to apply precedence rules. My experience has been that after years of practice coding that's second nature.

Also, consider math. Mathematics has been around a lot longer then CS and they've adopted precedence rules and get rid of the parenthesis whenever they can.

For those reason, I prefer to eliminate as many parenthesis as possible.


PEP8

1.Python uses underscore as naming separator in function and variable names, see PEP8

2.Two blank lines are used to separate function/classes

Improvements.

To make your module reusable you should use if __name__ == '__main__' condtion before invoking your main function.

So instead of calling play() you should do:

if __name__ == '__main__':
    play()

Your play_again and play function got difference only in print statements, so you can just combine them into a single function.

def start_game(first_run=False):
    if first_run:
        print("Do you wanna play Craps? Y/n ")
        response = input(">>> ").lower()
    else:
        response = input("Play Again? Y/n >>>").lower()
    if response == "y":
        check_roll(roll())
    else:
        input("ENTER to quit")

Note

I've renamed function into start_game since I find play a bit confusing. But you can keep your name if you want.

Now if you look at your check_roll and reroll function they are also the same except for win and lose conditions, so you can also combine them into a single one like this:

def check_roll(dice, win_conditions=(7, 11), lose_conditions=(2, 3, 12)):
    if dice in win_conditions:
        print("You win")
        start_game()
    elif dice in lose_conditions:
        print("You lose")
        start_game()
    else:
        print("Time to try to roll the point")
        check_roll(roll(), (dice,), (7,))

Also, I did small improvement to roll() function so now you can see values of dice you've rolled:

def roll():
    input("Press Enter to roll")
    dice = random.randint(1, 6), random.randint(1, 6)
    print("You rolled a {}" .format(dice))
    return sum(dice)

So in the end, what we have is this:

import random

def roll():
    input("Press Enter to roll")
    dice = random.randint(1, 6), random.randint(1, 6)
    print("You rolled a {}" .format(dice))
    return sum(dice)

def check_roll(dice, win_conditions=(7, 11), lose_conditions=(2, 3, 12)):
    if dice in win_conditions:
        print("You win")
        start_game()
    elif dice in lose_conditions:
        print("You lose")
        start_game()
    else:
        print("Time to try to roll the point")
        check_roll(roll(), (dice,), (7,))

def start_game(first_run=False):
    if first_run:
        print("Do you wanna play Craps? Y/n ")
        response = input(">>> ")
    else:
        response = input("Play Again? Y/n >>>")
    if response.lower() == "y":
        check_roll(roll())
    else:
        input("ENTER to quit")

if __name__ == '__main__':
    start_game(True)


Creating a TCP Listener and receiving data

A common convention is to prefix class members with _ so it's easier to see what a local variable is and what's a class member. In your case it would be _tcpClient or even _TcpClient.

This is a static method which indicates that it's possibly part of a static class. This is almost always a bad idea. static means it's global and global state is bad because it can get you into all kinds of trouble once your program grows in complexity.

You have a StopWatch but you're not actually using it.

I assume you use the Substring because the buffer is larger than the actual data received so you find the end by looking for the first \0. GetString() provides an overload which allows you to specify offset and length so this becomes unnecessary.

MSDN stipulates that you must close the NetworkStream once you are done with it because the client will not release it. Given that streams are IDisposable it would be best wrapped in a using block.

TcpClient is IDisposable as well so should be wrapped in a using block to make sure it gets cleaned up properly.

The method is recursive and there is no way to bail out because in case of error it calls itself again. This means your call stack is growing indefinitely and will fall over at some point. Each call will also allocate a new receive buffer every time.
A while loop with a break condition would probably be the better choice.

So in total the refactored code could look like this:
private static void ReceivePortMessages()
{
    byte[] receiveBuffer = new byte[10025];
    while (!_QuitProcessing)
    {
        int requestCount = 0;
        _TcpListener.Start();
        Debug.Print(" >> Listener Started");
        using (var tcpClient = _TcpListener.AcceptTcpClient())
        {
            Debug.Print(" >> Accepted connection from client");

            using (var networkStream = tcpClient.GetStream())
            {
                while (!_QuitProcessing)
                {
                    try
                    {
                        requestCount = requestCount++;
                        var bytesRead = networkStream.Read(receiveBuffer, 0, (int)tcpClient.ReceiveBufferSize);
                        if (bytesRead == 0)
                        {
                            // Read returns 0 if the client closes the connection
                            break;
                        }

                        string dataFromClient = System.Text.Encoding.ASCII.GetString(receiveBuffer, 0, bytesRead);

                        XmlDocument xm = new XmlDocument();
                        xm.LoadXml(string.Format("<root>{0}</root>", dataFromClient));
                        XmlElement root = xm.DocumentElement;
                        string rootName = root.FirstChild.Name;
                        RouteInboundXML(rootName, dataFromClient, sw);
                    }
                    catch (Exception ex)
                    {
                        Debug.Print("ReceivePortMessages: " + ex.ToString());
                        break;
                    }
                }
            }
            Debug.Print(" >> stopped read loop");
        }
        _TcpListener.Stop();
    }
}

It's still not ideal because the Read will block unless data is there to be received or the connection is closed. So if the other side stops sending data but keeps the connection alive you still have no nice way to bail out.


Implement a function to check if a linked list is a palindrome in c++

Building linked list from command line arguments

The multiple conditionals inside this loop is kind of ugly,
because head and prev will only ever be null once:

  for( int i = 1; i < argc ; i++ ) {
    myNodePtr tmp = new myNode(strtol(argv[i], NULL, 10));
    if(!head) {
      head = tmp;
    }
    if(prev){
      prev->next = tmp;
    }
    prev = tmp;
  }

You could avoid the unnecessary conditional evaluations by lifting the special treatment of the head outside the loop:

  myNodePtr head = nullptr;
  if (argc > 1) {
    head = new myNode(strtol(argv[1], NULL, 10));
  }
  myNodePtr node = head;
  for (int i = 2; i < argc; i++) {
    node->next = new myNode(strtol(argv[i], NULL, 10));
    node = node->next;
  }

Iterating until the middle and verifying the rest

Iterating until the middle could be written simpler:

  std::vector<int> stack;
  myNodePtr slow = head;
  myNodePtr fast = head;
  while (fast && fast->next) {
    stack.push_back(slow->val);
    slow = slow->next;
    fast = fast->next->next;
  }

At this point,
if the length is odd, slow will be pointing to the single middle element,
that should be skipped.
The length is odd if fast is not null, so you can write:

  if (fast) slow = slow->next;

Finally, to check that the rest of the list matches the content of the stack:

  while (!stack.empty()) {
    if (stack.back() != slow->val) {
      std::cout << "Not a palindrom!" << std::endl;
      return 1;
    }
    stack.pop_back();
    slow = slow->next;
  }

This alternative implementation uses much fewer conditions and cleanly separates the interesting steps, so I think it's easier to read.

From an interview point of view

At an interview,
if you write an iterative solution,
the interviewer is likely to ask to also write a recursive solution.
And vice versa.
You need to be able to ready to do both,
and discuss about the trade-offs of each technique.

This solution would get important criticism at an interview for several reasons:

Large chunk of code inside main method, instead of separated to small methods with single simple clear purpose
Knowledge of memory management is not demonstrated (the program simply relies on cleanup on exit)


Restructuring and consolidation

Logging configuration

When having a constant logging options like posted log_format or log_level=logging.DEBUG you might have been used logging.basicConfig or even dictConfig to apply specified options globally to all underlying cases.But since your intention is to allow the client create different specialized loggers with dynamic logging options, "base" config won't give much benefit. At least, it's good to remind of such a base configuration capability.

Handlers

All 3 handlers run the same common set of statements to ensure logging format:

if log_format is None:
    log_format = get_default_log_format()
console_handler.setFormatter(log_format)

That calls for consolidation and reducing duplication.Moreover, when creating some concrete logger instance a client may pass log_format as a raw format string like log_format='%(funcName)s:%(lineno)d — %(message)s', not as logging.Formatter instance. Thus, for further optimizations I'll eliminate get_default_log_format function and declare a constant:

LOG_FMT = '%(module)s - %(asctime)s — %(name)s — %(levelname)s - %(funcName)s:%(lineno)d — %(message)s'

According to the scenario where the client/caller operates only on .._logger functions to instantiate concrete loggers, that points to direct relation between specific logger and respective handler(s). And assuming that duplicated common code should be moved out from all handlers - they ceased pulling their weigh and are removed in favor of direct handler usage. See the final implementation below.

..._logger functions

"logger" creation functions perform a common set of actions:

logger = logging.getLogger(logger_name)
logger.setLevel(log_level)
logger.addHandler(handler)

that also calls for consolidation.The condition

if log_file is None:
    log_file = "execution.log"

is eliminated by simply making log_file a default argument log_file="execution.log".

To perform consolidation and reducing duplication a factory function logger_factory(logger_name, handlers_list, log_format, log_level) is introduced. It concentrates a common behavior and also allows to attach multiple handlers to the same logger.

The final optimized version:

import logging
import sys
import logging.handlers

LOG_FMT = '%(module)s - %(asctime)s — %(name)s — %(levelname)s - %(funcName)s:%(lineno)d — %(message)s'

def logger_factory(logger_name, handlers_list, log_format, log_level):
    logger = logging.getLogger(logger_name)
    logger.setLevel(log_level)

    if not isinstance(handlers_list, (list, tuple)):
        handlers_list = [handlers_list]
    for handler in handlers_list:
        handler.setFormatter(logging.Formatter(log_format))
        logger.addHandler(handler)

    return logger

def create_console_logger(logger_name, log_format=LOG_FMT, log_level=logging.DEBUG):
    return logger_factory(logger_name, handlers_list=[logging.StreamHandler(sys.stdout)],
                          log_format=log_format, log_level=log_level)

def create_file_logger(logger_name, log_file="execution.log", log_format=LOG_FMT, log_level=logging.DEBUG):
    return logger_factory(logger_name, handlers_list=[logging.FileHandler(log_file)],
                          log_format=log_format, log_level=log_level)

def create_rotating_file_logger(logger_name, log_file="out.log", max_log_bytes=2000000, max_log_backup_files=20,
                                log_format=LOG_FMT, log_level=logging.DEBUG):
    """ Creates rotating file logger with the given file name, max_log_bytes, max_log_backup_files and log_format.
         :param log_file: log file name
         :param max_log_bytes: the maximum size of file in Bytes
         :param max_log_backup_files: the number of backup files to store
         :param log_format: custom format as logging.Formatter object
         :param log_level: logging level
         :return: logging.Logger
     """
    handler = logging.handlers.RotatingFileHandler(log_file, maxBytes=max_log_bytes,
                                                   backupCount=max_log_backup_files)
    return logger_factory(logger_name, handlers_list=[handler],
                          log_format=log_format, log_level=log_level)

def create_file_console_logger(logger_name, log_file="execution.log", log_format=LOG_FMT, log_level=logging.DEBUG):
    handlers = [logging.FileHandler(log_file), logging.StreamHandler(sys.stdout)]
    return logger_factory(logger_name, handlers_list=handlers,
                          log_format=log_format, log_level=log_level)

if __name__ == "__main__":
    # To get a console handler, run this code
    console_logger = create_console_logger(logger_name="logger1")
    console_logger.debug("Hello World")

    # To get a file logger, run this code
    file_logger = create_file_logger(logger_name="logger3", log_file="out.log")
    file_logger.critical("This is a critical message")

    # To get a console and file logger, run this code
    console_file_logger = create_file_console_logger(logger_name="my_logging2", log_file="out3.log")
    console_file_logger.error("Error: This is from console file logger")


Tight coupling in using call back method

Instead of casting to MainActivity, you should be casting to IResultListener.

if (baseClass instanceof IResultListener)
            ((IResultListener) baseClass).onResultNotFound(tres);

That said, usually one registers a listener. So you'd have a List<IResultListener> somewhere, and then in this method you'd call a method fireEventResultFound(String result), which iterates over the list and calls onResultFound for each of them. This is called the Observer pattern (you can google that if you want to know more), and it decouples the reporting class from the observing class.

I also think you should move the parsing of hummings and musics, streams and custom_files to their own methods. That would greatly simplify this onResult method.

Also,

tres = tt.getString("acr_id");

Is this a possible bug? Everywhere else you're appending, but here you just overwrite the result.


First, taking a look at your code as a consumer of your API:

I like that the autocomplete for .on(" shows what events I can listen to.
How do I stop listening to an event? If I don't want countDown events anymore then I have to do countDown.listeners.get("countDown")!.splice(index, 1) which is ugly.
How do I cancel a countdown?
Why is listeners exposed? This is an internal property of your class that I shouldn't need to know about as a consumer. It should be either private or protected. It's also probably worth marking startCountDown as private or protected.
Why does the expired event pass an extra parameter, isExpired? If the expired event is fired, doesn't that imply that the countdown is expired?
The countDown event is not fired every second. What happened to second 9 and 6?

This is a common problem with timers, and is present in (almost) every JavaScript clock/timer question on this site. There are several possible solutions, the simplest of which is to check the time more frequently. The MDN notes on it is worth reading.

[![broken countdown ticks][1]][1]

TypeScript specific notes:

Turn on strict null checks. Yesterday. Without it, TypeScript ignores a whole class of errors.
Turn on no implicit any. Once turned on this will point out that the on method has a return type of any
Don't create a class to just hold properties. An interface is fine.

interface CountDownValues {
    days: number;
    hours: number;
    minutes: number;
    seconds: number;
}

Consider initializing properties where they are declared when using classes.

Other:

new Date().getTime() can be more concisely written as Date.now()
The thousand, sixty, and twentyfour variables make it harder to read your code. Get rid of them. You can make the code more readable by instead defining day, hour, etc.
Countdown is a word, you don't need to capitalize the D.
Using a map for events here is probably overkill. There are only two events and they are both known at compile time. I'd just use an object.
countDown is kind of an odd name for an event, without looking at your code I had no idea when it would be fired. I prefer tick, but there are other good options.

Rewrite:

I kept the feature set mostly the same, but wanted to add the ability to stop the timer, remove event listeners, and initialize a countdown before starting it. I let this run for ~15 minutes, and it never skipped a second or repeated one twice, which isn't conclusive, but I'm fairly confident it is stable.

Note that instead of firing the tick function multiple times per second, I do some math to figure out how long to wait and then schedule a tick based on that. This results in some more complicated code, but avoids the need to track what the last reported second was.

interface TickEvent {
    days: number;
    hours: number;
    minutes: number;
    seconds: number;
}

interface CountdownEvents {
    tick(values: TickEvent): void;
    expired(): void;
    stop(): void;
}

// Unfortunately we can't use T[K][] without getting messy.
type EventMap<T> = { [K in keyof T]: Function[] };

class Countdown {
    private listeners: EventMap<CountdownEvents> = { tick: [], expired: [], stop: [] };
    private timer?: number;

    on<K extends keyof CountdownEvents>(eventName: K, listener: CountdownEvents[K]): void {
        this.listeners[eventName].push(listener);
    }

    off<K extends keyof CountdownEvents>(eventName: K, listener: CountdownEvents[K]): void {
        const listeners = this.listeners[eventName];
        const index = listeners.indexOf(listener);
        if (index !== -1) {
            listeners.splice(index, 1);
        }
    }

    start(date: Date) {
        const end = Math.floor(date.getTime() / 1000);

        const tick = () => {
            const now = Date.now();
            const nowSec = Math.floor(now / 1000);
            const time = end - nowSec;

            if (time <= 0) {
                delete this.timer;
                this.listeners.expired.forEach(listener => listener());
                return;
            }

            const minute = 60;
            const hour = minute * 60;
            const day = hour * 24;

            const days = Math.floor(time / day);
            const hours = Math.floor(time % day / hour);
            const minutes = Math.floor(time % hour / minute);
            const seconds = time % minute;

            this.listeners.tick.forEach(listener => listener({ days, hours, minutes, seconds }));

            const timeToNextSecond = (nowSec + 1) * 1000 - now;
            this.timer = setTimeout(tick, timeToNextSecond);
        }

        tick();
    }

    stop() {
        if (this.timer) {
            clearTimeout(this.timer);
            delete this.timer;
            this.listeners.stop.forEach(listener => listener());
        }
    }
}

const countdown = new Countdown();
countdown.on("tick", event => console.log("tick", event));
countdown.on("expired", () => console.log("expired"));
countdown.on("stop", () => console.log("stopped"));

const date = new Date();
date.setSeconds(date.getSeconds() + 20);
countdown.start(date);

setTimeout(() => countdown.stop(), 3 * 1000);


Simple Programming Problems

  Write a program that prints all prime numbers. (Note: if your
  programming language does not support arbitrary size numbers, printing
  all primes up to the largest number you can easily represent is fine
  too.)

Your program says one is prime. That is not correct.

The only even prime number is two. You don't appear take advantage of that. That is inefficient.

A number can only be divisible by a number less than or equal to its square root. You don't appear take advantage of that. That is inefficient.

You are asked to "[print] all primes up to the largest number you can easily represent." In Go, type int is either 32 or 64 bits. You don't guarantee the largest number by using type int64. Your program is not correct.

You have no program termination condition. Your program is not correct.

And so on.

For example, fixing your code,

package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Println("prime numbers:")
    fmt.Println(2)

    for n := int64(3); n > 0; n += 2 {
        prime := true

        r := int64(math.Sqrt(float64(n))) + 1
        for i := int64(3); i < r; i += 2 {
            if n%i == 0 {
                prime = false
                break
            }
        }

        if prime {
            fmt.Println(n)
        }
    }
}

To provide a measure of performance, the results from a Go benchmark for all prime numbers up to 32,771:

BenchmarkPeterSO-4           500       2661556 ns/op
BenchmarkIbnRushd-4            3     492864429 ns/op


As the "guy" in question, I'm happy to discuss my approach :) feel free also to file issues on GitHub if you have feedback.

You are certainly correct that decorating functions as bash-cache does isn't necessary, but the intent is to simplify the development experience - to memoize a function all you have to do is make a call to bc::cache, and bash-cache (generally) handles the rest. No need to keep separate functions in sync or wrestle with naming schemes. Whether that's a feature or overkill is in the eye of the beholder, but I find it very flexible and expressive :)

As you've shown it's not too complicated to implement a reasonable caching mechanism in Bash, but the devil is really in the details. With bash-cache I've addressed a number of very subtle issues that most caching implementations fail to handle, including:

stdout and stderr are both cached and preserved separately (your approach only caches stdout, other approaches merge the two streams with >&)
the return code of the function is also preserved, few other implementations I've seen do this (correctly)
avoids a common gotcha with command substitutions ($(...)), which are actually lossy
stale cache data is regularly cleaned up in the background
caches are separated by user and chmod-ed to only be readable by that user; a global cache risks leaking sensitive data

Since this is CodeReview.SE, some tips on your approach:

Be sure to consistently quote all variables, including arrays like "$@"; without quotes Bash will expand variables and arrays with word-splitting, which is rarely desirable and often leads to bugs. In your code it's likely that whitespace arguments will break things. It's a great idea to run any shell code through ShellCheck and address the issues it flags.
file="/tmp/$(printf "%s" ${@})" is unsafe, as it munges arguments together without a delimiter, e.g. it will treat  foo 12 3 and foo 1 23 as the same set of arguments. It also will fail if any arguments contain invalid filename characters (notably /), which is (part of) why bash-cache hashes the arguments.
It's probably a good idea to asynchronously delete the cache file when it's too old, instead of making multiple date calls in subshells to determine whether the file is still valid. I'd have to benchmark to be sure but I suspect it will be faster.
${1} ${@:2} isn't necessary, just say "$@" (note the quotes)
Bash doesn't support nested/anonymous functions, so what you're doing in bbusers is actually just re-defining _users in the top-level namespace on every invocation, which isn't necessary or helpful. Just define _users as a normal function and then: bbusers() { cache _users "$@"; }.


Mutex

class Mutex:private std::mutex{
  public:

Don't see the need for your custom Mutex/Lock class. Just use the standard ones directly there is no need to add a layer of indirection that future developers need to go and check.

Excessive Flushing

Calling flush after each item:

std::cout<<t<<std::flush;

Is probably not a good idea. Let the user of your code decide when to flush he probably has more concept about what what is about to be printed and thus when flush needs to be called.

If you must do it then do it after all the items have been printed.

Template Recusrsion.

Rather than using a recursive call to print all the items:

Print(ts...);

Use a sub class and create a std::initializer_list

// std::cout<<t<<std::flush;
// Print(ts...);
// Create a list. This will act more like a loop than recursion.
// Items inside the {} are initialized left to right.
auto printer = { ItemPrinter(ts)... };

Then ItemPrinter just prints the item in the constructor.

template<typename T>
struct ItemPrinter { ItemPrinter(T const& t){std::cout << t;}};

As a nice benifit. You will not need the terminating case.

void Print(){}

Naming Convention.

Print

It is more standard to use an initial capitol letter to define a type. An initial lower case letter donates an object (which also encompasses functions).

Since you have a nameless type. With an object called Print. I would have called it streamPrinter. Then used your wrapper functions call that directly.

Declaration

The code works well as is for a single file program. But you have problems when using it from header files. Because the class is nameless you can not use it any declarations to mark the object external and thus you will be getting an instantiation of the object in every compilation unit. This will break your guarantee that it is thread safe as each has its own mutex.

I think your best bet is to put the Print object in its own file. Then expose all printing via wrapper functions which can be made external in the header file.

Expansion.

Currently your printer is only used for std::cout. Why not expand it so that it can be used for any stream.


The code is missing #include <type_traits>; it would have been nice to have had the test cases too.
It would be nice to be able to check the argument restriction using assert.  Unfortunately, this doesn't fit nicely with C++11 constexpr functions, which may contain only a single return statement.  If you might also compile against a newer standard, we could perhaps conditionally test it:
#include <cassert>

template <typename I, typename P>
constexpr I div_by_power_of_2(I dividend, P power_of_2_divisor) noexcept
{
#if __cplusplus >= 201402L
    assert((power_of_2_divisor & power_of_2_divisor - 1) == 0);
#endif
    return dividend >> log2_of_power_of_2(power_of_2_divisor);
}

I don't see why we have a template and specializations, rather than simple overloading of log2_of_power_of_2, particularly as we don't widen signed types to preserve sign.
Contrary to your comment, the constexpr is valuable, as it allows this function to be called from within another constexpr function, whether or not that one is being called with constant arguments.

Modified code
static constexpr unsigned
log2_of_power_of_2(unsigned non_negative_power_of_2) noexcept
{ return __builtin_ctz  (non_negative_power_of_2); }

static constexpr unsigned long
log2_of_power_of_2(unsigned long non_negative_power_of_2)  noexcept
{ return __builtin_ctzl (non_negative_power_of_2); }

static constexpr unsigned long long
log2_of_power_of_2(unsigned long long non_negative_power_of_2) noexcept
{ return __builtin_ctzll(non_negative_power_of_2); }

static constexpr int
log2_of_power_of_2(int non_negative_power_of_2) noexcept
{ return __builtin_ctz  (non_negative_power_of_2); }

static constexpr long
log2_of_power_of_2(long non_negative_power_of_2)  noexcept
{ return __builtin_ctzl (non_negative_power_of_2); }

static constexpr long long
log2_of_power_of_2(long long non_negative_power_of_2) noexcept
{ return __builtin_ctzll(non_negative_power_of_2); }

#include <cassert>

template <typename I, typename P>
constexpr I div_by_power_of_2(I dividend, P power_of_2_divisor) noexcept
{
#if __cplusplus >= 201402L
    assert((power_of_2_divisor & power_of_2_divisor - 1) == 0);
#endif
    return dividend >> log2_of_power_of_2(power_of_2_divisor);
}

#include <iostream>
int main()
{
    std::cout << div_by_power_of_2(15ul, 4) << '\n';
}


Polymorphic STL foreach without passing the container type

This line gives my nightmares:

std::unordered_map<void *, bool> _advance_iterator__instances_done;

First up the name is reserved. Prefer not to use identifiers without a leading underscore (the rules are not trivial and everybody gets them wrong so just avoid them).

Secondly the size of the map is unbound. If you have a really large application (runs a long time) this is going to continuously grow.

This construct

bool advance_iterator(Tc &container, Ti &iterator)
{
   static typename Tc::iterator it;

makes the whole thing not thread safe.

Your naming convention makes it confusing to read:

#define foreach(value_type, iterator, container) \
                           ^^^^^^^^^^^
                     This is never the iterator it is the value.

Overall I think the boost FOREACH is a better choice for C++03 and C++11 now has a built in version


Consider this example:

InvokeActionWithRetry(() =>
        {
            Console.WriteLine("action");
            throw new Exception();
        },
    3);

It prints 'action' four times. That's not what I expect from the API (but is what I expected from reading the code). I'd expect the number I pass in to be the total number of invocations - not the number of retries after the first attempt.

You need to check this arguments for this method as there is a lot of scope to pass in the weird values. e.g. what if retryAttempts is a negative number? That doesn't make sense!

You also need to check action for null.


I have the username and password for the admin stored in Web.config (Is that a good practice?).

No, it's not good practice to store the Admin login (or any login, for that matter) in the Web.config.

Depending on what ASP.NET model you're using, you have a few options. MVC has a built-in Roles provider which makes it simple to make certain pages/areas only accessible by  a specific role.

Web Forms is also pretty simple, though you have to roll your own access provisions. You can use the built-in Simple Membership if you like, which usually suits quite well once extended to fit your needs. (You can add properties to users pretty easily and such.)

You also aren't encrypting or hashing the password, which is a huge no-no. At the very least you should MD5 hash it, though for security I would recommend SHA1-salt hashing at the very weakest. Though, if you use the built-in Simple Membership for Web Forms or MVC, you'll get encryption and salting by default.

I didn't review the actual code as Heslacher did that just fine, but I do think you need to completely revisit the login system. ASP.NET has built-in providers for this, and they're super easy and, quite honestly, pretty fun to set up. (I don't know why no one has pointed this out in the several months this question has been here, or how it got on my radar, but hopefully you still get this advice.)


Throwing exceptions in the constructor is weird; you should either add a comment explaining OR just remove the exception. If you're going to always disallow creation of a PageObject, provide a static method which will do the things you want, rather than throwing exceptions all the time.

Exceptions are for exceptional flow - not for "business as usual". Right now your program reads like "... and then it crashes, which is completely normal." This sort of thing, without documentation, leads to maintenance nightmare. Why was this done? It's highly irregular! But if it was done this way, there must have been a reason? I mean, normally, there is no sane reason to do the sort of thing you just did...

public String getAttributeValue(ProfileAttribute profileAttribute) {
    return getProfileAttributeElement(profileAttribute).getText();
}

This can be deleted. The only constructor throws an exception, so barring weird reflection (in which case, you're doing it wrong), any methods which rely on instances cannot be called. The other option I can think of is if you have a subclass that uses this method. Then this method would see some use - but it's existence remains questionable.

Without the exception, however, you can make use of it as normal.


Kill All Connections For Domain Account Users

When you want users out of the database, do you have a timeframe as to when they should be allowed back in? The script you have above, will get rid of the users, but those users can just create a new connection to the database. What will you do when the user reconnects? Do you need to keep them out of the database for the entire time of the maintenance? What is the goal with keeping the users out of the database during the maintenance?

Additionally, if you kick people off out of the database, are you ok with losing the transaction that may be in flight?

What kind of maintenance do you want to do the database? Is it being done during a time of day when users should not be using the database?


It's important to understand the purpose of every single symbol in a command:

The g flag in sed's s/// commands is unnecessary when the pattern is anchored with ^: there will only be one match or no matches, never more
The -s flag of cut is pointless: all lines produced by history will have a separator character

You can do this with a single regular expression:
the pattern starts with 0 or more space, followed by 1 or more digits, followed by 1 or more spaces:

history | sed 's/^ *[0-9][0-9]*  *//'

Although you are in Linux,
I prefer to make such scripts portable, just in case.
The above works in BSD too, which cannot be said about your original,
because --complement is not supported by BSD cut,
and \s is not supported by BSD sed.

Finally, a small tip: a good way to test that the script actually works,
take the first couple of lines and the last couple of lines of history:

{ history | head; history | tail; } | ...


If the user is non-technical they may not know what an integer is, but
  I can't think of better wording.

[Positive] Number or [Positive] Whole Number would be alternatives.

Another possibility: Enter a Number between 0 and [X]. Non-technical people will assume that this means they should enter a whole number. If they enter a different number, give feedback accordingly.

Consistency

In your first version: getNumber outputs the prompt each time, while getBool does not. This should be consistent. The names of the input variable should be consistent as well (either prompt or message. I would prefer prompt.

Other

You can do sc.nextInt(); instead of String input = sc.next(); Integer.parseInt(input);.

As already mentioned on UX, show the possible values for the boolean answer in the prompt when asking the question. So

boolean wind = getBool("Regularly windy");

becomes

boolean wind = getBool("Regularly windy (y/n)");

Extract Method

You can extract the method to retrieve a string. I think that this makes the code a bit more readable, and you get getString method for free.

/*returns integer to question asked in prompt*/
public static int getNumber(String prompt) {
    while (true) {
        String input = getString(prompt);
        try {
            return Integer.parseInt(input);
        } catch (NumberFormatException ne) {
            System.out.println("\tPlease enter a positive whole number.");
        }
    }
}

/*returns boolean to question asked in prompt*/
public static boolean getBool(String prompt) {
    while (true) {
        String input = getString(prompt).trim().toLowerCase();
        if (input.equals("y")) {
            return true;
        } else if (input.equals("n")) {
            return false;
        } else {
            System.out.print("\tPlease answer y/n");
        }
    }
}

/*returns string to question asked in prompt*/
public static String getString(String prompt) {
    System.out.print("\t" + prompt + ": ");
    Scanner sc = new Scanner(System.in);
    return sc.nextLine();
}


You don't need your temp list, you can just use itertools.product to build it:

>>> list(itertools.product(ortho1, ortho2))
[(41, 18), (41, 17), (40, 18), (40, 17)]

Also, you should use some more descriptive names.

You can use the fact that tuples are also iterable and can be written like so: t = 0, 1, saving you the unneeded list brackets.

You can also compute the square root of target once and save it.

You should add a docstring describing what your function does.

I would separate the two concerns of your function. One is to find the side length of a square most closely matching target, the other one is finding a rectangle with ratio about 1:2.

You can use min and re-use your key function for that, since you only need the pair with the smallest distance and don't care about all others. min is \$\mathcal{O}(n)\$, whereas sort is usually \$\mathcal{O}(n \log n)\$. The abs is also not needed anymore, since we made sure that only those pairs with a product greater or equal the target are still left.

With this, your code becomes:

import math
import itertools

def get_plates_square(target):
    """Returns the integer side length of a square with an area at least `target`."""
    return math.ceil(target ** 0.5)

def get_plates(target):
    """
    Return a rectangle with integer sides with a ratio of about 2:1,
    which is closest to the given `target` area.
    """
    target_sqrt = target ** 0.5
    sides_a = math.ceil(target_sqrt * 1.5), math.floor(target_sqrt * 1.5)
    sides_b = math.ceil(target_sqrt / 1.5), math.floor(target_sqrt / 1.5)
    rectangles = [(a, b)
                  for a, b in itertools.product(sides_a, sides_b)
                  if a * b >= target]
    return min(rectangles, key=lambda x: x[0] * x[1] - target)


Express routing with a login action using SQLite

For larger projects this can get very complicated and nasty. You can refactor the db access into functions that take a callback as a parameter. Example:

// db_helper.js
module.exports.isUserAuthenticated = function(query, callback) {
  [db code here]
  callback(err, rows);
};

And then in your routes file:

// app.js
var db_helper = require('./path/to/db_helper.js');

....

app.post('/login', function(req, res) {
  var query = [parse from request object]
  db_helper.isUserAuthenticated(query, function(err, rows) {
    if (rows.length == 1) {
      [...]
      res.render(...);
    } else {
      [...]
      res.render(...);
    }
  });
});

Node-style callbacks typically have an error as the first parameter (null if there was no error), and associated data in other parameters.

Nesting callbacks can be a pain if this gets more complicated, so I suggest you look into Promises or async


Passing listener to customized extended View in Android

I think you have missed the point with the NumberPicker here. There is no need to add in a new level of abstraction for your application.

Right now your 'calling' code needs to implement a ValueChangeCallback class, and call setValueChangeCallback(callback). The ValueChangeCallback needs to implement the execute() method.

Sure, this works, but, the design is supposed to be a whole lot simpler, just do:

Make your calling code implement a NumberPicker.OnValueChangeListener and the onValueChange() method. Then, it can call setOnValueChangedListener directly.

Basically, your code should be simplified to:

import android.widget.NumberPicker;

public class RemListView extends NumberPicker  {

}

and your calling class should be changed to have a NumberPicker.OnValueChangeListener instance instead of a ValueChangeCallback instance, and, well, that's it.

Oh, and since your RemListView class is now empty, unless you have other stuff in there, you may as well delete the class and use NumberPicker directly.


Generating all unique permutations of a string

Pay attention to your substrings. Given s = "abc", then the following return empty strings.

String pre = s.substring(0,0);
String post = s.substring(3);

Consider (temporarily) adding logging statements inside your innermost loop and examining the results of calling permute("abc") to see how many times you add the same strings to the set. Try to avoid adding to the set a value already in the set concatenated to an empty string, since this gives you no new values in the set.


Your class name is Json yet your methods contain this acronym in all-uppercase: JSON. The naming conventions say: "Do capitalize only the first character of acronyms with three or more characters, except the first word of a camel-cased identifier."

fs isn't a clear variable name. Same for sw (why not use streamWriter?) and sr (streamReader). I'd even include writer.

Considering that you don't use var serializer = new JsonSerializer(); until later, why not delay this call until you need it?

I'm bothered by catch (Exception). Are you certain you don't want to know that something went wrong, and what exactly went wrong?


malloc in main() or malloc in another function: allocating memory for a struct and its members

Looking at the performance, the two versions should perform just about identically.  The second version has one less call/return, which can save a couple of CPU cycles, but if you have it multiple places in your code the additional code bytes and cache misses can overshadow that.  Either way you probably won't notice a difference.

Looking at readability and maintainability, the first version is much better.  You know at a glance what it is doing (rather than looking at several lines to figure it all out), you won't forget any important steps, and error checking is much easier since most of it can be handled in one place (excepting the last check for successful creation of the buffer).  Debugging can also be easier, since you can set a breakpoint on the creation or destruction functions if necessary.


In a word: dictionaries.

You have a class that only has class attributes and lacks any methods; that could just be a dictionary:

lang = dict(
    step = 0,
    cell = [0] * 30000,
    test_cell = [0] * 30000,
    pos = 0,
    test_pos = 0,
    loop = False,
    loop_ret = 0
)

(Alternatively, if you really want attribute (foo.bar) rather than key (foo['bar']) access to the values, look into collections.namedtuple.)

You have a whole bunch of elifs; that could also be a dictionary (with some judiciously-named functions):

commands = {
    "+": increment_byte,
    "-": decrement_byte,
    ...
}

This makes your interpreter loop:

def interpreter():

    lang = dict(...)
    commands = {...}

    code_input = raw_input('Code: ')
    steps = len(code_input)

    while lang['step'] < steps:
        command = code_input[lang['step']]
        if command in commands:
            commands[command](lang)
        lang['step'] += 1

along with e.g.:

def increment_byte(lang):
    """Increment the byte at the data pointer."""
    val = lang['cell'][lang['pos']]
    lang['cell'][lang['pos']] = ((val + 1) % 256)

(Note use of % per @user50399's answer.)

This has two advantages:

very simple loop in interpreter; and
commands acts as a syntax guide (covering @Dagg's comment).

You could also add some input validation:

def accept_input(lang):
    """Accept one char of input, storing its value in the byte at the data pointer."""
    while True:
        try:
            i = ord(raw_input("Enter char: "))
        except TypeError:
            pass
        else:
            if i in range(256):
                lang['cell'][lang['pos']] = i
                break
        print("Not a valid input.")

(Note switch to ord per @user50399's answer.)


Sum of all arguments ever passed to counter

Choose another name for the dictionary besides dict.  Don't ever hide the name of a built-in type.

Then...

d = {}
def counter(key,value):
    d[key] = d.get(key,0) + value
    return d[key]

You're done.  I see no need to build lists of all the passed values.


Selecting countries with different situations

I have formatted the queries. I am not able to test it, so if you can give the schema for this, or create it at SQL fiddle, that will be great. Data is not required.

SELECT cou.id,
       cou.title
FROM   countries cou
       LEFT OUTER JOIN continents con
                     ON  cou.continents_id = con.id
WHERE  (con.deliver = 1 AND con.active = 1 ) OR
       (cou.deliver = 1 AND cou.deliver = 0)

Please let me know in case there are any concerns.


Improve my if-statement to prevent double checks

Your code can be shortened to:

if(!array1.isEmpty() || !array2.isEmpty()) {
    mail.sendMail("Array1: " + getContent(array1) + ", Array2: " + getContent(array2));
}

When you have:

String getContent(ArrayList<String> list) {
    if(!list.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        for(String string : list) {
            sb.append(string);
        }
        return sb.toString();
    }
    return "-";
}


PHP framework building: System Class (reads configuration .ini file)

Some improvements(they would save your[and framework users] a lot of time on debug):

All system wide components should implement pattern Singleton, this would guarantee that you have only one System at the same period.
Try to create interface SystemInterface, this would allow you to create ServiceStub pattern(It's very useful on testing)
Split your class and move parser to another class(use Strategy pattern). Your system should depend on configuration, not file! Also this would allow you to create another config-files like .json or even .php
Configuration shouldn't be stored in applications main class, use ConfigurationRegistry for this(pattern Registry)


A few suggestions:

“only either can be used at a time not both” – nothing in the function enforces that at most one of these input parameters has been set. Something like this:

if (cpl_id is not None) and (target_no is not None):
     raise ValueError("At most one of cpl_id and target_no should be supplied")

would ensure that at most one of them can be specified by the user.
You have several lines of the form

found_target = foo == bar

I’d put some parentheses around the condition, because I think it makes it easier to read:

found_target = (foo == bar)

Later in the function you have two lines of the form

found_target = True if foo == bar else False

which can be reduced to the construction above.
You have one function that does both business logic (checking whether the plane is correct) and doing some work (printing to screen). You should really separate these two – this function should return True/False, and then the caller should handle printing an appropriate message.
This line:

if qo == 'callsign' or qo == 'squawk':

is a bit unwieldy because you have to add an extra or statement every time you add a new possibility for qo. Better to do something like:

if qo in ['callsign', 'squawk']:

which is easy to extend with more values.

(Although it's not clear why you're doing this check at all, given that qo will always be squawk in the function as defined.)
There are no comments or docstrings. I don’t know anything about planes, so I just have to trust that the conditionals are correct. It would be good to provide some explanation of what this all means – for example, what’s a CPL ID, or what is the qo_ prefix for?


Here are a few improvements I can think of.

HTML

As the name of the angular app - todos - is not particularly good. Most developers would follow a convention such as appending 'App' behind the name of the app so that other developers would know that they are looking at a module.

Ref: https://github.com/mgechev/angularjs-style-guide#naming-conventions

As with the name of the app, you could also rename the controller to mainController.

A problem with the list is that use cannot intutively tell that they can click on a task to edit it. You can fix that easily by wrapping an  tag around it.

{{ task.content}}

Just fixing the case of characters in the button.

        <input type="text" ng-model="task">
        <input type="button" value="Add Task" ng-click="add(task)">

Here instead of saying "Save Task" it would be better to change it to "Update Task" as it would more clearly convey the purpose of the button.

            <input type="text" ng-model="editMode.task.content">
            <input type="button" value="Update Task" ng-click="editMode.save(editMode.task)">

Javascript:

(function() {
    var Task = (function() {

You could rename the counter variable to better convey its meaning. Maybe even rename the content variable to taskTitle. One more thing, return function(...){...} is a Javascript statement, and although Javascript would not enforce it, you should always append a semicolon ; at the end.

        var taskIdCounter = 0;
        return function(content, isDone) {
            this.id = taskIdCounter++;
            this.content = content;
            this.isDone = isDone || false;
        }; // <-- Semicolon!
    }());
    var app = angular.module('todos',[])
    .service('todosBL', function() {
        this.tasks = [];
        this.add = function(content) {
            this.tasks.push(new Task(content));
        };

In the controller below, I will make use of the editedTaskId to update the task object from clone.

        this.update = function(editedTask, editedTaskId) {
          var i = this.tasks.findIndex(function(task){
              return task.id === editedTaskId
          });
          this.tasks[i] = editedTask;
        }
    })

Your logic about cloning the task object to update it is fine. Here's how I'd do it if I had to implement it.

    .controller('main', function($scope, todosBL) {
        $scope.todosBL = todosBL;
        $scope.add = function(task) {
            todosBL.add(task);
            $scope.task = null;
        };
        $scope.editMode = {
            editingTaskId: '',
            task: {},
            edit: function(task) {
                this.task = new Task(task.content, task.isDone);
                this.editingTaskId = task.id;
            },
            save: function(task) {
                todosBL.update(task, this.editingTaskId);
                this.task = {};
            }
        };
    });
}());


Create a background-image over a background-color with different opacities for each element

You can shorten that code a bit, and then, by using rgba(), you can have both transparent background and image in one pseudo, and using attr() together with the second pseudo, display the text.

The 4th argument in rgba() is the opacity level.

Stack snippet

.component {
 min-height: 100vh;
 min-width:100vw;
 font-size:5em;

 display:flex;
 justify-content: center;
 align-items: center;
 color:black;
}
.component::before {
 content: "";
 position: absolute;
 top: 0;
 left: 0;
 width: 100%;
 height: 100%;
 opacity:1;
 background: rgba(0,255,0,0.3) url("https://www.pngarts.com/files/5/Los-Angeles-Free-PNG-Image.png") center 100px/500px repeat;
}

.component::after {
 content: attr(data-text);
 position: relative;
}

If you intend to use something else inside the component, and to avoid using negative z-index on the pseudo (which can cause other issue when it comes to the stacking context), use e.g. a div and give it position: relative and it will float on top of the pseudo.

Stack snippet

.component {
 min-height: 100vh;
 min-width:100vw;
 font-size:5em;

 display:flex;
 justify-content: center;
 align-items: center;
 color:black;
}
.component::before {
 content: "";
 position: absolute;
 top: 0;
 left: 0;
 width: 100%;
 height: 100%;
 opacity:1;
 background: rgba(0,255,0,0.3) url("https://www.pngarts.com/files/5/Los-Angeles-Free-PNG-Image.png") center 100px/500px repeat;
}

.component div {
 position: relative;
}

    Awesome WebPage

If you want to alter the opacity on the background color and the image individually, you will need both pseudo, and here's how-to.

As the div will become before the ::after pseudo, markup wise, we need to give it z-index: 1 to "float" on top. Note, this is not as bad as using a negative z-index on the pseudo.

Stack snippet

.component {
 min-height: 100vh;
 min-width:100vw;
 font-size:5em;

 display:flex;
 justify-content: center;
 align-items: center;
 color:black;
}
.component::before,
.component::after {
 content: "";
 position: absolute;
 top: 0;
 left: 0;
 width: 100%;
 height: 100%;
 opacity:.3;
 background: green;
}

.component::after {
 opacity:.7;
 background: url("https://www.pngarts.com/files/5/Los-Angeles-Free-PNG-Image.png") center 100px/500px repeat;
}

.component div {
 position: relative;
  z-index: 1;
}

    Awesome WebPage


General feedback

There are a few ways that some of the loops can be simplified (see below). These may or may not improve the high CPU issue.

The code makes some repeated calls to functions with the same values in close proximity (e.g. calling th() with each value of rgb twice in rgbToHex()). Storing the returned values and re-using the stored values would make the code more efficient.

I'd consider suggesting the use of functional approaches (E.g. with Array.map(), Array.reduce()) but I wouldn't in this case, given that execution time is an issue.

Targeted feedback

There are some places where const could be used for any variable that doesn't get re-assigned - e.g. vals in ExtractColours::calculateCenter(), plen in ExtractColours::kmeans(), etc. This avoid unintentional re-assignment.

There are places where parseInt() is called without a radix - e.g.

let idx = parseInt(String(Math.random() * plen));

and

let h = parseInt(i).toString(16);

The radix should always be specified1 because it doesn't always default to 10.

Let's look at that method ExtractColours::calculateCenter(). The variable plen could be assigned to points.length (like it is in ExtractColours::kmeans()), instead of incrementing that in the second for loop. And then the division of each array element by plen could be moved into the previous for loop.

And vals is declared and assigned like this:

let vals = [];
let plen = 0;

for (let i = 0; i < n; i++) { vals.push(0); }

This could be simplified using Array.fill()

const vals = Array(n).fill(0);

1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Octal_interpretations_with_no_radix


First of all, I have no idea why you've got self in there. It's unnecessary (and indeed, you didn't even use it in the call to .grid.selModel...)

Secondly: I don't understand the point of setting a property in the first place. You're always returning the result of the grid.selModel... call, so the property isn't necessary. You could just have a local variable - or better yet, just return directly, with no properties or local variables. The method's just a decorator for another method's output.

Now, if the idea is that you can either use someGrid.getSelectedRecords() getter or someGrid.selectedRecords property, then you're going about things in a bad way.

If I see that I can use someGrid.selectedRecords directly, then no, it should not be overwritten if I call someGrid.getSelectedRecords(). That makes no sense. In fact, it'll cause something like this:

someGrid.getSelectedRecords() == someGrid.selectedRecords // true
someGrid.selectedRecords == someGrid.getSelectedRecords() // false

Wat?

So to directly answer your question: No, don't do what you're doing in that piece of code. But the reason why you shouldn't is because using both accessor methods and direct property access is a bad approach to begin with.

If you use getter and setter methods, your properties should be off-limits to external code. If you only use properties, you shouldn't add getter or setter methods, as they confuse the API greatly.

You could conceivably use Object.defineProperty() which'll let you, well, define a property but with explicit getter and setter functions (if the target runtime(s) support it). But frankly it's easier to just write getter and setter functions if you want to maintain a barrier between your object's instance data and the outside world.

But, again, in this particular case, your object doesn't seem to need any instance data at all as it just delegates to something else. This should work equally well, without getting properties mixed up in things:

Grid.prototype.getSelectedRecords = function () {
  return this.grid.selModel.getSelection().map(function (record) {
    return record.internalId;
  });
}

Returning the result of map and not storing has the added benefit of never returning a reference to instance data. The function will always return a brand new array.

Now, you might still want to memoize/cache those IDs, but in that case you'll be better served with "private" closure variables, rather than inherently "public" properties.

You could also go the opposite route and only use naked properties, and rely on users to use them correctly, or reap what they sow if they don't.
But that doesn't really apply here, since the method in question a shortcut for another object's method.

  I don't know if I want to write a setter/getter each time...

I can sympathize, but depending on what you're trying to accomplish you might have to.


Initial Mass Function for young star clusters and disk field stars

Improvise means something different then you think :)

log10(mnorm) seems to be needed to compute only once. And you can do it in your head. It is 0.

Same for log10(mc) (well not in your head this one :)).

imf_type seems useless when not zero. I am not pythonist, so, what does imf() return if imf_type is nonzero?

sigma**2 can also be computed once.

log10(mmin) and log10(mmax) can be computed once per mass_dist call.

myf.imf(x, imf_type) can be computed once per call to extend (or mass_dist, im not sure what that statement means, but I am almost sure that imf call can be moved at least one level up). This one is probably the biggest performance killer.

And there're probably more instances of this (anti)pattern.

As for the algorithm itself, I leave that to others :)


Assuming you're looking for numbers of the format XXX-XXX-XXXX (keeping in mind that this excludes international numbers):

I wouldn't separate the printing onto separate lines. I would build up the number (perhaps extracting this logic into a function) and then print the whole thing. You can also eliminate those unnecessary loops by generating numbers in different ranges and using different formatting strings to add the leading zeros (ex. a routing code of 2 should be 002).

You'll also probably want to handle the case that an invalid area code is input. For this, I pulled out the prompt into a separate function that can be used in a loop (until a valid area code is given).

Finally, for scripts you should wrap the main action in if __name__ == '__main__':

#!/bin/env python3
from random import randint

def random_phone_number(area_code):
    """Returns a random phone number (XXX-XXX-XXXX) with a given
    area_code."""
    prefix = randint(0, 999)
    line_number = randint(0, 9999)
    return f'{area_code:03d}-{prefix:03d}-{line_number:04d}'

def prompt_area_code():
   """Interactively prompts the user for an area code, returning it."""
   while True:
       try:
           area_code = int(input('enter an area code: '))
       except ValueError:
           pass

       if 0 <= area_code <= 999:
           return area_code

def main():
    print(random_phone_number(prompt_area_code()))

if __name__ == '__main__':
    main()

Things of note:

f-strings (new in Python 3.6)
Handling exceptions
int converts a string to an integer or raises a ValueError


Approximate integral in one line of code

Version 1.
It gives incorrect results for some delta values.
Example: Integrate(x => x * x, 0, 1, 0.1) gives 0.285 whenever other methods give 0.385.

Version 2.
Since the delta is a scalar that is a constant value for the Enumerable.Sum, it could be moved outside of the Enumerable.Sum.
Then we can replace the c => f(c) * delta with a method group f.
And also we can use Enumerable's extension methods as extension methods:

static double Integrate(Func<double, double> f, double low, double high, double delta)
{
    return delta * DoubleRange(low, high, delta).Sum(f);
}

public static IEnumerable<double> DoubleRange(double min, double max, double step)
{
    for (double value = min; value <= max; value += step)
    {
        yield return value;
    }
}

EDIT
The .Select(f).Sum() was replaced with the .Sum(f) as @mjolka advised.


Finding dictionary keys whose values are duplicates

It's easier to read code that tuple unpacks the values in the for from dict.items().

for key1, (code1, option1) in Duplicate_combos.items():

archive_duplicates is a duplicate of Real_duplicates. There's no need for it.
It doesn't seem like the output needs to be ordered, and so you can just make Real_duplicates a set. This means it won't have duplicates, and you don't have to loop through it twice each time you want to add a value.

This alone speeds up your program from \$O(n^3)\$ to \$O(n^2)\$.
Your variable names are quite poor, and don't adhere to PEP8. I have changed them to somewhat generic names, but it'd be better if you replace, say, items with what it actually is.

def find_duplicates(items):
    duplicates = set()
    for key1, (code1, option1) in items.items():
       for key2, (code2, option2) in items.items():
            if key1 == key2:
               continue
            elif code1 == code2 and option1 == option2 == 'No':
                duplicates.add(key1)
                duplicates.add(key2)
    return list(duplicates)

You don't need to loop over Duplicate_combos twice.

To do this you need to make a new dictionary grouping by the code. And only adding to it if the option is 'No'.

After building the new dictionary you can iterate over it's values and return ones where the length of values is greater or equal to two.

def find_duplicates(items):
    by_code = {}
    for key, (code, option) in items.items():
        if option == 'No':
            by_code.setdefault(code, []).append(key)

    return [
        key
        for keys in by_code.values()
        if len(keys) >= 2
        for key in keys
    ]

This now runs in \$O(n)\$ time rather than \$O(n^3)\$ time.

>>> find_duplicates({
        101: ['1', 'No'], 102: ['1', 'No'],
        103: ['1','Yes'], 104: ['1', 'No'],
        201: ['2', 'No'], 202: ['2', 'No'],
        301: ['3', 'No'], 401: ['4', 'No'],
})
[101, 102, 104, 201, 202]


First off, easy task, add a docstring to your function, validate_javascript_origins, and describe this function, and its arguments, preferably in detail.
Finally, if you're worried about input like username@site.end, you should add the check for the @ character. If it isn't valid input, or the input is interpreted in the wrong way, you should most definitely add this check.


Find palindromes in circular rotated string

After trying to optimize my current solution and getting nowhere fast, I went back to the drawing board and came up with this solution. The performance gains are outstanding: 543,334 ops per/sec vs. 275 ops per/sec

Performance Test

https://jsperf.com/largest-vs-subs

Solution

function circularPalindromes(s) {
    s = s.split('');

    let currentLength, equalsLength, j1, j2;
    const length = s.length;
    const length2 = s.length - 1;
    const largest = new Array(s.length).fill(0);

    for (let i = 0; i < s.length; i++) {
        currentLength = 1;
        j1 = (i < 1) ? length2 : i - 1;
        j2 = (i >= length2) ? 0 : i + 1;

        while (s[i] === s[j2] && currentLength < length) {
            currentLength++;
            if (++j2 >= length) j2 = 0;
        }
        equalsLength = currentLength;

        if (currentLength > 1) {
            checkEqual(largest, i, currentLength);
            i += currentLength - 1;
        }

        while (s[j1] === s[j2] && currentLength < length && j1 !== j2) {
            currentLength += 2;
            if (--j1 < 0) j1 = length2;
            if (++j2 >= length) j2 = 0;
        }

        if (currentLength > equalsLength) {
            if(++j1 >= length) j1 = 0;
            checkLargest(largest, j1, currentLength, equalsLength);
        }
    }

    return largest;
}

function checkEqual(largest, position, length) {
    const limit = position + length;
    const middle = position + (length >> 1);
    const even = (length & 1) === 0;

    for (let i = (position - largest.length + length < 0 ? 0 : position - largest.length + length); i < position; i++) {
        if (largest[i] < length)  largest[i] = length;
    }

    for (let i = position + length; i < largest.length; i++) {
        if (largest[i] < length) largest[i] = length;
    }

    for (let i = position, j = position; i < limit; i++, j++) {
        if (j >= largest.length) j = i % largest.length;
        if (largest[j] < length) largest[j] = length;
        if (i < middle){
            length--;
        } else if (i > middle) {
            length++;
        } else if (even) {
            length++;
        }
    }
}

function checkLargest(largest, position, length, equalsLength) {
    const limit1 = position + (length >> 1) - (equalsLength >> 1);
    const limit2 = position + length;

    for (let i = (position - largest.length + length < 0 ? 0 : position - largest.length + length); i < position; i++) {
        if (largest[i] < length) largest[i] = length;
    }

    for (let i = position + length; i < largest.length; i++) {
        if (largest[i] < length)  largest[i] = length;
    }

    for (let i = position, j = position; i < limit1; i++, j++) {
        if (j >= largest.length) j = i % largest.length;
        if (largest[j] < length) largest[j] = length;
        length -= 2;
    }

    for (let i = limit1 + equalsLength, j = limit1 + equalsLength; i < limit2; i++, j++) {
        if (j >= largest.length) j = i % largest.length;
        if (largest[j] < length) largest[j] = length;
        length += 2;
    }
}

console.log(circularPalindromes('cacbbba'));


Wow!  That is really slow.  I changed range(100) to range(5), just to get some timing numbers without dying of boredom.  So with that as my baseline, let's work on speeding it up.

set_color

def set_color(RN,pattern,z,c):
    for v in range(10):
        z = z**2 + c
        pattern.append(z)
    if abs(z) > 3.7918623e+90:
        t.color("#191970")
    elif abs(z) > 1.9472705e+45:
        t.color("#16167F")
    elif abs(z) > 4.4127888e+22:
        t.color("#13138F")
    elif abs(z) > 210066388901:
        t.color("#10109F")
    elif abs(z) > 458330:
        t.color("#0D0DAF")
    elif abs(z) > 677:
        t.color("#0B0BBF")
    elif abs(z) > 26:
        t.color("#0808CF")
    elif abs(z) > 5:
        t.color("#0505DF")
    elif abs(z) > 2:
        t.color("#0202EF")
    elif abs(z) > 1.75:
        t.color("yellow")
    elif abs(z) > 1.5:
        t.color("gold")
    elif abs(z) > 1.25:
        t.color("goldenrod")
    elif abs(z) > 1:
        t.color("darkgoldenrod")
    else:
        t.color("black")

The first argument, RN, is not used in this function.  So we can omit that, and save a little time not passing a useless argument.

        z = 0
        set_color(RN,pattern,z,c)
        pattern = []

The second argument, pattern, is being accumulated, and then discarded.  So busy work involving memory allocation for extending a list who's value is never used.  We can remove that argument and pattern.append(z).

The third argument, z, is always coming in as zero.  No point passing it as an argument; just initialize it inside the set_color function, which will save a little bit of time because we don't pass the extra argument.

Which just leaves passing in the argument c.  Getting better.

Then, you have a long string of if abs(z) > # checks.  How many times are you computing abs of a complex number?  How many times will the result be different?  Maybe we can compute it just once?

    abs_z = abs(z)
    if z > 3.7918623e+90:
        t.color("#191970")
    elif abs_z > 1.9472705e+45:
        ...

Unfortunately, that still leaves an ugly long string of if/elif/elif/else statements.  With 14 possibilities, you take an average of 7 tests to determine the correct value; with a binary search, this would reduce to 4.  We just need to put the values in a list, and use bisect.bisect to determine where the abs(z) would be inserted in the list.

import bisect

MAG = (1, 1.25, 1.5, 1.75, 2, 5,
       26, 677, 458330, 210066388901, 4.4127888e+22, 1.9472705e+45,
       3.7918623e+90)

COLOR = ("black", "darkgoldenrod", "goldenrod", "gold", "yellow", "#0202EF",
         "#0505DF", "#0808CF", "#0B0BBF", "#0D0DAF", "#10109F", "#13138F",
         "#16167F", "#191970")

def set_color(c):
    z = 0
    for _ in range(10):
        z = z**2 + c
    t.color(COLOR[bisect.bisect(MAG, abs(z))])

My timing hasn't shown a significant impact in speed yet, but I certainly like the set_color function much better now.  If you want to add more colours, it is simply a matter of filling in additional values in the arrays.

Mandelbrot

def Mandelbrot(RN,pattern,precision,check_rate,move_rate,x,y,i,c):
#draws line by line, 100 times
    for e in range(100):
        t.pendown()
#draws one line
        for e in range(precision):
            set_color(c)                 # Note: modified for new set_color
            RN = float(RN + move_rate)
            c = complex(RN,i)
            x = x + check_rate
            t.setposition(x,y)
#sets up values you'll need next row
        RN = -2.0
        i = i-.02
        t.penup()
        x = -200
        y = y - 2
        t.setposition(x,y)
    t.penup()

This looks backwards.  You pass in RN, but RN is computed in the loop.  You pass in x, but x is initialize to -200 each time through the loop.  You pass in c, but c is computed in the loop.  And most things seem to be computed just after they've been used for the next loop iteration!

Let's re-work this, moving calculation to before they are used, and see what it looks like.  Along the way, variable = variable + adjustment will be replaced with variable += adjustment, because it results in one less variable lookup in the Python interpreter.  Also, RN + move_rate is already a float, so we can omit the redundant float() call.  When looping over a range of values (y starting at 99, and going down by two 100 times, a for y in range(...) construct is used:

def mandelbrot(precision, check_rate, move_rate):
    i = 1.0
    t.penup()

    for y in range(99, 99 - 2 * 100, -2):
        rn = -2.0
        x = -200
        t.setposition(x, y)

        t.pendown()
        for _ in range(precision):
            c = complex(rn, i)
            set_color(c)

            rn += move_rate
            x += check_rate
            t.setposition(x, y)

        i -= 0.02
        t.penup()

Several PEP-8 changes: commas are followed by a space, variable names and method names are lowercase (technically, snake_case).  _ is used as the unused variable.  Operators have a space on each side.

Main

Again, float( ) calls are unnecessary.

if __name__ == '__main__':
    precision = 400
    check_rate = 400 / precision
    move_rate = check_rate / 100

    t.penup()
    borders()
    mandelbrot(precision, check_rate, move_rate)

Speed Up?

Despite my initial efforts, my very rough timing measurements don't show I've sped things up any.  But I do think the code has been cleaned up significantly.

Next step in my efforts will be to split this up into two parts:

computing a grid of Mandelbrot colour index values
drawing the image (using the computed grid of colour index values) with turtle graphics

Then, I can get more accurate timing information for each section.

Step 1 is open to parallel processing (Python threads won't help, due to the Global Interpreter Lock (GIL), but using processes should help), but that will only help if it is the large consumer of time.  I fear it is the turtle graphics.