Okay, you're doing a lot of [unnecessary] strdup. If we put all the code into a reusable function of its own, you don't free any of the strings, so you are leaking memory.
One way to alleviate that is to use strdupa instead of strdup. This does an alloca to get a stack frame allocation, so these strings don't have to be freed [they disappear with the stack frame when the function returns].
In fact, with better use of pointers, there's really no need to duplicate these intermediate strings at all.
And, there's still a lot of extra scanning/rescanning and strcpy/strcat.
Stylistically, tmp isn't too descriptive. And, it gets reused for two different purposes.

I've refactored your program to put the code into functions. I've added a test framework. And, I've created three additional versions that show what I would do to simplify and speed things up:
// logtod.c -- add timestamp to log file name

#define _GNU_SOURCE
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <libgen.h>
#include <stddef.h>
#include <time.h>

int opt_e;
int opt_n;

time_t stamptod;                        // previous time
int stamplen;                           // length of stampbuf
char stampbuf[100];                     // timestamp string

// todget -- generate timestamp
// RETURNS: stamp in stampbuf and length in stamplen
void
todget(time_t tod)
{
    struct tm *tm;

    if (tod == 0)
        tod = time(NULL);

    do {
        // use cached buffer [if possible]
        if (tod == stamptod)
            break;
        stamptod = tod;

        tm = localtime(&tod);

        stamplen = sprintf(stampbuf,"-%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d",
            tm->tm_year + 1900,tm->tm_mon + 1,tm->tm_mday,
            tm->tm_hour,tm->tm_min,tm->tm_sec);
    } while (0);
}

// logof_orig -- original code [leaks memory]
char *
logof_orig(char *buf1,const char *path,time_t tod)
{
    char *tmp = NULL;
    char *dir = NULL;
    char *base = NULL;
    char *file = NULL;
    char *ext = NULL;

    // get timestamp
    todget(tod);

    // split path to base and dir
    tmp = strdup(path);
    dir = dirname(tmp);
    tmp = strdup(path);
    base = basename(tmp);

    // split base to file and ext
    tmp = strchr(base,'.');
    if (tmp) {
        ext = strdup(tmp);
        file = strndup(base,strlen(base) - strlen(ext));
    }
    else
        file = strdup(base);

    buf1[0] = 0;

    // concat dir / file / time / ext
    if (dir)
        strcat(buf1,dir);
    strcat(buf1,"/");
    if (file)
        strcat(buf1,file);
    strcat(buf1,stampbuf);
    if (ext)
        strcat(buf1,ext);

    return buf1;
}

// logof_alloca -- original code [using strdupa et. al]
char *
logof_alloca(char *buf1,const char *path,time_t tod)
{
    //char buf1[1024] = { 0 };
    char *tmp = NULL;
    char *dir = NULL;
    char *base = NULL;
    char *file = NULL;
    char *ext = NULL;

    // get timestamp
    todget(tod);

    // split path to base and dir
    tmp = strdupa(path);
    dir = dirname(tmp);
    tmp = strdupa(path);
    base = basename(tmp);

    // split base to file and ext
    tmp = strchr(base,'.');
    if (tmp) {
        ext = strdupa(tmp);
        file = strndupa(base,strlen(base) - strlen(ext));
    }
    else
        file = strdupa(base);

    buf1[0] = 0;

    // concat dir / file / time / ext
    if (dir)
        strcat(buf1,dir);
    strcat(buf1,"/");
    if (file)
        strcat(buf1,file);
    strcat(buf1,stampbuf);
    if (ext)
        strcat(buf1,ext);

    return buf1;
}

// logof_stpcpy -- original code [using stpcpy vs. strcat]
char *
logof_stpcpy(char *buf1,const char *path,time_t tod)
{
    char *tmp = NULL;
    char *dir = NULL;
    char *base = NULL;
    char *file = NULL;
    char *ext = NULL;

    // get timestamp
    todget(tod);

    // split path to base and dir
    tmp = strdupa(path);
    dir = dirname(tmp);
    tmp = strdupa(path);
    base = basename(tmp);

    // split base to file and ext
    tmp = strchr(base,'.');
    if (tmp) {
        ext = strdupa(tmp);
        file = strndupa(base,strlen(base) - strlen(ext));
    }
    else
        file = strdupa(base);

    buf1[0] = 0;

    // concat dir / file / time / ext
    char *dst = buf1;
    if (dir)
        dst = stpcpy(dst,dir);
    dst = stpcpy(dst,"/");
    if (file)
        dst = stpcpy(dst,file);
    dst = stpcpy(dst,stampbuf);
    if (ext)
        dst = stpcpy(dst,ext);

    return buf1;
}

// copyout -- fill in destination buffer
char *
copyout(char *buf1,const char *path,int pathlen,time_t tod,
        const char *base,const char *ext)
{
    char *dst;
    ptrdiff_t cpylen;

    // get timestamp
    todget(tod);

    // get enough buffer space
    if (buf1 == NULL)
        buf1 = malloc(pathlen + stamplen + 1);

    dst = buf1;

    // ext must be to the right of base
    do {
        if (ext == NULL)
            break;
        if (base == NULL)
            break;
        if (ext >= base)
            break;
        ext = NULL;
    } while (0);

    // copy over all but extension
    if (ext != NULL)
        cpylen = ext - path;
    else
        cpylen = pathlen;
    dst = mempcpy(dst,path,cpylen);

    // copy over the date stamp
    dst = mempcpy(dst,stampbuf,stamplen);

    // copy over the extension
    if (ext != NULL) {
        cpylen = &path[pathlen] - ext;
        dst = mempcpy(dst,ext,cpylen);
    }

    *dst = 0;

    return buf1;
}

// logof_fix1 -- single malloc version
char *
logof_fix1(char *buf1,const char *path,time_t tod)
{

    // get length of path
    size_t pathlen = strlen(path);

    // find "base" in "/dir/base"
    const char *base = strrchr(path,'/');
    if (base != NULL)
        ++base;

    // find the file extension
    const char *ext;
    if (base != NULL)
        ext = strchr(base,'.');
    else
        ext = strrchr(path,'.');

    buf1 = copyout(buf1,path,pathlen,tod,base,ext);

    return buf1;
}

// logof_fix2 -- single pass scan
char *
logof_fix2(char *buf1,const char *path,time_t tod)
{
    const char *ext = NULL;
    const char *base = path;

    // find "base.ext" and ".ext" in "/dir/base.ext"
    const char *src = path;
    for (int chr = *src++;  chr != 0;  chr = *src++) {
        switch (chr) {
        case '/':
            base = src;
            ext = NULL;
            break;
        case '.':
            if (ext == NULL)
                ext = src - 1;
            break;
        }
    }

    // full length of path
    ptrdiff_t pathlen = (src - 1) - path;

    // get enough buffer space
    buf1 = copyout(buf1,path,pathlen,tod,base,ext);

    return buf1;
}

// logof_fix3 -- single pass scan [using strcspn]
char *
logof_fix3(char *buf1,const char *path,time_t tod)
{
    const char *ext = NULL;
    const char *base = path;

    // find "base.ext" and ".ext" in "/dir/base.ext"
    const char *src = path;
    while (1) {
        int len = strcspn(src,"/.");

        // point to start of separater
        src += len;

        // get the character
        int chr = *src;

        // end of string
        if (chr == 0)
            break;

        // separater is at the start of the source string
        if (len == 0) {
            src += 1;
            continue;
        }

        switch (chr) {
        case '/':
            base = src + 1;
            ext = NULL;
            break;
        case '.':
            if (ext == NULL)
                ext = src;
            break;
        }
    }

    // full length of path
    ptrdiff_t pathlen = src - path;

    buf1 = copyout(buf1,path,pathlen,tod,base,ext);

    return buf1;
}

// fixname -- compensensate for dirname changing "foo" into "./foo"
const char *
fixname(const char *out)
{

    if ((out[0] == '.') && (out[1] == '/'))
        out += 2;

    return out;
}

typedef long long tsc_t;

tsc_t
tscget(void)
{
    struct timespec ts;
    tsc_t tsc;

    clock_gettime(CLOCK_MONOTONIC,&ts);
    tsc = ts.tv_sec;
    tsc *= 1000000000;
    tsc += ts.tv_nsec;

    return tsc;
}

double
tscsec(tsc_t tsc)
{
    double sec;

    sec = tsc;
    sec /= 1e9;

    return sec;
}

// test control
typedef char *(*logof_p)(char *buf1,const char *path,time_t tod);
typedef struct {
    logof_p tst_fnc;
    const char *tst_tag;
    const char *tst_reason;
} dotest_t;

