Naming

Based on the naming guidlines variables/fields should be named "using a noun, noun phrase, or adjective". So getByQuerable should be renamed to something following the guidlines and also meaningful.

Optimization

you should extract the searching for Source and Target to separate methods. This helps for readability and makes it easier for Mr.Maintainer in a couple of months.
preparing the searchtext before the actual search takes place will speed up the query.
Right now if concordanceSearchOptions.MatchCase == false you call for each source/target in the where part the ToLower() method of the SearchText property.

Refactoring

    String searchText = concordanceSearchOptions.SearchText;
    if (concordanceSearchOptions.MatchCase)
    {
        searchText = searchText.ToLower();
    }

    if (concordanceSearchOptions.SearchInSource)
    {
        getByQueryable  = GetBySource(concordanceSearchOptions, searchText);
    }
    else
    {
        getByQueryable  = GetByTarget(concordanceSearchOptions, searchText);
    }

private IEnumerable<T> GetBySource(SearchOptions concordanceSearchOptions,String searchText){

}
private IEnumerable<T> GetByTarget(SearchOptions concordanceSearchOptions,String searchText){

}


The function should be called open_url according to Python coding
conventions.
The if/pass combination isn't so nice, it's just more to read.
I'd nest the conditions instead.
I don't get the exception handler.  Why exit hard?  Maybe there's a
short network outage and then the program just shuts down?  Let other
parts of the program handle those scenarios.  They need to deal with
urllib2 exceptions anyway.
PROXY_PASSWORD isn't verified, does None work as a value?

Otherwise looks fine; I'd suggest caching those handlers and only
installing them once, e.g.:

def install_open_url_handlers():
    # case 1: Proxy not required as no PROXY_URL found in environment.  Fall through to urlopen,
    # otherwise:
    proxy_url = os.getenv('PROXY_URL')
    if proxy_url is not None:
        proxy_user = os.getenv('PROXY_USER')

        # case 2: un-authenticated proxy, just load the proxy handler and then fall through to urlopen
        if proxy_user is None:
            handler = urllib2.ProxyHandler({})
        # case 3: Authenticated proxy.  Load password manager and proxyHandler, the fall through to urlopen
        else:
            password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
            password_mgr.add_password(None, proxy_url, proxy_user, os.getenv('PROXY_PASSWORD'))
            handler = urllib2.ProxyBasicAuthHandler(password_mgr)

        urllib2.install_opener(urllib2.build_opener(handler))

HANDLER_INSTALLED = False

def open_url(url, data=None):
    """ General purpose URL opener
    Handles no proxy - un-authenticated proxy and authenticated proxy

    urlencoding of the data argument to be performed prior to invoking this function

    :param url: The url to access
    :param data: Post data to accompany the url request
    :return: an open urllib object
    """
    global HANDLER_INSTALLED
    if not HANDLER_INSTALLED:
        HANDLER_INSTALLED = False
        install_open_url_handlers()

    # Access url using proxy defined above (or no proxy at all)
    return urllib2.urlopen(url, data)


Optimizing C++ equivalent of Matlab `filter` function

Few highlights:

std::copy(std::begin(z), std::end(z), std::begin(zOut));

To copy input values to overwrite them is just a waste of time. You will overwrite them then you do not need to copy old values, use z instead of zOut inside loops.

y.size() is possibly evaluated multiple times. It's a minor performance issue (and it may be inlined) but it depends on your actual implementation.

I don't know about valarray<T> implementation but if this is performance critical you may want to use a plain array.

I hope FilterResults constructor doesn't allocate anything (what valarray<double> default constructor does?) That said, this is C++, filter needs a state then you should design this using a Filter class with its private instance fields. You return just filtered data and you do not create/copy/move status. I imagine a Filter class like this:

class Filter
{
public:
    Filter(const valarray<double>& b, const valarray<double>& b)
    {
        // Validate parameters...
        this->a = a;
        this->b = b;

        // I omit z, I think there are very few chances you want
        // to set initial filter state...
    }

    valarray<double>& Process(const valarray<double>& input)
    {
        // Your code here, when you're done just return computed
        // result. "Final conditions" (filter status?) has not to
        // be returned, it's a private field.
    }

private:
    valarray<double> b, a, z;
};

As you can note some calculations/allocations will be performed in constructor. It won't change anything if each time you filter a different chunk of samples, using different filter, but in the other cases it will allow a big speed-up. Next step in design (to do something in C++) is to abstract away filter and its design: you may have a pure abstract base class Filter, an IirFilter implementation and one or more classes derived from FilterDesigner (let's say ChebyshevIirFilterDesigner to calculate filter coefficients). In general to mimic MATLAB approach may result in a sub-optimal implementation (because languages are different and because it will lead to a less than perfect OOP design.) If this class is a use-once function and you want to keep a function instead of a class you may drop finalConditions, do you actually use it? If you're implementing an on-line filter (for a continuous stream) then you'd better save it as private field (it's the z parameter you're using now)

You should never have using namespace std; You already use std:: consistently then you just add a possible source of conflicts.

Few more notes about performance:

In this case (I guess they do not use any esoteric math theory to perform an optimization) C++ performance should be pretty similar or even better than MATLAB. MATLAB may (I do not know what current implementation does) use SIMD/AVX instructions. Do not think you can have same throughput if you don't.

To perform a benchmark is more complex than this! At very least you should setup your machine for that and to perform calculations few thousands times to have an average and a distribution then inspect results to understand caching issues...


Parse a contrived message protocol with first byte data length followed by data

Below is an alternative example of how messages could be extracted.  Instead of a state machine with saved-state inside your splitmessages function, I have moved the saved-state out of the function into a structure that is passed-in.   I have also checked for unexpected data at the start of the function.  The return value is 0 on failure or the number of bytes consumed from the input stream on success.  I didn't check for size bytes occurring in the wrong place - replace the memcpy with a function that checks the bytes copied for that.

Note that your protocol has to distinguish between data bytes and size bytes. I have arbitrarily made the boundary 32, the first printable char.

#include <string.h>
#include <assert.h>

#define DATA_MIN_VALUE 32
#define DATA_MAX_SIZE  (DATA_MIN_VALUE)

struct message {
    size_t size;
    size_t remaining;
    char data[DATA_MAX_SIZE];
};
typedef struct message Message;

static inline size_t min(size_t a, size_t b)
{
    return a < b ? a : b;
}

static inline int is_data(unsigned char ch)
{
    return  ch >= DATA_MIN_VALUE;
}

static size_t
get_message(Message *msg, const unsigned char *bstream, size_t length)
{
    size_t len;
    assert(length);

    if ((msg->remaining == 0) && is_data(bstream[0])) {
        /* Data instead of message; caller must handle - eg. discard data up
         * to next message */
        return 0;
    }

    if (is_data(bstream[0])) {
        msg->size = 0;
        msg->remaining = bstream[0];
    }

    len = min(length-1, msg->remaining);

    memcpy(&msg->data[msg->size], &bstream[1], len);
    msg->size += len;
    msg->remaining -= len;

    return len + 1;
}

The code should compile but is untested.  Hope it helps to have another perspective.


Leftmost bisect search to find valid perfect square

Some small points:

ternary expression

No need for return True if lo ** 2 == num else False. you can use just return lo ** 2 == num

early return

If mid**2 == num, you can return early:

sq = mid ** 2
if num == sq:
    return True
if num > sq:
    lo = mid + 1
else:
    hi = mid -1

returns early in this case. This reduced the time for me to 36ms.

unpacking

If you want, you can use a ternary expression and tuple unpacking to redefine hi and lo

lo, hi = (mid + 1, hi) if num > sq else (lo, mid - 1)

but this is a matter of taste, and doesn't seem to save any time or memory.

memory

I don't see a lot of ways in which to reduce this method's memory usage. If you look at the distribution of all submissions, almost all use this bisect method, so memoty reduction will be based on the wims of the VM.


Find the intersect area of two overlapping rectangles

/**
 * Returns intersecting part of two rectangles
 * @param  {object}  r1 4 coordinates in form of {x1, y1, x2, y2} object
 * @param  {object}  r2 4 coordinates in form of {x1, y1, x2, y2} object
 * @return {boolean}    False if there's no intersecting part
 * @return {object}     4 coordinates in form of {x1, y1, x2, y2} object
 */
const getIntersectingRectangle = (r1, r2) => {
  [r1, r2] = [r1, r2].map(r => {
    return {
      x: [r.x1, r.x2].sort((a,b) => a - b),
      y: [r.y1, r.y2].sort((a,b) => a - b)
    };
  });

  const noIntersect = r2.x[0] > r1.x[1] || r2.x[1] < r1.x[0] ||
                      r2.y[0] > r1.y[1] || r2.y[1] < r1.y[0];

  return noIntersect ? false : {
    x1: Math.max(r1.x[0], r2.x[0]), // _[0] is the lesser,
    y1: Math.max(r1.y[0], r2.y[0]), // _[1] is the greater
    x2: Math.min(r1.x[1], r2.x[1]),
    y2: Math.min(r1.y[1], r2.y[1])
  };
};

/*  ↓  DEMO  ↓  */

const rectangle1 = { x1: 2, y1: 2, x2: 4, y2: 4 };
const rectangle2 = { x1: 3, y1: 3, x2: 6, y2: 2 };

console.log(getIntersectingRectangle(rectangle1, rectangle2));
// { x1: 3, y1: 2, x2: 4, y2: 3 }

First, both rectangles get transformed into object with keys x and y and sorted arrays of two of corresponding them coordinates as values.
r1 = {
  x: [2, 4], // x1, x2
  y: [2, 4]  // y1, y2
}
r2 = {
  x: [3, 6], // x1, x2
  y: [2, 3]  // Y2, Y1 !
}

That's because for this job it is important to know which of xs and ys is lesser and which is greater. Rather than Math.max() and Math.min() a single .sort() can be used.
Alternative would be to declare that (x1, y1) is assumed to always be top-left corner, but as I see in rectangle2 in your question, that is apparently not always the case.
Now, noIntersect is negated
!(a.left > b.right || b.left > a.right || a.top > b.bottom || b.top > a.bottom);

which tests if in both axes sides from one end of one figure exceed opposite-direction end side of the other figure, e.g. if left side of figure a is more to the right than the right side of figure b.
At the end we return false if there is no intersection of our rectangles, or an object with coordinates if there is. Intersecting part will always span from:
the greater of the 2 lesser xs of both rectangles
to
the lesser of the 2 greater xs of both rectangles.


You are representing each state of the universe as a list of bits. However, CPUs are experts at handling sequences of bits — that's what an integer is!

