C++ Super Simple HTML Tag Generating Code v0.1

At least in my opinion, there's quite a bit of room for improvement here. As far as usability goes, probably the most obvious change would be to directly support nesting. HTML and XML are frequently nested fairly deeply, but this doesn't really do anything to support nesting at all.

Looking at the code itself, I'd consider at least a couple of points:

1) You typically want to pass strings by const reference rather than value to avoid copying the string (unless you really need a copy, but you don't here). So:

std::string makeHtmlTags(std::string tagname, std::string tagcontent)

would change to:

std::string makeHtmlTags(std::string const &tagname, std::string const &tagcontent)

I would probably write ChangeHtmlTag to return the new string instead of modifying the existing one:

std::string changeHtmlTag(std::string const &tag, std::string const &newtagname)
{
    if(tag.at(2) != '/')
        return "<" + newtagname + ">";
    return "</" + newtagname + ">";
}

Rather than using .at, I'd also consider just returning the input intact if the input is too short to be a tag, then do the modification if it's long enough to be a tag.

The biggest problem I see, however, is that the code just doesn't seem like it does enough/has enough intelligence to make it obvious that using it gains much over playing with the strings directly.


Shorten and optimize php custom code for wordpress page template and use shortcodes

Here is an improvement, but I would recommend a few additional changes as well.
<?php global $post; ?>

    <?php
    $post = get_post(56);
    setup_postdata($post);
    get_template_part('template-parts/content', 'page');
    ?>

    <?php foreach ([1, 3, 2] as $post_id) : ?>

                <?php
                $post = get_post($post_id);
                setup_postdata($post);
                get_template_part('template-parts/content', 'page');
                ?>

    <?php endforeach; ?>

<?php
// Reset back to the original post
$post = get_queried_object();
setup_postdata($post);
?>

Since you're new to PHP here are some notes on PHP specifically

you only need to get the global variable once. Once a global variable is pulled in, it exists for the entire scope (whatever that scope happens to be).
if your column code is the same it should be in a foreach loop

Some WordPress stuff

get_template_part should only accept two parameters $slug and $name, maybe you meant get_template_part( 'template-parts/content', 'page' . get_post_format() ) possibly?
changing the global $post will typically cause a lot of problems down the line, so I would not do that unless you're certain it needs to be done. I would recommend something like a WordPress shortcode or PHP function that handles your template for non-current post data. Only use get_template_part for calling templates for the currently queried post.
if you do change the global $post, you'll (typically) need to reset it back to the original value because the rest of the (WordPress) code is dependent on it.

Please let me know if you're interested in using a WordPress shortcode for your columns.
Hope that helps!
Edit: As a side note, it looks like your html is malformed and a little bit different from the init question. Can you please check that as well. Also, please let me know if you're interested in using WordPress shortcodes. We can certainly optimize more, as we can write a little extra something today to will provide us a lot of value in the future. If WordPress is something you're never going to come back to again, then these micro-optimizes are not worth while. If this is something you plan to stick we, then it would be a good idea to take things a bit further. Thanks!


SPOJ ADDREV challenge - Adding reversed numbers

The biggest savings comes from computing the results directly from the textual representation of the inputs, instead of converting inputs to numbers, reversing them, adding them, reversing the result and then converting it to text.

Just add the character codes of the inputs to the current carry (initially 0, of course) and deduct the difference between '0' and 0 since the intermediate result contains it twice. If the result is greater than '9', subtract 10 and set the new carry to 1. Rinse and repeat.

P.S.: the task description talks about 'reversed' numbers but one might as well call them 'Little Endian'. That's why one can simply add the digits as they come in and push the result digits out, until the longer of the two inputs ends and the carry is down to 0...


Logging a user in and creating a session

Potential improvements

generateToken(email, password) {
  let user, session;

  return module.exports.destroyInactive()
    .then(() => users.checkPassword(email, password, sharedSecret))
    .then(_user => user = _user)
    .then(() => signedon.getByEmailAddressThisProcess(email))
    .then(([rows]) => {
      if (rows.length > 0) {
        return Promise.reject(`A user with email: ${email} is already logged in`);
      }

      return xprocess.getByProcessId(process.pid);
    }).then(xproc => {
      session = generateSession(user);

      return signedon.signin(session, xproc.pid);
    }).then(() => parseSessionToToken(session));
}

Your method falls into the nested promises antipattern, very similar to the classic callback pyramid of doom.

This solution relies on chaining promises. Since we need the variables user and session in non-adjacent promises we need to have references of them outside of the promise chain.

Since you are already using Promises which are an ES6 feature, you can take advantage of extra ES6 goodness. See es6-features.org for more.

ES6 features

Enhanced object method properties

generateToken: function (email, password) can be simplified by using  to generateToken(email, password)

Arrow Function Expression Bodies

users.checkPassword(...) is implicitly returned. Since this is a Promise, the chain won't continue to be executed until the returned Promise is resolved/rejected. This means we can just return the promise and not have to continue to nest using checkPassword(...).then(...)

Array Matching

let rows = result[0] can be simplified to rows = [result], which can then be used as the resolve parameter (([rows]) => ...)

Promise.reject

Returning Promise.reject allows us to reject the Promise without nesting.

Template Literals/String Interpolation

Provide a (subjectively) more readable solution by not having to concatenate strings with variables.

'A user with email: ' + email + ' is already logged in.'

becomes

`A user with email: ${email} is already logged in`

Arrow Function Statement Bodies

Since we are doing multiple things inside the rows Promise,  we use => statement bodies.

Due to this we need to explicitly return the Promise (so that the chain doesn't continue to execute until the Promise is resolved/rejected). Otherwise undefined will be resolved, not waiting for the Promise.

Note:

Nowhere are you catching rejected promises using catch, are you catching a rejected generateToken attempt?

Promises can greatly improve readability and remove nested callbacks when used correctly, but it is important to not allow them to "swallow" errors. At the very least make sure to log rejected Promises. A simple somePromise(...).catch(console.error) is better than nothing. Prefer console.error over console.log when possible since it's more "noisy".


Take a Ten Minute Walk: A City Tour Solution

var directions = {
  'n': 0,
  's': 0,
  'e': 0,
  'w': 0
}

Quotes are optional on all valid property names.

walk.forEach( function(direction) {
  directions[direction]++;
}

Syntax error here. Plus, making whitespaces consistent would make this code less of an eye sore. Consider using an IDE that will yell at you for inconsistent formatting.

var displacement = {
  x: directions['n'] - directions['s'],
  y: directions['e'] - directions['w']
}

Storing in an object is unnecessary. x and y can just be variables here.

An alternate approach is to represent the directions into 2 columns, vertical and horizontal. Then the directions on the same axis are represented 1 and -1. This way, knowing if you're back is a matter of checking if both axes sum up to zero. No subtraction required.

   V  H
N  1  0
S -1  0
E  0  1
E  0  1
W  0 -1
Result: [0, 1]
// Off by 1 to the east. Also, length is less than 10.

This is also a good functional programming exercise on how to think of functions as data transformations instead of machine commands. In the following code, each array method transforms the data from directions to a boolean in three discrete steps.

const directionVector = {
  N: [1, 0],
  S: [-1, 0],
  E: [0, 1],
  W: [0, -1]
}

const isValidWalk = walk => walk.length === 10 && walk
  .map(direction => directionVector[direction])
  .reduce((prev, next) => [prev[0] + next[0], prev[1] + next[1]], [0, 0])
  .every(v => v === 0)

// length check goes first so code doesn't even try if it's not 10
// map converts direction into vectors: N -> [V, H]
// reduce sums all vectors: [V1, H1] + [V2, H2] + ... = [Vs, Hs]
// every checks if sum values are all zero: Vs === 0, Hs === 0

// Too short
console.log(isValidWalk(['N', 'S', 'E', 'W', 'W', 'E']))

// Too long
console.log(isValidWalk(['N', 'S', 'E', 'W', 'N', 'S', 'E', 'W', 'N', 'S', 'E']))

// We're back!
console.log(isValidWalk(['N', 'S', 'E', 'W', 'N', 'S', 'E', 'W', 'N', 'S']))

// We're lost
console.log(isValidWalk(['N', 'S', 'E', 'W', 'N', 'S', 'E', 'W', 'N', 'E']))


Making an iterative formula shorter in Excel

Why not create user-defined functions? User-defined functions can be used in the same flavor as Excel functions (i.e. =CUSTOM_FUNC_FOO(A1:B2)), and be composed similarly in formulas. There are many advantages: better readability (because the logic is encapsulated), better algorithms (because you gain access to programming structures). The downside is that you need to write a bit of VBA, which you may not be familiar with (it's not complicated though).


Show number of pages next to Flickr threads

First at all I not so used to usercript. But in general I think your solution is overengineered.

I can point:

Readability of code is not good.
The "standar" for JavaScript usually is camel case.

Regarding your questions:

You don't have any complicated workflow or expecting several answers, so I wouldn't use promises.
As I said before, I think your code is really hard to read for only being three functions
You could remove the HTML in line creating the elements by JavaScript, but I don't think is so much for calling it "evil"...
You could
Don't think so

Few changes I would made:

Only declare one, 'use strict'

var url = "https://api.flickr.com/services/rest?";

var POSTS_PER_PAGE = 100;

var params = {
    url: document.URL,
    api_key: 'fe753c0dd6068fb6c74cb70458b1b9a0',
    method: 'flickr.urls.lookupGroup',
    format: 'json',
    nojsoncallback: 1
};

Whit this change I don't think that you are gaining so much whit your current function call_flickr.

So I would split it in two functions each one whit the call. Like this:

'use strict';

var url = "https://api.flickr.com/services/rest?";

var POSTS_PER_PAGE = 100;

var params = {
    url: document.URL,
    api_key: 'fe753c0dd6068fb6c74cb70458b1b9a0',
    format: 'json',
    nojsoncallback: 1
};

function numberOfPages(data) {
    var url = '/groups/' + data.topics.path_alias + '/discuss/';
    data.topics.topic.forEach(function (topic) {
        var pages_number = Math.ceil(topic.count_replies / POSTS_PER_PAGE);
        var link = url + topic.id + '/';
        var last_link = link + 'page' + pages_number;
        var current_element = $('a[href=' + link + ']');
        if (pages_number > 1) {
            current_element.after(' ' + pages_number + '');
        }
    });
}

function threadsList(data) {
    params.group_id = data.group.id;
    params.method = 'flickr.groups.discuss.topics.getList';

    $.get(url, params, function (data) {
        numberOfPages(JSON.parse(data));
    });
}

function main() {

    params.method = 'flickr.urls.lookupGroup';

    $.get(url, params, function (data) {
        threadsList(JSON.parse(data));
    });

}

main();


First, your process method violates the Single Responsibility Principle: It calculates something, and it prints it out. Such coupling makes it inflexible. It's better to return a String, and letting the caller decide what to do with it.

Second, you're code is way too complicated, handling all the different cases which are very dependent on the ASCII layout. Imagine next you want to support digits as well - oh my...

I would suggest to do something along the lines...

public String process(String input, int n) {
    String abc = "abcdefghijklmnopqrstuvwxyz";
    String abcABC = abc + abc.toUpperCase();
    int len = abcABC.length();

    Map<Character, Character> map = new HashMap<Character, Character>();
    for (int i = 0; i < len; i++) {
        map.put(abcABC.charAt(i), abcABC.charAt((i + n + len) % len));
    }

    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < input.length(); i++) {
        Character ch = map.get(input.charAt(i));
        if (ch == null) {
            throw new IllegalArgumentException("Illegal character " + input.charAt(i));
        }
        sb.append(ch);
    }
    return sb.toString();
}

Note that I need to know nothing about ASCII encoding using that approach, so supporting other chars is a no-brainer.


Binary Indexed Tree is a suitable data structure for this question. However, you have to be careful of how you want to use it. For me, I would use it for storing values of "Functions".
Based on the code you posted here, it is difficult to tell if you modularized it properly. However, since you said it works for small input, then I believe that you have coded correctly. Try to add comments to each helper function, so others can easily follow the logic.
Add cases where input values exceed the maximum value or are below the minimum value specified in the original question under restriction section. Checking extreme cases is really important.
As you said yourself, the naming of the codes is poor. Try to use more meaningful name, i.e. in this problem, I would name "Function" as F, or "BIT_XXX" for each helper function that involves BIT implementation. Also, try to separate the main operations with helper functions (and add lots of comments).

Good luck!!


Thanks for sharing your code!
Naming
Finding good names is the hardest part in programming, so always take your time to think about the names of your identifiers.
avoid single character names
Since the number of characters is quite limited in most languages you will soon run out of names. This means that you either have to choose another character which is not so obviously connected to the purpose of the variable. And/or you have to "reuse" variable names in different contexts. Both makes your code hard to read and understand for other persons. (keep in mind that you are that other person yourself if you look at your code in a few month!)
On the other hand in Java the length of identifier names is virtually unlimited. There is no penalty in any way for long identifier names. So don't be stingy with letters when choosing names.
avoid abbreviations
In your code you use some abbreviations such as the variable ara. Although this abbreviation makes sense to you (now) anyone reading your code being not familiar with the problem (like me) has a hard time finding out what this means.
If you do this to save typing work: remember that you way more often read your code than actually typing something. Also for Java you have good IDE support with code completion so that you most likely type a long identifier only once and later on select it from the IDEs code completion proposals.
OOP
Your code is a procedural approach to the problem.
There is nothing wrong with procedural approaches in general, but Java is an object oriented (OO) programming language and if you want to become a good Java programmer then you should start solving problems in an OO way.
But OOP doesn't mean to "split up" code into random classes.
The ultimate goal of OOP is to reduce code duplication, improve readability and support reuse as well as extending the code.
Doing OOP means that you follow certain principles which are (among others):

information hiding / encapsulation
single responsibility / separation of concerns
same level of abstraction
KISS (Keep it simple (and) stupid.)
DRY (Don't repeat yourself.)
"Tell! Don't ask."
Law of Demeter ("Don't talk to strangers!")

Here is a OO-ish approach to the problem.
The idea is that a "cell" (a position in an the array) "knows" its neighbors. This the solution does not need to iterate over the whole array multiple times. My approach need to visit only 4 cells per iteration. This I have 90% less compares to do compared to your procedural approach. The ratio gets better the bigger the array gets...
I introduced two custom classes:

a Cell class that does the actual search logic recursively.
a StartPosition class as a Data Transfer Object (DTO) which is needed to enable a method to return both, x and y coordinate of the starting point.

I ignored your restriction to only use Scanner as the only allowed import because it is somewhat overstated.
import java.io.PrintStream; // implicit dependency from System.out.
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Scanner;

public class DirectionArray {
    class Cell {
        private final int value;
        private final TreeSet<Cell> neighborsSortedByValue = new TreeSet<>((c1, c2) -> c1.value - c2.value);

        public Cell(int value) {
            this.value = value;
        }

        public void addNeighbor(Cell neighbor) {
            neighborsSortedByValue.add(neighbor);
        }

        public void findSink(Collection<Cell> pathToSink) {
            pathToSink.add(this);
            Cell minNeighbor = neighborsSortedByValue.first();
            if (minNeighbor.value < this.value)
                // recursive call if lesser value neighbor exists
                minNeighbor.findSink(pathToSink);
        }

        @Override
        public String toString() {
            return value + " ";
        }

    }

    class StartPosition {
        private int x;
        private int y;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        PrintStream out = System.out;
        new DirectionArray().runToSink(in, out);
    }

    void runToSink(Scanner in, PrintStream out) {
        Cell[][] cellArray = readArray(in);
        setNeighbors(cellArray);

        StartPosition startPosition = askForStartPosition(in, out);

        Collection<Cell> pathToSink = new ArrayList<>();
        cellArray[startPosition.x][startPosition.y].findSink(pathToSink);
        print(pathToSink, out);
    }

    private Cell[][] readArray(Scanner in) {
        int row = in.nextInt();
        int col = in.nextInt();
        Cell[][] cellArray = new Cell[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                cellArray[i][j] = new Cell(in.nextInt());
            }
        }
        return cellArray;
    }

    private void setNeighbors(Cell[][] cellArray) {
        for (int i = 0; i < cellArray.length; i++) {
            for (int j = 0; j < cellArray[i].length; j++) {
                setNeighborsToCell(i, j, cellArray);
            }
        }
    }

    private void setNeighborsToCell(int i, int j, Cell[][] cellArray) {
        for (int x : new int[] { -1, 1 }) { // one force, one back
            // neighbors in column
            cellArray[i][j].addNeighbor(cellArray[calculateNeighborIndex(i, x, cellArray.length)][j]);
            // neighbors in row
            cellArray[i][j].addNeighbor(cellArray[i][calculateNeighborIndex(j, cellArray[i].length, x)]);
        }
    }

    private int calculateNeighborIndex(int i, int x, int length) {
        return (length + i + x) % length;
    }

    private StartPosition askForStartPosition(Scanner in, PrintStream out) {
        StartPosition startPosition = new StartPosition();
        out.println("Give starting point(x) ");
        startPosition.x = in.nextInt();
        out.println("Give starting point(y) ");
        startPosition.y = in.nextInt();
        return startPosition;
    }

    private void print(Collection<Cell> pathToSink, PrintStream out) {
        for (Cell pathStep : pathToSink) {
            out.print(pathStep);
        }
    }
}

Finally I created a test driver a class that runs the solution with your test data. This test class is run by the JUnit framework:
import static org.hamcrest.CoreMatchers.endsWith;
import static org.junit.Assert.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Scanner;

import org.junit.Test;

public class DirectionArrayTest {

    @Test
    public void test() {
        Scanner scanner = new Scanner(new ByteArrayInputStream(
                ("5 5\n" + // array dimensions
                 "1  2  3  4  5\n" +
                 "6  7  8  9  10\n" +
                 "11 12 13 14 15\n" +
                 "16 17 18 19 20\n" +
                 "21 22 23 24 25\n" +
                 "2 2\n" // start position index
                 ).getBytes()));

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PrintStream out = new PrintStream(byteArrayOutputStream);

        new DirectionArray().runToSink(scanner, out);

        System.out.println(byteArrayOutputStream.toString());
        assertThat(byteArrayOutputStream.toString(), endsWith("13 8 3 1 "));
    }

}


Intuitively I think that I don't like to encapsulate all of my program in a with SafeGPIO() as GPIO call, so I searched the library and found at_exit. Using this you should be able to have something like the following in SafeGPIO.py:

import at_exit
from RPi import GPIO as RPi_GPIO

# Something useful to re-export GPIO?! Possibly the following?
GPIO = RPi_GPIO

@atexit.register
def cleanup():
    RPI_GPIO.cleanup()

Not sure on how to re-export the GPIO, but if this construct works you only need to do from SafeGPIO import GPIO, and then when Python exits it will call the original GPIO.cleanup().

Now the real question is why don't the RPi module automatically do this if this is a best practice when using RPi? Sadly, I don't know the answer to that, but it could be a reason for it, which might affect whether this is actually a good solution or not.

PS! I've addressed some more variants related to how to do cleanup in this answer, where I also focus a little more on choosing different options related to use cases.


Project Euler #8 - Largest product in a sequence

There are some obvious items, and then some not-so-obvious ones, that should be addressed.

The most obvious, is this line here:

sum = sum * i;

Really? That's a sum. Don't you mean product?

The next obvious item is that the function should take the number of digits, and the input sequence, as parameters. I would expect a function like:

function eulerProblem8(span, digits) {
    ....

and then the function returns the largest value.

Now, about the algorithm, this is more complicated. There is a way to do it in \$O(n)\$ time complexity. You can scan all the data just once, with a zero-counter, and multiplication and division.

scan each position in the input
if your sequence will be longer than the span, remove the unneeded digit using division (if the value is non-zero - or decreasing the zero-counter if the value is zero).
if the next value in the sequence is zero, increment the zero counter, otherwise include the digit by mutiplying the product.
if the new product is larger than previous products, then remember this new maximum
report the maximum.

Consider the following....

function eulerProblem8(span, sequence) {

    var follow = -1;
    var zeroes = 0;
    var maxprod = 0;
    var prod = 1;
    var digit;

    for (var lead = 0; lead < sequence.length; lead++) {

      // determine the least digit
      if (lead - follow > span) {
        follow = lead - span;
      }

      if (follow >= 0) {
        // remove least digit
        digit = Number(sequence[follow]);
        if (digit == 0) {
          zeroes--;
        } else {
          prod /= digit;
        }
      }

      // include the next digit
      digit = Number(sequence[lead]);
      if (digit == 0) {
        zeroes++;
      } else {
        prod *= digit;
      }

      // if there are no zeros in the sequence, and it exceeds previous...
      if (zeroes == 0 && prod > maxprod) {
        maxprod = prod;
      }
    }

    return maxprod;
}

var amountOfDigits = 13;
var sequence = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"

document.getElementById('result').innerHTML = "Max: " + eulerProblem8(amountOfDigits, sequence);

result

unused


Converting int value to String without using toString and parseInt method

To improve your intToString() method you should consider using a StringBuilder, and specifically the method StringBuilder.append(int).

Iterate digits in your int, and for each digit you can append(eachDigit) to the StringBuilder element. This will also reduce the complexity of intToString() to \$O(n)\$ since you do not need to create a new String instance each iteration. To get a String object from the StringBuilder, use StringBuilder.toString(). Or, if you are not allowed, you can use StringBuilder.subString(0).

You should also use a StringBuilder.append() (using the same idea) to reverse the resulting string (your second loop in your code).

Since it is not homework (as per comments), I have no problems providing a code snap. It should look something like this:

public static String intToString(int n) {
    if (n == 0) return "0";
    StringBuilder sb = new StringBuilder();
    while (n > 0) {
        int curr = n % 10;
        n = n/10;
        sb.append(curr);
    }
    String s = sb.substring(0);
    sb = new StringBuilder();
    for (int i = s.length() -1; i >= 0; i--) {
        sb.append(s.charAt(i));
    }
    return sb.substring(0);
}

Notes:

You can also use StringBuilder.reverse() instead of the second loop.
In here, \$O(n)\$ means linear in the the number of digits in the input number (n is the number of digits in the input number - not the number itself!) If you are looking for the complexity in terms of the initial number (it is \$O(\log(n))\$) since you divide your element by 10 each iterations, you have a total of \$\log_{10}(\text{number})\$ iterations for each loop, which results in \$O(\log(\text{number}))\$.


The database access information (server address, user name, password, database name) are repeatedly hard coded in each PHP file instead of having them in one common place, where they can be easily changed and configured for each run time environment (development, production, etc.)

Additionally a (production) database should not be accessed using a root user with a blank password.

Personally I never accessed a database in PHP using the built-in low level functions. I found using a database access library lead to less boilerplate code, they had a better readable API, and most importantly built-in security measures, that you can't forget to use. At the very least I would outsource database access into separate repository classes/modules/services.

A common security measure for logins is to have the script return the same result for both unknown account name and wrong password, so that an attacker can't find out if a specific user has an account or not.


Checking some rules before a Telegram bot replies to a message

If you want to get rid of your nested code then you should make a function and use guard statements.

If we simplify your code a bit, we can have:

if C and D and D[0] == '-':
    return a  # Ignoring other code, for simplicity
elif C and not D:
    return b
else:
    return c

Instead you can have:

if C:
    if not D:
        return b
    elif D[0] == '-':
        return a
return c

If you use the guard clause then you get:

if not C:
    return c
if not D:
    return b
if D[0] != '-':
    return c
return a

Using the same logic, you can expand all your ifs to guard clauses. And the rest is easier than the above to change.
Which can leave you with:

def gen_response(channel, description, replies, message_words):
    if not channel:
        return replies.enter_addmessage_error

    if not description:
        return replies.enter_desc_error

    if description[0] != '-':
        return replies.enter_addmessage_error

    if not (is_channel(channel) and is_length(description)):
        return replies.enter_chan

    if not channel_is_size(channel):
        return replies.small_chan.format(min_channel_size)

    write_results(' '.join(message_words[1:]))
    return replies.success_add.format(channel)

bot.reply_to(message, gen_response(channel, description, replies, message_words))


Classify the urgency by comparing the current time to two timestamps

A couple notes:

Is CardState an enum?  If not, this function doesn't return a CardState object, but rather what appears to be values described within CardState class constants.  Your signature should reflect this.
I honestly don't think it is that problematic to have multiple if conditions as you are doing, as your usage is not increasing cyclomatic complexity of the method.  Now, if you started introducing new states, then it may get unwieldy and be good reason for refactoring.  As your code is now, it is very straightforward and easy to understand.  Why over-complicate?
Is currentTime a good variable name?  This method does nothing to ensure the passed Date object represents a time that is "current". Why name this variable *Time when it holds a Date object?
Consider less verbose determinePackageState vs. determineStateOfPackage package vs. sourcePackage.
You could possibly set getTime() value to constant in order to remove redundant calls (though this is probably splitting hairs).

This might result in (slightly) easier to read code such as:

  static determinePackageState(date: Date, package: Package): CardState {
    const timestamp: number = date.getTime();
    if (package.targetTime.getTime() <= timestamp) {
      return CardState.URGENT;
    }
    if (package.warningTime.getTime() <= timestamp) {
      return CardState.WARNING;
    }
    return CardState.FRIENDLY;
  }


JavaScript architecture example on an HTML page

You have globals everywhere. Your cross module communication strategy is "uniquely named globals everywhere". I assume you know globals are bad but modul8 has a good article about it

Use a module bundling strategy using tools like browserify or modul8

// common.js
function log(message) {
    console.log((new Date()) + ': ' + message);
}

window.onerror = function(message) {
    log('Unhandled error: ' + message);
}

module.exports = { log: log };

You just got rid of those ugly company names as your namespacing strategy. And you also removed that ugly boilerplate code. Here your common.js file exports an object with the log method

// Url.js
var log = require("common.js").log;

function Url(url) {
    this.url = url;
}

Url.prototype.addParameter = function(name, value) {
    this.url += '?' + name + '=' + value;
};

Url.prototype.ajax = function() {
    log('Send ajax to: ' + this.url);
};

module.exports = { Url: Url };

You Url module explicitly requires your common file. It now has the log method.

//billing.js
var Url = require("Url.js").Url,
    $ = require("jQuery");

$('#submitButton').click(function() {
    var url = new Url('http://bla.com/process/billing');
    var creditCardName = $('#ccName').val();
    url.addParameter('name', creditCardName);
    url.ajax();
}

And billing explicitly requires Url and jQuery.

// billing.html
<!DOCTYPE html>

        <title>Billing</title>

        Enter name on credit card: <input type="text" id="ccName" />

        <button id="submitButton">Submit Payment</button>

And your billing html file loads a single precompiled billing bundle.


Procedural function for prepared MySQL statements in PHP

The main thing that needs to be refactored here is the approach itself. Calling a function like this

list($result, $numrows, $err) = my_mysqli_stmt($db_handler, $query, $params);

is absolutely not the way to go.

Definitely, there should be only one result, especially because this function returns superfluous variables which you don't really need.

$numrows is really useless as any time you need the count, you can count $result itself.

Returning $err is wrong too. You need to understand how a web-site works. If you take a look an any site around, including this one, none of them tells you silly errors like "Error finding a book". If an error occurs, the site just shuts down completely, because a database error is a disaster, and nothing useful will be shown anyway. that's why in case of error only a generalized page with excuses is shown. So in the end, in case of error, your function should return nothing, but actually throw an error to tell PHP that something terrible happened.

Therefore, the proper usage of such a function would be

$query = "SELECT title FROM books WHERE id=?";
$result = my_dbstmt($db_handler, $query, [$bookid]);

if(!$result) print("Book not found");
else print("Book found");

This is the most important thing about your function, while everything else is just nitpicks in comparison:

There is a built-in function str_repeat which is doing exactly the same as your array2typestring.
There is an argument unpacking operator which is doing exactly the same as your referencing magic
there is a mysqli_fetch_all() function which is...  so you get the idea.

using all this knowledge, you can write your function like this

function my_dbstmt($handler, $query, $params = [])
{
    $stmt = mysqli_prepare($handler, $query);
    $types = str_repeat('s', count($params));
    mysqli_stmt_bind_param($stmt, $types, ...$params);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    return mysqli_fetch_all($result);
}

The function above supports only SELECT queries. To make it support other queries is not a good idea, and better be implemented using different methods within the same class - the thing OOP is good for. But as you decided to stick with procedural, it could be done with different result type returned by this function: for SELECT queries it will return an array and for everything else the number of affected rows.

function my_dbstmt($handler, $query, $params = [])
{
    if ($params)
    {
        $stmt = mysqli_prepare($handler, $query);
        $types = str_repeat('s', count($params));
        mysqli_stmt_bind_param($stmt, $types, ...$params);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
    } else {
        $result = mysqli_query($handler, $query);
    }
    if ($result)
    {
        return mysqli_fetch_all($result);
    } else {
        return mysqli_affected_rows($result);
    }
}

Now this function can be used with DML queries as well and even with any other type of query, like CREATE TABLE or SHOW PROCESSLIST.

Now you can ask what about errors. It should be no concern of this function at all. All database errors should be converted to PHP errors and treated exactly the same way. To convert mysqli errors to PHP errors you need only one command - mysqli_report(). So in the end your code should look like

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db_handler = mysqli_connect($dblocal, $dbuser, $dbpass, $dbname)

$query = "SELECT title FROM books WHERE id=?";
$result = my_dbstmt($db_handler, $query, [$bookid]);

if(!$result) echo "Book not found";
echo print $result[0]['title'];

and for the DML query it would be

$query = "DELETE FROM books WHERE id=?";
$result = my_dbstmt($db_handler, $query, [$bookid]);
echo "$result books has been deleted";

Note that you'd better avoid blunt use of persistent connections as it will give you nothing you imagine but only problems.


You could move the door.locked check into the door.unlock() function (or into a new function) which would allow you return a promise for both cases:

function unlockDoor(door) {
   return door.locked
          ? door.unlock()
          : Promise.resolve();
   }
}

function openDoor(door) {
    unlockDoor(door).then(() => {
            door.handle.turn();
            door.handle.push();
        });
}


Functional, recursive FizzBuzz in JavaScript

Functional programming is not about writing as many functions as you can. I would suggest to start with a function library (e.g. Ramda) and write as few new functions as needed, taking advantage of currying.

Obviously, your loop function has side effects: it modifies result and i.

Without going to deep into FP rabbit hole, your function could look like this:

function getFizzBuzzArray() {
    function getFizzBuzz(v) {
        var ret = R.concat(
          v % 3 === 0 ? 'fizz' : '',
          v % 5 === 0 ? 'buzz' : ''
        );

        return ret || v;
    }

    return R.map(getFizzBuzz, R.range(1, 101));
}

document.write(getFizzBuzzArray());
<script src="https://cdn.jsdelivr.net/ramda/0.18.0/ramda.min.js"></script>


Two duration widgets for a break timer, with ± buttons

Extract common logic to helper method

These functions have duplicate logic, but different data:

function augLength() {
  var length = parseInt($("#lengthBreak").text());
  length += 1;
  $("#lengthBreak").text(length);
}

function augLengthSession() {
  var length = parseInt($("#lengthSession").text());
  length += 1;
  $("#lengthSession").text(length);
}

A simple improvement is to extract the common logic to a helper method:

function inc(selector) {
  var length = parseInt($(selector).text());
  length += 1;
  $(selector).text(length);
}

function augLength() {
  inc("#lengthBreak");
}

function augLengthSession() {
  inc("#lengthSession");
}

Parsing an int

Instead of:

  var length = parseInt($(selector).text());

Always when using parseInt, you should specify a radix parameter to indicate the base, for example for base-10:

  var length = parseInt($(selector).text(), 10);

And, what if the text cannot be parsed? It's good to make it default to something, say, 0, which you can achieve simply with:

  var length = parseInt($(selector).text(), 10) || 0;

DOM lookups are expensive

Instead of:

function inc(selector) {
  var length = parseInt($(selector).text(), 10) || 0;
  length += 1;
  $(selector).text(length);
}

It's better to do the DOM lookup once and reuse:

function inc(selector) {
  var dom = $(selector);
  var length = parseInt(dom.text(), 10) || 0;
  length += 1;
  dom.text(length);
}

Extracting more common logic

The inc helper can be extended to take care of the decrements too, by adding a second parameter:

function inc(selector, increment) {
  var dom = $(selector);
  var length = parseInt(dom.text(), 10) || 0;
  length += increment;
  dom.text(length);
}

function augLength() {
  inc("#lengthBreak", 1);
}

function augLengthSession() {
  inc("#lengthSession", 1);
}

function dimLength() {
  inc("#lengthBreak", -1);
}

function dimLengthSession() {
  inc("#lengthSession", -1);
}

Functions as parameters

You can do without the augLength, dimLength, augLengthSession, dimLengthSession functions, if you like, by using another helper that returns a function:

function makeIncrementer(selector, increment) {
  return function () { inc(selector, increment); };
}

Which then you can call directly from the ready block:

$(document).ready(function() {
  var lengthInit = $("#lengthSession").text();
  $("#timer").text(lengthInit);
  $("#dimBreak").click(makeIncrementer('#lengthBreak', -1));
  $("#augBreak").click(makeIncrementer('#lengthBreak', 1));
  $("#dimSession").click(makeIncrementer('#lengthSession', -1));
  $("#augSession").click(makeIncrementer('#lengthSession', 1));
});


Searching for a word in a list of tuple extracted from a db via SQL

You could try doing the filtering at the database level. Something like:

sql = "SELECT COUNT(*) FROM mydata WHERE myTextColumn MATCH %s"
for word in wordList:
    db = cursor.execute(sql, word).fetchall()
    dicoVolume[word] = db[0][0]

This would have the same word boundary caveats mentioned by Ludisposed, but it would save retrieving the entire table. Whether it's faster will probably depend on the relative sizes of the table and the word list, and if the column has an index it can use.

Edit: To use full text indexes with SQLite, it seems you need to create the table as an FTS table, and then do your searches using the MATCH command:

CREATE VIRTUAL TABLE mydata USING fts3(content TEXT);
INSERT INTO mydata VALUES ('some test data');
SELECT count(*) FROM mydata WHERE content MATCH 'test';

SQL Fiddle: http://sqlfiddle.com/#!7/fd6c5/8


Project Euler 25 - 1000-digit Fibonacci Number

I translated the given C# code to Java, and timed it on my machine using the Unix time command. It ran in 0.161 seconds. Your original code ran in 1.023 seconds. Here's the Java translation of the C# code:

import java.math.BigInteger;

public class Euler25 {
  public static void main(String[] args) {
    int i = 0;
    int cnt = 2;
    BigInteger limit = (new BigInteger("10")).pow(999);
    BigInteger[] fib = new BigInteger[3];

    fib[0] = BigInteger.ONE;
    fib[2] = BigInteger.ONE;

    while ((fib[i]).compareTo(limit) < 0) {
        i = (i + 1) % 3;
        cnt++;
        fib[i] = fib[(i + 1) % 3].add(fib[(i + 2) % 3]);
    }
    System.out.printf("Fibonacci %d has 1000 digits\n", cnt);
  }
}

Not to be excessively negative, but the solution in the C# code is much cleaner than the one you implemented. No shame in that; it happens to all of us. But I assume you wanted some advice on making the code you have run faster, because if you just wanted to copy that C#, you easily could have. So that's the direction I'll go with the rest of the answer.

It honestly puzzles me that this code is so much faster than yours. I would have expected the BigInteger math to be the really slow part, but this code does the same amount of BigInteger math as your original code.

Your code does take quite a bit more memory, since it stores all the Fibonacci numbers it calculates, whereas this code only stores what it needs to calculate the next one, and uses an integer to count how many Fibonacci numbers it's seen so far. An array list is backed by an array, so actually accessing the items shouldn't be much slower than with a plain array, but there might be some kind of cache or memory allocation effect. With this code, the compiler can block out a single, static chunk of memory. In the original code, the ArrayList that stores Fibonacci numbers keeps on expanding, so the backing array might have to be reallocated several times. Every time the array is reallocated, everything stored in it has to be moved over to the new storage space, which is pretty slow if you have a big list. If that turns out to be the problem, you can try passing the ArrayList constructor a guess for big you think the list might get (the default size is ten).

If I were you, I would profile the code and look for some issue like that. Dig into the ArrayList implementation and see if it's spending a lot of time reallocating. Just see where the code is spending its time, and try to figure out why that's where it's spending its time. If you don't already have a profiler you like, Netbeans has a pretty good one built in, and I'm sure Eclipse and other Java IDEs also have them. If you profile and post some of your numbers, we can probably give you better help with diagnosing performance issues.

EDIT: @ChrisHayes discovered why the code is so much slower: it's the toString call. I took the original code and just replaced the toString call with a check against a limit of \$10^999\$ as the C# code does. Still used the array list, still stored all the Fibonacci numbers. As Chris Hayes observed, this reduced the runtime from about 900ms to about 13ms. The author of this blog post also found that BigInteger.toString() was quite slow. An answer on this page implies that BigIntegers are stored in a way that makes it easier to implement the BigInteger.toString(radix) method that lets you convert a BigInteger into other bases, like hexadecimal or ternary. One could apparently implement BigInteger in a more specific way that makes it quick to convert into a base-10 string, but difficult or impossible to convert into strings in other bases, but the standard library implementers chose a representation which was more general, but slower to convert into a string.

See the end of the answer for my final version of the code, including modifications I made to get rid of toString.

[/EDIT]

Aside from the performance issues, I had some readability issues—not that your code was unreadable, just that it was harder to read than it had to be, and that contributed a little to the confusion that we had over where the number 4872 was coming from. The biggest one is the variable x. Unless you're working with coordinate axes, please don't call variables x. The C# code gives the analogous variable the name cnt, which is better, since you can tell it's probably some kind of counter. In general, that C# code is quite clean, so it's a good model to learn from, though I'd probably just go all the way and call it count. n could also work, since it's traditional to index the Fibonacci numbers with n. (This is another reason why x is confusing; if I'm reading a program about Fibonacci numbers, I can process F_n or the like pretty easily, but F_x is just strange.)

I also found your use of the do-while loop with a boolean flag confusing. A for or while loop with a break statement would have been better, but I think the best would be to let the do-while work for you, and write something like this:

do {
    tempAns = fibonacciNumbers.get(n-1).add(fibonacciNumbers.get(n-2));
    fibonacciNumbers.add(tempAns);
    n++;
} while (tempAns.toString().length() < 1000);

which takes advantage of the fact that tempAns gets initialized before the loop condition is checked.

The BigInteger class has built-in constants for zero and one, since they're so common. So you can initialize your array list like this:

fibonacciNumbers.add(BigInteger.ONE);
fibonacciNumbers.add(BigInteger.ONE);

It's a bit shorter than BigInteger.valueOf(1). (I like Java well enough, but it sure can get long.)

Here's the entire code sample with my suggested changes, including the one that eradicates toString and boosts performance that Chris Hayes suggested:

import java.util.ArrayList;
import java.math.BigInteger;

public class ProjectEuler25 {
  public static void main(String [] args) {
    long start = System.nanoTime();
    ArrayList<BigInteger> fibonacciNumbers = new ArrayList<BigInteger>();
    int n = 2;  // Index of current Fibonacci number.
    BigInteger tempAns = null;
    BigInteger limit = new BigInteger("10").pow(999); // First 1000-digit number.

    fibonacciNumbers.add(BigInteger.ONE);
    fibonacciNumbers.add(BigInteger.ONE);
    do {
        tempAns = fibonacciNumbers.get(n-1).add(fibonacciNumbers.get(n-2));
        fibonacciNumbers.add(tempAns);
        n++;
    } while (tempAns.compareTo(limit) <= 0);

    Long stop = System.nanoTime();
    System.out.println("The first term in the Fibonacci sequence " +
                       " to contain 1,000 digits is term: " +
                        fibonacciNumbers.size());
    System.out.println("Execution time: " + ((stop - start) / 1e+6) +
                       " ms");
  }
}


This is a really solid start. I only have a couple of suggestions.

Instead of defining the rules outside of the Validator class, it might be a good idea to sub class Validator and set the rules inside the constructor.
Create public methods specifically for each kind of validator.

Some pseudo code to get the main idea:

validator.php

class Validator
{
    private $rule_collection = array();

    public function __construct()
    {
    }

    public function ruleFor($property)
    {
        if (!isset($this->rule_collection[$property]))
            $this->rule_collection[$property] = new RuleBuilder($property);

        return $this->rule_collection[$property];
    }

    public function validate($model)
    {
        $valid = true;

        foreach ($this->rule_collection as $property => $rule_builder)
        {
            foreach ($rule_builder->rules as $rule)
            {
                if (!$rule->validate($model->$property))
                    $valid = false;
            }
        }

        return $valid;
    }
}

rule_builder.php

interface IRule
{
    public validate($value);
    public get_message();
}

class RuleBuilder
{
    private $property;
    public $rules = array();

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

    public function isRequired()
    {
        return $this->addRule(new RequiredRule());
    }

    public function length($min, $max = -1)
    {
        return $this->addRule(new LengthRule($min, $max));
    }

    public function addRule(IRule $rule)
    {
        $this->rules[] = $rule;
        return $this;
    }
}

And your specific validator:

class UserValidator extends Validator
{
    public function __construct()
    {
        $this->ruleFor('name')
            ->isRequired()
            ->length(20);
    }
}

To use it:

$user = new User();
$user->name = "Foo";
$validator = new UserValidator();

if ($validator->validate($user))
    // save
else
    // redraw form and show errors

This way all of your rule classes are hidden. All of the validation rules are portable because they are created inside a model specific class, and it's easy to use an IDE's auto complete feature to discover which rules are available since the RuleBuilder class has strongly typed methods encapsulating each rule.

On top of that, the IRule interface just accepts a value and not a model, making each rule unit testable to ensure your validation library is functioning properly.

And for those who do some .NET/C# development, this pattern probably looks familiar if you've used the FluentValidation NuGet package for Visual Studio. Say what you want about .NET development, but there are some gems out there. I do like the pattern that FluentValidation uses.


Querying multiple related records in Rails

I would try to use as much as possible what is provided by ActiveRecord. I was thinking to something like:

class Account < ActiveRecord::Base
  belongs_to :accountable, touch: true, polymorphic: true
  CLAUSE_FOR_RELATED = '"accounts"."accountable_type" = \'%s\' AND "accounts"."accountable_id" IN (%s)'.freeze

  class << self
    def related_to_user(user)
      group_ids = user.groups.pluck('groups.id')
      friend_ids = user.following_friendships.pluck('friendships.following_id')

      query = [
        compose_clause('Group', group_ids.join(', ')),
        compose_clause('User', [user.id, *friend_ids].join(', '))
      ].join(' or ')

      where(query)
    end

    def related_to_group(group)
      member_ids = group.members.pluck('users.id')
      where(compose_clause('User', member_ids.join(', ')))
    end

    private
    def compose_clause(accountable_type, ids)
      sprintf(CLAUSE_FOR_RELATED, accountable_type, ids)
    end
  end
end

Now in Rails 5 you could even write it like:

class Account < ActiveRecord::Base
  belongs_to :accountable, touch: true, polymorphic: true

  class << self
    def related_to_user(user)
      group_ids = user.groups.pluck('groups.id')
      friend_ids = user.following_friendships.pluck('friendships.following_id')

      where(accountable_type: 'Group', accountable_id: group_ids).or(
         Account.where(accountable_type: 'User', accountable_id: [user.id, *friend_ids])
      )
    end

    def related_to_group(group)
      member_ids = group.members.pluck('users.id')
      where(accountable_type: 'User', accountable_id: member_ids)
    end
  end
end


In fact, you can:

public static String getFirstTwoNumbersOfString2(String s) {
    StringBuilder sb = new StringBuilder(2); // Capacity of 2 chars.

    for (char c : s.toCharArray()) {
        if (Character.isDigit(c)) {
            sb.append(c);

            if (sb.length() == 2) {
                break;
            }
        }
    }

    return sb.toString();
}

Above you can nicely ask Character whether a given character is a digit. Also, StringBuilder.append runs in constant amortized time unlike string concatenation which will build a copy of two concatenated strings.

Hope that helps.


Closure, anonymous functions or binds on delayed functions

Actually, what you are looking for is already done in Lodash via debounce or throttle. And yes, a closure is probably the best way to do this. So let's take your closure example and improve it.

Instead of returning a function, why not just define the function normally. That way, there's no developer overhead. Devs shouldn't know about your limiter function just to make their APIs.

// We'll be fine with this
function get(input, html_output) {
  if (!input) return;

  $.ajax('/_api/pp_search/' + input).done(function (data) {
    html_output[0].innerHTML = data;
  });

}

delay is a bit deceiving as the word "delay" can mean a lot of things. It can mean "pause", which then equates to sleep which does an entirely different thing. "debounce" and "throttle" are actually better names. Verbose names aren't that bad as well (except for the extra keystrokes). Something like holdExecutionUntilAfter.

Now for the implementation, let's accept a delay and the function we want to delay. Our return will be our "proxy" function that controls the real function from executing.

function holdExecutionUntilAfter(fn, delay){
  var timer = null;

  return function(){
    if(timer) clearTimeout(timer);

    setTimeout(function(){
      fn.apply(null, arguments);
      clearTimeout(timer);
    }, delay);
  }
}

As simple as that! What it does is get a reference of the real function into a closure. Then we return a "proxy" function which well be using to call the real function. When it gets called, it resets the timer and kicks off another. We use apply to pass in the arguments like you normally would in the regular call. Usage will be as simple as:

var get = delay(function(input, html_output){
  if (!input) return;
  $.ajax('/_api/pp_search/' + input).done(function (data) {
    html_output[0].innerHTML = data;
  });
}, 500);

get(event.currentTarget.value, $results);

// or verbosely

function get(input, html_output){
  if (!input) return;

  $.ajax('/_api/pp_search/' + input).done(function (data) {
    html_output[0].innerHTML = data;
  });
}
var proxiedGet = delay(get, 500);

proxiedGet(event.currentTarget.value, $results);


As mentioned in comments above, your question is about gamedesign. But since you brought your code here already, here's a suggestion: use better variable names - aa and b are very non-descriptive and as the amount of code will grow, you'll have a hard time to understand what's going on there with variables like these.
So instead of b, use something like MAX_POLLEN. When you'll see it in the code you'll immediately know what it is. And since it's UPPERCASE, which is a Python's convention for constants, you'll also know it won't change its value over time.


Counting length-2 substrings that are common to two strings at the same offset

If I were you I would try to write more concise solutions. Readability is extremely important. If you write code that is hard to read, it will not be reused as much, it will be hard to change or extend the code, your code will probably perform worse, and it will be hard to find bugs.

Your first approach can be based on your intuition, but then you should look at your code, and try to find ways to simplify it. With time and experience, this will get easier and easier, and your intuitive solution will more closely resemble a concise solution.

Ignoring the complexity of your solution, here are some things that could be better:

Your first two for loops perform exactly the same functionality, and you shouldn't duplicate code. Whenever you copy-paste a piece of code, think about extracting it to a method. This will increase the readability, maintainability, and reusability of your code.
define variables when they are needed, not earlier. The fewer variables a reader has to remember at any point, the easier it will be to understand your code. count for example isn't needed at the beginning of the method, but just in the last for loop, so declare it there. Another example is sub2, which isn't needed at all, and which also doesn't have a very expressive name.
use spaces around - and + to increase readability.
don't declare variables that are only used once, but use those values directly, eg arrayA[i] = a.substring(i, i+2);.
use curly brackets even for one line statements to increase readability and possibly avoid future bugs.
be consistent. Why do you use i as loop variable for the first two loops, but not the third? If there is no reason, use i for all.
Why have if (j >= b.length())? It's not intuitively clear what it does, so you should at least add a comment.


private static List<String> getDistinctCompanies(List<HashMap<String, Object>> list) {
    Iterator<HashMap<String, Object>> iterList = list.iterator();
    String company;
    List<String> companyList = new ArrayList<String>();
    while (iterList.hasNext()) {
        HashMap<String, Object> map = iterList.next();
        company = (String) map.get("company");
        if(companyList==null || (!companyList.contains(company))) {
            companyList.add(company);
        }
    }
    return companyList;
}

There is no need to check if companyList==null because that won't ever happen because 4 lines prior you create the list.
The scope of map is defined to be inside the while loop, but company is defined outside whereas it is only used in the while loop as well.
You should name your variables proper. Shortening names doesn't add any value. Instead of iterList a simple iterator or listIterator would be much better.
You should leave your variables and operators some space to breathe. This helps to make your code more readable. companyList==null vs companyList == null.


Display all Prime Factors from user input

For both of your functions prime and factor you have something like:

for i in range(num):
    if not (i == 0 or i == 1):
        if num % i == 0:
            factors.append(i)

when you could shorten by using range(start,stop):

for i in range(2,num):
    if num % i == 0:
        factors.append(i)


Query SteamIDs for presence of an avatar

I normally wouldn't recommend this, but...
According to your query execution plan, it is doing 22719171 table scans in order to fetch the next row. What I think the problem stems from is querying across databases, which may have to open a connection for each Handler_read_rnd_next, then close the connection each time. One way or the other, if your columns are properly indexed, something like this shouldn't take near that long. I think something about the setup is causing the optimizer to go into a loop across two databases, and SQL is not good at looping. To make this more set-based, I'd suggest pulling your data sets into one of the two databases with a construct like a temp table:
START TRANSACTION;
  DROP TEMPORARY TABLE IF EXISTS vanrust_corev2.users_with_avatars;
  CREATE TEMPORARY TABLE vanrust_corev2.users_with_avatars (SteamID INT NOT NULL);
  INSERT INTO vanrust_corev2.users_with_avatars (SteamId) VALUES
    SELECT
      a.SteamID
    FROM vanrust_forum.tblPlayerAvatars a
COMMIT;

Then, you could simply join the record sets within the vanrust_corev2 database. This would increase I/O for a bit, but likely remove the need to connect between 2 databases millions of times while it does table scans:
SELECT
*
FROM
vanrust_corev2.tblPlayerLog log
WHERE
NOT EXISTS (
  SELECT
  a.SteamID
  FROM vanrust_corev2.users_with_avatars a
  WHERE a.Steamid = log.SteamID
);

And of course it's a good idea to DROP TEMPORARY TABLE vanrust_corev2.users_with_avatars; when you are done, although it will otherwise automatically drop when the session is ended with the database.

On another note, I strongly recommend you start naming aliases in a way that describes what they represent. log is OK, but a doesn't seem to mean anything.


Emulating super() in Python 3.x using Python 2.7

First of all, +1 on the idea.  Maybe you could submit this to the Python developers for Python 2.7.13 :)

Your super class is called mySuper.  Oh, the sound of my in a variable name!  Such are the names that are used when describing code to a non-programmer.  We shouldn't allow that in real code.  It is a Super class; that's all there is to it.  If you were to keep my in there, however, it should be PascalCase, not mixedCase.  (That is, MySuper, not mySuper).  It should be thus for compliance with PEP 8, the Python style guide.

Why Meta?  Well, obviously it is a meta class, but for what?  The name should describe it more aptly.  This happens to be an incredible meta class, so call it SuperMeta ;)

Instead of a couple concatenations, use string formatting:

setattr(cls, '_{}__sup'.format(name), Super(cls))


You don't need iteration at all for this problem.

Consider; the sum of all numbers from 1 to n is equal to n*(n+1)/2.  Also the sum of all numbers less than n that divides d equals d times the sum of all numbers less than n/d.

So the sum of all numbers less than 1000 that divides 3 is

3*floor(999/3)*(floor(999/3)+1)/2

Likewise the sum of all numbers less than 1000 that divides 5 is

5*floor(999/5)*(floor(999/5)+1)/2

Adding the two numbers would overcount though.  Since the numbers that divides both 3 and 5 would get counted twice.  The numbers that divides both 3 and 5 is precisely the numbers that divides 3*5/gcd(3,5)=15/1=15.

The sum of all numbers less than 1000 that divides 15 is

15*floor(999/15)*(floor(999/15)+1)/2

So the final result is that the sum of all numbers less than 1000 that divides either 3 or 5 equals:

  3 * (floor(999/3)  *  (floor(999/3)+1))/2
+ 5 * (floor(999/5)  *  (floor(999/5)+1))/2
-15 * (floor(999/15) * (floor(999/15)+1))/2


Or run your code when the document is ready, by putting it at the end of the page (or use a framework which supports something like $(document).ready()):

//-->

As I already said, that's a relic, stop doing it.


Calculation of Reynolds number for a pipe

There is no reason to abbreviate parameter names to three letters.  That just makes the code unnecessarily cryptic.  (Using names like rho instead of density could be an acceptable alternative, if brevity is essential.)  Furthermore, consider naming the function more specifically, so that it is obvious that it applies to cylindrical pipes.

As per PEP 8, binary operators should have have spaces for readability.

There is no good reason to catch ZeroDivisionError.  If the viscosity is 0, then this function would return None, and would likely cause other problems elsewhere in your calling code.  Just let the ZeroDivisionError propagate naturally, and your code would be easier to debug.  (Furthermore, your two comments are pointless and redundant.)

Watch your spelling ("dimentionless" → "dimensionless", "charakterize" → "characterize").

def reynolds_pipe(density, velocity, diameter, viscosity):
    """
    Calculate the Reynolds number for a given pipe flow.
    The resulting Reynolds number is dimensionless.
    It is used to characterize flow patterns.

    Arguments:
    density -- density of the fluid in [kg/m3]
    velocity -- the mean velocity of the fluid in [m/s]
    viscosity -- dynamic viscosity of the fluid in [Pa*s]
    diameter -- inside diameter of the pipe in [m]
    """
    return density * velocity * diameter / viscosity


words treats any whitespace as a separator, not just spaces. Use Data.Char.isSpace.

It's fine otherwise.

When reimplementing the standard library, you can exploit the standard version as a reference implementation to compare your version to:

map (\x -> words x == words' x) ["", "  ", "a", "a ", " a", "a  b", "aa bb", "aa\nbb", "a b\nc\td"]


Calculating sum after ranged-based subtractions

Performance
From what I understand, your solution is as good as it would get. The "n^2" (it's more like O(n*m)) performance seems inevitable. It also seems that an array is the optimal data structure since you must index into it.
If you really want to remove the worst case (decreasing from the entire array), you could keep a count of the number of times you have subtracted from the whole array and let the array value be array[idx] - theCountIMentioned and the final sum be sum - n * theCountIMentioned. Despite this, the performance would still be nearly n^2, especially since decreasing all but one of the values would be an O(n) operation, so the worst case would be O(n * m).
Readability
On another note: to make the inner loop more readable consider the following two functions:
inline int min(int a, int b){
    return (a < b)? a : b;
}

inline int max(int a, int b){
    return (a > b)? a : b;
}

This would make the inner loop's header much more readable. (It would be for(int j = max(0, idx - 1 - count); j < min(idx + count, n); j++)).
Also, you should make the variable names more readable.

n = arrayLength or even arrLen.
m = numberOfOps or even opCt.


Simple app to take username and password from the user

Just a few things:

Don't use \n as a literal, we use Environment.NewLine instead.
Don't use "string concatenation" (string + string), instead use string.Join, string.Format or a StringBuilder. I.e.:

Console.WriteLine(option1 + "\n" + option2);

Should be:

Console.WriteLine("{0}{1}{2}", option1, Environment.NewLine, option2);

Just as well, you should, ideally, switch this to two Console.WriteLine statements:

Console.WriteLine(option1);
Console.WriteLine(option2);

A method should have on responsibility (SRP):

public static bool Login(string username, string password)
{
    if(username == "asd" && password == "asd")
    {
        Console.WriteLine("Welcome");
        return true;
    }
    else
    {
        return false;
    }
}

The Console.WriteLine statement does not belong there, Login should simply return true or false in this case.


Find one duplicate in container with N+1 integers between 1 and N

Never use goto

There are times where you have a compelling reason to use goto. This really isn't one of them. Either make your function recursive, since it is in all but name. Or rewrite it to be iterative. Both of those would be preferred solutions. The reason I say this is because your logic is sort of logic a binary search, except the two different changes in range occur in different places and use different mechanisms. This makes it difficult to understand and, I imagine, debug.

A Better Algorithm

Add a helper function that will count the number of elements in your given range, breaking out early if you hit the amount you're going for:

template <typename It, typename V>
It find_if_extra(It first, It last, V start, V end)
{
    V count = 0;
    for (; first != last; ++first) {
        if (*first >= start && *first <= end) {
            ++count;
            if (count > end - start + 1) {
                return first;
            }
        }
    }

    return last;
}

This is basically the same thing you were doing in your loop, except substituting the return/goto pair for two returns. Now, we can just rewrite your original function to use this helper and the goto goes away:

template <class It>
It FindOneDuplicate(It first, It last) {
    using value_type =
        typename std::iterator_traits<It>::value_type;

    value_type N = std::distance(first, last) - 1;
    value_type start = 1;
    value_type end = N/2;

    for (;;) {
        auto it = find_if_extra(first, last, start, end);

        if (it != last) {
            // recurse lower unless we're done
            if (start == end) {
                return it;
            }

            N = end;
            end = (N + start) / 2;
        }
        else {
            // recurse higher
            start = end + 1;
            end = N;
        }
    }
}

Assumptions on types

There's no reason to cast n to be an int. size_t is fine:

size_t n = std::distance(first, last) - 1;

Similarly, I would initialize element with auto. You take arbitrary iterators, what if we had a huge container of size_t? You'd overflow.

Also, avoid this construction:

auto current{first};

in favor of

auto current = first;

The former may change meaning in the future, and there's no reason to prefer it anyway.

Testing

Your test just outputs something to the screen. Ideally, you would write test that actually verify the behavior of your program.


Bug:

When I input -6 and -3 I expect the result to be 3 but  I get a RecursionError exception instead:

RecursionError: maximum recursion depth exceeded in comparison

For the sake of UX:

Leave some space between the text you display and the data to input:

Enter a number6
Enter a number5

This would be the minimum better:

Enter a number: 6
Enter a number: 5

You know what your program does, but not the user, so your messages must be clear and precise. Ask the user not to input a number but an integer number. Otherwise this can mislead the user to input a real number, or input a character by mistake (or even try to break into your software):

Traceback (most recent call last):
  File "cr.py", line 12, in <module>
    a= int(input("Enter a number"))
ValueError: invalid literal for int() with base 10: 'g'

Your program does not give a choice for the user to exit. The minimum you can do for this purpose is to handle the KeyboardInterrupt exception corresponding to when the user presses Ctrl + c
The messages are intended to communicate with the user, so let him know what the programs does:

print('Computing the GCD of two numbers.\n')

Divide and conquer:

This is a consequence of the aformentioned: it is time to implement a function whose only purpose is care about the user's input:

def read_an_integer_user_input():
    a = None
    while type(a) != int:
        try:
            a = int(input('Enter an integer: '))
        except ValueError:
            print('I expect an integer value. Try again.')
        except KeyboardInterrupt:
            print('\nGoodbye!')
            break
    return a

Do not print, return:

We expect the function that computes something to return the result not to print it. Not only this is the function definition by essence, but this way you give more chance for your code to be reused and properly. So instead of coding print(r2) I would write return r2; by the way, do not leave space between  print and (.
Iterative version:

Given the recursion bug previsouly mentioned, I would opt for an iterative implementation of your code:

def compute_gcd(a,b):
    a = abs(a)
    b = abs(b)
    while b:
        a, b = b, a%b
    return a

Full program:

Let us gather the elements above to build a small coherent program:

def compute_gcd(a,b):
    a = abs(a)
    b = abs(b)
    while b:
        a, b = b, a%b
    return a

def read_an_integer_user_input():
   a = None
   while type(a) != int:
       try:
           a = int(input('Enter an integer: '))
       except ValueError:
           print('I expect an integer value. Try again.')
       except KeyboardInterrupt:
           print('\nGoodbye!')
           break
   return a

if __name__ == '__main__':
    print('Computing the GCD of two numbers.')
    a = read_an_integer_user_input()
    b = read_an_integer_user_input()
    if a and b:
       print('The GCD of {} and {} is: {}'.format(a, b, compute_gcd(a, b)))


Generate Letter Combinations of a Phone Number

You can set the keypad lookup as a constant instead of computing it dynamically. Setting it up as constant makes it clearer that what your intent is.

KEYPAD = {
    '2': 'abc',
    '3': 'def',
    '4': 'ghi',
    '5': 'jkl',
    '6': 'mno',
    '7': 'pqrs',
    '8': 'tuv',
    '9': 'wxyz'}

itertools.product can accept multiple lists. And in python, you can use * to unpack an iterable into positional arguments, and ** to unpack as keyword arguments.

To sum up:

def t9_mode(numbers):
    if len(numbers) == 1:
        return KEYPAD[numbers[0]]
    maps = map(KEYPAD.get, numbers)
    return [''.join(_) for _ in itertools.product(*maps)]

does the job.


Bugs

@JS1's answer was spot-on:
the counting of digits this way was buggy:

    int maxDigits = 1 + (int) (Math.log(max(arr)) / Math.log(radix));

Because Math.log(...) gives NaN for negative numbers,
and negative infinity for 0,
which breaks the digit count and the sorting.

This unit test exposed the bug:

@Test
public void test_m300_m200_m999() {
    sortAndVerify(new int[]{-30, -200, -999});
}

I could fix this by finding the max absolute value.

private static int getMaxAbs(int[] arr) {
    int maxAbs = 0;
    for (int num : arr) {
        int absNum = Math.abs(num);
        if (absNum > maxAbs) {
            maxAbs = absNum;
        }
    }
    return maxAbs;
}

There is another bug, related to floating point arithmetics.
Even after taking the max of absolute values for counting digits,
this test still fails:

@Test
public void test_m300_m200_m1000() {
    sortAndVerify(new int[]{-300, -200, -1000});
}

The problem is that Math.log(1000) / Math.log(10) doesn't give 3 as expected,
but 2.9999999999999996, which then gets truncated to 2 in the line that calculates maxDigits.

The fix for this is to count the digits in a simple loop instead of using divisions with Math.log that is prone to floating point arithmetic issues:

private static int countDigits(int num, int radix) {
    if (num == 0) {
        return 1;
    }
    int work = num;
    int count = 0;
    while (work > 0) {
        work /= radix;
        ++count;
    }
    return count;
}

Optimize

This step is a bit wasteful:

    List<List<Integer>> buckets = splitBySign(arr);
    flattenBuckets(arr, buckets);

The splitting step will visit all elements to create the buckets,
and then the flatting step will visit all elements again to write back to the array.

A more efficient approach is possible:

Create a helper array to store the negative numbers in the right order
Iterate from the back of the target array

If the current item is negative, write it to the next position in the helper array
If the current item is positive, write it to the next position from the back of the target array

After one pass, the positive numbers will be clustered at the end of the target array, in the correct order, and the negative numbers will be at the beginning of the helper array
Copy the beginning of the helper array to target

Implementation:

private static void reverseAndShiftNegatives(int[] arr) {
    int len = arr.length;
    int[] negative = new int[len];
    int negativeFront = 0;
    int back = len - 1;
    for (int i = back; i >= 0; --i) {
        int num = arr[i];
        if (num > 0) {
            arr[back--] = num;
        } else {
            negative[negativeFront++] = num;
        }
    }
    System.arraycopy(negative, 0, arr, 0, negativeFront);
}


Using global variables in my node.js program configuration

You say you're using globals because "I have added a watch function to watch for the changes in the config.json file". You don't need globals for this. If you declare the variables at the top level, like you've done with http and server, they'll be accessible everywhere in your script, including inside the anonymous function where you're using them.* You could get rid of the (function() { ... })(); wrapper round the first bit (not sure why you've wrapped that bit) and then declare them there.

"I know using global variables in JavaScript is bad practice." Using global variables in any language is bad practice if you can avoid it.

*A function like this, which uses variables declared outside the function, is called a "closure".


Testing input integers for the palindrome property

This one is easy! Remember the reverse-digits function? If a number is the same as its reverse, then it's a palindrome.


list_init should initialize all the members of the allocated node before returning.  This way the caller won't have to remember to NULL out the pointers it isn't explicitly setting.

One way a doubly linked list can be implemented is to use a fake node to hold the list head and tail pointers.  In your case, that node would always have a NULL data pointer, and initially the next and prev nodes would point to itself (this could be set up in a new list_create function, which could either initialize an already allocated node, or allocate and return a new one).

This would simplify list_append, as you'd already have a pointer to the last node, and you wouldn't need any extra code to handle an empty list (your current error handling in this case doesn't return after the fprintf, which will result in a crash).  'list_remove_last` would also be simplified.

Walking the list when using that fake node (like you do in list_print and list_find) would need a slightly different end condition.  You'd start at the head, walk to the first node, then stop when you find a node with a NULL data pointer (which would mean you're back at the head node).

Your current list_destroy has one problem, where the variable that is passed to it still points at the (now deleted) list when it returns, so the caller needs to handle this.  Using the fake node scheme, this would leave just the fake head node (which can be cleaned up via a list_destroy function).


Just some comments on the last part of the command.
Since you don't use any of the extra features of uniq, you can drop replace
sort -nr | uniq
with
sort -nr -u

I don't see a reason to sort in reverse, and then take the first line with head -1, when you could instead use tail -1.
sort -nu | tail -1

While outputting duplicated lines to tail might take some time if there is a lot of duplication, since you only actually want the final line, you can probably drop the -u flag in sort. If you wanted the most recent 3 dates, you'd need to add it back in.


Finding whether a set and an array have any strings in common

You can use the following stream in place of for-loop

Arrays.stream(items)
            .anyMatch(stringSet::contains);

What you are trying to do is loop through the items, and any time the item is contained in the string set u want to return true.
anyMatch function breaks as soon as any of the items returns true


Build an Array of StringBuffer with x elements from a List of n elements

StringBuffer

The first thing that comes to mind is the fact that you're using a StringBuffer instead of a StringBuilder. A StringBuffer is synchronized which means it has the additional overhead that comes with it. Unless you are doing this in a multithreaded environment that affects this piece of code, switching to a StringBuilder will be a good improvement.

ToString

Inside your loop you do b.append(',').toString(). Since you never do anything with the String that it returns, you are essentially needlessly creating a String each time it is hit.

Strongly typed collections

You have the collection accounts defined as List accounts = new ArrayList();: there is no type specified.

Proper handling would be List<Account> accounts = new ArrayList<>(); so you're working with Person objects instead of general Objects.

This is aside from any remarks on whether or not your code fits your problem description, as @rolfl states. I don't see where you split it in sublists of 3 elements.


My 2 cents:

You could use $().hide() instead of assigning your custom hiding css class
Similarly you could use $().show() instead of removing your custom hiding css class
You do not have to check the length of a jQuery query, just call remove(), it will work.
Your building of html inside the success callback is ugly, have a helper function to construct it and consider using DOM functions instead of HTML building. I personally tend to show/hide the select element and then rebuild the list with this helper function:

function setOptions( id , array )
{
  //Get the element
  var select = document.getElementById( id ) , i
  //Remove potentially existing children, somewhat heartless
  while (select.firstChild)
    select.removeChild(select.firstChild);
  //Add the new children
  for( i = 0 ; i < array.length ; i++ )
  {
    var element = new Option( array[i].id , array[i].name );
    select.appendChild(element);
  }
}

Assiging the listener in the success callback is also too much, consider building a listener that takes into account new elements on document instead $(document').on('change', etc.
Same for the mouseover / click event listeners

Simply having the document element ( or any other parent element that stays in the DOM ) and the selector inside the on call should activate the listeners for new elements.

function initializeListeners()
{
  $(document).on('change', '#value-select', function() {
      $('#options-table').removeClass('no-display-table');

      var selectedValue = $('#value-select option:selected').text();
      var element = '
' + selectedValue + '	';
          element += ' x
';

      $('#options-table tbody').append(element);

      $('#options-table').on('mouseover', '.remove', function() {
          $('.remove').css('cursor', 'pointer');
      });

      $('#options-table').on('click', '.remove', function() {
          $(this).parent().parent().remove();

          if($('#options-table tbody tr').length == 0)
              $('#options-table').addClass('no-display-table');
      });
  });
}


Program for converting an array of bytes to hexadecimal

Well, aside from the fact that you could just reduce the program to outputting a single string-literal, let's look at it:

Excellent code-formatting. That's far too rare.
The calculation for outstrlen is all kinds of bent. Both middle factors don't make any sense.

sizeof(bytearr) * sizeof(char)   * sizeof(bytearr[0]) * hexlen
size_in_bytes   * bytes_per_byte * bytes_per_byte     * digits_per_byte

Just to be "safe", you zero outstr before overwriting it...
That isn't safe, that's redundant.
There's no good reason to use bzero() and make your program unportable. Just use memset() if you must.
Why do you print into a temporary buffer, only to append it to the output-string?

Print directly into the final destination. No need for an intermediate.
If you build a string bit by bit, don't be Shlemiel The Painter. No need to make a linear algorithm quadratic.

As you immediately exit the program, freeing memory is just busy-work. Still, as I'm not sure what you are trying to learn there, it might be excused.
As an aside, return 0; is implicit for main() in C99+ and C++. Not sure you that's really relevant, but here you go.

Equivalent program (C99+ or C++):

#include <stdio.h>

int main() {
    printf("Hexadecimal string:\n0b343332\n");
}


Merging two lists of dicts based on the value of a specific key

itertools.groupby() is a good start.  To process each group, you want to take advantage of functools.reduce().  reduce() does the right thing, whether there is just one record in a group or multiple records.

Your code suffers from readability problems.  One obvious issue is that a, b, c, d, e, and f are horribly meaningless variable names.  Another problem is that the only way to see what it does is to trace through the code.  (Well, it would help if you wrote the entire introductory text to this question as a giant comment, but ideally the code should be eloquent enough to speak for itself.)

Let's start with the goal of being able to write this:

a=[{'time': '25 APR', 'total': 10, 'high': 10},
   {'time': '26 APR', 'total': 5, 'high': 5}]

b=[{'time': '24 APR', 'total': 10, 'high': 10},
   {'time': '26 APR', 'total': 15, 'high': 5}]

merger = merge_list_of_records_by('time', add)
print(merger(a + b))

Then, it's a matter of writing a merge_list_of_records_by() function to make that happen.

from functools import reduce
from itertools import groupby
from operator import add, itemgetter

def merge_records_by(key, combine):
    """Returns a function that merges two records rec_a and rec_b.
       The records are assumed to have the same value for rec_a[key]
       and rec_b[key].  For all other keys, the values are combined
       using the specified binary operator.
    """
    return lambda rec_a, rec_b: {
        k: rec_a[k] if k == key else combine(rec_a[k], rec_b[k])
        for k in rec_a
    }

def merge_list_of_records_by(key, combine):
    """Returns a function that merges a list of records, grouped by
       the specified key, with values combined using the specified
       binary operator."""
    keyprop = itemgetter(key)
    return lambda lst: [
        reduce(merge_records_by(key, combine), records)
        for _, records in groupby(sorted(lst, key=keyprop), keyprop)
    ]


C function to check the validity of a date in DD.MM.YYYY format

Use descriptive variable names

Instead of int a, b, c, give them more descriptive names:

int day, month year;

sscanf() will ignore trailing garbage

The function sscanf() will stop parsing after the last conversion. So the string "1.2.3...." will be cleared by your check for digits and period characters, and then sscanf() will read 3 integers, and returns 3. But obviously, this is an invalid date.

It would be best if you could have sscanf() determine the validity of the whole input string. One way is to use the %n conversion to check how many characters of the string were parsed so far, and then check that this corresponds to the whole string. This is how you can do that:

int day, month, year, chars_parsed;

if (sscanf(date, "%2d.%2d.%4d%n", &day, &month, &year, &chars_parsed) != 3)
    return false;

/* If the whole string is parsed, chars_parsed points to the NUL-byte
   after the last character in the string.
 */
if (date[chars_parsed] != 0)
    return false;

You don't need 12 ifs to check the month

You can just write:

if (month < 1 || month > 12)
    return false;

And similar for days and perhaps even years if you want to limit the allowed range.

Avoid redundant checks

It is likely that your program will normally handle valid date strings. So you want to optimize for this case. In your code, you are checking for the string to be empty at the start, but this is not necessary; if the input string is empty, then sscanf() will not return 3, so it will already correctly return false. Since most input strings will be valid, checking the string length is just a waste of CPU cycles.

Similarly, checking for each character to be a digit or a period is redundant if you just use sscanf() with the %n method to check that there was no trailing garbage after the year.

Better date checking

Just checking whether the month is between 1 and 12 and day between 1 and 31 is not enough. A given month might have less than 31 days. There are also leap years to consider. And if you want to allow dates far in the past, you run into the problem that we have had different calenders. To give an idea of how difficult the problem is, watch: https://www.youtube.com/watch?v=-5wpm-gesOY

One way to validate the date is to use the C library's date and time conversion routines. After scanning the day, month and year, create a struct tm from that, then convert it to seconds since epoch using mktime(). This might still accept invalid dates, but if you convert that back to a struct tm, you can check whether that conversion matched the original input:

int day, month, year,
sscanf(date, "%2d.%2d.%4d", &day, &month, &year);

struct tm input = {
    .tm_mday = day,
    .tm_mon = month - 1,
    .tm_year = year - 1900,
};

time_t t = mktime(&input); /* note, this might modify input */
struct tm *output = localtime(&t); /* prefer localtime_r() on systems that support it */

if (day != output->tm_mday || month != output->tm_mon + 1|| year != output->tm_year + 1900)
    return false;

These routines will probably still not handle dates hundreds of years in the past correctly, but it should suffice for recent dates.


Is returning a nullptr in case of bad parameters okay?

No, you should instead throw an ArgumentException (or possibly one of its derived types). This way, if an user of your code makes a mistake, they will get an exception clearly explaining the problem, instead of getting a confusing NullReferenceException at a later point.

  What about handling error if any should occur when creating the native object Codegen?

Again, you should throw a suitable .Net exception. In this case, I think a custom exception would be appropriate.

  Should I just encompass this in a try/catch block and wrap a native exception inside a managed one?

Not necessarily. Unmanaged exceptions are represented as the managed SEHException. So, if that's enough for you, you don't have to do anything.

But if you want to be able to handle some specific unmanaged exceptions from the managed code, or if you want to preserve some information from the unmanaged exception (SEHException doesn't really do that), you should catch the unmanaged exception and throw a new managed exception. For example:

public ref class UnmanagedException : Exception
{
public:
    UnmanagedException(String^ message)
        : Exception(message)
    {
    }
};

…

try
{
    // call some code that can throw std::exception here
}
catch (const std::exception &ex)
{
    throw gcnew UnmanagedException(gcnew String(ex.what()));
}


Find primes that are also primes when its digits are rotated

A 2+ digit fare prime number can never have an even digit, or a 5 digit in its set of digits, because a rotation which moves an even digit or a 5 to the last digit will be divisible by 2 or 5.  You could use that as a filter for your possible fare primes from the list of primes you calculate.

When calculating primes, you can stop at sqrt(num).  Any number greater than sqrt(num) that evenly divides num will have a compliment number less than sqrt(num) that you have already tested.

Speaking of primes that you’ve calculated, why don’t you use those for your subsequent prime test?  Why try dividing by every number from 2 up to int_num when you could just try the numbers in primes upto int_num.

... or just ask if int_num in primes.  Speed tip: turn primes into a set() first for faster inclusion testing.

Your digit_list code is very inefficient. For any number, once you’ve split the number into digits, you don’t need to resplit it into digits again for each rotation.  Actually, you don’t even need to split it into individual digits.  This will give you the rotated values:

digits = str(i)
for j in range(1, length):
    int_num = int( digits[j:] + digits[:j])


I'm going to assume that the corner cases are what you want, i.e. a date
"range" of a single day is acceptable - otherwise you'd have to overhaul
the calculation a bit.

I'm not going to attempt to remove the while loops - I don't know a
better alternative; six lines self-contained logic each isn't too bad
IMO.

First things first, I'd recommend a couple of things for better
readability and interactivity:

Use proper docstrings instead of comments, so that both tools and
human readers know what the functions are about.  At the moment
help(forward_date_range) isn't too helpful, but with that change it
would be much more so.
Similarly, the _dt suffix isn't that readable either.  I'd either
drop it or expand it to _date so that it's more obvious.

Next, I'd try to remove some more duplication:

The string '%Y-%m-%d' comes up a total of twelve times.  Either put
that into a constant (if you don't ever want users to supply a
different format), or make it an optional function parameter.
The structure of both functions is also quite similar, so while the
loop might not be worth to factor out, the pre- and postprocessing
definitely is.  Also, timedelta(days=1) is another constant in the
code.
Importing the right names (e.g. datetime and timedelta) could also
cut down the number of tokens to read.
There's also an opportunity to cache the result of end - span into a
separate variable so as to not repeat it in every loop.
(From @mathias-ettinger) The loop doesn't have a break to exit it
early, so the else branch will always be executed.  In that case it
makes sense to just put it on its own line without the else which
doesn't change the meaning in any respect.

Lastly, I'd probably say that the conversion from and to datetime
objects doesn't belong into these functions and should be done
separately instead.  If you want to keep it like it is there are still
some opportunities for helper functions to cut down the noise.

The result I'm posting below can still be compressed further, but at
that point it would be generally getting more functional and less like
regular Python code.

So there we have it:

from datetime import datetime, timedelta

DATE_FORMAT = '%Y-%m-%d'
DATE_STEP = timedelta(days=1)

def _strptime(string):
    return datetime.strptime(string, DATE_FORMAT)

def _strftime(date):
    return date.strftime(DATE_FORMAT)

def _date_range_parameters(start, end, span_days):
    start = _strptime(start)
    end   = _strptime(end)
    span  = timedelta(days=span_days)
    return start, end, span

def forward_date_range(start, end, span_days):
    """
    Generate tuples with intervals from given range of dates (forward).

    forward_date_range('2012-01-01', '2012-01-5', 2)

    1st yield = ('2012-01-01', '2012-01-03')
    2nd yield = ('2012-01-04', '2012-01-05')
    """
    start, end, span = _date_range_parameters(start, end, span_days)
    stop = end - span

    while start < stop:
        current = start + span
        yield _strftime(start), _strftime(current)
        start = current + DATE_STEP

    yield _strftime(start), _strftime(end)

def backward_date_range(start, end, span_days):
    """
    Generate tuples with intervals from given range of dates (backward)

    backward_date_range('2012-01-01', '2012-01-5', 2)

    1st yield = ('2012-01-03', '2012-01-05')
    2nd yield = ('2012-01-01', '2012-01-02')
    """
    start, end, span = _date_range_parameters(start, end, span_days)
    stop = start + span

    while end > stop:
        current = end - span
        yield _strftime(current), _strftime(end)
        end = current - DATE_STEP

    yield _strftime(start), _strftime(end)


Some general ideas first, without fully understanding your criteria:

Work with arrays, not with ranges

name the variables according to their function, be precise

CellInfo => CellContentLength, LengthOfCellText, ...
mergedCells => CellsToSplit
cellRow => CurrentCell, ...


Refactoring APEX to keep all database calls outside of for loops

The first step would be to create a set of Timelogs that you are interested in and then query for the related Worklogs. Querying Timelogs and getting child Worklogs is probably the simplest solution.

Sample code:

Set<Id> timelogIds = new Set<Id>();
for (Worklog__c worklog : worklogs) {
  timelogIds.add(worklog.Timelog__c);
}

// Get timelogs and related child worklogs
Map<Id, Timelog__c> timeLogs = new Map<Id, Timelog__c>(
                             [SELECT Id,
                             (SELECT ... FROM Worklogs__r) //query child relationship
                             FROM Timelog__c
                             WHERE Id IN :timelogIds]);

for (Worklog__c worklog : worklogs) {
  List<Worklog__c> tempList = timeLogs.get(worklog.Timelog__c).Worklogs__r;
  // iterate through tempList to check for overlapping records
}


Leetcode 1275. Find Winner on a Tic Tac Toe Game

The second half of your code is inefficient, as it computers is_win(b) unnecessarily. It can be written as:

    if is_win(moves[::2]):
        return 'A'
    elif is_win(moves[1::2]):
        return 'B'
    elif len(moves) == 9:
        return 'Draw'
    else:
        return 'Pending'

This removes the redundant not a and not b, the redundant parentheses and the redundant computation of is_win in case A has won already.

When I saw is_win for the first time, I didn't understand it.

Maybe my chances had been better if you renamed d1 to diag1.
You could also write diag1 and diag2 on separate lines, to align their coordinates vertically.
You could also inline the diag1 and diag2 so that you don't need a name for them at all.

I'm thinking of:

def is_win(pos: List[List[int]]) -> bool:
    pos = set(tuple(i) for i in pos)
    horiz = 3 in Counter(r for r, _ in pos).values()
    verti = 3 in Counter(c for _, c in pos).values()
    diag1 = not (set([(0, 0), (1, 1), (2, 2)]) - pos)
    diag2 = not (set([(0, 2), (1, 1), (2, 0)]) - pos)
    return horiz or verti or diag1 or diag2

To avoid unnecessary computations here as well, you can let your IDE inline the variables except for pos.

Instead of not (set1 - set2), the expression set1.issubset(set2) is clearer because it avoids the confusing not:

    diag1 = {(0, 0), (1, 1), (2, 2)}.issubset(pos)
    # or:
    diag1 = {(0, 0), (1, 1), (2, 2)} <= pos

Or you could make checking the diagonals similar to horizontal and vertical:

    diag1 = 3 in Counter(r - c for r, c in pos).values()
    diag2 = 3 in Counter(r + c for r, c in pos).values()


This actually looks pretty solid.

Another approach would be to sub-class the Renderer and make it responsible for retrieving the base classes' to_partial_path.

For me this feels a bit cleaner because it is sub-classing versus monkey-patching and because the renderer is supposed to find and load the template anyway while the model class shouldn't case about the (non-)existence of the view at all.

After looking at it for a while, I would the make sub-classes partial_path check if the template exists and find the template of the base class if it doesn't.


Member list reveals member information on click (#2)

this popped out at me, I haven't looked at the entire code completely yet, so take this with a grain of salt please

not sure why you do this

   Member Name 2

I would probably write it like this instead

    Member Name 2

I am pretty sure that you don't need that extra div
I think the image tag is going to act similar to the div tag, and I assume that you want to style the image and not the div anyway,  it looks more like a container for the image which I think is redundant. ( I have been wrong before and am not afraid to admit it when someone gives me some solid evidence )

that is the only thing that I can see right now, but I haven't spent much time looking at it either.