#define DOTEST(_fnc,_reason) \
    { .tst_fnc = logof_##_fnc, .tst_tag = #_fnc, .tst_reason = _reason },

// list of tests
dotest_t tstlist[] = {
    DOTEST(orig,"original code [leaks memory]")
    DOTEST(alloca,"original code [using strdupa et. al]")
    DOTEST(stpcpy,"original code [using stpcpy vs. strcat]")
    DOTEST(fix1,"single malloc version")
    DOTEST(fix2,"single pass scan")
    DOTEST(fix3,"single pass scan [using strcspn]")
    { .tst_fnc = NULL }
};

int fnclen;                         // maximum length of a function name
char *dotest_prevbuf;               // previous output buffer
tsc_t dotest_prevtsc;               // best time for previous test
tsc_t dotest_origtsc;               // best time for original test

// dotest_ratio -- show ratio of times
void
dotest_ratio(tsc_t curtsc,tsc_t prevtsc,const char *who)
{
    double ratio;
    const char *tag;

    if (curtsc > prevtsc) {
        tag = "slower";
        ratio = curtsc;
        ratio /= prevtsc;
    }
    else {
        tag = "faster";
        ratio = prevtsc;
        ratio /= curtsc;
    }

    printf(" -- %.3fx %s",ratio,tag);
}

// dotest -- perform test of single function
void
dotest(dotest_t *tst,const char *path)
{
    char *out;
    tsc_t tscbest = 1LL << 62;
    int showout = 0;
    int fail = 0;

    out = malloc(1000);

    // do test multiple times to eliminate variations in caching, speed step,
    // timeslicing, etc. and take the best/minimum time
    for (int iter = 10;  iter > 0;  --iter) {
        tsc_t tscbeg = tscget();

        out = tst->tst_fnc(out,path,stamptod);

        // get elapsed time
        tsc_t tscend = tscget();
        tscend -= tscbeg;

        // get best time
        if (tscend < tscbest)
            tscbest = tscend;
    }

    if (dotest_origtsc == 0)
        dotest_origtsc = tscbest;

    // compare against previous test data
    do {
        if (dotest_prevbuf == NULL) {
            showout = 1;
            break;
        }

        const char *curfix = fixname(out);
        const char *oldfix = fixname(dotest_prevbuf);
        if (strcmp(curfix,oldfix) != 0)
            fail = 1;
    } while (0);

    printf("%.9f %-*s",
        tscsec(tscbest),fnclen,tst->tst_tag);

    // compare against previous test timing
    do {
        if (dotest_prevbuf == NULL)
            break;

        dotest_ratio(tscbest,dotest_origtsc,"orig");
        dotest_ratio(tscbest,dotest_prevtsc,"prev");
    } while (0);

    if (opt_n)
        printf("\n");

    if (showout || fail)
        printf(" %s (%s)",out,fail ? "FAIL" : "PASS");

    //if (! opt_n)
        printf("\n");

    free(dotest_prevbuf);
    dotest_prevbuf = out;
    dotest_prevtsc = tscbest;
}

void
doall(const char *path)
{

    printf("\n");
    printf("PATH: %s\n",path);

    dotest_origtsc = 0;
    for (dotest_t *tst = tstlist;  tst->tst_fnc != NULL;  ++tst)
        dotest(tst,path);

    free(dotest_prevbuf);
    dotest_prevbuf = NULL;
}

int
main(int argc,char **argv)
{

    --argc;
    ++argv;

    for (;  argc > 0;  --argc, ++argv) {
        char *cp = *argv;
        if (*cp != '-')
            break;

        cp += 2;
        switch (cp[-1]) {
        case 'e':
            opt_e = ! opt_e;
            break;
        case 'n':
            opt_n = ! opt_n;
            break;
        }
    }

    // get maximum length of a function name
    for (dotest_t *tst = tstlist;  tst->tst_fnc != NULL;  ++tst) {
        int curlen = strlen(tst->tst_tag);
        if (curlen > fnclen)
            fnclen = curlen;
    }

    // show the function names and their descriptions
    for (dotest_t *tst = tstlist;  tst->tst_fnc != NULL;  ++tst)
        printf("%-*s -- %s\n",fnclen,tst->tst_tag,tst->tst_reason);

    // use the same timestamp for all tests
    todget(0);

    doall("/var/log/mine.log");
    doall("/var/log/mine");
    doall("/var/log.xxx/mine");
    doall("mine.log");
    doall("mine");
    doall("/var/log/mine.log.gz");
    doall("/.log");
    doall("/.");

    printf("complete\n");

    return 0;
}

Note that I did the fix2 version. But, I thought that using strcspn might be faster, so I added fix3.
That's because strcspn [under glibc, at least] is insanely optimized to very wide memory fetches. But, a side effect is that there's some extra table lookup initialization at entry to the function, so the strings should be long enough to overcome that initial deficit.
After looking at the resultant code, I'm thinking that the number of times strcspn has to be called, the extra complexity of the code, would make fix3 [probably] slower and less desirable than fix2

Here's the program output:
orig   -- original code [leaks memory]
alloca -- original code [using strdupa et. al]
stpcpy -- original code [using stpcpy vs. strcat]
fix1   -- single malloc version
fix2   -- single pass scan
fix3   -- single pass scan [using strcspn]

PATH: /var/log/mine.log
0.000000274 orig   /var/log/mine-20201110175328.log (PASS)
0.000000150 alloca -- 1.827x faster -- 1.827x faster
0.000000132 stpcpy -- 2.076x faster -- 1.136x faster
0.000000063 fix1   -- 4.349x faster -- 2.095x faster
0.000000067 fix2   -- 4.090x faster -- 1.063x slower
0.000000137 fix3   -- 2.000x faster -- 2.045x slower

PATH: /var/log/mine
0.000000197 orig   /var/log/mine-20201110175328 (PASS)
0.000000095 alloca -- 2.074x faster -- 2.074x faster
0.000000097 stpcpy -- 2.031x faster -- 1.021x slower
0.000000049 fix1   -- 4.020x faster -- 1.980x faster
0.000000052 fix2   -- 3.788x faster -- 1.061x slower
0.000000093 fix3   -- 2.118x faster -- 1.788x slower

PATH: /var/log.xxx/mine
0.000000219 orig   /var/log.xxx/mine-20201110175328 (PASS)
0.000000104 alloca -- 2.106x faster -- 2.106x faster
0.000000106 stpcpy -- 2.066x faster -- 1.019x slower
0.000000058 fix1   -- 3.776x faster -- 1.828x faster
0.000000062 fix2   -- 3.532x faster -- 1.069x slower
0.000000103 fix3   -- 2.126x faster -- 1.661x slower

PATH: mine.log
0.000000268 orig   ./mine-20201110175328.log (PASS)
0.000000126 alloca -- 2.127x faster -- 2.127x faster
0.000000106 stpcpy -- 2.528x faster -- 1.189x faster
0.000000061 fix1   -- 4.393x faster -- 1.738x faster
0.000000051 fix2   -- 5.255x faster -- 1.196x faster
0.000000071 fix3   -- 3.775x faster -- 1.392x slower

PATH: mine
0.000000208 orig   ./mine-20201110175328 (PASS)
0.000000088 alloca -- 2.364x faster -- 2.364x faster
0.000000089 stpcpy -- 2.337x faster -- 1.011x slower
0.000000056 fix1   -- 3.714x faster -- 1.589x faster
0.000000042 fix2   -- 4.952x faster -- 1.333x faster
0.000000047 fix3   -- 4.426x faster -- 1.119x slower

PATH: /var/log/mine.log.gz
0.000000278 orig   /var/log/mine-20201110175328.log.gz (PASS)
0.000000154 alloca -- 1.805x faster -- 1.805x faster
0.000000132 stpcpy -- 2.106x faster -- 1.167x faster
0.000000062 fix1   -- 4.484x faster -- 2.129x faster
0.000000071 fix2   -- 3.915x faster -- 1.145x slower
0.000000139 fix3   -- 2.000x faster -- 1.958x slower

PATH: /.log
0.000000256 orig   //-20201110175328.log (PASS)
0.000000134 alloca -- 1.910x faster -- 1.910x faster
0.000000110 stpcpy -- 2.327x faster -- 1.218x faster
0.000000058 fix1   -- 4.414x faster -- 1.897x faster /-20201110175328.log (FAIL)
0.000000047 fix2   -- 5.447x faster -- 1.234x faster
0.000000063 fix3   -- 4.063x faster -- 1.340x slower /.log-20201110175328 (FAIL)

PATH: /.
0.000000254 orig   //-20201110175328. (PASS)
0.000000134 alloca -- 1.896x faster -- 1.896x faster
0.000000109 stpcpy -- 2.330x faster -- 1.229x faster
0.000000053 fix1   -- 4.792x faster -- 2.057x faster /-20201110175328. (FAIL)
0.000000042 fix2   -- 6.048x faster -- 1.262x faster
0.000000063 fix3   -- 4.032x faster -- 1.500x slower /.-20201110175328 (FAIL)
complete

UPDATE:

I see your point about too much strdup(), but it's necessary with dirname() and basename() as they will mangle their argument.

As I mentioned, raw strdup leaks memory. And, even with dirname/basename some of the dups aren't needed.
And, I've never used either dirname and/or basename for pretty much the same reason [they modify their arguments]. So, I've written my own variants that copy the results to a buffer selected from a pool of static buffers

I like the approach you took with fix1 as it is still very obvious what is going on.

I intended to provide a progression from simple/slow to faster, so you can choose.

Although fix2 is arguably faster, it's a little obfuscated

Perhaps, but it's actually [loosely] derived from production code I have for doing the same thing. You wanted [some] comments. Personally, I felt your code was difficult to follow.

and would not handle extensions such as .log.gz correctly

That wasn't part of your original test data. But, my production code handled it, just not what I recreated for this post. It's a three line fix:
diff --git a/logtod/logtod.c b/logtod/logtod.c
index 28f5702..c212ba9 100644
--- a/logtod/logtod.c
+++ b/logtod/logtod.c
@@ -264,9 +264,11 @@ logof_fix2(char *buf1,const char *path,time_t tod)
        switch (chr) {
        case '/':
            base = src;
+           ext = NULL;
            break;
        case '.':
-           ext = src - 1;
+           if (ext == NULL)
+               ext = src - 1;
            break;
        }
    }

I've updated the original code block and the output

UPDATE #2:
I've updated the code and program output [again ;-)].
I moved the setting of the timestamp buffer to outside the benchmarked/timed area to [better] compare just the times for the scanning/output code (e.g. because sprintf is somewhat heavyweight and took up the bulk of the time spent).
And, I replaced a strlen call in copyout with just a pointer/offset calculation.
And, I added calculation of the speed ratio of the various methods against one another.


Project Euler # 48 Self powers in Python

You can compute the sum of the powers with sum() and a generator expression:
total = sum(i ** i for i in range(1, n + 1))

instead of a for-loop. Retrieving the last 10 digits can be done with the modulus operator % instead of converting it to a string:
return total % (10 ** 10)

Your code already runs in fractions of a second. For even larger exponents it would be more efficient to compute only the last 10 digits of each intermediate result. This can be done with the three-argument form of pow():

pow(x, y[, z])
Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z).

Putting it together:
def self_power(n):
    """returns sum of self powers up to n."""
    MOD = 10 ** 10
    total = sum(pow(i, i, MOD) for i in range(1, n + 1))
    return total % MOD

This runs a tiny bit faster:

$ # Your version:
$ python3 -m timeit 'import euler48; euler48.self_power0(1000)'
50 loops, best of 5: 9.55 msec per loop

$ # Improved version:
$ python3 -m timeit 'import euler48; euler48.self_power(1000)'
100 loops, best of 5: 2.19 msec per loop

But it makes a big difference if the numbers become larger:

$ # Your version:
$ python3 -m timeit 'import euler48; euler48.self_power0(10000)'
1 loop, best of 5: 6.65 sec per loop

$ # Improved version:
$ python3 -m timeit 'import euler48; euler48.self_power(10000)'
10 loops, best of 5: 28.6 msec per loop


Calculating the number 8 chars long which contains all possible numbers containing the numbers from 0 to n