Given two bits, the way to find out whether exactly one of them is 1 is to use the ^ operator (XOR).

You should be able to solve this challenge using bit-shifting (<< and >> operators) and ^.


There is no reason to use lists instead of arrays, new int[size] will give you an array full of 0s without any overhead.

You can get away with creating only one array (leftMax) and then while computing the values of rightMax, instead of saving them into an array, complete the full calculation of how much to add to ans. Like this:

public int TrapDynamicProgramming(int[] height)
{
    if (height == null || height.Length == 0)
    {
        return 0;
    }

    int ans = 0;
    int size = height.Length;
    int[] leftMax = new int[size];

    leftMax[0] = height[0];
    for (int i = 1; i < size; i++)
    {
        leftMax[i] = Math.Max(height[i], leftMax[i - 1]);
    }

    int rightMax = height[size - 1];
    for (int i = size - 2; i >= 0; i--)
    {
        rightMax = Math.Max(height[i], rightMax);
        ans += Math.Min(leftMax[i], rightMax) - height[i];
    }

    return ans;
}


You need to include the headers your code depends on; don't assume that the user of your code will include them for you:
#include <vector>
#include <ostream>  // see note below

Never require your user to bring names into the current namespace; type names used in your public interface should always be qualified:
template<class T>
void Vec_WriteFile(const std::vector<T>& vec, std::ifstream file, char del = '\n')

Don't attempt to write to an istream.  Your output should go to an ostream instead.  You could use an ofstream, but that's quite specific.  Instead, you should accept a reference to any ostream; the user can then pass an ofstream or std::cout or any other output stream:
template<class T>
void Vec_WriteFile(const std::vector<T>& vec, std::ostream& file, char del = '\n')

There's nothing in your code that wouldn't work for a std::list equally as well as for a std::vector, so you can be more general:
template<class Container>
void Vec_WriteFile(const Container& vec, std::ostream& file, char del = '\n')

Naming: del evokes "delete" in my head before I reset and think "delimiter".  It might be better written in full, or perhaps as sep for "separator".

Layout: at first glance, it's not obvious which code is controlled by the for condition, as you have inconsistent indentation.

Writing a backspace over the final delimiter isn't the same as not writing the delimiter.  If you want the delimiter between items but not after the final item, the usual way is to track whether the loop is in its first iteration:
bool first = true;
for (...) {
    if (first)
        first = false;
    else
        file << del;
    file << element;
}

Error reporting: instead of just assuming that the writes are all successful, we could report via the return value from the function.  This may help the user remember to deal with errors, which could be overlooked if they have to check the stream state after the call.

My version:
#include <ostream>

template<class Container>
std::ostream& write_container(const Container& c,
                     std::ostream& out,
                     char delimiter = '\n')
{
    bool write_sep = false;
    for (const auto& e: c) {
        if (write_sep)
            out << delimiter;
        else
            write_sep = true;
        out << e;
    }
    return out;
}


Reading Maps of strings and doubles from CSV

This really looks like you over-designed the solution. And especially tricky since it won't work right now. (You're calling an unknown method getMap(FILE_TO_LOAD), it's missing the 2 mapping functions as parameters).

Why not just create a factory class that creates maps from the CSV files?

public class MapFactory {
    private static final String STRING_FILE = "resources/stringMap.csv";
    private static final String DOUBLE_FILE = "resources/doubleMap.csv";

    //private constructor to prevent pointless instance creation of this class
    private MapFactory() {
    }

    private static Map<String, String> createStringMap() {
        return createMapFromFile(STRING_FILE, Function.identity());
    }

    private static Map<String, Double> createDoubleMap() {
        return createMapFromFile(DOUBLE_FILE, Double::parseDouble);
    }

    public static <T> Map<String, T> createMapFromFile(String inputFile, Function<String, T> parseFunction) {
        Map<String, T> mapResult = new HashMap<>();
        File f = new File(inputFile);
        try (Scanner sc = new Scanner(f)) {
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                String[] lineParts = line.split(";");
                mapResult.put(lineParts[0], parseFunction.apply(lineParts[1]));
            }
        } catch (FileNotFoundException fntf) {
            System.err.println("File " + f.getPath() + "was not found.");
        } catch (Exception e) {
            System.err.println("Something went wrong with reading " + f.getPath());
        }
        return mapResult;
    }
}

You should really change the names of "stringMap" and "doubleMap" to something more meaningful. I can't do that for you here since you did not provide the actual use of your code.

Notice how I just extracted the common part into it's own method here?

I did throw away the map field so you'll need to re-read the file on each new creation. This greatly depends on how you plan on using these maps. With this solution the different classes that use the maps are free to modify it without breaking any other classes that use the map.

Alternatively you can also save the map in a field and use (thread safe) lazy loading to only initialise the map once, the first time it's used like this:

public class MapFactory {
    private static final String STRING_FILE = "resources/stringMap.csv";
    private static final String DOUBLE_FILE = "resources/doubleMap.csv";

    //private constructor to prevent pointless instance creation of this class
    private MapFactory() {
    }

    private static class StringMapHolder {
        private static final Map<String, String> STRING_MAP =createMapFromFile(STRING_FILE, Function.identity());
    }

    public static Map<String, String> createStringMap() {
        return StringMapHolder.STRING_MAP;
    }
    private static class DoubleMapHolder {
        private static final Map<String, Double> DOUBLE_MAP = createMapFromFile(DOUBLE_FILE, Double::parseDouble);

    }

    public static Map<String, Double> createDoubleMap() {
        return DoubleMapHolder.DOUBLE_MAP;
    }

    private static <T> Map<String, T> createMapFromFile(String inputFile, Function<String, T> parseFunction) {
        Map<String, T> mapResult = new HashMap<>();
        File f = new File(inputFile);
        try (Scanner sc = new Scanner(f)) {
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                String[] lineParts = line.split(";");
                mapResult.put(lineParts[0], parseFunction.apply(lineParts[1]));
            }
        } catch (FileNotFoundException fntf) {
            System.err.println("File " + f.getPath() + "was not found.");
        } catch (Exception e) {
            System.err.println("Something went wrong with reading " + f.getPath());
        }
        return mapResult;
    }
}


In the absence of different strings because of symlinks, hardlinks, multiple IPs for the same machine and hostnames instead of raw IPs, then yes, the synchronized combined with intern is thread-safe; no idea about performance, which is probably not an issue anyway.

If you only run all of this from a single program then it's probably okay in general, otherwise you should look into locking on the remote machines, i.e. constructing your command so that it locks on a .file.lock file or so.


You would benefit from removing the hard-coded strings out of the code. Best to put them in an app.config file or a resource file. The config file has the additional advantage that the strings could be changed by the user without recompiling.

The naming of the methods and properties is not standard for C#. Use Pascal case for public methods and properties with no underbar, e.g.

Sims3.CachePath = configCachePath;
Sims3.ClearCache();

The naming of local variables and private methods uses camel case, e.g.

isClearedTick();


JavaScript Determine if Array has Almost Increasing Sequence

Your code has complexity \$ O(N^2) \$ (with \$ N \$ being the array length), and also creates up to \$ N \$ temporary arrays.

Also note that your increasingSequence function accesses arr[-1], the
loop should start with let i = 1.

As already mentioned in the comments, the result can be
obtained with a single traversal of the array, thus reducing the complexity to \$ O(N) \$, and without additional storage.

The idea is to find the first element  violating the (strict) increasing
condition, i.e. the first index i with a[i - 1] >= a[i]. Then one of
a[i-1] or a[i] must be removed, and both cases can occur,
as the following examples show:

a = [ 4, 9, 5, 6, 7 ], i = 2  -->  remove a[i - 1] = 9
a = [ 4, 5, 1, 6, 7 ], i = 2  -->  remove a[i] = 1

Therefore we check if

a[i - 2], a[i - 1], a[i], a[i + 1]

can be made strictly increasing by removing one of the middle elements.

Since no more elements can be removed, the remaining elements, starting at index i + 1, must be strictly increasing.

There are also some shortcuts, e.g. if the array has at most 2 elements,
or if the “first decrease” is at the end of the array.

An implementation could look like this (it gives the correct result
in all your test cases):

const almostIncreasingSequence = a => {
    if (a.length <= 2) {
        return true;
    }

    // Find first i such that a[i - 1] >= a[i]:
    let i = 1;
    while (i < a.length - 1 && a[i - 1] < a[i]) {
        i++;
    }
    if (i >= a.length - 1) {
        return true; // Increasing if last element is removed.
    }

    // Can a[i - 1] be removed ?
    let case1 = (i == 1 || a[i - 2] < a[i]) && a[i] < a[i + 1];
    // Can a[i] be removed ?
    let case2 = a[i - 1] < a[i + 1];

    if (!case1 && !case2) {
        return false;
    }

    // Check that a[i + 1], ... is increasing.
    for (let j = i + 2; j < a.length; j++) {
        if (a[j - 1] >= a[j]) {
            return false;
        }
    }

    return true;
};

(JavaScript is not my first language, so take this just as a
suggestion, it surely can be implemented in a more idiomatic way.)


Create unique string from id to build an link shortening system