Presumably you want to avoid the 8 levels of nested loops?  (This isn't an efficiency thing, merely a code cleanliness issue.)

If so, use a length-8 array of integers, and use it to do "counting" in a while loop.

int[] cnt = new int[8];

while (1) {

    // ... Do something ...

    // Update
    for (int i = 0; i < 8; i++) {
        cnt[i]++;
        if (cnt[i] != cr) break;
        cnt[i] = 0;
    }
}

I'll leave termination of the while loop as an exercise for the reader...

Note: If you find this pattern occurring all over the place in your code, you could be cunning and put the update logic into a helper class.  And then your outer loop could become:

for (Counter c = new Counter(8,cr); c.isActive(); c.increment()) {
    ...
}


Will multi-threading or other method make my program run faster?

As stated in the comments, multi-threading might not be what you are looking for.

I think there is room for improvement on the way you read your file. Currently:

you read the whole file into a string all_emails = f.readlines()
you remove duplicates rs_emails_set = set(rs_emails)  # remove duplicates
and you read every element of this array for email in rs_emails_set:

Reading this comment, I strongly recommend you to test the following:

processed_emails = set()
for email in f:
  if email not in processed_emails:
    # validate email or not
    processed_emails.add(email)

Instead of immediately writing the good and bad emails files, you could store those into 2 lists and write them at once at the very end (removing some I/O with the filesystem as well)


C++ reimplementation of Python's threading.Event

You can simplify things using RAII.
bool isSet () {
    isSetLock.lock ();
    bool isSetRet (isSet_);
    isSetLock.unlock ();
    return isSetRet;
};

Can be simplified to:
bool isSet () {
    std::lock_guard<std::mutex>  lockGuard(isSetLock);    // Calls lock.
    return isSet_;
};                                                        // Calls unlock
                                                          // in destructor.

Why do you have two different mutexes? There should only be a single one:
void wait () {
    if (!isSet ()) {
        std::unique_lock <std::mutex> setTriggerUniqueLock (setTriggerLock);
        setTrigger.wait (setTriggerUniqueLock);
    }
}

This should be:
    std::unique_lock <std::mutex> setTriggerUniqueLock(isSetLock);
    while (isSet()) {
       setTrigger.wait(setTriggerUniqueLock);
    }

Note: While the thread is paused (waiting) in the condition variable the mutex is unlocked (so other threads can still lock the mutex). The thread is only released from the condition variable (after a notify) when it has re-acquired the lock.
Note: You have to use while here (not if). After the thread is woken you need to retest the condition because another thread may have re-locked the isSet_ variable before this thread re-acquired the lock.
Note: The condition variable has this built in:
    std::unique_lock <std::mutex> setTriggerUniqueLock(isSetLock);
    setTrigger.wait(setTriggerUniqueLock, [&](){return !isSet_WithoutNeedingToLockAsWeHaveTheLock()});

Note: After doing this your notify_all() should be on setTrigger.


Haskell zmq & protobuf message forwarding

1) If you have used hprotoc to generate Haskell modules then you should be able to use defaultValue and optional fields will be assigned to Nothing by default i.e.

header = ProtoMsg.ReqResponse.ReqResponse {
    message_id = Nothing,
    user_id = Nothing,
    request_id = Nothing,
    ProtoMsg.ReqResponse.status = Just ProtoMsg.Status.OK,
    failure_message = Nothing
}

could be replaced with

header = defaultValue {
    ProtoMsg.ReqResponse.status = Just ProtoMsg.Status.OK
}

2) Instead of your lazyToStrictBS you could use the standard function toStrict in the bytestring package


global

there is no need to make primes a global. You only read from it, but don't assign to it, you can use it as is. It will be even faster if you make primes a local variable by passing it in as a parameter, so Python uses the  LOAD_FAST bytecode instead of LOAD_GLOBAL. Since primes is called, indexed and sliced a lot, this can make a difference.

while condition

i1 < len(primes) and i2 < len(primes) and i3 < len(primes) and .... Since i1<i2<i3, only i3 < len(primes) is needed. If you use len(primes) so often, it pays to make it a local variable.

return, don't print

your method immediately prints the results. In general it is better to split the calculation and presentation, so to let the method return or yield the values, and another method do the presentation

looping

I suggest you watch the talk Loop like a Pro by David Baumgold. It's recommended material for every python programmer.

Instead of looping over the indices, you can loop over the primes-list immediately.

For p, and the first index (i), you can loop over enumerate(primes)

Then you can use this index i to slice primes to only include the elements with an index larger than p and go on to r, so you arrive at the following, naive implementation:

def generate4_naive(a, b, c, limit):
    for i, p in enumerate(primes):
        for j, q in enumerate(primes[i+1:], i+1):
            for r in primes[j+1:]:
                product = p**a * q**b * r**c
                if product < limit:
                    yield p, q, r, product

If you include the early breaks, you arrive at something like this:

def generate4(a, b, c, limit):
    for i, p in enumerate(primes):
        for j, q in enumerate(primes[i+1:], i+1):
            sub_product = p**a * q**b
            for r in primes[j+1:]:
                product = sub_product * r**c
                if product > limit:
                    break
                yield p, q, r, product
            if sub_product * primes[j+1]**c > limit:
                break
        if p ** a * primes[i+1] **b * primes[i+2] ** c > limit:
            return

then I also used primes as a local variable by changing the signature: def generate4b(a, b, c, limit, primes):

Performance:

limit = 1_000_000
%timeit tuple(generate3(2,3,4, limit=limit))

16.6 µs ± 166 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit tuple(generate3b(2,3,4, limit=limit, primes=primes))

16.2 µs ± 138 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit tuple(generate4(2,3,4, limit=limit))

14.2 µs ± 643 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit tuple(generate4b(2,3,4, limit=limit, primes=primes))

7.72 ms ± 516 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit list(generate4_naive(2,3,4, 1_000)) # primes also only to 1000

940 ms ± 84.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


I think you can simply create a method (or even a property) in your master page, and use it in your pages to follow and adhere to the principal of DRY (Do not repeat yourself). Also in master page function (or property), you can use caching by a hidden class field, to make the performance even better. For example in your master page:

private User user;
public User User
{
   get
   {
       if (user == null)
       {
          // Load user and assign it to the user field
          user = LoadUser(HttpContext.Current.User.Identity.Name);
       }
       return user;
   }
}

Then in your pages, you can refer to your master page, by casting it to the type of your master page. For example, if the name of the master page class is GeneralMaterPage, then in a page using that master page, you can write:

public Page_Load(Object sender, EventArts e)
{
    User user = (MasterPage as GeneralMasterPage).User;
}

This way, you've implemented user extraction and loading code in one place. However, there is a better method for that.

You can write an HTTP Module and bind to AuthenticateRequest event, and do the authentication mechanism yourself. Then, if the user is valid, you can simply create a GeneralPrincipal including the real user name and populate HttpContext.Current.User with that principal.

Take a look at this link.


Filtering data from an exisiting table using psycopg2+sqlalchemy

You should avoid doing [0] after your query. Instead, add a .limit(1) at the end of your select.
SQA supports named column references on individual result tuples. So in addition to supporting [5], which is (as you've identified) a bad idea - it should just support .time assuming that's what your column name is. However, even better is - rather than selecting the entire table_data - simply select only the column you want.


Text file manipulation with Java 8 and Guava

You are using Java 8's functional stream programming, but you leave out method chaining. Depending on how you chain methods, it could be more or it could be less readable. You might be imagining this:

readFile("dictionary.csv").stream().map(line -> Splitter.on(",").splitToList(line)).collect(Collectors.toMap(l -> Lists.newArrayList(l.subList(0, 2)), l -> l.get(2)));

There is no way I could read that. However, consider this:

Map<List<String>, String> translationMap = readFile("dictionary.csv").stream()
            .map(line -> Splitter.on(",").splitToList(line))
            .collect(
                Collectors.toMap(
                    l -> Lists.newArrayList(l.subList(0, 2)),
                    l -> l.get(2)
                )
            );

I find this much more readable. By simply reading vertically, I can determine that the code does this:

Reads dictionary.csv into a list of strings (via readFile).
Split each string in the dictionary on ",", into a List<String>.
Collect the List<String>s into a Map, where

The keys are the first two elements of each list, still in a List
The values are the 3rd element of each list.

On the other hand, your code as is is littered with type names; do I really need to know that that is a Stream<List<String>> when that's easily determined from context?:

List<String> translationFileContent = readFile("dictionary.csv");
Stream<List<String>> translationLines = translationFileContent.stream().map(
  line -> Splitter.on(",").splitToList(line));
Map<List<String>, String> translationMap = translationLines.collect(Collectors.toMap(l -> Lists.newArrayList(l.subList(0, 2)), l -> l.get(2)));

Alternatively, if you really like the temporary variables, put some empty lines in there to separate logical sections. Also, consider using Project Lombok, where you could just do this:

List<String> translationFileContent = readFile("dictionary.csv");
val translationLines = translationFileContent.stream().map(
    line -> Splitter.on(",").splitToList(line));
val translationMap = translationLines.collect(Collectors.toMap(l -> Lists.newArrayList(l.subList(0, 2)), l -> l.get(2)));

(Coder discretion advised on where you should use val).


I see a few things that may help you improve your code.

Sort the input

If the input is sorted, we can assure that the City id for vectors is strictly non-decreasing.  I'd add these two things for that.

std::sort(input.begin(), input.end());

And then this member function:

bool City::operator<(const City &other) const {
    return id < other.id;
}

Don't repeat calculations

Unless there's something very strange, the distance from city A to city B is the same as the distance from city B to city A.  For that reason, we can populate the vectors two at a time:

for (int c1 = 0; c1 < input.size(); c1++) {
    for (int c2 = c1; c2 < input.size(); c2++) {
        input[c1].addNeighbor(input[c2]);
        input[c2].addNeighbor(input[c1]);
    }
}

This is also why I suggested to sort the input vector.  I would also suggest calculating the distance once and then using it for both vector additions.  Doing that will require a little more code restructuring.  The inner loop can simply be this:

input[c1].addNeighbor(input[c2]);

And rewrite the member function like this:

void City::addNeighbor(City &city) {
    if (getCityID() == city.getCityID()) {
        return;
    }
    unsigned distance = Utilities::distanceSquared(*this, city);
    neighbors.emplace_back(Neighbor{city.getCityID(), distance});
    city.neighbors.emplace_back(Neighbor{getCityID(), distance});
}

Note that we avoid calculating the distance if they are the same ID, but not if the distance between them is actually zero.  In this case the argument to the function must not be const because we need also to modify it.

Also, although you did not provide the code for it, I notice that you have a NearestNeighbor() function.  There are some efficient ways to deal with that, depending on how you intend to use it.  One could sort the vectors (once) when population of them is complete or one might use a std::priority_queue instead of a std::vector.

Pass const references where practical

Passing an object by value can cause an object copy.  For example this function:

unsigned int Utilities::distanceSquared(City a, City b);

should instead be written like this:

unsigned int Utilities::distanceSquared(const City &a, const City &b);

Avoid floating point if only integers are needed

Integer operations are usually faster than floating point operations.  So here's how I'd write your distanceSquared function:

namespace Utilities {
unsigned int distanceSquared(const City &a, const City &b) {
    int dx{b.getXCoord() - a.getXCoord()};
    int dy{b.getYCoord() - a.getYCoord()};
    return dx*dx + dy*dy;
}
}

As @TobySpeight correctly points out, this assumes that no overflow occurs.  On my randomly generated test data, the ranges of the x and y coordinates are restricted so that is guaranteed, with my compiler, that no overflow can occur, but it's worth verifying that for your real data as well.


I think you can use object literals. The user of your plugin can pass in an array of object literals:

var settings = [
    {bg_x_speed_in: ..., bg_x_speed_out_set : ...}
    , {bg_x_speed_in: ..., bg_y_speed_out_set : ....}
    , {bg_x_speed_in: ..., bg_x_speed_out_set : ....}
];

In your code, loop through the array; each element contains the settings for one object.


Find the integer representing the last sub-string of a string

Well the short answer would be str.rfind().

>>> find_last = lambda s, t: s.rfind(t)
>>> find_last("aaaa", "a")
3

Though I'm not sure how much you're required to implement yourself. (Does the task allow usage of .find() at all?) Maybe it could be written like this:

def find_last(s, t):
    start = 0
    while True:
        if s.find(t, start) < 0:
            return start - 1
        start += 1

def find_last(s, t):
    for i in range(len(s)-len(t), -1, -1):
        if s[i:i+len(t)] == t:
            return i
    return -1


There are some problems with your code, especially

Naming

Names like s, N or x won't tell much about what they are used for. So maby slot, size and value would be a better fit.
It is not possible to push a 0 to the stack
The Stack is limited to only integers. If you want to push a decimal or a SomeClass you just can't.
Conventions

The default naming conventions for C# is to use PascalCase casing for naming methods, so push and pop should be Push and Pop.

Read: Naming guidelines for NET
You really should take care of the index of the last inserted value. This makes it easier and better to maintain if you need to pop or push.


Random string generator that 'guesses' user inputted word

Docstrings

Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docstring is defined by including a string constant as the first statement in the object's definition.

def guess_word():
    """Do calculations and return correct guessed word."""

Style

check pep0008 https://www.python.org/dev/peps/pep-0008/ the official Python style guide and here are some comments:

import string

def main(word):

Surround top-level function and class definitions with two blank lines.

ntries = 0
if b==word:

Use descriptive variable names, improves readability and general
understanding of the code.
Always surround these binary operators with a single space on either
side: assignment (=), augmented assignment (+=, -= etc.), comparisons
(==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and,
or, not). Except when = is used to set a function parameter.

The code

len_word

len_word = len(word)
ntries = 0
while True:
    letters = []
    for i in range(len_word):

the variable len_word is unnecessary, can be expressed:

while True:
    letters = []
    for i in range(len(word)):

Random brute forcing:

a sample size of 6 out of 26 alphabets has 230230 possible combinations (where order is unimportant and each combination has n! re-orderings where n = combination length (letters in the word) what is very obvious is that with such algorithms, it is very likely that zombie dinosaurs start showing up before the code guesses the correct word (10 years to be able to guess a 10 letter word for 500,000 secret words/passwords examined per second). So if what you are trying to build is a password cracker, the algorithms that are better than brute forcing are beyond the scope of this review.

What your mini-program does is trying n digit random choices and comparing them to the secret word which number of trials is variable

input a word: red
Mission accomplished. It took 8428 tries.

input a word: red
Mission accomplished. It took 16894 tries.

and since it's a random choice(not entirely random because it's based on a so-called 'pseudo-random' algorithm, you might generate the same number of trials for a random.seed(n)) this is not the case however, it tries different possibilities, so with some bad luck, that with some word lengths might keep running until aliens start making documentaries about us.

Assuming we can check each character separately:

(** This is not the case of password crackers in the real world which must guess the exact word).

# Note: I have tried making the program guess the letters one by one, and then
# check if said letter was right, but it seemed to make the problem even worse.

and since you asked about separate letter comparison:

import string

def guess_word():
    """Match characters with user input and return number of iterations, correct guess."""
    possible = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation + ' '
    secret_word = input('Enter word: ')
    yield len(possible) * len(secret_word)
    for index in range(len(secret_word)):
        for char in possible:
            if secret_word[index] == char:
                yield char

if __name__ == '__main__':
    word = list(guess_word())
    print(f"Total: {word[0]} iterations.\nWord: {''.join(word[1:])}")


(Y.E.S.E.J.) Yet Another Singleton with Enum in Java

Despite some other comments, I believe there are times when a singleton is very appropriate, and a powerful tool. The best practice, in Java, since the introduction of enums, is to use them for singletons.

But, your implementation is broken.

When using an enum as a singleton, you should treat the enum as a regular-ish class, and do everything in instance methods, and not have any static content. Then, by declaring just one member in the enum, you get just one instantiation.... always.

So, your code would be better as:

public enum SingletonClassA {
    INSTANCE;

    private final Map<Character, Character> characters;

    // private constructor
    SingletonClassA() {
        Map<Character, Character> aCharMap = new HashMap();
        aCharMap.put('a', 'e');
        aCharMap.put('o', 'u');
        // in order to keep short I erased other puts.
        characters = aCharMap;
        counter++;
    }

    public boolean containsKey(char letter) {
        return characters.containsKey(letter);
    }
}

Your use case then becomes:

SingletonClassA.INSTANCE.containsKey(aLetter);


Replace color in image measured by Euclidean distance

Nice code.
Let's look at the function signatures.
As gbartonowen noted, two typos on corlor for color.
The keyword defaults are lovely,
thank you for appropriately dealing with a magic number, and defaulting the filespec.
Lots of keywords will lead to a somewhat long signature, though, as reported by $ flake8:

E501 line too long (106 > 79 characters)

Recommend you always run such a linter before sharing code.
And heed the linter's advice.
In the same vein we see things like PEP-8 wants spaces in the w, h, k assignment,
or (w * h, k) expression.
And, this being python rather than java,
snake-case identifiers of d and dist_matrix would be much more appropriate.
Python convention says the Gentle Reader should expect D to be a class.
(Yes, I know this clashes with conventions of the mathematical community,
something had to give. Ok, on to more substantive comments.)

An identifier of data is always on the vague side,
it's a bit like naming your variable the_thing.
Yes, it's accurate, but often it could be a little more informative.
Consider a rename along these lines:

    img = np.asarray(Image.open(image), dtype='int32')

(Hmmm, as I look at that, maybe we'd like identifiers of in_file and out_file?)

The cdist() call, which defaults to Euclidean, is pretty interesting,
since RGB is not a perceptually uniform color scheme.
Consider mapping to Lab* colorspace and using that for comparisons.

It is slightly tricky for a naive caller to correctly pass in area,
so it warrants mention in the docstring you're going to write,
or at least in a comment.
Similarly for the modification signature.
Consider raising an error if c1 < c2 or r1 < r2 does not hold.

The l, r identifiers are well chosen,
and I eventually puzzled out their meaning,
but I wouldn't mind a comment mentioning "left, right",
as I kept thinking in terms of "row".
I also wouldn't mind seeing comments explaining the need for each reshape().

If speed is a concern, then figuring out how to get modification()
to broadcast values to a sub-rectangle would be the thing to focus on.

The saturating aspect of [2, 0, 0] is slightly surprising,
please comment on it, and how it deliberately interacts with clip().
Also, the list is not pythonic, this should definitely be the tuple (2, 0, 0).
A more descriptive name, perhaps red_modification, would be appropriate.

Protecting def modification so import won't see it
kind of make sense, but is a little weird.
You don't want that example to be part of your public API, that's fine.
But consider using def _modification in the usual way,
so the __main__ clause is just a one-liner.

Well, OK, two lines, as the magic tuple (36, 35, 30)
needs a name like dark_gray.

Looks good, ship it!


Longest Increasing Sub-Sequence using Dynamic Programming in Python

It works correctly for all the test cases I've tried.

Fortunately I thought this was a different algorithm, and so tested with "dogcatcatdog".
The answer you give is "dot" where it can be "acdo" or "acdg".
This is better shown with the transformation ord(c) - 97, where yours gives (3, 14, 19) where it can be (0, 2, 3, 14) or (0, 2, 3, 6).
I'll come back to tests as my changes will not fix this.

There are a couple of ways to improve your program:

Make and use a closure.
Allow the code to work with things other than tuples.
Limit the calls to the dictionary.

I'd use a closure as then you don't need to pass the cache, or memo in your case, to the function every function call.
It makes sure that all calls to the function whilst recursing are using the same cache and there are no dodgy edge-case cache problems.
These are unlikely but it adds clarity none the less.

A simple call of tuple allows your code to work on a much larger array of data-types, all the built-in ones and any that allow the conversion to a tuple.
Your excuse that lists are mutable and so don't work is poor, as the only reason that you have to convert your code to a tuple is as you append (seq[-1],) to the output.
I'd also like to point out that your code doesn't work with strings that are immutable in the same way tuples are.

Finally if you are concerned with performance.
A simple easy way to improve usage is to use memo.get.
You use seq in memo to then use memo[seq].
Instead you can use memo.get(seq, None).
This is as whilst dictionary's are \$O(1)\$, they still take a long time to get to the correct key.
This is as they hash the object, perform a transform on that hash, then use that modified hash to extract the data.
And so can take a while.

If I were to do all the above then I'd get to:

def lin(seq):
    seq = tuple(seq)
    cache = {}
    def inner(seq):
        if len(seq) == 1:
            return seq

        ret = cache.get(seq, None)
        if ret is not None:
            return ret

        longest = (seq[-1],)
        for index in range(1, len(seq)):
            till_index = inner(seq[:index])
            till_index += (seq[-1],) if till_index[-1] < seq[-1] else ()
            longest = max(longest, till_index, key=len)
        cache[seq] = longest
        return longest
    return inner(seq)

This functions the same way as before, and it keeps most of the same logic.
It's cleaner and allows you to add more corrections to the input, without doing them every recursion.

I also tried using a generator, however it changed your programs functionality.
The code that I used is:

last = seq[-1]
sub_sequences = (
    j + (last,) if j and j[-1] < last else ()
    for j in (inner(seq[:i]) for i in range(len(seq)))
)
longest = max((last,), *sub_sequences, key=len)

This gives the correct output when you enter 'dogcatcatdog'.
But if you change the input to 2, 5, 3, 7, 11, 8, 13, 6 then your original gives the correct result, where the generator doesn't.
Here's what they return:

> dogcatcatdog
dot (original)
acdg

> 2, 5, 3, 7, 11, 8, 13, 6
2, 5, 7, 11, 13 (original)
2, 5, 6

From this we can tell that your algorithm probably isn't the best.
As it doesn't work 100% of the time, and if you make it lazy it doesn't work other times.

I'll leave you to figure out if and how you want to amend this.
But I'd point you in the way of Wikipedia if you want an efficient method to do this.
It uses a binary search to find the max, and some funky stuff to get the list.
I'd also change lo ≤ hi to lo < hi in it's version as you don't want repeating numbers.


Simplify test for divisibility by all numbers 1…20

Ruby refactor: use Enumerable.all?:

def divisible?(n)
  (1..20).all? { |x| n % x == 0 }
end

Mathematical refactor:calculate the least common multiple of the integers in the range (Integer#lcm is available from Ruby 1.9):

def divisible?(n)
  n % (1..20).reduce(:lcm) == 0
end

This second snippet is, of course, more efficient once you pre-calculate (1..20).reduce(:lcm) only once and store it somewhere.


OK, here's the simpliest version of try:except: block for your case:

# some code
for inrow in res2:
    # some code
    try:
        cur.execute(insertstmt)
    except MySQLdb.ProgrammingError:
        pass

That's pretty much it. You probably want to know which queries failed, so you should use for example that version:

    try:
        cur.execute(insertstmt)
    except MySQLdb.ProgrammingError:
        print "The following query failed:"
        print insertstmt

Now as for the other question. You have to use a delete query. For example:

DELETE FROM TBLB WHERE dateK < CURDATE();

or something like that (note that CURDATE is a built-in MySQL function). Read more about delete queries here:

http://dev.mysql.com/doc/refman/5.0/en/delete.html


Is your mock ATM class literally named _atm?!  Or is it a non-static class that you have assigned to an instance named _atm?  Either way, I don't like it and find the _atm class to be useless in your limited example.
The BankAccount class, which you do not share, should have a Deposit and Withdraw method, both accepting a BankTransaction as a input argument.  You should include validation of a particular transaction within each method, i.e. do not accept a deposit of negative amount.  You also do not share BankTransaction with us.
CheckBalance is not needed, as you would just as easily show the BankAccount.AccountBalance property.  Also the property name could be shortened to Balance since it is the balance of the bank account.


Finding the largest of a series of numbers being XORed

Putting all variables of the same type onto a single line can be bad for readability and maintenance:

unsigned int T,N,Q,i,a,p,q,count,max,n[100000],res[100000];

Since the single-character variables are similar, they can still be together.  The rest of them, however, should be on separate lines.  Also, since i is a loop counter, it's best to declare it as close as possible to its for loop instead.

unsigned int T, N, Q, a, p, q;
unsigned int count;
unsigned int max;
unsigned int n[100000]
unsigned int res[100000];


You need to change/add just one little thing. You need to call the Randomize () method before using the Rnd () method. You should only call it once, so it would be good, to call the Randomize() method inside of the constructor of your class like:

Private Sub Class_Initialize()
    Randomize
End Sub

If you don't do this you will get for each iteration the same "random" number.
Don't get me wrong, this doesn't mean that all numbers will be the same but assume you start your application. For example you will get the RGB numbers 11, 54, 142 for the first call of your method. If you restart your application you will again get these same numbers on the first call.

To prevent this, you need to 'seed' the Rnd () method to get random values each time.


Is this how an MVC controller supposed to be?

MVC has a strict definition. However, frameworks don't actually follow MVC (yet they call themselves such). It's like a free-for-all on framework design, approaches can differ.

Enough of that theory, let's do code.

One issue here is the constructor. If the class is subclassed, but doesn't call the parent when the constructor is overridden, then nothing will run. I suggest you separate a router logic from the controller. The order should be like

Also, I think it's best you place all request data (parameters, headers) into an object, like a $request parameter handed into the function that's called in the controller by the router (pre-cleaned and pre-formatted). Also, throw in getters to normalize the data, so that you won't be doing 'isset` all the time. Something like:

$pass = $req->post('password'); // Gets the password param from a post request, else false

Don't render by parts, like header, content, footer in the controller. It's best you invest in having a templating system. The template has the fully formed HTML, and all your render does is fill in the blanks. See mustache templates, you might like it.

So the order is:

Receive request (in CodeIgniter, that's the index.php)
index.php loads core libraries and dependencies (like routers, url parsers, db driver, XSS prevention, stuff like that).
Parse the request and simplify where needed. What you could do is

Sanitize all inputs from XSS and SQL injections.
Normalize input by placing encapsulating them in an object. Throw in a getter, so that you only need to call something like $request->post('password') to get the password from a POST request.

Then the router determines the route from the request, includes that class, creates an instance, and executes the appropriate method. Something like $classInstance->theAction($normalizedRequestData)
Now we are in the controller. Controller then talks to the model, do something here and there, gets the data, and renders the view with the data from the DB.

$this->render('VIEW_NAME',$dataFromDB);

Template parser kicks in, renders the data and generates the HTML which then gets send back to browser.

If you're a visual guy like I am, I'd prefer to look at a diagram rather than a wall of text. Luckily, CodeIgniter drew their data flow, which got me sold. It's pretty handy diagram, which can be used as basis for framework design.


Parsing formatted output — as you have done with $(date | awk '{ OFS=" "; print $1,$2,$3,$6 }') — is a dangerous game: it's hard to say exactly what awk should expect as input.  For example, on GNU/Linux, I get:

$ LC_TIME=en_CA.UTF-8 date
Fri Sep  2 23:54:56 PDT 2016
$ LC_TIME=C date
Fri Sep  2 23:54:56 PDT 2016

However, on macOS, I get:

$ LC_TIME=en_CA.UTF-8 date
Fri  2 Sep 2016 23:54:56 PDT
$ LC_TIME=C date
Fri Sep  2 23:54:56 PDT 2016

Note the difference in the output in the en_CA.UTF-8 locale.  More "exotic" locales could produce even wilder output.  I don't recommend parsing the output of date, but if you do, be sure to explicitly state the locale using LC_TIME=C date.

What would be a better approach, then?  The date command's format specifiers are meant for just this kind of thing, and you can get quite close to your desired output.  On GNU/Linux:

$ date +'%a %b %e %Y%n%I:%M %p'
Fri Sep  2 2016
23:54 PM

On macOS:

$ date +'%a %b %e %Y%n%I:%M %p'
Fri Sep  2 2016
23:54 pm

Although the format specifiers are only loosely standardized, I would still consider this to be a more idiomatic and reliable solution than yours.  If you insist on getting exactly the format that you specified in your example, then a bit of post-processing might be needed.

$ date +'%a %b %e %Y%n%I:%M %p' | sed -e 's/  //' -e 's/[Aa][Mm]$/A.M./' -e 's/[Pp][Mm]$/P.M./'


I don't think you need the b flag when opening a csv file.
Python 3 doesn't let me use it. I think you can drop it.

To eliminate one level of nesting,
you can use a dict comprehension, and the update method of a dictionary:

with open("/path/to/file.csv") as infile:
    reader = csv.DictReader(infile)
    fieldnames = reader.fieldnames

    for row in reader:
        row.update({fieldname: value.strip() for (fieldname, value) in row.items()})

Notice that I also renamed the variables, as they were very poorly named.
I also removed the "r" flag from the open, as that's the default mode anyway.

I don't think there's a simpler way to do this.
I tried using a dialect, but this is the best I could get:

with open("/path/to/file.csv") as infile:
    csv.register_dialect('strip', skipinitialspace=True)
    reader = csv.DictReader(infile, dialect='strip')
    fieldnames = reader.fieldnames

    for row in reader:
        print(row)

Which does NOT work as intended: whitespace is stripped from the left of each field, but not from the right.
My first thought was actually to set delimiter=r'\s*,\s*' when registering the dialect,
but that doesn't work because delimiter must be a single character,
it cannot be a regex.
So, if you want to strip spaces from the values,
you have no choice but do it yourself.


Thread-safeness

As others have pointed out in the comments, your implementation is not thread-safe. threading.Lock() returns a new lock each time it is called, so each thread will be locking a different lock. Instead, you should have a single lock as an instance member object:

def __init__(self, cacheSize=10):

    # this variables maps image names to file locations
    self.Cache = {}

    # this variables maps image names to timestamp of last request
    # filed for them. Is volatile - requires local clock to never change,
    # or that there is a separate clock service that guarantees global
    # consistency.
    self.RequestTimestamps = {}

    self.CacheSize = cacheSize

    self.lock = threading.Lock()

Then, you use it like so:

def insert(self, imageName, imageLocation):

    '''
    Insert a new image into our cache. If inserting would exceed our cache size,
    then we shall make room for it by removing the least recently used.
    '''

    with self.lock:

        if len(self.Cache) == self.CacheSize:
            self.removeLeastRecentlyUsed()

    self.Cache[imageName] = imageLocation
    self.RequestTimestamps[imageName] = time.time()

Additionally, using time.time() for access orders can cause inconsistent results: it's not guaranteed to have good precision, and is dependent on the system clock steadily increasing. If the system clock is manually set back, you lose your consistent ordering. Instead, a safer way would be to use an OrderedDict, where you remove and re-insert items as they are accessed, and use OrderedDict.popitem(False) to remove the least-recently inserted item.

PEP8 compliance

Your variables and methods are written with a mixture of PascalCase (Cache.RequestTimestamps), which is typically only used for class names, and camelCase (Cache.removeLeastRecentlyUsed, leastRecentlyUsedKey), which is typically not used in Python. You should use snake_case instead for variables and methods, and use it consistently:

def __init__(self, cache_size=10):

    # this variables maps image names to file locations
    self.cache = {}

    # this variables maps image names to timestamp of last request
    # filed for them. Is volatile - requires local clock to never change,
    # or that there is a separate clock service that guarantees global
    # consistency.
    self.request_timestamps = {}

    self.cache_size = cache_size

def remove_least_recently_used(self):

    '''
    Should only be called in a threadsafe context.
    '''

    if self.request_timestamps:

        # scan through and find the least recently used key by finding
        # the lowest timestamp among all the keys.

        least_recently_used_key = min(self.request_timestamps, key=lambda image_name: self.request_timestamps[image_name])

        # now that the least recently used key has been found,
        # remove it from the cache and from our list of request timestamps.

        self.cache.pop(least_recently_used_key, None)
        self.request_timestamps.pop(least_recently_used_key, None)
        return

    # only called in the event requestTimestamps does not exist - randomly
    # pick a key to erase.

    random_choice = random.choice(self.cache.keys())
    self.cache.pop(random_choice, None)

And while we're looking at this method...

Single exit only

While there are many arguments against the single-exit-only style, none of them apply here. There's no good reason to have the return inside of the if in Cache.removeLastRecentlyUsed. Instead, wrap the rest in an else:

if self.request_timestamps:

        # scan through and find the least recently used key by finding
        # the lowest timestamp among all the keys.

        least_recently_used_key = min(self.request_timestamps, key=lambda image_name: self.request_timestamps[image_name])

        # now that the least recently used key has been found,
        # remove it from the cache and from our list of request timestamps.

        self.cache.pop(least_recently_used_key, None)
        self.request_timestamps.pop(least_recently_used_key, None)
else:

    # only called in the event requestTimestamps does not exist - randomly
    # pick a key to erase.

    random_choice = random.choice(self.cache.keys())
    self.cache.pop(random_choice, None)


Consider:

let dictionary = ["3": "c", "1": "a", "2": "b”]

If you want to get separate arrays of keys and values, sorted by the order of the Int values of the keys, you can do:

let (keys, values) = dictionary.map { (Int($0.key) ?? 0, $0.value) }  // get `Int` keys
    .sorted { $0.0 < $1.0 }                                           // now sort by those `Int` values
    .reduce(into: ([Int](), [String]())) { arrays, entry in           // divide that up into two arrays
        arrays.0.append(entry.0)
        arrays.1.append(entry.1)
}

That results in a keys of [1, 2, 3] and values of ["a", "b", "c"].

But a key observation is that you actually have to explicitly sort your results. Dictionaries, unlike arrays, are unordered. E.g. regardless of what order the keys appeared in a dictionary literal or JSON, when you iterate through the key-value pairs in a dictionary, the order may be different. You have to convert to an array and sort it yourself if order is important.

The above arbitrarily uses 0 for any keys (if any) that couldn’t be converted to an Int. If you just wanted to drop those entries, you could alternatively do:

let (keys, values) = dictionary.compactMap { entry in Int(entry.key).map { ($0, entry.value) } }
    .sorted { $0.0 < $1.0 }                                       // now sort by those `Int` values
    .reduce(into: ([Int](), [String]())) { arrays, entry in       // divide that up into two arrays
        arrays.0.append(entry.0)
        arrays.1.append(entry.1)
}


Event emitter in JavaScript without using Node's built in class or any additional libraries

Constructors should be PascalCase, i.e. EventEmitter - not eventEmitter. Of course, EventEmitter is the exact name of Node's own implementation, so I'd pick something else.
Don't hardcode file and line number in errors. Those get added automatically, which is the whole point. And besides, if you hardcode them, you'll have to keep them up to date (line numbers are already misleading), etc.. It's interpreter-generated metadata, not data.
Also, this a minor thing but don't use "should" in an error description. You're throwing an error because, something must be something - not just because it ought to. So event names must be strings, and listeners must be functions.
Don't bother with maintaining the listeners count manually. You can just do this (ES6 syntax, but you can translate it):

Object.keys(this.events).reduce((count, key) => count + this.events[key].length, 0);
// => number of listener functions

You can add that as a getter function with Object.defineProperty or just have a getListenerCount method. If you add it as a method you can even choose to only get the count for a named event, i.e. getListenerCount('someEventName').
This:

if (typeof cb !== 'function' || cb === null || cb === undefined)

is very redundant. The only thing that matters is whether cb is a function. Doesn't matter if it's null or undefined - it's still not a function.
You don't need to return this if you intend to use a function as a constructor. You can, but you don't need to.

Here's a quick refactoring based on the points above:

function EventBase() {
  this.events = {};
};

EventBase.prototype = {
  on: function (event, listener) {
    if (typeof event !== 'string') throw new TypeError("Event must be a string");
    if (typeof event !== 'string') throw new TypeError("Listener must be a function");
    this.events[event] || (this.events[event] = []);
    this.events[event].push(listener);
  },

  off: function (event, listener) {
    if (arguments.length === 0) {
      // remove all listeners
      this.events = {};
      return;
    }

    if (!this.events[event]) {
      // return if there's no event by the given name
      return;
    }

    if (arguments.length === 1) {
      // remove all listeners for the given event
      delete this.events[event];
      return;
    }

    // remove specific listener
    this.events[event] = this.events[event].filter(function (func) {
      return func !== listener;
    });
  },

  emit: function (event) {
    if (!this.events[event]) {
      // return if there's no event by the given name
      return;
    }

    // get args
    var args = [].slice.call(arguments, 1);

    // invoke listeners
    this.events[event].forEach(listener => listener.apply(this, args));
  },

  getListenerCount: function (event) {
    // get total number of listeners
    if (arguments.length === 0) {
      return Object.keys(this.events).reduce((count, key) => count + this.getListenerCount(key), 0);
    }

    // return zero for non-existing events
    if (!this.events[event]) {
      return 0;
    }

    // return count for specific event
    return this.events[event].length;
  }
};


Reversal of a singly-linked list in Rust

Before I begin, I recommend reading Learning Rust With Entirely Too Many Linked Lists.

Avoid unwraps, especially those after checking is_some. Use pattern matching instead.
The first test in reverse is redundant with the rest of the logic.
Implement Debug or Display to DRY up the printing of the list.
You should have some tests, especially for edge cases: 0, 1, and 2 items.
I'm not a fan of side effects inside of a map - it should err more on the side of purely functional. I'd use a match, even though it's more lines of code.
I'd simplify the iterator by just keeping a &Link
You could choose to remove the temporary variable from push_front.
for item in foo.iter() is usually written as for item in &foo, which implies that you need to implement IntoIterator for a reference to your type.

use std::fmt;

type Link<T> = Option<Box<Node<T>>>;

struct Node<T> {
    elem: T,
    next: Link<T>,
}

struct List<T> {
    head: Link<T>,
}

pub struct Iter<'a, T: 'a> {
    next: &'a Link<T>,
}

impl<T> List<T> {
    pub fn new() -> Self {
        List { head: None }
    }

    pub fn push_front(&mut self, elem: T) {
        self.head = Some(Box::new(Node {
            elem: elem,
            next: self.head.take(),
        }));
    }

    pub fn reverse(&mut self) {
        let mut prev = None;
        let mut current_node = self.head.take();

        while let Some(mut current_node_inner) = current_node.take() {
            let next = current_node_inner.next.take();
            current_node_inner.next = prev.take();
            prev = Some(current_node_inner);
            current_node = next;
        }

        self.head = prev.take();
    }

    pub fn iter(&self) -> Iter<T> {
        Iter { next: &self.head }
    }
}

impl<'a, T> IntoIterator for &'a List<T> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        match self.next.as_ref() {
            Some(next) => {
                self.next = &next.next;
                Some(&next.elem)
            }
            None => None,
        }
    }
}

impl<T> fmt::Debug for List<T>
    where T: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for item in self {
            write!(f, "{:?} ", item)?;
        }
        Ok(())
    }
}


Observation
Array allocated and initializes capacity elements. Which sort of defeats the purpose of having a capacity. The point of using a capacity is that you should not be paying the price of calling the constructor on elements that you don't use.
Code Review
You should put your code into a namespace.

This does not seem correct.
    DynamicArray()
        : m_size(0)              // Size is zero fine.
        , m_capacity(1)          // But a capacity of 1 with no memory allocated!
                                 // I would say the capacity here is zero
                                 // as you have no room to add any elements.
        , m_array(nullptr)
    { }

You have accepted the initializer list elements by value.
    DynamicArray(std::initializer_list<T> elements)

So you have already made a copy of the list.
Since you have made a copy of the list the elements in the list are yours to mutate if you want to so here you could use move semantics rather than copy semantics.
        std::copy(elements.begin(), elements.end(), m_array);
        // RATHER DO THIS
        std::move(elements.begin(), elements.end(), m_array);

Normally you expect to see the move operators marked as noexcept
    DynamicArray(DynamicArray<T>&& other)

This allows certain optimizations when you use standard algorithms and containers.

Normally I write the swap function in terms of the swap method.
    friend void swap(DynamicArray<T>& obj1, DynamicArray<T>& obj2) noexcept
    {
        std::swap(obj1.m_size, obj2.m_size);
        std::swap(obj1.m_capacity, obj2.m_capacity);
        std::swap(obj1.m_array, obj2.m_array);
    }

    // I would write it like this:

    void swap(DynamicArray<T>& other) noexcept
    {
        using std::swap;
        swap(m_size,     other.m_size);
        swap(m_capacity, other.m_capacity);
        swap(m_array,    other.m_array);
    }
    friend void swap(DynamicArray<T>& lhs, DynamicArray<T>& rhs) noexcept
    {
        lhs.swap(rhs);
    }

Now methods (like move operators) don't need to call a free function to do a swap. They simply call the method version of swap and get the same affect.

Nice try.
    // Resizes array to store n elements.
    // Guarantees strong exception safety.

Unfortunately not quite. You can not do anything that may throw while the state of the object has been mutate but not in the final state.
    void resize(int n)
    {
        T *temp = new T[n];
        m_capacity = n;                                  // Mutation here

        std::copy(m_array, m_array + m_capacity, temp);  // Throw possible here
        delete[] m_array;                                // Throw possible here.
        m_array = temp;                                  // Final mutation
    }

The way to do this is in three phases:
    void resize(int n)
    {
        // Phase 1: Make your copy.
        T *temp = new T[n];
        std::copy(m_array, m_array + m_capacity, temp);

        // Phase 2: Mutate "ALL" your state to final state.
        //          You can not call anything that is not `noexcept`
        //          This limits you to very basic operations.
        m_capacity = n;
        std::swap(temp, m_array);

        // Phase 3: Clean up
        delete[] temp;           // Note the swap above.
    }

Note we can simplify this:
    void resize(int n)
    {
        // Phase 1: Make your copy.
        DynamicArray  copy(*this, n);  // Private constructor
                                       // Allocates n spaces but copies size
                                       // objects from the passed item.

        // Phase 2: Mutate "ALL" your state to final state.
        //          You can not call anything that is not `noexcept`
        //          This limits you to very basic operations.
        //          Luckily swap method is `noexcept`
        swap(copy);

        // Phase 3: Clean up
        // the object copy's destructor will do cleanup.
    }

I am a fan of one liners for methods that are this imple.
    bool empty() const
    {
        return m_size == 0;
    }

Its OK to have a print method. But to make it more C++ like I would also add the operator<< so you can stream it. This means modifying print to take a stream.
    void print(std::ostream& out = std::cout) const
    {
        for (int i = 0; i < m_size; i++)
        {
            out << m_array[i] << " ";
        }
        out << "\n";
    }
    friend std::ostream& operator<<(std::ostream& str, DynamicArray const& data)
    {
        data.print(str);
        return str;
    }

In the standard library containers that use operator[] make it a non checked interface. It is the responsibility of the user to validate before calling. They add an additional checked interface at() when the user want to validate that the index is range.
    T& operator[](int index)
    {
        m_check_range(index);
        return m_array[index];
    }

    // Think of this situation
    for(int loop = 0; loop < dA.size(); ++loop) {
        std::cout dA[loop];
    }

    // Here we have already guaranteed that the index is within the correct
    // range but we your code still forces an additional check (that we
    // know is never going to fail).

    // If I need to check then I call the `at()`version.
    printArrayElement(std::size_t index)
    {
         std::cout << dA.at(index);   // Use checked accesses
    }

Self Plug
I have a lot of other pointers in my articles about writing a vector:
https://lokiastari.com/series/


A couple of hints, to avoid spoiling the problem.

Hint 1

   What would happen if every entry in A were N + 1?

Hint 2

   What is the complexity of max(counter)?


I guess my first suggestion is that, unless you really understand cryptography, you really should not be writing your own encryption libraries. Use an existing one like libsodium (or something based on it) , or, if you can't install the libsodium extension in your environment, perhaps the defuse/php-encryption library which is well-regarded.

Now on to your specific code...

I would start by not having your $key in your codebase at all.  Any sensitive information - passwords, encryption keys, etc. should never be placed in your code base where these items can be visible in your revision control systems.  Ideally, you can derive this from environmental configuration and inject the secure material during environmental deployment.

Stylistically, you should consider starting all PHP class names with uppercase letter (which is pretty much de facto standard) and stay away from mixing camelCase and snake_case in your code libraries as you are doing here with camelCase class name and snake_case method and variable names. I know PHP is not good about this within it's built-in classes and functions, but that doesn't mean you shouldn't be in your own code.

From a use standpoint, is there really reason for a class like this to be instantiated, or should these be static methods?


Wrapper for dynamically-allocated memory block

Code Review
Namespace
It would be nice to put your code inside its ownnamespace to avoid potentially collisions. Memory would seem like a good general name that would be reused by other people at some point.
Style
This is minor.
But most C++ developers put the * beside the type not the name. This is the reverse of the standard C style which is to put the * beside the name.
    uint8_t *ptr;

C++ is all about the type of the object. Putting the star with the type helps to correctly associate the type as a pointer.
Don't use inline unless you are required.
Anything inside the class declaration also automatically marked inline. Also the keyword inline has little to no affect on the compiler (ie it is ignored by every modern compiler) and its decision to actually inline the code.
    inline Memory() : ptr(nullptr), size(0) {}

The only time it is needed is when a method is defined in a header file included in multiple compilation units. Then it is used by the linker to note that the one definition rule is not being broken.
Constructors
All the constructors are good. Though I did have to double check the copy constructor.
    inline Memory() : ptr(nullptr), size(0) {}
    inline Memory(size_t size) : ptr(new uint8_t[size]), size(size) {}
    inline Memory(const Memory &other) : Memory(other.size)
    {
        std::copy(other.ptr, other.ptr+size, ptr);
    }
    inline Memory(Memory &&other) : Memory() { swap(*this, other); }

BUT: The move constructor should also be marked noexcept (except that your move constructor will not throw). This does not do anything for the class itself. But it allows for optimizations in the standard library if you put your class in a container.
Example: When resizing a std::vector<Memory> it will use a noexcept move constructor if it exists otherwise it has to fall back to the copy constructor to provide that strong exception guarantee.
Assignment
This is wrong. I missed the copy caused by pass by value in the parameter

    inline Memory& operator=(Memory other)
    {
        swap(*this, other);
        return *this;
    }

The copy assignment operator has the semantics of doing move assignment. I don't think this is a good idea. You might get some surprised people that don't see that coming when there Memory object changes under the noses when they do an assignment.
I would convert this to a copy operator and then create a move assignment operator (don't forget to mark the move assignment as noexcept).

I would still add a move assignment operator (since you have move constructor).


Performance serving static files with Rust and Hyper

Initial feedback:

Reading to a string is wasteful if you just want to dump data. A Vec is simpler since you don't care about UTF-8 validity; this will also allow for images to be served.
Returning "Not found" for a failure to read seems like a lie. Should be a HTTP 5xx-series error.
Avoid code duplication by returning the content type from the match and setting it afterward.
text/plain is an unconventional default content type, generally I see application/octet-stream.
Extract a constant for the default content type instead of repeating it.

Turning towards performance, start by performing a base-line performance test of a failure URL:

$ wrk http://127.0.0.1:5000/nothing
Running 10s test @ http://127.0.0.1:5000/nothing
  2 threads and 10 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency   290.75us   44.99us   1.50ms   90.46%
    Req/Sec    17.00k   537.99    18.05k    73.76%
  341686 requests in 10.10s, 26.72MB read
  Non-2xx or 3xx responses: 341686
Requests/sec:  33831.33
Transfer/sec:      2.65MB

Then a test with an existing but blank file:

$ wrk http://127.0.0.1:5000/exists
Running 10s test @ http://127.0.0.1:5000/exists
  2 threads and 10 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency   432.23us   77.26us   1.67ms   85.00%
    Req/Sec    11.49k   586.77    12.74k    65.84%
  231023 requests in 10.10s, 25.34MB read
Requests/sec:  22874.91
Transfer/sec:      2.51MB

Then a test with a 1 MiB file:

$ wrk http://127.0.0.1:5000/big
Running 10s test @ http://127.0.0.1:5000/big
  2 threads and 10 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    38.58ms    5.60ms  94.66ms   95.67%
    Req/Sec   129.41     16.53   171.00     85.50%
  2595 requests in 10.06s, 2.53GB read
Requests/sec:    257.93
Transfer/sec:    257.96MB

This isn't terrible. The biggest problem I see is that you are using an asynchronous library in a completely synchronous manner. Using a threadpool to offload loading the files increases throughput to ~3x of the previous value:

$ wrk http://127.0.0.1:5000/big
Running 10s test @ http://127.0.0.1:5000/big
  2 threads and 10 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    13.60ms    3.75ms  62.03ms   84.27%
    Req/Sec   370.48     43.96   415.00     89.50%
  7403 requests in 10.04s, 7.23GB read
Requests/sec:    737.26
Transfer/sec:    737.35MB

Its possible caching might help even further, but I didn't attempt it.

extern crate futures;
extern crate futures_spawn;
extern crate futures_threadpool;
extern crate hyper;

use futures::Future;
use futures_spawn::SpawnHelper;
use futures_threadpool::ThreadPool;
use hyper::StatusCode;
use hyper::server::{Http, Request, Response, Service};
use std::ffi::OsStr;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::sync::Arc;

struct Router {
    pool: ThreadPool,
}

impl Service for Router {
    type Request = Request;
    type Response = Response;
    type Error = hyper::Error;
    type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;

    fn call(&self, req: Request) -> Self::Future {
        let full_path = "src/static".to_owned() + req.path();

        let data = self.pool.spawn_fn(move || {
            let mut f = File::open(full_path)?;

            let mut data = Vec::new();
            f.read_to_end(&mut data)?;
            Ok(data)
        });

        let mut headers = hyper::header::Headers::new();

        const UNKNOWN_CONTENT_TYPE: &str = "text/plain";
        let content_type = match Path::new(req.path()).extension().and_then(OsStr::to_str) {
            Some(ext) => match ext {
                "html" => "text/html",
                "css" => "text/css",
                "js" => "application/javascript",
                _ => UNKNOWN_CONTENT_TYPE,
            },
            None => UNKNOWN_CONTENT_TYPE,
        };
        headers.set_raw("Content-Type", content_type);

        let r = data.map(|data| {
            Response::new()
                .with_status(StatusCode::Ok)
                .with_headers(headers)
                .with_body(data)
        });

        Box::new(r)
    }
}

fn main() {
    let addr = "127.0.0.1:5000".parse().unwrap();

    let router = Arc::new(Router {
        pool: ThreadPool::new_num_cpus(),
    });

    let server = Http::new()
        .bind(&addr, move || Ok(Arc::clone(&router)))
        .unwrap();

    println!(
        "Listening on http://{} with 1 thread...",
        server.local_addr().unwrap()
    );
    server.run().unwrap();
}


Your code shouldn't work:
You are calculating:
$$\int_a^b f(t) \, g(t - \tau) \; d\tau$$
but convolution is defined as:
$$f(t) \, * \, g(t) \equiv \int_{-\infty}^{\infty} f(\tau) \, g(t - \tau) \; d\tau$$
so the default limits of integration should be \$-\infty\$ to \$\infty\$. More importantly you should use the proper argument for f (the integration variable). Finally, naming the integration variable y feels unusual.

from sympy import oo, Symbol, integrate
def convolve(f, g, t, lower_limit=-oo, upper_limit=oo):
    tau = Symbol('__very_unlikely_name__', real=True)
    return integrate(f.subs(t, tau) * g.subs(t, t - tau),
                     (tau, lower_limit, upper_limit))


When in Qt, act like Qt.

Qt already has an ownership model, and it works by passing the parent object (as a raw pointer) in the constructor (so there's no window of exception-triggered leakage).  And Qt has its own weak pointers (including QObjectPointer).

I wouldn't try to outsmart Qt on pointer lifetime and ownership - but keep watching development, and if a future version of the library starts accepting smart pointers to transfer ownership, then reach out and grab it at that time!

In my personal opinion, the code you show is less clear than the Qt-native equivalent:

#include <QWidget>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QObject>

class MyWindow : public QWidget {
    Q_OBJECT
public:
    MyWindow(QWidget* parent = nullptr);
private:
    QLabel *const label;
    QPushButton *const button0;
    QPushButton *const button1;
    QVBoxLayout *const layout;
    int count = 0;
private slots:
    void setText();
};

#include <QApplication>
MyWindow::MyWindow(QWidget *parent)
    : QWidget{parent},
      label{new QLabel{"old text", this}},
      button0{new QPushButton{"Increment", this}},
      button1{new QPushButton{"Quit", this}},
      layout{new QVBoxLayout{this}}
{
    layout->addWidget(button0);
    layout->addWidget(button1);
    layout->addWidget(label);
    setLayout(layout);
    connect(button0, &QPushButton::clicked, this, &MyWindow::setText);
    connect(button1, &QPushButton::clicked, qApp, &QCoreApplication::quit);
}
void MyWindow::setText() {
    label->setText(QString{"Label updated %0 times"}.arg(++count));
}

Here, I've made the widget pointers const for safety, so we know that they will be valid for the lifetime of the MyWindow object.

I've also used the method-pointer version of connect() - I recommend this where practicable, to get more checking at compile time.  Connect by name only when you really have to, such as when you can't know the complete types of the objects you're connecting.  See also Connecting overloaded signals and slots in Qt 5 if you have trouble with overloads.

Your code and comments suggest that you're concerned about leaking memory if an exception is thrown in an initializer.  For example, consider a failure to allocate/construct button0 after label was successfully created; will label then be left in limbo?  Although our ~MyWindow() destructor is not called (and we don't even need a non-default one), its superclass destructors will be.  And that includes the ~QObject destructor, which deletes its children.  We know that label will be deleted, because its constructor returned (and adding itself as a child is among the first things it does).

None of this would be true (and we would not be exception-safe) if we forgot to include the optional parent parameter (this) when constructing label; if we were to initialize it without a parent and then its setParent() method in the body of the constructor, we would have a gap where Qt wouldn't own it properly.

We can demonstrate this by wrapping one or more of the allocations in a function.  The following code allows you to experiment with throwing exceptions for the different child objects:

int alloc_succeeds = 3;
#include <stdexcept>
template<typename T, typename... Args>
T *createWidget(Args... args)
{
    if (--alloc_succeeds < 0)
        throw std::bad_alloc();
    return new T{args...};
}

#define PARENT this
//#define PARENT nullptr

#include <QApplication>
MyWindow::MyWindow(QWidget *parent)
    : QWidget{parent},
      label{createWidget<QLabel>("old text", PARENT)},
      button0{createWidget<QPushButton>("Increment", PARENT)},
      button1{createWidget<QPushButton>("Quit", PARENT)},
      layout{createWidget<QVBoxLayout>(PARENT)}
{

Change the value of alloc_succeeds to determine how many constructors are successful.  If we run the code under Valgrind, we see that by changing PARENT to nullptr, we can get our objects to leak (we also see some of the leaks of Qt itself, so it's helpful to run both to eliminate false positives).


How about using std::accumulate():

Live Demo

#include <string>
#include <iterator>
#include <algorithm>
#include <numeric>

const int NUM_OF_POS = 10;

std::string findSameSales (int numSold, const int salesArray[], const std::string namesArray[])
{
    int index = -1;
    return std::accumulate(salesArray, salesArray + NUM_OF_POS, std::string(" "), [numSold, namesArray, &index](std::string sales, int sold) { index++; return sold == numSold ? sales + " , " + namesArray[index] : sales; });
}

Alternative on more lines:

std::string findSameSales (int numSold, const int salesArray[], const std::string namesArray[])
{
    int index = -1;
    auto accumulator = [numSold, namesArray, &index](std::string sales, int sold)
    {
        index++;
        return sold == numSold ? sales + " , " + namesArray[index] : sales;
    }
    return std::accumulate(salesArray, salesArray + NUM_OF_POS, std::string(" "), accumulator);
}

I really believe you should use STL algorithms for these kinds of things. Only roll your own loop etc. when you cannot use them. But this for example is almost the same as in the C++ reference docs so almost a "model case".


Comparison of Fibonacci (Multinacci) Functions in Python3

Everything looks fine to me. Just some small suggestion:

Don't define limit as a global. You can make it an attribute of the function itself: fibnum1.limit

In the matrix version I would return a tuple instead of a list. Also I would define two variables for f[0] and f[1] as follows:

@lru_cache(maxsize=None)
def _matrix_fib(n, k):
    if n == 1:
        return (0, 1)
    else:
        f0, f1 = _matrix_fib(n // 2, k)
        c = k * f0 * f0 + f1 * f1
        d = f1 * (f1 + 2 * k * f0)
        if n % 2 == 0:
            return (c, d)
        else:
            return (d, k * c + d)


You can define two helper functions: one traverses the leftmost branch using post-order and another one traverses the rightmost branch using pre-order. See what I mean:

static void top_view_post_order(node* root)
{
    if (!root) return;

    top_view_post_order(root->left);
    cout << root->data << " ";
}

static void top_view_pre_order(node* root)
{
    if (!root) return;

    cout << root->data << " ";
    top_view_pre_order(root->right);
}

void top_view(node * root)
{
    top_view_post_order(root);
    top_view_pre_order(root->right);
}

The above passed the hackerrank's test.

Edit: What comes to static fields in functions, most books suggest that their presence is an indicator of a design flaw; don't do them - pass some structure to the function as "state information". Also, if you were to write multithreaded code, there is a great potential for data races as well.


Sublime Text 2 R Build System (source file, send selection to interactive session)

In the main loop of the script,
you don't need the $a variable.
You can use an infinite loop,
and break out of it when the if condition becomes true.
You also don't need the semicolons at the end of the lines.

The script can be simplified to:

while :; do
    if xdotool search --name 'Running R' windowactivate --sync; then
        xdotool key --window 0 ctrl+shift+v
        echo 'Initialized.'
        break
    fi
    sleep 2  # decreasing the value increases asynchrony behavior.
done

As for this comment:

# in this workaround
# I could not find a better way to properly
# catch the terminator ending,
# after it receives the 'Running R' name.

Unfortunately I don't know a better way either.


In the interest of eliminating all duplicate code, here's a way to make the nested showupN pieces of code all get executed in one function:

function showSpecialNavigation(){
    var showIndex = 1;
    var maxShowIndex = 5;   // process from .showup1 to .showup5
    var allShows = $();     // initially empty object of .showupNN objects

    function setDrag() {
        allShows.css({display: 'block'});
        $(".dragged").each(function(i9) {
            $(this).delay(20*i9).animate({width: '130px'}, 300);
        }).promise().done(function(){
            $(".transition").bind("mousemove", function(event){
                var dragged         =   $(this).find('.dragged');
                var containerWidth  =   $(this).width();

                var stopLeft        =   56;
                var stopRight       =   132;
                var mouse2Container =   event.pageX - $(this).offset().left;
                var controller      =   mouse2Container-56;

                if((stopRight > mouse2Container) && (mouse2Container > stopLeft)){
                    dragged.stop(true, false).animate({left: controller}, 200);
                }
            });
        });
    }

    function showup() {
        var showList = $(".showup" + showIndex++);
        // accumulate all showupNN we've processed for use later
        allShows = allShows.add(showList);

        // set doneCnt so we know when all are done
        var doneCnt = showList.length;
        showList.each(function(i) {
            $(this).delay(50*i).fadeIn('fast').delay(10).find('img').fadeIn('fast', function() {
                // when last one is done, go to the next level or the next activity
                --doneCnt;
                if (doneCnt == 0) {
                    if (showIndex <= maxShowIndex) {
                        // go to next level of .showupNN
                        showup();
                    } else {
                        // go to next activity after
                        setDrag();
                    }
                }

            });
        });
    }

    var navs = $('.special-navigation_section');
    navs.each(function(i) {
        $(this).delay(400*i).fadeIn('fast');
        $(this).find('li').each(function() {
            $(this).delay(400*i).fadeIn('800');
        });
    }).promise().done(function(){
        navs.find('a.transition_text').fadeIn('800');
    }).promise().done(function(){
        showup();
    });
});


Counting the occurrence of each letter in a string

The trick is to group by the character, as you are doing, then do a second grouping by the count:

var testString = "abbsabwertbfacsfgggdfgasc";

var characterCounts =
    from character in testString
    group character by character into characterGroup
    group characterGroup.Key by characterGroup.Count() into countedCharacterGroup
    orderby countedCharacterGroup.Key descending
    select new
    {
        Characters = new string(countedCharacterGroup.ToArray()),
        Count = countedCharacterGroup.Key
    };

var topCharacterCount = characterCounts.First();

Console.WriteLine("{0},{1}", topCharacterCount.Characters, topCharacterCount.Count);

Breakdown

First, we do the same initial grouping:

from character in testString
group character by character into characterGroup

Next, we group the characters by the number of times they appear:

group characterGroup.Key by characterGroup.Count() into countedCharacterGroup

Then, we order based on the character counts:

orderby countedCharacterGroup.Key descending

Finally, we create a string for each set of characters with the same count:

select new
{
    Characters = new string(countedCharacterGroup.ToArray()),
    Count = countedCharacterGroup.Key
}

We can also get rid of the loop, instead grabbing the top count and writing the joined character string:

var topCharacterCount = characterCounts.First();

Console.WriteLine("{0},{1}", topCharacterCount.Characters, topCharacterCount.Count);


Efficiently read in 2nd column of CSV into List of Lists in Python 3

General remarks

pep 8

for your names and code style, try to follow pep-8

lower_case for variable and function names
spaces around operators

main guard

put the calling of your functions after a if __name__ == '__main__':, so you can load the script from somewhere else without it executing the code immediately

looping

Don't loop over indices. Code like for i in range(nr_files):  is a lot cleaner using enumerate: for i, filename in enumerate(file_names).

I suggest you check out the excellent 'Looping like a Pro' talk by David Baumgold

functions

Instead of having 1 function to load the files, loop over them and pick the correct element, seasiest would be to split if into different functions:

takes the list of files, and passes them on one by one to the parse
parse a single file

Generators

The most pythonic an efficient approach to do this would be to use generators, pathlib.Path and the built-in csv module

My solution

parse one file

This function takes a filehandle, and parses the requested element from the line

import csv
from pathlib import Path

def parse_file(filehandle, field_name):
    kwargs = {  # https://docs.python.org/3/library/csv.html#csv-fmt-params
        'delimiter': ',',
        'skipinitialspace': True,
        # ...
    }
#     field_name = b  # or the column name
    reader = csv.DictReader(filehandle, **kwargs)  # or csv.reader if there is no header, and it might be faster
    for line in reader:
        yield line[field_name]

This can be easily tested like this:

from io import StringIO
csv_str = '''a, b, c
0, 1, 2
3, 4, 5'''
with StringIO(csv_str, newline='') as file:
    print(list(parse_file(file, 'b')))

['1', '4']

parse multiple file

def parse_files(files):
    for file in files:
        try:
            with filename.open('r', newline='', ) as csv_file:
                yield list(parse_file(csv_file))
        except FileNotFoundError:
            print("ERROR: FILES ARE MISSING!!!!")
            raise

Now we have a good method to parse the information, we just need to call it with the subsequent files

main

def main(files):
    results = list(parse_files(files))
    return results

if __name__ == '__main__':

    files= [Path("DOCS/1.csv"),Path("DOCS/2.csv")]
    main(files)


Efficiency of a recursive implementation of the Sieve of Erasthotenes in Python

Algorithm

This is not quite the Sieve of Eratosthenes. The true sieve touches only the multiples of each prime, so it has complexity \$n \log \log n\$. Filtering copies the whole list repeatedly, which is equivalent to a different algorithm, trial division, with different complexity (probably \$n^2 / (\log n)^2\$). That's a dramatic difference, which led Melissa O'Neill to write a slightly famous academic rant about this.

But that's not a problem for an educational program. The rest of this review is about your implementation.

Recursing on each prime has depth \$\pi(n) \approx n / \log n\$, which will overflow the stack for any large \$n\$. Can you do it iteratively instead?

Names

iterable is a misleading name: the function uses len(iterable), but iterables don't necessarily support len. So it doesn't work on all iterables.

iterable is also an uninformative name: it doesn't say what the argument means. It isn't just any iterable, it's a list of candidate primes, so it could be called candidates.

Similarly, container isn't just any container, it's a list of primes, so it should be called primes. Also, sieve modifies it, which is unusual enough that it requires a comment, and it could even appear in the name: it could be called output_primes.

Interface

Modifying an argument is confusing and error-prone. Why not build a list and return it?

Why does the caller need to provide a list of candidates? Wouldn't it be simpler to just pass n and have sieve take care of building the candidates?

If the recursive function needs a different interface from the caller, you can use one function to do the recursion, and wrap it with another that presents a clean interface to the caller.

Innards

Repetition: container.append(iterable[0]) appears in both branches of the if. It could be moved before the if.

The program checks len(iterable) != 1, so what happens if len(iterable) == 0? Oops: it tries to use iterable[0] and crashes. It's generally safest to check for 0, not 1. This would also get rid of the repetition.

Optimization

Improving the algorithm will help a lot more than micro-optimizing. If you switch to the true Sieve of Eratosthenes and it still isn't fast enough, there are algorithmic improvements like the Sieve of Sundaram.

Before optimizing, measure performance! Optimization is hard and it's easy to get it wrong, so let measurements guide you.

Other

This function should have a docstring saying what it does: "Prime number sieve: Given a list of candidates, append the primes to output_primes."

Your question says the program uses filter, but it actually uses a list comprehension to do the same thing. This is not a problem with the program, just slightly confusing.


Two keyboard handlers for a video game character

The short code wins hands down. I understood it immediately, and more importantly, I can trivially verify that the code is reasonably error free. This is much harder with the longer code.

You say that the longer code is easier to understand but I claim that this is objectively wrong.

Case in point, the long code uses lots of magic numbers: 1, 0, -1, … what do these stand for? Ah, the short code tells us: they are directions.

The longer code also makes us scroll (depending on the screen size) to see the whole method. This significantly impacts ease of understanding. I believe there were even studies demonstrating this empirically (but I cannot cite them; Code Complete would probably be the relevant reference here).

The one thing I would change in the short code is the lookup itself: define the dictionary separately, maybe even outside the method, and perform the lookup as follows:

var action = movement_commands[key[1]];

And maybe think about tokenising key properly, i.e. assigning the parts to variables before using them. However, I think that the method is short enough to make this unnecessary.

You also said that the longer code is more efficient but I’d like to see a benchmark before I believe that. You probably think that the first code is slower because of the dictionary lookup. But consider that JavaScript is a dynamic language – every single variable access is potentially a dictionary lookup internally. So there is no difference in performance – indeed, the short code could be faster since there’s less variable lookup involved.

(Of course the two code snippets do different things: the long version handles jumping, and they behave differently when the character was previously walking in one direction and now you cancel walking into a different direction.)