I played with your code for a while, declared constants for your functions to use so that the static values didn't need to be regenerated with each call, added spacing around operators, curly braces for condition blocks, simplified expressions, reduced the total number of function calls, and generally made things more direct.
One point of concern is that you are using arithmetic to translate the values -- for this reason you will need to be wary of the upper limit for your system.  It would be a good idea to throw an exception when your calculation breaks the int max limit.  Also, scientific notation can monkey wrench things too.  I used number_format() to prevent scientific notation while I was testing -- I don't know how much extra mileage this will grant you.  This has been a fun rabbit hole to go down.
define('ALNUM_MAP', str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'));
define('DIGIT_MAP', array_flip(ALNUM_MAP));

function idToString($id) {
    if ($id < 62) {
        return ALNUM_MAP[$id];
    }
    $string = '';
    while ($id) {
        $id = number_format($id, 0, '', '');
        $string = ALNUM_MAP[$id % 62] . $string;
        $id = (int)($id / 62);
    }
    return $string;
}

function stringToID($string) {
    $id = 0;
    for ($i = strlen($string) - 1, $pow = 0; $i >= 0; --$i, ++$pow) {
        $id += DIGIT_MAP[$string[$i]] * (62 ** $pow);
    }
    return number_format($id, 0, '', '');
}

echo idToString(247698); // bcBi
echo "\n---\n";
echo stringToID('bcBi'); // 247698
echo "\n---\n";
//echo idToString(32611315596050636800); // M1ckM4ckUS4
//echo "\n---\n";
//echo stringToID('M1ckM4ckUS4'); // 32611315596050636800
//echo "\n---\n";
echo idToString(8483692923010050); // M1ckM4ckU
echo "\n---\n";
echo stringToID('M1ckM4ckU'); // 8483692923010050

That said, since you are starting with fully numeric values and you want to reduce their character count by converting to an alphanumeric string, then I have a far simpler way based on this answer that I post on Stack Overflow a couple years back.  (Be sure that the incoming values are string-type, not integer-type.)
Code: (Demo)
define('ALNUM_MAP', str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'));
define('DIGIT_MAP', array_flip(ALNUM_MAP));

function numToAlnum($num) {
    return strtr($num, ALNUM_MAP);
}

function alnumToNum($alphaNum) {
    return strtr($alphaNum, DIGIT_MAP);
}

$ids = ['4440', '464426', '43304441302845', '262018191701180', '273381111186152545352'];
foreach ($ids as $id) {
    $idLength = strlen($id);
    $alphaNum = numToAlnum($id);
    $alNumLength = strlen($alphaNum);
    $backToId = alnumToNum($alphaNum);
    var_export(['original' => $id, 'encoded' => $alphaNum, 'decoded' => $backToId, 'reduction' => $idLength - $alNumLength]);
    echo "\n---\n";
}

As stated in my SO post, using strtr() is a fantastic technique because it is designed to translate the longest substring that it can find as it traverses the input string.  This translation operates on a different algorithm, so it will not give exactly the same length reduction as your technique, but it will not suffer from any numeric/math-based side-effects either.


Need Loops for PHP Username/Pass Encryption Script

the first thing that came to my mind to make this cleaner was an array or rather several arrays.

maybe something like this:

$user = array('admin','g','homer','marge','bart','lisa','maggie','dog');
$admin = array('admin','23!bseEsF@','homeradmin','margeadmin','bartadmin','maggieadmin','dogadmin');

$password = array(8); //my syntax may be wrong here
$adminPassword = array(8); //my syntax may be wrong here

for ($x=0; $x < count($user); x$++)
{
    $password[$x] = crypt($user[$x], base64_encode($user[$x]));
    $adminPass[$x] = crypt($admin[$x], base64_encode($admin[$x]));
}

And then your Echo's would look like this.

echo $user1 . ":" . $pass1 . "
";
for ($y=0; $y < count($user); $y++)
{
    echo $user[$y] . ":" . $pass[$y] . "
";
}
for ($z=0; $z < count($admin); $z++)
{
    echo $admin[$z] . ":" . $adminPass[$z] . "
";
}

The only way that this works is if all the arrays are the same length and arrays in PHP are base 0. otherwise you have to change the for declarations a little bit.

Again I say that my Syntax may not be perfect or even well formed,  but this is much cleaner than what you have.

Syntax not Guaranteed


More functional way of writing this palindrome extractor?

It can be as simple as:

scala> val str =  "I like racecars that go fast"
str: java.lang.String = I like racecars that go fast

scala> for { i <- 2 to str.size; s <- str.sliding(i) if s == s.reverse} yield s
res5: scala.collection.immutable.IndexedSeq[String] = Vector(cec, aceca, racecar)


Readability

Version 1:
This is unreadable. If you presented that me in a professional context I would literally fire you (for real).

Version 2:
This is arguably readable. But you are making it hard for yourself and other people. You are probably going to be breaking your companies coding guidelines and I can see your colleagues complain. But its all subjective. I would not like you if we were working on the same code base.

Version 3:
This is a reasonable readable version.

Code Review
Your use of exceptions is a bit much. Exceptions are great when you can not correct the problem at the point of the error and need to transfer control to a higher level context and thus can take a reasonable action based on context.
Here you are throwing exceptions and catching them in the same function (i.e you are not moving to a higher context). It's not terrible, but you can achieve the same effect with error codes (and the error codes do not cross an interface boundary so are OK). I am not going to argue for error codes or against them. In this case that is a style thing and how your team likes to handle the situation.
The only issue I have is that exception that are throw can potentially change over time, and you don't catch the any (catch (...)) and thus can potentially have an accidental application termination with no error message.
I don't know how many arguments this takes. But it exits on the first parameter error. You may want to check all the parameters and generate more errors (if possible). This potentially will allow the user to fix all the parameters at once rather than having to run the application multiple times fixing one parameter at a time.


You can improve iterating over the array by using np.ndenumerate to get the current coordinates and current item. From the coordinates you can derive the neighbouring elements.
You can also use inverse checking to only set the respective field to False if a neighbor does not match:

from contextlib import suppress

def compare_neighbors(arr):

    comp_arr = np.full(arr.shape, True, dtype=bool)

    for (x, y), item in np.ndenumerate(arr):
        # Check left.
        if x >= 0:
            if arr[x-1, y] != item:
                comp_arr[x, y] = False
                continue

        # Check right.
        with suppress(IndexError):
            if arr[x+1, y] != item:
                comp_arr[x, y] = False
                continue

        # Check top.
        with suppress(IndexError):
            if arr[x, y+1] != item:
                comp_arr[x, y] = False
                continue

        # Check bottom.
        if y >= 0:
            if arr[x, y-1] != item:
                comp_arr[x, y] = False
                continue

    return comp_arr


Use more functions
Currently, the entirety of your hangman game lies inside the run() call. You can split certain parts of it to their own functions, such as checking for win condition, asking for character input, displaying the current state etc.
Empty prints
Use \n to get a new line in console, instead of putting in empty print statements.
Checking guessed character
For strings, you can just check if the character is in string or not, since you have no need for the count of repetitions itself.
ord, chr and bytearray
They are of no use. You do not need a bytearray of ordinals, simply splitting the word into a list would be enough (not really needed though).
Type hints
With newer python, type hinting feature has also become available. Use them to assist you with the type of values for the variables.

So, your program could also be rewritten like:
class Hangman:
    def __init__(self, target: str, guesses: int):
        assert self.is_ascii_alphabetical(
            target
        ), "Provided secret word is not ascii alphabetical string."
        self.secret_word = target
        self.guesses = guesses
        self.guessed_word = ["_"] * len(target)
        self._finish = False

    def is_ascii_alphabetical(self, value: str) -> bool:
        return value.isascii() and value.isalpha()

    def display(self, real_word: bool = False):
        if not real_word:
            print(f"\n\n{''.join(self.guessed_word)}\n")
        else:
            print(f"\n\n{self.secret_word}\n")

    def read_character(self) -> str:
        while True:
            guess = input("Guess a letter: ")
            if len(guess) != 1:
                print("Invalid guess.")
                continue
            elif not self.is_ascii_alphabetical(guess):
                print("Non-letter guessed.")
                continue
            if self.is_guess_repeat(guess):
                print("Already guessed this letter.")
                continue
        return guess.lower()

    def update_guessed_word(self, character: str) -> None:
        self.guessed_word = [
            new if new == character else old
            for old, new in zip(self.guessed_word, self.secret_word)
        ]

    def is_guess_repeat(self, guess: str) -> bool:
        return guess in self.guessed_word

    def is_guess_valid(self, guess: str) -> bool:
        if guess not in self.secret_word:
            return False
        return True

    def is_game_over(self) -> bool:
        return self.guesses <= 0

    def is_game_won(self) -> bool:
        return "_" not in self.guessed_word

    def run(self):
        while not self._finish:
            self.display()
            print(f"Remaining guesses: {self.guesses}")
            guess = self.read_character()
            if self.is_guess_valid(guess):
                self.update_guessed_word(guess)
            else:
                self.guesses -= 1
            if self.is_game_won():
                self.display(True)
                print("You won.")
                self._finish = True
            elif self.is_game_over():
                self.display(True)
                print("You lost.")
                self._finish = True

if __name__ == "__main__":
    # Merriam-Webster Word of the Day: October 2, 2020
    hangman = Hangman("pachyderm", 6)
    hangman.run()


Do not use Dictionary when order matters.

Your code assumes that iterating over Dictionary will yield elements in the order in which they were added, but that's not guaranteed at all (emphasis mine):

  For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey, TValue> structure representing a value and its key. The order in which the items are returned is undefined.

And even if this wasn't an issue, the intervals logically are not keys and values, so that's another reason not to use dictionary.

In simple cases like this, consider using anonymous type:

var intervals = mask.Split(',').Select(
  element => new
  {
      from = Convert.ToInt32(element.Split('-').First()),
      to = Convert.ToInt32(element.Split('-').Last())
  });


app.controller('FirstCtrl', function($scope, todos){

You're using the implicit dependency injection method which uses the argument name as the dependency name. If you will be minifying the code (which mangles the name, rendering this approach useless), you either have to use explicit dependency (ie. .controller(name, [dep1, dep2, ... fn]) or use ng-annotate.

Additionally, you should name your controller properly. Normally, what we do is append "Controller", "Service" etc. to the name. In this case, it should be like "ToDoController". Also prevents ambiguities in dependency injection.

if ($scope.input == "" || $scope.input == undefined){
  return false;
}

Angular has built-in validation. Usually, I call submit passing in form's valid property and the data. If the valid property of the form is true, then it is safe to assume that the data that came with it has passed Angular's validation.

$scope.todos.list.push({
  task:$scope.input,
  completed: false
});

This operation must be delegated to the factory, not in the controller. The issue is when you start to share data across different controllers. If you happen to have another section of the UI able to add new todos to the main list, then you'd be duplicating your push logic in another controller.

Delegating this to the factory will need you to expose a function that the controller can call, pass in the data, and the factory update the list accordingly. Since the controller has reference to the same list, changes will appear magically.

restrict: "E",

If you're targetting IE8, then you should be aware that "E" isn't an option. You'd have to use "A" and write attribute directives instead of element name directives.

controller:'FirstCtrl as First'

I would recommend that a directive have its own scope ("isolate scope" as they call it), and that the binding to the controller be explicit. My concept of "directives" are like "custom elements" - portable, self-contained code. One can easily write the following:

<to-do>
  <to-do-list list="todos"></to-do-list>
  <to-do-form onSubmit="addTodo"></to-do-form>
</to-do>

Where:

<to-do> is a wrapper, a directive with a transclude (allows inner html).
<to-do-list> is a directive that renders the to-do list, given an array to its list property.
<to-do-form> is a directive that renders an input, which calls a function assigned to onSubmit.

The controller will then look like this:

app.controller('TodoController', function($scope, ToDoFactory){

  // Get a reference to the ToDos and expose it to the template
  $scope.todos = ToDoFactory.getToDos();

  // Expose a way to call a function that adds todos
  $scope.addTodo = function(toDo, isValid){
    if(!isValid) return;
    ToDoFactory.add(toDo);
  }
});

The factory:

app.factory('ToDoFactory', function(){
  var todos = [];

  return {
    add: function(todo){
      todos.push(todo);
    },
    getToDos: function(){
      return todos;
    }
  }
});

The list be like:

app.directive('toDoList', function(){
  return {
    restrict: 'E',
    template: '

{{ todo }}

',
    scope: { list: '=' }
  }
});

The input be like:

app.directive('toDoForm', function(){
  return {
    restrict: 'E',
    template: '<form name="toDoForm"><input type="text" ng-model="todo" ...validations...><button type="submit" ng-click="onSubmit(todo, toDoForm.$valid)">Add</button></form>',
    scope: { onSubmit: '=' }
  }
});

Also, directives have a link function which can act as your setup area, much like a controller's function. This is helpful especially when setting up watches, data manipulations etc.


Implement bash auto completion in Python

Splitting words

The Python script splits the shell command's full line to words using shlex.
I see a few issues with this:

I'm not sure this will split the line exactly the same way as the shell would. Looking at help(shlex), I see "A lexical analyzer class for simple shell-like syntaxes", and I find that not very reassuring.
I think command line completion should be blazingly fast, so I look suspiciously at anything that needs to be import-ed, such as shlex.
Looking at the Programmable Completion section in man bash, it seems that Bash populates the COMP_WORDS array with the result of the split.

Therefore, it would be good to pass COMP_WORDS to the Python script,
which would eliminate all the above concerns.

One way to achieve this would be to call the Python script with:

python3 script.py complete "$COMP_CWORD" "${COMP_WORDS[@]}"

And then change the Python script accordingly:

#!/usr/bin/env python3

import sys

def complete(comp_cword, *comp_words):
    prefixes = ("test", "test-中文", "test-한글")
    word = comp_words[int(comp_cword)]
    items = (prefix + "-level-" + comp_cword for prefix in prefixes)
    return (item for item in items if item.startswith(word))

if __name__ == "__main__":
    sys.stdout.write(" ".join(complete(*sys.argv[2:])))
    sys.stdout.flush()

Avoid converting generators to list when not needed

No lists were needed in the original script, everything could have been just generator expressions.

Keep it simple

I don't understand why the script imports os and uses os.sys and nothing else in os.
You could just import sys instead.

I don't understand why sys.argv.__getitem__(slice(2, None)) was used instead of the simple and natural sys.argv[2:].

This line is complex, it takes attention to understand:

word = "" if len(split) - 1 < int(current_word) else split[int(current_word)]

This is a lot easier to understand:

if len(split) - 1 < int(current_word):
    word = ""
else:
    word = split[int(current_word)]

Looking further, word is used only in a filter .startswith(word).
That filter will match every string.
In which case, to maximize performance,
it would be best to not create word, and not do any filtering,
but return items directly:

if len(split) - 1 < int(current_word):
    return items

On even closer look,
I don't see how COMP_CWORD can ever be an index out of range.
So the check for bounds was unnecessary.
(Strictly speaking, an index out of bounds may be possible when splitting words with shlex, since that might not be identical to the shell's own word splitting. Even then, it would be a highly unlikely case, therefore a more Pythonic way to handle the situation would be using a try-expect for a IndexError.)

Use better names

The name i is really best reserved for loop counters.
(Even then, often you may find better names...)

In the suggested solution above I renamed the parameter names to match the shell variables they come from.
I find this reduces the cognitive burden when reading the documentation of the variables in man bash, and the implementation of the completion code in Python.


I'm not really into Neural Networks, but I do read code and I do have some suggesting for what to do next related to this code.

Code and Style Comments

Number in variable names, not good – Even though you spelt out the number, still having numbers in a variable names indicates that you might be doing something wrong. I'm thinking of the hiddenNode_One& co.
Please fix your indentation – This excerpt is taken directly from your code:

public class Neuron {
private float activationValue, weight;
private String neuronName;
private ArrayList<Neuron> outputs = new ArrayList<Neuron>();
private float[] inputs;
int inputCounter = 0, nInputs;

public Neuron(float activationValue, float weight, String neuronName, int nInputs){
    this.activationValue = activationValue;

This looks like a list of variable declaraction outside of classes and methods, and only with a second look it's possible to see that you are actually declaring a class Neuron, its class variables, and a class constructor of public Neutron(). And finally you indent for the method definition.  Here is the same code with better indentation:

public class Neuron {
    private float activationValue, weight;
    private String neuronName;
    private ArrayList<Neuron> outputs = new ArrayList<Neuron>();
    private float[] inputs;
    int inputCounter = 0, nInputs;

    public Neuron(float activationValue, float weight, String neuronName, int nInputs){
        this.activationValue = activationValue;

This looks a lot better, and it's easier to follow the program flow.
Is it wise to lock the number of inputs? – In your constructor you lock the number of inputs for any given Neuron, which might lead to confusing situations later on if you want to reorder your network.
Feature: To many input()'s will trigger index error – Since you keep increasing the inputCounter whenever this method is called, you'll run out of array elements to update, and will finally trigger an index error.

In the same code, you'll only fire() once when the inputCounter exactly equals the preset number of inputs. So if the input of a Neuron changes afterwards, the network is never updated. Neither of these seems to be correct.
Always generate input() even when not over the activation value? – In light of preceding point, it seems kind of strange to do the input(0) sequence, as that might for some networks trigger the index error before it should. Wouldn't it be better to leave out the no input part?

That is, unless that is a requirement due to the value swapping from over and under the activationValue during the lifetime of the network, in which case you really need to address the case of connecting inputs to the Neuron receiving the input.
Why delay the summation of inputs, and the signal value – In my mind it would be better to update a sum and the signal value whenever receiving an input, instead of when doing the fire().

Imaging having a network of thousands of nodes, and you having to calculate this for each fire event you trigger, even though the input possibly didn't change?  To me it makes more sense to do this within the input() having a sum variable, and to have a class variable (or method) holding (or returning) the sum * weight.

Do however know that this would require proper knowledge of which input is being updated, so that if you receive a secondary input on that Neuron you'll correctly adjust the sum, and not blatantly keep adding the new value.
Order of calculation and output – Most likely your System.out.println(neuronName + ":" + signal) should be replaced with a call to some logger, but I would also put this one in front of the signal > activationValue loops. As it is in a bigger network you would get the output of the latter nodes, before the first nodes. For the output to make sense, it would be wiser to have the output directly after the calculation of signal.

Some General Thoughts on Neural Networks

In my mind a neural network is something dynamic, which could/should easily be able to change and reconnect towards other neurons (or nodes). So here are some concerns I have related to your code:

No visualization of the neural network – It's not possible to visualize your network. I think it would've been nice to have a way to visualize it, so that you can see how it is connected with which triggers and so on.
No connection of the input towards the neurons – There is no connection between the neurons connected to another neuron and the input. In other words, if the hiddenNode_Two decides to change its input, and thusly it fires an output, you don't have a way to know which of the inputs of the outputNode actually changed. This doesn't seem correct.
No dynamic in neuron connection – You've got no methods to remove and change your network. In addition you've limited the neuron at construction time to a given set of inputs. Thusly disallowing a re-ordering of your network based on any future learning.

Imaging having a network doing something related to alphabetic calculation. At the start you could start out with a few nodes, but after a while you see the need to split the a-e node as it is overworked. Your code as it stands, would require a full reconstruction, and not a simple replacement of that node with a few extra nodes.

One way to implement this interconnection, and related sums and signal values, could be to introduce a static list of Neurons, and extend each Neuron with dynamic lists of indexes into this list to describe its inputs and outputs.

This would allow for methods identifying all the inputs or outputs, by checking whether the input or output list for a given neuron is empty or not. You could also make static methods traversing based on input nodes describing the paths to new nodes (possibly with circular node connection detection) until you reaches the output nodes.


Input Injection

Your function seems to depend at least on the input file, but this file is asked for by the function. You should follow the IoC principle and pass the file from outside (through function parameter).

var file = ConfigurationManager.AppSettings["catalogue-lines-import-file"];
var lines = ImportCatalogueLines(file);

Maybe like that, but dont get confused, as your method Is private, this should be pushed even further, somewhere outside the entire class....

Always False Conditional

if (header[i] == "catcode")
                        catCodeColumn = i;

                    if (header[i] == "prodcode")
                        prodCodeColumn = i

It Is impossible for header[i] to be equal to two different values at the same time. Use else if or switch.

Duplicit Columns Check

Further if you are super paranoid you might want to check that catCodeColumn And prodCodeColumn Is not assigned more than once. That would mean there Is a duplicit column header (one that you care of).

Redundant Comparisions

catCodeColumn.HasValue == false || prodCodeColumn.HasValue == false

The comparision to false Is redundant, use the negation operator "!".

!catCodeColumn.HasValue || !prodCodeColumn.HasValue

Or use de Morgans law

!(catCodeColumn.HasValue && prodCodeColumn.HasValue)

Split by comma or do proper csv parsing?

In case some column value contains a comma character (not talking about the quotes needed for it to work), your implementation Will fail to handle it. Of course only if the csv ever contains such values. Even if it should not, you say that users can modify it as they like. Time to get paranoid!

Error Reporting

You should not log everything to Console inside the function.  Especially not if you caught an exception, mute it and return possibly half-built result. Instead throw a custom exception, possibly let it carry the half-built list. But dont return with incomplete result. And put the logging to Its own scope.

General Remarks

Other than that I think your approach Is quite reasonable. If you cannot hardcode or configure the columns offset ať compile time, you have to determine it dynamically... But ofc if you used a proper csv parser with additional features like header checking, the code would look quite different, probably shorter...


Optimizing rendering with a lot of transformations and save/restore

I see this was the second javascript question you posted here and it is unfortunate that there have been no responses in the nearly four years since then. Perhaps you have learned a few things about JavaScript since then.
Looking at the draw method I see that it stores a reference to this in a variable called self. This pattern happens frequently in JavaScript code but it is unnecessary. I see that some of the functions in table utilize self but that could be avoided by binding those functions to this with Function.bind().
It also appears that ctx is passed to each function as a parameter, which is also unnecessary because ctx is hoisted at the top-level and visible within each function as well.
The functions in table associated with keys "[" and "]" could be simply set to ctx.save.bind(ctx) and ctx.restore.bind(ctx), respectively. Furthermore, the functions in table associated with keys "+" and "-" can be set to ctx.rotate.bind(ctx, this.angle) and ctx.rotate.bind(ctx, -this.angle), respectively.
I'm not sure if those changes will be enough to reduce the CPU load. If not, then consider taking out function calls (i.e. calling table[char]) and using a series of if statements or switch statement in the for loop.
Demo
While it may not be much, see the demo below which hopefully provides some proof that the suggestions lead to a slight performance gain (see the drawB() method). I considered using jsPerf but that might be a bit of a stretch to use for this code.

var rules = [
  //["F", "F[+F]F[-F]F"]

  //["F", "F+F--F+F"]

  //["1", "1F1F"],
  //["0", "1F[+0][-0]"]

  //["F", "F+F-F-F+F"]

  ["F", "FF"],
  ["X", "F-[[X]+X]+F[+FX]-X"]
];
var angle = 10;
const times = [{
  y: [],
  line: {
    color: "blue",
    width: 4,
    shape: "line"
  },
    name: "Original draw()"
}, {
  y: [],
  line: {
    color: "green",
    width: 4,
    shape: "line"
  },
    name: "Simplified draw()"
}];

function LSystem(rules, angle, init, level) {
  this.rules = {};
  this.angle = angle * Math.PI / 180;
  this.parseRules(rules);
  this.path = this.generateLevel(init, level);
}
LSystem.prototype.parseRules = function(rules) {
  var self = this;
  rules.forEach(function(rule) {
    self.rules[rule[0]] = rule[1];
  });
};
LSystem.prototype.applyRule = function(input) {
  var output = "";
  for (var i = 0; i < input.length; i++) {
    var char = input[i];
    if (char in this.rules) {
      output += this.rules[char];
    } else {
      output += char;
    }
  }
  return output;
};
LSystem.prototype.generateLevel = function(input, level) {
  if (level == 0) return input;
  return this.generateLevel(this.applyRule(input), level - 1);
};
LSystem.prototype.draw = function(x, y) {
  var start = +new Date();
  var self = this;
  var path = this.path;
  var table = {
    "F": function(ctx) {
      ctx.moveTo(0, 0);
      ctx.lineTo(5, 0);
      ctx.translate(5, 0);
    },
    "+": function(ctx) {
      ctx.rotate(self.angle);
    },
    "-": function(ctx) {
      ctx.rotate(-self.angle);
    },
    "[": function(ctx) {
      ctx.save();
    },
    "]": function(ctx) {
      //ctx.stroke();
      ctx.restore();
      //ctx.beginPath();
    }
  };
  ctx.save();
  ctx.clearRect(0, 0, 500, 500);
  ctx.beginPath();
  ctx.moveTo(x + 0.5, y + 0.5);
  ctx.translate(x + 0.5, y + 0.5);
  for (var i = 0; i < path.length; i++) {
    var char = path[i];
    var cmd = table[char];
    cmd && cmd(ctx);
  }
  ctx.stroke();
  ctx.restore();
  const end = +new Date();
  times[0].y.push((end - start));
  if (times[0].y.length > 1) {
    avg.innerText = times[0].y.reduce((a, b) => a + b) / times[0].y.length;
  }
};
LSystem.prototype.drawB = function(x, y) {
  var start = +new Date();
  var table = {
    "F": function() {
      ctxB.moveTo(0, 0);
      ctxB.lineTo(5, 0);
      ctxB.translate(5, 0);
    },
    "+": ctxB.rotate.bind(ctxB, this.angle),
    "-": ctxB.rotate.bind(ctxB, -this.angle),
    "[": ctxB.save.bind(ctxB),
    "]": ctxB.restore.bind(ctxB)
  };
  ctxB.save();
  ctxB.clearRect(0, 0, 500, 500);
  ctxB.beginPath();
  ctxB.moveTo(x + 0.5, y + 0.5);
  ctxB.translate(x + 0.5, y + 0.5);
  for (var i = 0; i < this.path.length; i++) {
    var char = this.path[i];
    var cmd = table[char];
    cmd && cmd();
  }
  ctxB.stroke();
  ctxB.restore();
  const end = +new Date();
  times[1].y.push((end - start));
  if (times[1].y.length > 1) {
    avgB.innerText = times[1].y.reduce((a, b) => a + b) / times[1].y.length;
    avgB.classList.toggle('faster', parseFloat(avgB.innerText) < parseFloat(avg.innerText));
    avgB.classList.toggle('slower', parseFloat(avgB.innerText) > parseFloat(avg.innerText));
    avg.classList.toggle('faster', parseFloat(avg.innerText) < parseFloat(avgB.innerText));
    avg.classList.toggle('slower', parseFloat(avg.innerText) > parseFloat(avgB.innerText));
  }
}

// main
var ctx,
  ctxB,
  s = new LSystem(rules, angle, "X", 5),
  sB = new LSystem(rules, angle, "X", 5),
  output;
window.onload = function() {
  ctx = document.querySelector("canvas").getContext("2d");
  ctxB = document.getElementById("cnvB").getContext("2d");
  output = document.querySelector("pre");

  ctx.translate(50, 500);
  ctx.rotate(Math.PI / 180 * -65);
  ctx.translate(0, -250);

  ctxB.translate(50, 500);
  ctxB.rotate(Math.PI / 180 * -65);
  ctxB.translate(0, -250);

  //ctx.translate(250, 500);
  function d(t) {
    requestAnimationFrame(d);
    ctx.clearRect(0, 0, 500, 500);
    ctxB.clearRect(0, 0, 500, 500);
    s.draw(0, 250);
    sB.drawB(0, 250);

    s.angle = Math.PI / 180 * (25 + Math.sin(t / 1000));
    sB.angle = Math.PI / 180 * (25 + Math.sin(t / 1000));
  }
  output.textContent = s.path.length;
  requestAnimationFrame(d);
};
canvas {
  border: 1px solid black;
}

output.slower {
  background-color: red;
  color: white;
}

output.faster {
  background-color: green;
  color: white;
}

 Avg time for draw()	 <output id="avg"></output> ms

  Avg time for modified draw() 	<output id="avgB"></output> ms

<canvas width="500" height="500"></canvas>
<canvas width="500" height="500" id="cnvB"></canvas>

Result
Below is a chart comparing the elapsed times of 100 calls to the original draw method and the modified draw method.


A .py utility file for neural network learing rate policies

Overall I rather like this. It's a nice way to think about "configurable functions". Minor stuff:

Due to order of operations, the parens around self.lr_base * (self.lr_mult ** epoch) are not needed
It's worth splitting out a temporary variable for cfg['OPTIM']
Consider annotating your member variables and method signatures with PEP484 type hints
Decimals in 1.0 are not necessary due to float promotion
Spaces before colons - "cos" : - are not PEP8-standard
You've not shown unit tests. If you don't have them, write them.

If you're interested, a different (not necessarily better) way of thinking about these functions is that they can start as normal, non-class functions, where the first parameter(s) are the configuration needed; then call partial() to get a callable reference that you can then use as if it has only epoch as a parameter from the perspective of  LambdaLR.


Basically, you're testing a lot of paths you don't have to.  It would probably be more efficient to find a 1-digit number that is divisible by 1, then use that digit to find a 2-digit number that is divisible by 2, then use those two digits to find a 3-digit number that is divisible by 3, then recursively backtrack if you run out of options at one level.

Here's some code to illustrate.  It returns essentially instantly in my REPL.  You call it by pizza 1 0 initially.

import Data.List ((\\))
import Data.Char (digitToInt, intToDigit)
import Data.Maybe (listToMaybe, mapMaybe)

pizza :: Integer -> Integer -> Maybe Integer

pizza 10 accum = Just (accum * 10)

pizza n accum =
  let usedDigits = map digitToInt $ show accum
      unusedDigits = map toInteger $ [1..9] \\ usedDigits
      previous = accum * 10
      divisibleDigits = filter (\digit -> (previous + digit) `mod` n == 0) unusedDigits
  in listToMaybe $ mapMaybe (\digit -> pizza (n + 1) (previous + digit)) divisibleDigits

However, for one-shot problems like these, your solution is fine.  If you can't write a faster algorithm in less than 9 minutes (of your programmer time), you haven't actually saved any time.


Yes, it's too complex. Make the elements relate to each other, so that you can use a single event handler. This is the typical pattern used to link two DOM elements together, so that one can hide/show/otherwise interact with the other.

Show1
Show2
Show3

This is default content.

This is content 1.

This is content 2.

This is content 3.

And:

$('a').click(function (event) {
  event.preventDefault();
  $('p').hide();
  $($(this).attr('href')).show();
});


Rearrange String such that similar characters are placed at least 'K' distance apart

I think it's unlikely that interviewers are expecting you to write perfect code up on the white board.  The main goals of these tasks is to get an insight into how you go about solving problems, knowledge of the language features and attention to detail.  You can demonstrate attention to detail by writing 100% correct code, however you can also demonstrate it in other ways.  My starting point is usually to clarify the requirements with the interviewers.  You can do this in the context of unit testing to help identify some test cases that you are considering and getting them to clarify what the expected outcomes from those cases would be.  These can be added to the board so that you have a reference.  So, for example:

What happens if you are passed an empty string
What happens if there is only 1 characters
What happens if you've got "aa" as suggested by @coderodde
What happens with "AAABBBCC", which is your example.  You've said it should be "ABCABCABC", which has introduced an extra C.  Is this really right?

Clarifying the problem not only demonstrates attention to detail and helps you to understand the problem, it also buys you some time to think about how best to solve the problem.

Next you need to think about the algorithm you're going to implement.  Consider jotting it down on paper or the whiteboard so that you've got a reference design, that way you can worry about the order/steps required without having to worry about the language constructs/syntax at the same time.

Have some kind of checklist in mind for what you need to consider in your solution. For example:

Public interface
Parameter checking
Error handling
Exceptions
etc

This will help you to at least consider these things.  You can then talk about them if appropriate, even if you choose not to write them up on the board.  So "I'd check 'k' to ensure it's a positive integer at the start of this method and throw IllegalArgumentException if it wasn't, however I'm not going to write it on the board so that I can concentrate on the main algorithm".

As far as your actual code you've posted goes, the spec isn't entirely clear (as demonstrated by some of questions above).  You're missing error checking on your rearrange method.  For example you don't check if k<=0, what's going to happen if this is passed?

Try to be more expressive with variable names.  It's tempting when you have to write them down to shortcut names (heap,tempK,k,tempList etc), however if you do this in much the same way it causes problems for future maintainers, it makes it harder for you to remember what the variables represent and for the interviewers to follow your algorithm.

This line also looks a bit odd to me:

Deque<Node> tempList = new LinkedList<Node>();


Use the right data structure for the job. If you have

            if int(n) not in primes:

called more than a small constant number of times then primes should not be a list. If you change

primes = [i for i in gen_primes(10000000)]

to

primes = set(i for i in gen_primes(10000000))

you will see a significant speedup.

The algorithm could also be improved. I don't want to go into too much detail here because that's not in keeping with the ethos of Project Euler, but I think I can give you a couple of hints:

The problem statement says that there are only eleven primes matching the criterion. What property of primes with the criterion allowed them to prove that? How can you apply that property to generate them faster?

   If you have found all of the truncatable primes of length n, do you need to loop over all truncations of a candidate number of length n+1?


PEP 8

You still haven't followed PEP 8. Please:

Install (for example) Pylint.
You can run it as pylint filename.py.
If you use Vim you can install syntastic and every time you save it will run either flake8 or pylint.
There are alternatives for other text editors please install one, it will save you time in the long run.

def main

You have used if __name__ == "__main__": which is good. It is even considered more idiomatic (see this answer under "An Even Better Way") to do this:

def main():
    words = ('foo', 'foog', 'food', 'asdf')
    root = TrieNode()
    for w in words:
        root.insert(w)
    result = []
    root.find_prefix([], result)
    print result

if __name__ == "__main__":
    main()

Immutability

You don't mutate words. I would turn it into a tuple.


Extension of PHP `round()` for PHP_ROUND_UP and PHP_ROUND_DOWN

General

Instead of having your function convert string values to numbers, throw an error if, for example !is_float($number). round() only accepts a float value, so I think you should follow their convention.

Also, this will allow you to remove is_numeric() (or, above, you could check for is_numeric() only).

This if-condition doesn't have an else, so when poor input is entered, the user could potentially not get any response at all -- terrible for debugging!

Performance

empty($number) is checked two times, you can reduce that to none since is_float() will automatically return false if there is nothing (or throw an error is there's no argument).


Object Oriented Javascript

Many people think that to write OO javascript you need to use the class syntax. This is not at all true. You can write very good OO javascript without ever using the class syntax, including inheritance, encapsulation (private and protected states), static properties, and polymorphism (JS is the polymorphic king)

Style and code

I can't help but feel there is a lot missing from your code.

Problems I see

It drops requests if they timeout but only when a new request is added by the same client. The object ignores all existing client requests if the client makes no more requests.
You have a const MAX_REQUESTS_IN_TIME_FRAME but the code keeps on adding requests irrespective of this value when addRequestAndCheckIsAllowed is called.
There is no easy way to know that the limit has been reached without creating and adding a new request. To me it seems like you may use the two objects to deduce this state, if so that would violate encapsulation rules, as that is for the object to do not external code.

Some points on you code.

Id is an abbreviation and as such is named with a lower case "d"  ie clientId not clientID
Using Array.filter to remove items from an array is easy, but it generates lots of unused arrays for GC to clean up. Splicing items is far more efficient.
It is good to break long lines into multiple lines to stop them going past the right of screen. However doing so for short lines just makes the code harder to read. You have done this in 3 places for lines that fit even the stack's snippets thin format. More thought on good names can help reduce line lengths.
addRequestAndCheckIsAllowed that is a mouth full, maybe addRequestValidate is a better option?

OO points

Underscore does not make a private variable, avoid its use as its just noise
The constants MAX_REQUESTS_IN_TIME_FRAME and REQUEST_MAX_AGE also are public, and just add to the global scope. Put them inside the objects that use them.
RequestBuffer is only used by RateLimiter, it should not be visible outside RateLimiter
RequestBuffer need only expose a way to store requests and a way to see if a request is valid. This can be done via a getter allowed and a setter store
RequestLimiter should only expose the function addRequestAndCheckIsAllowed all the rest should be protected as private functions and properties.
You create a client request ad hoc, should be an object created via a function. Better yet as it is strongly associated with the RequestLimiter you can add it as a static such as RequestLimiter.Request In the example I add it using define property to ensure it is protected

Encapsualtion and private state

An important part of OO code is that you can protect the object's state by limiting access. In many languages this is done by declaring private variables and methods. Javascript does have a way to define private objects properties but it is very new, and personally because it adds a prefix to the variable name I can not agree with its use. There is a better way.

If you use function syntax to define objects. You can protect state via closure. You can protect object properties using Object.freeze or use Object.defineProperty. You can add statics directly to the function or via Object.defineProperty to protect them.

Getters and Setters

Additionally to help protect an object's state, objects use functions to access properties. These are called getters and setters and allow the objects to ensure only valid states can be set, or read. It also allows you to easily define read or write only properties.

Rewrite

The rewrite uses function syntax to create the same objects as your code. It includes examples of a getter, a setter, a static and private properties and objects via closure. I renamed RequestBuffer to just Buffer as it is inferred by context what it holds and the name no longer lives in the global scope.

The code feels like its missing functionality, but I can only go by what you have supplied.

function RateLimiter() {
    const buffers = {}, MAX_IN_TIME_FRAME = 100, MAX_AGE = 1000;
    function Buffer(maxAge = MAX_AGE) {
        const requests = [];
        function update() {
            var i = requests.length;
            const maxTime = Date.now() - maxAge;
            while (i--) {
                if (requests[i].time >= maxTime) {  requests.splice(i, 1) }
            }
        }
        return {
            set store(request) {
                requests.push(request);
                update();
            },
            get allowed() { return requests.length <= MAX_IN_TIME_FRAME }
        };
    }
    function addClient(id) {
        if (buffers[id]) { return buffers[id] }
        return buffers[id] = Buffer();
    }
    return Object.freeze({   // freeze the interface to protect state
        addRequestValidate(request) {
            const buffer = addClient(request.clientId);
            buffer.store = request;
            return buffer.allowed;
        },
        canClientRequest(id) { return buffers[id] ? buffers[id].allowed : true }
    });
}
Object.defineProperty(RateLimiter, 'Request', { // Request constructor as a static of RateLimiter
    enumerable: false, configurable: false, writable: false,
    value: function(clientId) { return { clientId, time: Date.now() } }
});

Using function syntax to define object makes the new token optional.

const rateLimiter = new RateLimiter();
//const rateLimiter = RateLimiter();//  works the same

const request = RateLimiter.Request(1);
// or
// const request = new RateLimiter.Request(1);

const isRequestAllowed = rateLimiter.addRequestValidate(request);

The state of this

I personally believe that good OO JavaScript rarely uses the this token. You will notice that this is not used at all in the above code.

The token this can be so ubiquitous that it occurs multiple times on almost every line of code, it becomes noise, detracting from the overall readability. You used the token 'this' 15 times and your code contains 15 lines of expressions and statements.

More importantly this is JavaScript's achilles heel as it can be easily hijacked. Many people do this as standard practice via Function.call. This means that no matter how much effort you put into protecting an object's state you can never fully trust the state of this

Example using Function.call to change object's state

class ObjA1 {
    constructor() { this.a = "A" }
    log() { console.log(this.a) }
}
const a = new ObjA1();
a.log(); // State is correct

// Hijacking the state.
a.log.call({get a(){console.log("Hijacked and running external code"); return "Boo"; }});

What is even more worrying is if you have code running on a public page (ie you have 3rd party advertising scripts) this can be hijacked by malicious 3rd parties and used to gain access to secure content.

The class syntax encourages you to use the token this while function syntax is more conducive to defining a trusted named state.

function ObjA1() {
     const obj = {  // this is replaced by obj
         a : "A",
         log() { console.log(obj.a) }
     }
     return obj;
}


Damerau Levenshtein Implementation in Kotlin

For determining correctness of your implementation I recommend referring to an existing implementation such as Apache commons-lang or the newer commons-text:

commons-lang:

StringUtils.java:7997-8254
StringUtilsTest.java:2378-2479

commons-text

LevenshteinDistance.java
LevenshteinDistanceTest.java
ParameterizedLevenshteinDistanceTest.java
LevenshteinDetailedDistance.java
LevenshteinDetailedDistanceTest.java
LevenshteinResults.java

As far as your Kotlin code goes, here are my comments:

Kotlin already guarantees that a and b are not null as you've used CharSequence for their type instead of CharSequence?. As such, the requireNotnull statements are unnecessary.
I do not believe you gain much from aLength and bLength. a.length and b.length read clearly and are read in constant time so the additional variables seem unnecessary to me.
You can place the last lambda argument in a function call into parentheses  as you have done but I personally find moving it out of the parentheses easier to read and more idiomatic:

val d = Array(a.length + 1, { IntArray(b.length + 1) })

becomes

val d = Array(a.length + 1) { IntArray(b.length + 1) }

In some languages variable names like maxdist are common and expected but in Kotlin (and Java) I find it more common and expected to have variables names avoid abbreviations, use camel casing, etc. I recommend using maxDistance instead of maxdist.
You are returning a Pair<Int, Array<IntArray>>. This is fine but data classes are so much better and Kotlin makes it so easy to define and use them. I recommend creating your own type to return. e.g.:

data class DamerauLevenshteinResult(val count: Int, val d: Array<IntArray>)


Ternary gate handling - more succinct way then a bunch of if statements

public void computeOutput() {
    output.setValue(
            (input1 == null || input0 == null)
            ? false
            : (input0.getValue() ^ input1.getValue()));
}


String compression by using repeated characters count

String as an Array

You got your string parameter:

string originalString

Then you turned it into a list:

OriginalList.AddRange(originalString);

Then you turned it into an array:

charArray = OriginalList.ToArray();

And finally used it as:

character = (charArray[i]);

Instead of all that, you could have just done this:

character = (originalString[i]);

Class Design

Instantiating a StringCompression class every time you wanna compress a string can be avoided by just declaring the function CompressionMethod as static since the class has no members anyway. So in Main, you only have to do:

StringCompression.CompressionMethod("String here");

Or better: make it an extension method.

String Builder

Instead of a list of strings in:

CompressedList = new List<string>();

You could instead use a String Builder to create the resulting string.


Django model design to analyse user activities on external websites

Is the logic clear in the models?

Somewhat. Your narrative didn't touch on the Nick table, which I think many people would name a User table. You didn't make it clear if user alice on the site example1.com is different from alice on example2.com - that's a namespace issue. Your table implies they would be distinct, that there is a compound primary key on (site, username). That would be good DB modeling, but weird from a UX perspective, if you put yourself in Alice's shoes. I would personally lean toward designing this with a unified username namespace across all sites, and similarly a unified thread_id namespace. That way you're always free to shard it out later (or partition it out) by site, but you're never forced to.

The Thread table appears to me to be broken. That is, no PK is defined, and I don't even see an obvious one. You have thread_type, but no thread_id. Maybe pub_date has enough entropy for uniqueness? I'm willing to believe that if we're looking at posts from a single user, but site wide? No, that is difficult to believe. I recommend adding some unique identifier. Remember that Primary Key dictates physical layout on disk, and the details of which rows are near which other rows will affect query performance.

  Regarding the first_seen and last_seen fields in Nick model: if I can look up the Activity model inexpensively in runtime, I would rather not to have them, since the two fields need to be computed each time I insert a new record. What are my better options here?

I'm not happy with the Activity model. Substantively, you haven't described a Primary Key. I propose compound PK (username, post_date), assuming the timestamps are high enough resolution, otherwise the more complex (username, post_date, thread_id). You can assign IDs how you like, in ranges or even as GUIDs, but the post_date will matter for query performance. Trivially, rename to singular "username" and singular "thread_id" (or "thread" if you really want). Probing Nick when computing str() seems silly, as you already have exactly the right username. I notice you chose to leave site out of this table.

Updating the last_seen and (hardly ever) the first_seen columns is not such a big burden. And suppose that last_seen is not part of the UX, not displayed on screen. Then you could choose not to update it in timely fashion. Or if it is displayed, you could let transient memcached track recent updates. However you do it, at some later time, like 5 minutes or hourly or daily, you could do a reporting run where you read max(post_date) from Activity and update Nick. Or keep it out of Nick and instead update some offline reporting table. I'm just saying you have lots of flexibility in how you handle this detail. Nothing wrong with denormalizing in the name of query performance. Just wait till you can benchmark two competing queries so you understand what you're trading off.

  There will be about 10 sites included, should I have another model just for sites?

Not based on what you've told us so far. A GROUP BY (or DISTINCT) would soon extract the current set of sites from one of your existing tables. You've not yet invented any requirements that require mutable site attributes be stored in the database.

  The url field in Activity model exists only for a forum type, meaning quite a few millions of records (Blogs and News) will not have a value there, is this a good practice?

Depends on your query details, but sure, looks fine the way it is. Many urls will be NULL or will be the empty string, depending on whether you choose to make it a nullable column. Either way, it's not like you're losing much.

For rows without an URL, I bet you could avoid writing the row in the first place. I bet a carefully structured thread_id could encode all of (is_original, low_timing_resolution_post_date, unique_thread_number) within 64 or even 32 bits.


General comments:

try to indent your code properly - it is hard to read at the moment
follow the language conventions: variable should start in lower case (Hour24 => hour24)
similarly, opening braces are at the end of the line, not at the beginning of a new line (like in C-like languages)
try to do only one thing in one method - at the moment your methods do the conversion and print at the same time

Regarding your question about efficiency - a more efficient way (less time to code and fewer lines of code) would be to use existing libraries.

With Java 8, you could use the java.time API:

private static final DateTimeFormatter FMT_24 = DateTimeFormatter.ofPattern("HH:mm:ss");
private static final DateTimeFormatter FMT_12 = DateTimeFormatter.ofPattern("h:mm:ssa");

public static String convertTimeTo24(String time12) {
  LocalTime time = LocalTime.parse(time12, FMT_12);
  return FMT_24.format(time);
}

public static String convertTimeTo12(String time24) {
  LocalTime time = LocalTime.parse(time24, FMT_24);
  return FMT_12.format(time);
}

And to avoid duplicating code, you could refactor the two methods into:

public static String convertTimeTo24(String time12) {
  return convertFormats(time12, FMT_12, FMT_24);
}

public static String convertTimeTo12(String time24) {
  return convertFormats(time24, FMT_24, FMT_12);
}

private static String convertFormats(String fromTime, DateTimeFormatter fromFormat,
                                                      DateTimeFormatter toFormat) {
  LocalTime time = LocalTime.parse(fromTime, fromFormat);
  return toFormat.format(time);
}

Your main method needs to be changed accordingly.


JavaScript function that flips brackets direction

Your function seems to work fine, but you can condense it a bit by search for all bracket types in one regex replace with the following pattern:
/[\(\)\[\]\{\}]/g

and then use the replace function that takes a replace function as argument:
const brs = "()({}{[][";
function flipBracketsDirection(str) {
  return str.replace(/[\(\)\[\]\{\}]/g, br => brs[brs.indexOf(br) + 1]);
}

brs holds all the replaceable brackets with the opening brackets twice, so brs[brs.indexOf(')') + 1] finds '(' as the next char in brs;
You could also let brs be an object like:
const brs =
{
  "(": ')',
  ")": '(',
  "{": '}',
  "}": '{',
  "[": ']',
  "]": '[',
};

and then cquery it as:
function flipBracketsDirection(str) {
  return str.replace(/[\(\)\[\]\{\}]/g, br => brs[br]);
}

Your version actually query the string nine times, where the above only iterates it once.
As an alternative to the 'sophisticated' brs dictionary-solution, you could just create a function with a switch statement:
function swapBracket(br) {
  switch (br) {
    case '(': return ')';
    case ')': return '(';
    case '{': return '}';
    case '}': return '{';
    case '[': return ']';
    case ']': return '[';
  }
}

And call that instead, this way:
function flipBracketsDirection(str: string) {
  return str.replace(/[\(\)\[\]\{\}]/g, swapBracket);
}

flipBracketsDirection('}hello{');
// will return {hello}

Your tests cases could also be simplified, so it is easier to maintain - for instance like:
  let strs = [
    ')hello(',
    'this has ]some text[',
    'flip }any{ brackets',
    'even with )))]multiple[((( brackets'
  ];

  for (let s of strs) {
    let t = flipBracketsDirection(s);
    console.log(t);
    console.log(flipBracketsDirection(t));
    console.log("");
  }

Both the above suggestions should conform to the DRY principle.


Here is an alternate algorithm:

while ((c = getchar()) != EOF) {
    switch (c) {/* switch instead of if-else... */
    case '\n':
        nc = 0;
        putchar(c);
        break;
    case '\t':
        for (i = COLUMN - nc % COLUMN, nc += i; i > 0; --i) {
            putchar('-');
        }
        break;
    default:
        ++nc; /* increment is faster than increment plus divide */
        putchar(c);
        break;
    }
}

nc keeps track of the current column position within the line.


Prepending textbox to Wikipedia thumbnail picture

Nice idea.
Here's a solution that breaks down each of the steps into tiny, single purpose functions, whose names reveal exactly what they do.  This removes all the nesting and makes the solution easier to follow.
New logical steps:

Identifying a valid link (this was always broken out in the oringal solution)
"Upgrading" a link into a preview link (this is no longer coupled to 1., and can be re-used for other links)
Fetching the link's html
Extracting just the body text from the html
Filling the preview window with text

Some ideas that might be nice:

It might be nice to have the preview window vanish if you click the same link again.
Remove old contents from preview window, rather than prepending

Other notes:

I put the each statement that kicks everything off at the bottom, so that you can still copy paste into the console, even though it's more logical to have it at the top, since it's the "main" method, so to speak.
I removed the alerts, since I didn't think they were necessary.

Refactored code:
function turnIntoPreviewLink(link) {
  $(link).click(function(e) { e.preventDefault(), previewContents(link.href); })
}

function previewContents(wikiUrl) {
  grabHtml(wikiUrl).done(function(html) {
    addContentToPreview(bodyText(html));
  })
}

function grabHtml(wikiUrl) {
  return $.ajax({ type: 'get', url: wikiUrl });
}

function bodyText(html) {
  return $(html).find('#bodyContent #mw-content-text p').text();
}

function addContentToPreview(text) {
    $(".infobox .vcard .plainlist").addClass($(".infobox tbody").prepend(text));
}

function isValidWikiPage(url) {
  return url.indexOf('wikipedia.org') >= 0;
}

$("a").each(function(i, link) {
  if (isValidWikiPage(link.href)) turnIntoPreviewLink(link);
});


When you declare your variables, like @COMMUNICATION_TYPE VARCHAR, you really need to specify a length.

MSDN

  When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified when using the CAST and CONVERT functions, the default length is 30

So go ahead and declare them 20, 50, and 250, respectively, as you did in your table declarations

Additionally, in order to SET @ACTION_TYPE = $action you need to output this from your MERGE() statement.

...
WHEN NOT MATCHED BY SOURCE THEN
DELETE
OUTPUT $action INTO @ACTION_TYPE;

More commonly MERGE() would be used with a set. That is, you would take in a table variable into your STORED PROCEDURE and your MERGE statement would conduct it's logic on each row. Thus, you could have some rows that were INSERTED, some that were UPDATED, and some that were DELETED. In this instance, you would store the OUTPUT to a table variable or temp table.

CREATE TABLE #MyTempTable(...)
...
MERGE
...
OUTPUT $action, deleted.*, inserted.* INTO #MyTempTable;

INSERT INTO CRM_PERS_CONTACT_INFORMAITON_HISTORY
SELECT(...) FROM #MyTempTable


Check for idle status in meteor by using 'setInterval'

I think interval is overkill why not something like this:

var timer;
Template.example.onRendered(function() {
  timer = setTimeout(showModal, 60000* 15);
});

Template.example.events({
    'mousemove, mousedown, touchstart, keypress': function() {
       clearTimeout(timer);
       timer = setTimeout(showModal, 60000* 15);
    }
});
showModal = function(){};

Edit:

You just want to wait for 15 minutes so set a time out for that time and eventually reset timer. Create a timer variable that will hold the timer id so you can reset (delete&recreate) when a user do something.


Adding some wait time between API requests to avoid overloading the server

Create throttling for API calls is just one aspect of making your API integration resilient. There are many other types of failures to handle. Instead of weaving the error handling into your code, you should consider using something like Polly https://github.com/App-vNext/Polly
There a more details on it here http://www.thepollyproject.org/2018/03/06/policy-recommendations-for-azure-cognitive-services/


PHP login page using prepared statements

There are several problems with your code.

An extra query to get exactly the same row you just requested
Unreliable password hashing
Inconsistent query handling with strange query()/confirm() pair.
A lot of things intermixed here - POST, database internals, everything.

To make it better you have to store passwords after hashing them with password_hash() function and also utilize an improved version of query() function.
So the final code would be like this (it is using my simple DB wrapper which is based on PDO, but could be implemented using mysqli as well). So the idea is that you do all the prepared statements' related stuff inside the database class, and never touch it inside a user function.

function login_new_member($email, $password)
{
    $user = DB::run("SELECT * FROM users WHERE email=? AND com_code IS NULL", [$email]);

    // you really should switch to password_hash/password_verify
    // and make the following line as
    // if ($user && password_verify($password, $user['pass']))
    // but for now
    if ($user && md5($password) === $user['password']))
    {
        if ($user['user_closed'] == 'yes')
        {
            DB::run("UPDATE users SET user_closed='no' WHERE email=?", [$email]);
        }
        $_SESSION['log_email'] = $user['email'];
        $_SESSION['username'] = $user['username'];
        header("Location: ../public/member/indexhold.php?register_new");
        exit();
    } else {
        echo "Email or password was incorrect";
    }
}

so this function should be called like this

if(isset($_POST['login_button'])) {
    login_new_member($_POST['log_email'], $_POST['log_password'])
}


You can use generics if you don't insist on it being an indexer:

public T GetAttribute<T>(string attribute)
{
    return (T)base.GetAttribute(attribute);
}

I'm not so sure about the other things you're doing. Convert.ChangeType() could just hide errors in your code. If you want to change the type of something, you should know about it and do it explicitly, not try to hide it.

The same applies to your catch. You should never catch (Exception) in library code, handle only the exceptions you know about (in this case, most likely just InvalidCastException). And returning a value that might be the wrong type on failure? That seems dangerous to me as well.


Form every unique combination of the items of a list of lists

This seems more complicated than it needs to be.  Consider the following code

        int currentIndex = current.size();
        for (String s : factors.get(currentIndex)) {
            current.add(s);
            multiply(factors, current, results);
            current.remove(currentIndex);
        }

This code adds and removes an element to the current list.  In between, it calls itself recursively.  Then consider

        if (current.size() >= factors.size()) {
            // Don't really need to make a deeper copy with String values
            // but might as well in case we change types later.
            List<String> result = new ArrayList<>();
            for (String s : current) {
                result.add(new String(s));
            }
            results.add(result);

            return;
        }

When we find that we've processed an entire result, we add to the results and return.

Note that we could optimize that a bit by switching from a deep copy to a shallow copy.  With strings, that shouldn't make a difference.  I did the deep copy because we aren't restricted to strings with this kind of operation.

        if (current.size() >= factors.size()) {
            results.add(new ArrayList<>(current));

            return;
        }

That's the shallow version.

The whole thing:

    private static void multiply(List<List<String>> factors, List<String> current, List<List<String>> results) {
        if (current.size() >= factors.size()) {
            // Don't really need to make a deeper copy with String values
            // but might as well in case we change types later.
            List<String> result = new ArrayList<>();
            for (String s : current) {
                result.add(new String(s));
            }
            results.add(result);

            return;
        }

        int currentIndex = current.size();
        for (String s : factors.get(currentIndex)) {
            current.add(s);
            multiply(factors, current, results);
            current.remove(currentIndex);
        }
    }

    private static List<List<String>> multiply(List<List<String>> factors) {
        List<List<String>> results = new ArrayList<>();
        multiply(factors, new ArrayList<String>(), results);
        return results;
    }

I added the second method so that I could call it like

        System.out.println(Arrays.toString(multiply(group).toArray()));

Otherwise I would have needed to use more lines in the caller.

This version outputs the products in the same order as shown in your question, where your code outputs them in reverse order.  I don't know if this matters or not.

I find this to be more straightforward than your version.  It builds up to the answer.  Your version builds the answer on its way back from the recursion, which is why the results are backwards.

It also avoids some things that I didn't like about your version:

            for (List<String> string : subList) {

I'm not sure exactly what it is, but it's not a string.  It's a List.  I'd have probably called it something like strings or pieces in lieu of a better name.

                        result2.add(tmp2);

I'm not a fan of numbered variables.  I find it especially confusing here, as result and result2 are the same type but tmp and tmp2 are not.

I'm not crazy about your use of tmp for a loop index variable.  It seems like there should have been a better name.  That variable is no more temporary than any other.

            List<String> result = new ArrayList<String>();
            for (List<String> string : subList) {
                result = new ArrayList<String>();

You could just say

            for (List<String> string : subList) {
                List<String> result = new ArrayList<>();

The first initialization doesn't do anything before it is overwritten and result is never used beyond a single loop iteration.


Sorting a long string with a composite of strings and integers + symbols

listify function

Since, as you mentioned in the comments, the function is meant to read a single first line from a file only - you can use the next() built-in function:

def listify(filename):
    """Reads the first line from a file and splits it into words."""
    with open(filename) as input_file:
        return next(input_file).strip().split()

remove_any_symbols function

You can actually pre-define the allowed characters as a constant - no need to re-define them for every function call. You can also make it a set for faster lookups:

ACCEPTABLE_CHARACTERS = set(string.ascii_letters + string.digits)

def remove_any_symbols(input_string):
    """Removes any symbols from a string leaving the leading dashes."""
    filtered_characters = [c for c in input_string if c in ACCEPTABLE_CHARACTERS]
    prefix = "-" if input_string.startswith("-") else ""
    return prefix + ''.join(filtered_characters)

Or, a regex-based version (less understandable overall, but see if it is going to be faster):

PATTERN = re.compile(r"""
    (
        (?<!^)-  # dash not at the beginning of a string
        |  # or
        [^A-Za-z0-9\-]  # not letters, digits and dashes
    )+
""", flags=re.VERBOSE)
def remove_any_symbols(input_string):
    """Removes any symbols from a string leaving the leading dashes."""
    return PATTERN.sub("", input_string)

Pre-process the complete string

With regexes, it would also be possible to pre-process the input string as a whole, checking for the dashes at the beginning of words. This may lead to applying remove_any_symbols() on the complete input string read from a file:

PATTERN = re.compile(r"""
    (
        (?<!(?:^| ))-  # dash not at the beginning of a word
        |  # or
        [^A-Za-z0-9\- ]  # not letters, digits, dashes and spaces
    )+
""", flags=re.VERBOSE)
def remove_any_symbols(input_string):
    """Removes any symbols from a string leaving the leading dashes for each word."""
    return PATTERN.sub("", input_string)

if __name__=="__main__":
    input_file = sys.argv[1]

    with open(input_file) as f:
        data = next(f).strip()

    list_of_words = remove_any_symbols(data).split()

    print(sort_em_up(typed_list(list_of_words)))


Review

Remove unused imports

You don't use any of these imports, just remove them to reduce clutter
Read PEP8 the python style guide

Functions and variables should be snake_case
There should be a <space> in between operators

Instead of appending to a list, you could create the string for the start

So instead of making st = [], do st = '' and st += char, no need to join then

However you could make the shifting a separate function, and then ''.join() becomes needed again
When looping, loop over the item not the index

Instead of for i in range(len(s)) you could directly loop over the char --> for i in s
There is a function to determine if we encounter an uppercase or lowercase

You could use char.isupper() or char.islower()
Simplify the shifting

You could use the fact that if you subtract the start ord('a') or ord('A') and then modulo, the extra check of if temp > x becomes not needed
Notice how the operations for each case (upper, lower) are mostly similar

Putting it all together

import string
APLHA_LEN = len(string.ascii_lowercase)

def shift_letter(letter, shift):
    start = ''
    if letter.isupper():
        start = ord('A')
    elif letter.islower():
        start = ord('a')
    return chr((ord(letter) - start + k) % APLHA_LEN + start) if start else letter

def ceasar_cipher(st, shift):
    return ''.join(shift_letter(letter, shift) for letter in st)

BUT, there is a better way...

As mentioned by someone already you could use the maketrans function very nicely for ceasar ciphers.

Giving you something like this

from string import ascii_lowercase as lc, ascii_uppercase as uc

def ceasar_cipher_translate(st, k):
    trans = str.maketrans(lc + uc, lc[k:] + lc[:k] + uc[k:] + uc[:k])
    return str.translate(st, trans)

NOTE That this code assumes Python3.x


AIO programming challenge - Friendlist - Who has the most friends?

Take a look at my snippet which passes all the test cases.
First thing you can improve is both reading and incrementing (in the same loop) number of friendships for each id. Try to not use also count method of the list, it also searches through the whole list every time.

#!/usr/bin/python
friendlist = [0] * 1001

with open("listin.txt", "r") as listin:
    for i, line in enumerate(listin):
        if i > 0:
            a,b = line.split()
            friendlist[int(a)] += 1
            friendlist[int(b)] += 1

max_friends_num = max(friendlist)
listout = open("listout.txt", "w")
for id,val in enumerate(friendlist):
    if val == max_friends_num:
        listout.write(str(id)+'\n')
listout.close()

Best regards!


Linked list implementation of binary heap insertion

It's always worth tidying up indentation and removing random blank lines (e.g. after {).

Naming: in C# it's conventional that method names are in UpperCamelCase, but even if you choose not to follow the convention it's important to be consistent. Here Heapify follows the convention but insert doesn't.

The name Heapify usually refers to taking an unstructured array of data and structuring it as a heap in linear time. The method implemented here should probably have a name like UpHeap.

It's not clear how insert is supposed to be used. Is it called passing the root of the tree? And where does count come from? It seems to me that BinaryHeap should be BinaryHeapNode and should be a private inner class of a public BinaryHeap which exposes public void Insert(int value).

        int parent = (count - 1)/2;

What does this represent? Elsewhere parent is a BinaryHeap, and it's obvious what it means, but as far as I can guess this variable is actually the size of the right subtree.

            if (((parent == 0) && (node.left == null)) || (parent % 2 == 1))

Why? I need some comments somewhere in the code to say how the tree is structured. This looks like an attempt to keep it balanced, but I'm not convinced that it works. (I suspect it should check the parity of count rather than parent). Maybe if I knew precisely what it was trying to do I could be convinced.

I don't understand the necessity of all those asserts, but IMO it would be cleaner to remove the duplication by pulling them out of the cases as

            if (node.left != null)
            {
                Debug.Assert(node.data < node.left.data);
            }
            if (node.right != null)
            {
                Debug.Assert(node.data < node.right.data);
            }

or

            Debug.Assert(node.left == null || node.data < node.left.data);
            Debug.Assert(node.right == null || node.data < node.right.data);

The recursive insert calls Heapify at each level that it touches. Heapify bubbles up. That means there's unnecessary duplication of work here.

Why is Heapify public?

if (condition)
{
    DoStuff();
}
else
{
    if (otherCondition)
    {
        OtherStuff();
    }
}

creates unnecessary indentation and vertical spacing, both of which make it harder to read the code. Rewrite as

if (condition)
{
    DoStuff();
}
else if (otherCondition)
{
    OtherStuff();
}