Ooooh boy, a prime number finder with the question, "how do I make this faster." It's like asking a bartender what their favorite drink is: it really depends. However, before we get to performance, let's tackle some of the stylistic considerations in this code.

Wrap the actual executing code in a if __name__ == '__main__' block.
Follow standard naming conventions for functions and variables (not to mention spacing).
The algorithm you're implementing is fairly complicated. Add some brief comments and docstrings to explain what's going on.
Either use descriptive names for your variables or add comments/docstrings explaining what they are.
Name your constants. Why r < 1000000? This would be clearer if we had something like MAX_PRIME_VALUE = 1000000, r < MAX_PRIME_VALUE.

Now in terms of performance. Are there ways to make this faster? Yes, of course. If you had a dictionary of all prime numbers <= 1000000, then you could do a simple lookup and be done. The ultimate trade-off between runtime and storage space is to simply pre-compute all the answers to your question. Also, it depends on what hardware/software you have available (pure no-library python? Only sympy? Numpy? Numba? Cython? CUDA?). So in order to answer this question, you really need to ask what your use case is and what trade-offs you're able to make.

For the sake of argument, let's use your code above as our basic requirements. Let's say we have access to sympy and basic Python, but nothing else. As a baseline, let's consider a trivial prime number finder that use nothing but pure Python. We'll just count up from 3 up to sqrt(n): it's naive, it's dead simple to write, and it's actually reasonably fast just because Python is a decent language (and it even has an O(sqrt(N)) runtime, which is not a bad place to start):

def naive_is_prime(n):
    if n == 2:
        return True
    if n < 2 or n % 2 == 0:
        return False

    # Consolidated code thanks to GZ0's comment
    return all(n % i != 0 for i in range(3, int(n ** 0.5 + 1), 2))

And a couple benchmarks:

%timeit myisprime(11)
1.23 ms ± 26.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit naive_is_prime(11)
1.11 µs ± 47.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Uh oh, that's not a good place to begin, with the naive code giving us a 1000x speedup. Well, maybe that's just because the numbers are so small; maybe the overhead of using sympy will shine when we start considering larger primes. Unfortunately, it slows down rapidly, and waiting for it to compute if tiny numbers are prime takes an unbearable amount of time:

%time myisprime(61)
Wall time: 28.3 s

whereas the naive implementation above continues to be almost instantaneous up until fairly large primes:

%timeit naive_is_prime(2**31 - 1)  # 2147483647
2.7 ms ± 160 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

I think the moral of the story is that "premature optimization is the root of all evil". I fall into this all the time, and even did so while answering this question (I had a more complicated baseline to show off that performed much worse than that trivial code), and it's very tempting to use a fancy package like sympy to accomplish what's not a very fancy problem. Start simple, then look into some common approaches to the problem (like the Sieve approach) and figure out if they actually help you or not.


Am I using Angular directives correctly?

If the only reason is to avoid a few more DOM elements, this sounds like an overkill to me. It is so much easier to use ng-show or hiding/showing depending on the class like it is done in TodoMVC:

    ...

 ...

    <input class="edit"> ...

Then in CSS:

#todo-list li.editing .view {
    display: none;
}
#todo-list li.editing .edit {
    display: block;
}

Also it does not feel right to do DOM manipulation with .html() jQuery-style, maybe use dynamic template property instead.

If having additional elements in DOM is really a concern,
there are also ng-if and ng-switch.
Though I personally prefer ng-show/ng-hide exactly because
this way I don't have to rebuild the DOM.

To put this into perspective, I have tried using ngRouter on my site 33hotels.com, which does rebuild the view every time the route is changed. That felt in considerable delay. Instead I have all my Views inside my DOM at all times and only hide/show them depending on the route. The performance difference is dramatic - it now feels instant.

Finally, both templates have common fragment, which does not make code feel DRY. Upon any change you'll have to edit each of them. I would simply keep the common part outside any directive, and put the dynamic part inside ng-whatever.

Also note that the HTML tag
 has semantic meaning, not presentational. That is, it marks your main header. Any presentation adjustment should be done via CSS.


Is this spaghetti javascript code? How can it be refactored with a javascript library or framework?

I would do it the following way:
As far as I got it, you want to select several Areas (e.g. something like Papersize and landscape or portrait format) and want to keep state of what selected so far.

I did not refactor your whole code, but reengineer it a bit:

A

B

For the sake of the example I limit my self to these two Areas. You could easily extrapolate to your needs.

First I bound the forEach-function from the array with the following statement:

var forEach=Function.prototype.call.bind([].forEach);

After that I used an object to keep the state for me:

var selectedItems={
    a:false,
    b:false,
    c:false,
    d:false
};

That's what you usually would do with something like a "Model"

(cf. Backbone.Model.extend({}); in http://backbonejs.org/).

But for this usecase, that simple object would do the trick.

Next I would define a toggle function for each group (in my example only for "left"):

var toggleSelectionLeft=function(elem){
    target=$(elem.target);
    target.hasClass("selected")?target.removeClass("selected"):target.addClass("selected");
    var id=elem.target.id;
    selectedItems[id]=!selectedItems[id];
};

This togglefunction handles the adaption of the css and sets the state of our object. Usually you would further decouple these tasks, in only triggering an "elementSelected" event, to which thwo functions would subcribe: (1) update the model and (2) adapt the CSS. These are two different tasks. For the sake of this simple example I left them together (So don't do this at home g).

After all your behaviour is declared, you could go on, binding the "click" to the wanted behaviour:

forEach($(".left"), function(elem){
    $(elem).on("click", toggleSelectionLeft);
});

A working example is under: http://jsfiddle.net/Susv4/
For submitting values to the server you could easily evaluate our "model".


You could remove some duplication with a getPortraitValue function:

function getPortraitValue($apiData, $key) {
    $portrait = $apiData['portrait'];
    if (isset($portrait[$key])) {
        return $portrait[$key];
    }
    return null;
}

$portrait = new Portrait();
$portrait->setXCoordinate(getPortraitValue($apiData, 'x')
    ->setYCoordinate(getPortraitValue($apiData, 'y'))
    ->setWidth(getPortraitValue($apiData, 'w'))
    ->setHeight(getPortraitValue($apiData, 'h'))
    ->setOffset(getPortraitValue($apiData, 'offset')
    ->setUrl(getPortraitValue($apiData, 'url');
return $portrait;


Should we create a new constant or modify an existing one

It depends on the meaning of this constant. If the value ROW_LOC - 1 has logical relation to ROW_LOC (e.g. it means that it should go right before ROW_LOC in some list) then just use ROW_LOC - 1 there, but if it's just 0 - then either define a new constant or just use 0 as value, depending on situation.

What I would suggest is to rename ROW_LOC to more meaningful (descriptive) name unless it's a well-known acronym in your company.


Returning Key Values from Stored Procedures

I think you've already answered your own question to some degree: there are multiple options for returning data from a stored procedure and they all behave differently so there is no single answer. But there are definitely some general guidelines and common practices.

RETURN is a control-of-flow statement: its primary use is to exit a procedure, not to return data. But of course return codes are a very common feature of many programming languages, and the documentation makes that usage pattern explicit:

  A stored procedure can return an integer value called a return code to
  indicate the execution status of a procedure

So you should use this not to return data, but to return metadata about the execution of the procedure. Usually this means did it succeed or fail, and if it failed what was the error status. Whether or not you actually want to use this feature is entirely up to you, of course.

Output parameters are the standard way of returning scalar values, and are especially useful when the procedure is called by another piece of TSQL code, because as you mentioned sharing data between stored procedures is not always easy, especially if you want to share a result set. The only obvious reason not to use them for scalar values is if your client code - perhaps an ORM or DAL - and/or coding practices make it easier to consume a result set (more on that below).

I'm not going to comment on your XML solution because I'm not an XML guy, but it seems very awkward and unless your client code could only consume XML then I'm not sure what the point would be.

A result set is more flexible than an output parameter because it can return multiple rows (obviously), so if you need a result set then it's the only choice anyway.

(Strictly speaking that isn't true, because you can return a cursor as an output parameter, but avoiding cursors whenever possible is a good rule in TSQL and I personally don't see any advantage over returning a result set. Other than it being easier for calling code in TSQL to consume the cursor.)

That all means that the 'correct' answer to your question is to use an output parameter when returning one key value, or a result set when returning more than one. But, that will add some complexity to your calling code because it needs to know which procedures return output parameters and which ones return result sets (or both).

For that reason it's not uncommon for organizations to make explicit coding rules that say that stored procedures must always return data in result sets (usually one and only one per procedure). Then developers don't need to worry about it, they just always write code to consume result sets, even if some result sets always have just one row. This is an important consideration, because developers' time is usually by far the most expensive component of any application, so anything you can do to make development simpler, faster and less error-prone is very worthwhile.

Perhaps there's a performance difference between using output parameters and result sets, but if you're worried about that then set up a test and gather some performance data (it's almost always better to test and measure performance yourself before asking someone else's opinion, since that person's general answer may turn out to be wrong for your specific case). And even if there is some performance difference, if it isn't big enough to impact your application then you can ignore it and use whichever mechanism you prefer.


Looks fine to me,

I would consider making extend a property of prototype though.

For nitpickings, I think

function Test() {
    this.tester = 'The instance was successfully created';
};

is preferred to

test = function() {
    this.tester = 'The instance was successfully created';
};

This ways developers will know to use new when using test.
Please read Learning JavaScript Design Patterns for the cons of using the new keyword.

You probably want to store the entire plugin object provided to extend, not just keep init.

You probably want to throw an exception if the plugin does not have an init  property.

I am not sure if you realize that method1 and method2 are at the end of the script also "core methods"?


Like 200_success said, the key is in thinking at the higher level. But I think his approach can be simplified.

Lets first define a row function, which simply calculates a list of numbers in an n'th row of our output:

# When n=3, returns [3, 2, 1, 2, 3]
def row(n):
    return list(reversed(range(2, n+1))) + list(range(1, n+1))

And now we can use this to print out the lines:

for n in range(1, 5):
    print(row(n))

Giving us the following output:

[1]
[2, 1, 2]
[3, 2, 1, 2, 3]
[4, 3, 2, 1, 2, 3, 4]

The core of the problem is now solved. The only thing left is formatting. For this we can write another function, which formats each number in list into a three-character box (with "%3s"), and also appends a certain amount of padding to make sure lines are aligned like a pyramid:

def formatted_row(n, num_rows):
    padding = '   ' * (num_rows-n)
    return padding + ''.join(["%3s" % x for x in row(n)])

Now we're almost there. Just need to tie it all together:

# When n=3, returns [3, 2, 1, 2, 3]
def row(n):
    return list(reversed(range(2, n+1))) + list(range(1, n+1))

def formatted_row(n, num_rows):
    padding = '   ' * (num_rows-n)
    return padding + ''.join(["%3s" % x for x in row(n)])

num_lines = eval(input("Enter the number of lines: "))
for n in range(1, num_lines+1):
    print(formatted_row(n, num_lines))


There's something in here that doesn't seem to make a lot of sense:

    try:
        if not type_:
            type_ = type(input_)
        input_ = type_(input_)
    except ValueError:
        print("Expected input of type {} but got {}".format(
            type_, type(input_)))
        continue

If type is falsy, get the type of the input and re-cast the input? That seems unnecessary. And in this case the whole type validation seems unnecessary. You could skip the validation of the specified type is falsy.

A very minor thing, the default start of a range is 0, so you could just skip that.


Using a DependencyProperty ChangedCallback as a validation measure

Yes, you should use CoerceValueCallback instead to coerce your Level property (what you are trying to do is not "validation" strictly speaking).

private static object CoerceLevel(DependencyObject d, object value)
{
    var control = (MyUserControl)d;
    if (control.SelectedCard == null) return null;
    var level = (int?)value;
    if (level.HasValue)
    {
        return Math.Min(Math.Max(level.Value, control.SelectedCard.MinLevel), control.SelectedCard.MaxLevel);
    }
    else
    {
        return control.Level;
        //or
        //return DependencyProperty.UnsetValue;
    }
}


Calculating minima values for each column of given data

Note: this only works if there are exactly two minima in each row.

You can avoid the loop by computing minima along axis 1 of the data array.

minima = signal.argrelmin(data, axis=1)
minimas = list(data[minima].reshape(-1,2))


Replace CASE WHEN statement with something more sensible

COALESCE(…, …, 2147483647) will never return NULL.  Furthermore, MIN(…) will only return NULL when all of its inputs are NULL.

Assuming that every NewPrice and every Price is at most 2147483647, the following query should be equivalent.

SELECT COUNT(*)
     , ISNULL(MIN(COALESCE(NewPrice, Price)), 0)
    FROM MerchantsProducts


There are a few things I would like to point out to you.

Style

Python has an official style guide called PEP8. Under "Indendation" there is the following rule most Python programmers stick to:

  Use 4 spaces per indentation level.

Reference: PEP8 - Indentation

This would also make your code consistent with the provided test code.

Though not strictly part of PEP8, most of the tools integrated in Python IDEs would also tell you that s is not a good variable name. Use something that is more descriptive (n_paths maybe?).

While we're at it, you can wrap long lines such as the sum of the four traverse calls on multiple lines to allow better readability in case you have, say two documents next to each other or a small screen. Including the previous note, s = ... could be transformed into, e.g.

n_paths = traverse(row, col + 1) \
    + traverse(row + 1, col) \
    + traverse(row - 1, col) \
    + traverse(row, col - 1)

The nonlocal keyword

I suspect you slightly missunderstood what nonlocal does. All variables from an outer scope are automatically available to read from in nested scopes. This means in your case, traverse can see num_of_rows and num_of_cols from robot_paths automatically.

Statements like nonlocal or global only come into play whenever you want to assign to a variable not in your local scope. The Python interpreter would then recognize, that you don't want to create a new local variable with the given name, but instead use an already existing one from an outer scope. This SO answer has a nice example to show you that effect.


How to improve wordfeud solver algorithm?

This is a rather interesting problem, first let's analyze a couple of algorithms and their respective algorithmic complexities.

We say that A is the set of characters given to us from the Wordfeud game: the set of characters from which we can form words. B is the lexigraphically sorted set of all valid words we can form, in practise, the words of a dictionary. The set of words in B that we can form from the characters in A is C.

Naive algorithms

The naive algorithm for this problem is to simply loop through all elements of B and check whether these words can be formed from the characters in B, with a regex like proposed here, or with a frequency map. If so, we put the word in C. For an average word length k and n words in B this runs in worst-case O(n k) time.

This is the fastest we can go without doing some kind of precomputation. In my tests, this algorithm runs in about 2s on the dictionary in /usr/share/dict/words in Ruby on 2 Ghz. This is the mean running time from different sets of A of 25 characters of which about 15 letters are distinct.

A simple iteration on this naive algorithm, is the observation that if a character is not in A, then we do not have to loop through all the words that start with this letter in B. E.g. if there's no letter c in A, we can skip to the words beginning with d when we encounter the first word which begins with c in B and so on. We can precompute a table that stores this information, i.e. the intervals at which the words start with a letter k. E.g. words with index 1..3482 in B all start with a. Thus if A does not contain a, we can just jump to the word with index the 3482 + 1.

The speed of this iteration depends on how many words in B start with each character in A. Say that v is the highest number of words that starts with any character in B, and i is the number of distinct characters from which we can form words, then this runs in worst-case O(v i) time. In my tests, this was about twice as fast as the previous algorithm.

Another iteration is threading it. For each segment we check (e.g. the words from a..b) we create a thread that checks this. With native threads, this halves the run time once again. This got me down to about 0.5s with the above setup running on JRuby.

Using a Trie

A trie is a tree data structure to store prefixes of strings. You start with a root node, and from there you have 25 edges, one for each character in the alphabet. If you follow one of these edges, e.g. the edge for the letter 'a' there will be X new edges. For each of those edges the prefix a + that letter exists in B. For instance one of the edges in X could be p and from there we could follow another edge e.

The vertex we landed at after following e is marked, because if we follow the edges back to the root node and save the characters on the way to the root in reverse order, we get a word in B: ape. The edge p existed because ap is a prefix of ape, and thus a prefix in B, as stated in the previous definition.

With this data structure in mind, we can design a new algorithm. Build a freqency map with default value 0 from A, i.e. a map where the key is the letter in A and the value of that key is the amount of times this letter occurs in A.

Traverse the tree with a depth-first search where you recursively traverse all options that you can do while all keys in the frequency map are > 0. Every time you hit a vertex which is marked, you traverse up to the root node to determine the word and add this word to C.

In reality you might want to pay the memory cost of storing the word at the vertex so you avoid traversing back to the root node every time you hit a marked vertex.

I won't get into algorithmic complexity analysis of this one, since it is rather complicated to analyze. However, in my tests, creating the trie from the dictionary takes less than 1s (e.g. for a web-service this penalty can just be paid when starting the app) and querying with a frequency table of A takes about 0.05s.

I do not know C#, however, I implemented this algorithm in Ruby.


We'll have a look at your code from the top to the bottom. The proper indentation makes that easy.

Magic numbers and defines

First of all, it's great that you've used BUF_SIZE instead of magic numbers, e.g.

char buf[1024 * 4]; // bad!

However, #defines can be error prone. You've used parentheses, which are often necessary. Furthermore, BUF_SIZE doesn't exist in your compiled program anymore, which can lead to some confusion if you want to debug. So consider the possible alternatives. In this case, a #define is fine. But there is no need for abbreviation:

//! Buffer size for reading from stdin.
#define BUFFER_SIZE (1024 * 4)

While we're at it, add some documentation. BUFFER_SIZE and buf[BUFFER_SIZE] are only some lines away from each other, but that might change later. The ! after // is Doxygen specific, you can ignore it if you don't use Doxygen.

Declarations and initializations

You use C99 and therefore can declare variables as late as you want. Whenever you declare a variable but set it a lot later, try to rewrite it as initialization at the right point. For example, ch isn't used until ch = buf[k]. We should keep it's scope limited. That way we cannot accidentally reuse variables.

If we follow this suggestion then i, k and ch get limited in their scope. We will have a look at that later, though. And since we already renamed BUF_SIZE to BUFFER_SIZE, we could also rename buf to buffer. You can of course choose other names, but again: there is no need to abbreviate. Disk space isn't expensive anymore, so choose names that you still understand after several months or years when someone calls you in the middle of the night.

Input and sizeof usage

fread(...,..., SIZE ,...) may not return SIZE. That can either happen if you're at the end of the file or if an error happens. You should check the FILE* with feof or ferror if that happens.

We stay at fread. While it's unlikely that you change buffer's type, it's usually good practice to use sizeof(*buf) or sizeof(buf[0]). If you ever change char buffer[BUFFER_SIZE] to mychar buffer[BUFFER_SIZE], you don't have to remember to change sizeof(char) to sizeof(mychar).

State machines and repetition

Your loop is essentially a state machine. The state machine itself looks fine. However, there is a lot of repetition. We have

while (i-- > 0) fputs(placeholder, stdout);

four times. That really asks for a function:

/**
 * \brief Puts the given \c str \c count times on \c stream.
 * \param str null-terminated character string to be written
 * \param count number of times \c str shall be written
 * \param stream output stream
 * \returns a non-negative value on success
 * \returns EOF on error and sets the error indicator
*/
inline void fputs_repeat(const char * str, size_t count, FILE * stream) {
    int value = 0;
    while (count-- > 0) {
        value = fputs(str, stream);
        if (value == EOF) {
            return EOF;
        }
    }
    return value;
}

Now we can just use fputs_repeat(placeholder, indentation, stdout) wherever you've used while (i-- > 0) .... We would now end up with the following variant:

#include <stdio.h>
#include <stdlib.h> /* EXIT_SUCCESS */

#define BUFFER_SIZE (1024 * 4)

inline void fputs_repeat(const char * str, size_t count, FILE * stream) {
    int value = 0;
    while (count-- > 0) {
        value = fputs(str, stream);
        if (value == EOF) {
            return EOF;
        }
    }
    return value;
}

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

    char buffer[BUF_SIZE] = {0};
    const char placeholder[] = "  ";
    unsigned int indent = 0;
    char is_string = 0;
    char escaped = 0;
    size_t n;

    while (0 < (n = fread(&buffer, sizeof(buffer[0]), BUFFER_SIZE, stdin))) {
        // exercise: add error handling
        for (unsigned int k = 0; k < n; k++) {
            char ch = buffer[k];

            if (is_string) {
                /* Inside quoted string */
                putchar(ch);
                if (! escaped) {
                    if (ch == '"') {
                        /* Unescaped quote, string just ended */
                        is_string = 0;
                    } else if (ch == '\\') {
                        escaped = 1;
                    }
                } else {
                    escaped = 0;
                }
                continue;
            }

            switch (ch) {

            case ' ':
            case '\t':
            case '\n':
            case '\r':
                /* Ignoring original formatting */
                break;

            case '{':
            case '[':
                putchar(ch);
                putchar('\n');
                fputs_repeat(placeholder, ++indent, stdout);
                break;

            case '}':
            case ']':
                putchar('\n');
                fputs_repeat(placeholder, --indent, stdout);
                putchar(ch);
                if (indent == 0) putchar('\n');
                break;

            case ',':
                putchar(',');
                putchar('\n');
                fputs_repeat(placeholder, indent, stdout);
                break;

            case ':':
                putchar(':');
                putchar(' ');
                break;

            case '"':
                /* String/property key start, see if clause on top */
                putchar('"');
                is_string = 1;
                break;

            default:
                /* Numbers, true, false, null */
                putchar(ch);
                break;
            }
        }
    }

    return EXIT_SUCCESS;
}

Output

You use putchar quite often. In some instances multiple calls can get replaced by puts or fputs. For example, instead of

putchar(',');
putchar('\n');

you could just use

puts(",");

and instead of

putchar(':');
putchar(' ');

you could use

fputs(": ", stdout);

Either way, if you're striving for performance, you want to keep the number of function calls low, so consider an output buffer if your current variant isn't fast enough for your liking. But first measure your program before you change it.

Goals

Let's revisit your goals and check them now.

  given valid input produce valid formatted JSON output

Since you don't introduce additional characters in strings and never remove characters from the original JSON except whitespace (outside of strings), you've reached that goal.

  constant memory usage

As there is only a single buffer, you've reached that goal too, although fputs might buffer.

  minimal viable program (smallest program that solves a particular problem)

Ah, that's a definition problem. What's minimal? What's "smallest"? Your program is short, but a single additional function removed some repetition which can lead to a technical debt. That function won't increase the size of your program, though.

  feature free

Check.

  easy to read and understand

The ! escaped logic took a little bit, but apart from that, goal reached.

  be C99 compatible

Yes, but use those features I've mentioned above (inline functions, late declarations).

  Also program doesn't handle SIGPIPE, therefore it may be killed. Just tested it. I don't see a clear solution, should I set SIG_IGN?

If the input pipe is broken, the JSON input will suddenly end and you have invalid JSON. Do you need to handle invalid JSON at that point? It's a non-goal, as you said.


Optimize setting parameters from query string

You are correct that it would be much faster to parse all the parameters once into an object and then just access them from there rather than refind every single parameter from scratch each time:

function getParameters(sourceURL) {
    var pairs, parts, i, output = {};
    sourceURL = sourceURL || window.location.search;
    // strip off leading ?
    if (sourceURL.charAt(0) === "?") {
        sourceURL = sourceURL.slice(1);
    }
    // split into individual pairs
    pairs = sourceURL.split("&");
    for (i = 0; i < pairs.length; i++) {
        // split each pair
        parts = pairs[i].split("=");
        if (parts.length < 2) {
            parts.push("");
        }
        // make key always be lowercase and store key/value pair
        output[decodeURIComponent(parts[0]).toLowerCase()] = decodeURIComponent(parts[1]);
    }
    return output;
}

var params = getParameters();

Then, you can fetch an individual parameter anytime from the params object.  In fact, you won't even need to store them all in globals since there already stored in this one variable.

var Query_MenuTiles = params["menutiles"];

Working demo: http://jsfiddle.net/jfriend00/pj5ocazd/


Rather than declaring the variables with let (you should always prefer const) and concatenating and reassigning, consider creating arrays of numbers and dates instead, eg:
[2, 3] and ["2020-09-15", "2020-09-16"]
Then after the loop is done, join all elements by newlines.
For the regular expression, rather than split, I think match would be more appropriate. You can use \((\d+)\) (\S+):

\( - literal (
(\d+) - 1st capturing group, composed of digits
\) - literal )
  - literal space
(\S+) - 2nd capturing group, composed of non-spaces

Then extract the 1st and 2nd capturing groups.

const data = [
  "(2) 2020-09-15", "(3) 2020-09-16"
];
const numbers = [];
const dates = [];
for (const item of data) {
  const [, number, date] = item.match(/\((\d+)\) (\S+)/);
  numbers.push(number);
  dates.push(date);
}
console.log(numbers.join('\n'));
console.log(dates.join('\n'));


First thing first, make it into a function, such that your main will be
int main(){
    const int siz = 6;
    int arr[siz] = {4,6,3,1,3,8};

    std::cout << "Before sort\n";
    printarr(arr,siz);

    sort(arr, siz);

    std::cout << "After sort\n";
    printarr(arr,siz);
}

Since you've tagged it c++, do not use c-style array. Use std::vector. Use std::swap. Currently, it is plain old c. Nothing wrong with it, except the tag.

Optimization wise, well, bubble sort does not deserve it.


Your function looks usable, useful and follows PEP8, well done.
Coupling types and kind together seems like a poor descision. Since functions are firstclass in Python you can just pass the function.

This would change your functions to something like:

my_input(int, msg, msg_wrong, False)

This would have the drawback that if you don't pass a valid function, then it will blow-up. But has the added benifit of allowing more types with less code.

import datetime
my_input(datetime.fromisoformat, msg, msg_wrong, False)

You can also fix the drawback by changing kind to an argument with a default value.

def my_input(msg, msg_wrong, detail, kind=str)
my_input(msg, msg_wrong, True)

It's not immediatly clear why you would want to log only certain errors with the detail argument.

If I were to show or silence errors I would use the logging module.
I'll leave configuring the logger to you, but usage would be:

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

...

def my_input(kind, msg, msg_wrong):
    method = types.get(kind, str)
    while True:
        try:
            value = method(input(msg))
            break
        except ValueError as e:
            logger.debug(e)
            print(msg_wrong)
    return value

...

print(my_input("int", msg, msg_wrong))
logger.setLevel(logging.DEBUG)
print(my_input("hello", msg, msg_wrong))
print(my_input("complex", msg, msg_wrong))

It's not apparent to me why you'd like to log some but not other errors. If being able to change the level of different calls to my_input is of the upmost importance then it'd make more sense to me for you to pass the logging level.

def my_input(kind, msg, msg_wrong, level=logging.DEBUG):
    ...
            logger.log(level, e)

I'm not used to seeing assignment, break and then a return out of a while true loop. When I do this I only use return.

import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

def my_input(msg, msg_wrong, cast=str):
    while True:
        try:
            return cast(input(msg))
        except ValueError as e:
            logger.debug(e)
            print(msg_wrong)

msg = "-> "
msg_wrong = "Error"

print(my_input(msg, msg_wrong, int))
print(my_input(msg, msg_wrong))
print(my_input(msg, msg_wrong, complex))


While this is a reasonable initial attempt, this is not exactly what a modern chess engine would do. In fact, even if you would code the remaining pieces (you only have pawn now), the engine wouldn't be strong.

Before that, we should clear up some chess terminology:

We don't say simulation, we say search
The term AI is okay but even a better term would be engine

There're some very serious issues with your implementation:

You will need to account for transposition. This can be done by hashing.
You should take account of horizon effect by Quiescene Search.
You should really consider alpha-beta search or the related nega-max search.
In your code, you're just trying to brute force all moves in the deep-first fashion, this is absolutely unacceptable for chess programming. The search space will blow your code off. I repeat, you can't search every single position in chess, it's pointless.
What kind of move representation are you using? This looks like a simple array to me, maybe you'd consider a faster implementation?
Why is moving a pawn to the king is an advantage?

Depends on what you want to achieve, if you just want to code something that moves, it's fine. Unfortunately, the current code is nowhere close to anything what a modern chess engine is expected. As an experienced engine developer, I'd rate the code zero. It has lots improvement opportunities.

Please read about alpha-beta for your next attempt.


Console Application Customizer - GetBootstrap v2.7.0

It is normally a good idea to separate data from behavior as this way we follow SOLID guidelines.

I recommend creating a ProgressBar object and maybe a ProgressBarOperationService or the like with the behavior.

The ProgressBarOperationService would receive the ProgressBar that needs the operation in all its methods.


A few things I would do differently:

static char * ReadAllBytes(const char * filename, int * read)
{
    ifstream ifs(filename, ios::binary|ios::ate);
    ifstream::pos_type pos = ifs.tellg();

    // What happens if the OS supports really big files.
    // It may be larger than 32 bits?
    // This will silently truncate the value/
    int length = pos;

    // Manuall memory management.
    // Not a good idea use a container/.
    char *pChars = new char[length];
    ifs.seekg(0, ios::beg);
    ifs.read(pChars, length);

    // No need to manually close.
    // When the stream goes out of scope it will close the file
    // automatically. Unless you are checking the close for errors
    // let the destructor do it.
    ifs.close();
    *read = length;
    return pChars;
}

How I would do it:

static std::vector<char> ReadAllBytes(char const* filename)
{
    ifstream ifs(filename, ios::binary|ios::ate);
    ifstream::pos_type pos = ifs.tellg();

    std::vector<char>  result(pos);

    ifs.seekg(0, ios::beg);
    ifs.read(&result[0], pos);

    return result;
}

Note:

static std::vector<char> ReadAllBytes(char const* filename)

It may seem like an expensive copy operation. But in reality NRVO will make this an in-place operation so no copy will take place (just make sure you turn on optimizations). Alternatively pass it as a parameter:

static void ReadAllBytes(char const* filename, std::vector<char>& result)


Dictionary brute force on DES encrypted passwords

You're keeping us in suspense — I'm dying to know which password matched!

Many password crackers also test for common character substitutions, e.g. o → 0, i → 1, s → $.

Other than that, the general technique seems sound.

I do have a few general remarks, though.

What is #define _XOPEN_SOURCE for?  Sometimes, defining it will change some of the functions you call.  However, it would only have any effect if you put it before your #includes.
It would be good to make a function, even for a simple program like this.  I suggest that main() be responsible for parsing and validating the command line and opening the word list, calling crack(const char *pwhash, FILE *wordlist) to do the actual work.
You don't close the word list if you find a match.
Consider returning a non-zero exit status if the password is not found.  That makes your program more useful to scripts.


Usually I use this approach when I want to create custom views but I don't implement actions inside the view, instead I am using a callback like the click listener :).

Also another minor thing is that there is no need to do getChildAt() so you can find a specific view from a child view if you don't happen to have id's with the same names. Instead you can call findViewById directly on this(the root view).


Adding a duplicate entry randomly into a list in haskell using random monad

It's very good that you structured your code into several smaller functions.

Some ideas for improvement:

Style: It's very useful to stick to a particular style guide and maximum line width. Also I'd recommend to avoid

name = do exp1
          exp2

in favor of

name = do
  exp1
  exp2

because if you need to change name, you need to change the whole code block (and your code is indented unnecessarily to the right).
Do include signatures for all top-level functions. This makes code much more readable and safer (because the compiler helps you typecheck that the function do what you intended). And, it helps to specialize functions properly, for example, with properly typed listEntryDuplicate you won't need those fromIntegral calls.
Function infiniteDuplicateLists can be expressed using mapM and repeat as

infiniteDuplicateLists :: (MonadRandom m) => [a] -> m [[a]]
infiniteDuplicateLists = mapM addRandomDuplicate . repeat

However note that it relies on the fact that MonadRandom allows to traverse infinite lists, which is a bit strong assumption. While it works, I don't think MonadRandom gives any guarantees that it will work in the future. Traversing infinite lists works generally only for some specific monads, see also Why the Haskell sequence function can't be lazy or why recursive monadic functions can't be lazy? Instead I'd recommend sticking to finite lists, like

duplicateLists :: (MonadRandom m) => Int -> [a] -> m [[a]]
duplicateLists n = replicateM n . addRandomDuplicate

In addRandomDuplicate you unnecessarily compute the length of the list twice.

The full code could look like

import Data.List
import Control.Monad
import Control.Monad.Random

main :: IO ()
main = do
    putStrLn $ "list comparison " ++ prettyList list
    g <- getStdGen
    let shuffled = evalRand (duplicateLists count list) g
    putStrLn $ "lists after \n"
               ++ intercalate "\n" (map prettyList shuffled)
  where
    count = 5
    list = ["a","b","c"]

duplicateLists :: (MonadRandom m) => Int -> [a] -> m [[a]]
duplicateLists n = replicateM n . addRandomDuplicate

prettyList :: (Show a) => [a] -> String
prettyList list = " [ " ++ intercalate "," (map show list) ++ " ] "

addRandomDuplicate :: MonadRandom m => [a] -> m [a]
addRandomDuplicate genlist = do
     let l = length genlist
     frompos <- getRandomR (0, l - 1)
     topos   <- getRandomR (0, l)
     return $ listEntryDuplicate frompos topos genlist

listEntryDuplicate :: Int -> Int -> [a] -> [a]
listEntryDuplicate from to list =
      start ++ [repeat] ++ end
    where
      repeat = list !! from
      (start, end) = splitAt to list

Another room for improvement is replacing lists with a better data structure. For small lists it's not necessary, but if you are going to use longer lists, I'd definitely recommend using Seq, whose operations have only O(log n) time complexity as opposed to O(n) for lists. (See also How fast is Data.Sequence.Seq compared to []?)


Xorgens4096 PRNG with global seeder in C#

The only thing I see that needs correcting is the locking.  Remember that

lock (hash) {
    // body
}

is syntactic sugar for:

var local = hash;
try
{
    System.Threading.Monitor.Enter(local);
    // body
}
finally
{
    System.Threading.Monitor.Exit(local);
}

When you update the hash variable in one thread, the next thread to come in will have a different object that it locks, and so the blocks will execute in parallel.  It's usually a mistake to try to reuse part of your model as a lock.  I always recommend a dedicated object like

static readonly Object _lock = new Object();

Other than that, I only suggest:

if (String.IsNullOrEmpty(seed) == false)

should be:

if (!String.IsNullOrEmpty(seed))


Calculate function with optional operator argument

Use a function declaration function rechne2b(a, b, {operator}){ rather than a function expression let rechne2b = function(a, b, {operator}){
There is only a single optional argument so don't use the rest operator ...
The optional argument is passed in an object so you should use destructuring assignment  function rechne2b(a, b, {operator}) to extract the operator if given.
Avoid switch statements if you can by using a lookup (see example)

Rewrite
function rechne2b(a, b, {operator}) {
    const ops = {
        subtrahiere(a, b) { return a - b },
        multipliziere(a, b) { return a * b },
    };
    return ops[operator] ? ops[operator](a, b) : a + b;
}


Better way for securing direct access to php files

Your approach seems good to me.

You can find some alternatives here, but most have downsides (not every server parses htaccess files, get_included_files is self-contained but works differently for different PHP versions, etc).

Additionally, you should think about moving everything outside the web-root that should not be accessible directly.

You might also want to rethink how you handle the error. Using an imperative in the error message gives the impression that the user can fix the error, which they can't. This might confuse legitimate users that accidentally accessed the script. So instead of Please do X, something like You can't access X would be better.

Ideally, you would handle the case of accessing an existing but forbidden PHP file exactly like a non-existing PHP file is handled (for example by showing a custom 404 error page).

And lastly, SECURE isn't that great of a name, as it's very generic. Something like IS_INCLUDED, NO_DIRECT_SCRIPT_ACCESS, or similar might be better.


Calculating average value of points around given point in a wider field

We don't need an x_range. We need a range of proper indices over space, as it enables us to use space[start..stop].iter().sum(). We need a combination of x_range and y_range.
So let's start by building one from hand:
fn local_average((x, y): (i32, i32), n: i32, (width, height): (i32, i32), space: &[i32]) -> i32 {
    let y_range = cmp::max(y - n, 0)..cmp::min(y + n + 1, height);
    let x_range = cmp::max(x - n, 0)..cmp::min(x + n + 1, width);

    let size = (x_range.end - x_range.start) * (y_range.end - y_range.start);
    let mut total: i32 = 0;

    for yi in y_range {
        let start = (yi * width + x_range.start) as usize;
        let end = start + ((x_range.end - x_range.start) as usize);

        total += space[start..end].iter().sum::<i32>();
    }

    total / size
}

Note that the code above was formatted by rustfmt. The rustfmt-style is very common in Rust projects, and several projects reject contributions until they are properly formatted. For cargo based projects use cargo fmt.
Either way, we now replaced the inner loop by a single sum(), which is more explicit about our goal. This is also a mixture of both your code styles. At this point, we might as well replace x_range by x_size, but that's a question of style.
For an easier use of local_average, we could introduce type Point = (i32, i32) and type Rect = (i32, i32), however, again, that's a matter of preference.


Algorithm

your implementation has some serious bugs and unexpected behaviour.

If passing String.Empty as second parameter, it throws an IndexOutOfRangeException
If passing the unique ending part of the first parameter appended by at least one character to the second parameter, it throws an IndexOutOfRangeException

string test = "giladdarmonwhatareyoudoing";
int index = StrStr(test, "ng1");

If you are passing null as either first or second parameter a NullReferenceException is thrown. Here it would be better to throw an ArgumentNullException by using a guard clause.

if (test == null) { throw new ArgumentNullException("test"); }
if (strToFind == null) { throw new ArgumentNullException("strToFind"); }

your implementation could be improved by

checking if strToFind.Length > test.Length
checking if test.Length - i > strToFind.Length

Naming

You shouldn't use hungarian notation. Consider to rename strToFind to searchForm or searchArgument.

Refactoring

After extracting the inner loop to a separate method, removing the now unneeded if (test[i] == strToFind[0]) and implementing the above we will get

public int StrStr(string value, string searchArgument)
{
    if (value == null) { throw new ArgumentNullException("value"); }
    if (searchArgument == null) { throw new ArgumentNullException("searchArgument"); }
    if (searchArgument.Length == 0) { return 0; }

    int searchLength = searchArgument.Length;
    int length = value.Length;

    if (searchLength > length) { return -1; }

    for (int i = 0; i < length; i++)
    {
        if (length - i < searchLength) { return -1; }

        if (IsMatchAtIndex(value, searchArgument, i)) { return i; }
    }
    return -1;
}

private bool IsMatchAtIndex(String value, String searchArgument, int startIndex)
{
    for (int j = 0; j < searchArgument.Length; j++)
    {
        if (value[startIndex + j] != searchArgument[j])
        {
            return false;
        }
    }
    return true;
}

I prefer the above, but you could also add

if (length - i < searchLength) { return -1; }

inverted as condition to the for loop like

for (int i = 0; i < length && length - i >= searchLength; i++)
{
    if (IsMatchAtIndex(value, searchArgument, i)) { return i; }
}


shared_ptr basic implementation for non array types

It might be difficult to get great feedback on this shared_ptr just because it omits so many of the features of std::shared_ptr. I mean I'd be tempted to just list all the features it doesn't have and then fail to review the code at all:

Atomic/thread-safe accesses to the reference count.
Implicit conversion from shared_ptr<T> to shared_ptr<U> whenever T* is convertible to U*.
shared_ptr<void>.
Custom and type-erased deleters.
The "aliasing constructor."
weak_ptr.
Implicit conversion from unique_ptr.
make_shared.

~shared_ptr() noexcept {             // destructor

The comment is redundant. And so is the noexcept: in C++11-and-later, destructors are implicitly noexcept, and it's idiomatic not to write it explicitly.

Contrariwise, it is extremely important to provide a noexcept swap function! You're missing the noexcept keyword here:

void swap (shared_ptr& other) {

By the way, it's weird to put a space between the name of the function and its opening parenthesis. Prefer swap(shared_ptr& other).

You've got a typo in a comment: assignent. Look for typos elsewhere. Where there's one mistake, there's often more than one. (Also, eliminate that redundant comment.)

      --(*ref_count_);
        if (*ref_count_ == 0) {

Your accesses to *ref_count already aren't thread-safe; but FYI, here's where the race condition would sneak in if you just went and made ref_count a pointer to a std::atomic<int>. In a multithreaded environment, it might well be that *ref_count_ == 0, but that doesn't mean that you're the one whose decrement took it to 0.

constexpr shared_ptr() noexcept : ptr_{nullptr}, ref_count_{nullptr} {}

If you used C++11 non-static data member initializers (NSDMIs) for ptr_ and ref_count_, you could =default this constructor.

T *ptr_ = nullptr;
int *ref_count_ = nullptr;

constexpr shared_ptr() noexcept = default;

shared_ptr& operator = (shared_ptr&& other) noexcept {   // move assignment operator
    *this = other;
}

Why did you bother implementing this overload at all, if you're not going to make it more efficient? Either omit it entirely (so that there's only one assignment operator), or implement it as e.g.

shared_ptr& operator=(shared_ptr&& other) noexcept {
    if (this != &other) {
        decrement_ref_count_and_delete_if_needed();
        ptr_ = std::exchange(other.ptr_, nullptr);
        ref_count_ = std::exchange(other.ref_count_, nullptr);
    }
    return *this;
}

By the way, once you make your swap function noexcept, you might consider saving some brain cells by using the copy-and-swap idiom:

shared_ptr& operator=(shared_ptr&& other) noexcept {
    shared_ptr(std::move(other)).swap(*this);
    return *this;
}

  void reset() noexcept {
    decrement_ref_count_and_delete_if_needed();
  }

This is wrong. Consider:

shared_ptr<int> p(new int);
shared_ptr<int> q = p;
p.reset();
assert(p.get() != nullptr);  // oops

  void reset(T* ptr) {
    decrement_ref_count_and_delete_if_needed();
    ptr_ = ptr;
    if (!ref_count_) {
      ref_count_ = new int{1};
    }
    *ref_count_ = 1;
  }

This is also wrong. Consider:

shared_ptr<int> p(new int);  // A
shared_ptr<int> q = p;       // B
p.reset(new int);            // C
p = shared_ptr<int>();       // D
assert(q.use_count() == 0);  // oops!

Line A sets the refcount to 1. Line B increments the refcount to 2. Line C repoints p.ptr_ (but does not change p.ref_count_ — oops!), and then resets the refcount to 1. Line D decrements the refcount to 0 and frees the int that was allocated on line C. Now q.ptr_ still points to the int that was allocated on line A, but *q.ref_count_ == 0.

The correct implementation of reset(T*) is simply

  void reset(T *ptr) {
      *this = shared_ptr(ptr);
  }

(I strongly advise against ever making calls to reset from user code, by the way, because every call to reset can be more readably expressed as a simple and type-safe assignment.)

int use_count() const noexcept {
    return *ref_count_;
}

There's an unspoken precondition here: that use_count() shall never be called on a shared_ptr in the default-constructed ("disengaged", "moved-from", "partially formed") state. If you keep this precondition, then the Lakos Rule would suggest that this function shouldn't be noexcept. However, I think it would be more natural to write

int use_count() const noexcept {
    return ref_count_ ? *ref_count_ : 0;
}

so that the function always has well-defined behavior.


Python beginner looking for feedback on simple dice game

I'm pretty new as well, but I like to create an exception whenever I try to convert user input to an integer. Something like this-
while True:
    try:
        number_of_dices = int(input("How many dices would you like to roll?"
                                    " (0 to quit) >"))
    except ValueError:
        print("Please enter a number.")


While your solution appears to work, and I cannot see any bugs, there are a number of best-practices that you are not employing in your solution. It is alsmost as if your code works by coincidence, rather than by design. There are a number of things that look like desperate attempts to make it work... and, like duct-tape, they work, but they are not pretty.

General

You have not described your algorithm in any detail. You have two recursive calls in your recursive method, and you have no documentation as to why. Recursion, in general, is relatively complex to understand, and can be unintuitive. You should help the person reading your code to understand.... and you do nothing. I had to debug the code to watch it happen to understand why you do things the way you do. This is not fair.

Naming conventions

Your Set<PlatePair> is called platePair. At minimum the variable name should be a plural, because, as it stands, it makes sense that platePair is a single PlatePair, and not a Set<PlatePair>. My preference would be 'moves' which indicates what the data represents

Oh, your class is called ToweOfHanoi, but should contain an 'r' as in TowerOfHanoi

Collections

Speaking of Set<PlatePair> ... really? Your actual implementation of the Set<PlatePair> is a LinkedHashSet. The LinkedHashSet will iterate the results in the same order they were inserted, which is why this solution actually works, but, you do not expose that property of the LinkedHashSet to the calling functions. There is nothing stopping a user from calling:

Set<PlatePair> result = new HashSet<>();
moveTowers(4, "A", "B", "C", result);

and this would produce crap results.

Frankly, you should not be using a set at all. You should be using a List.... because that is what it is, a List of moves to make.

This is your duct tape LinkedHashSet is a desperate solution to trying to bring order to a data collection that is designed to maintain unique contents (a Set) rather than an ordered collection of non-unique data (a List). Your moves are not unique... you often move a tile from tower A to tower C.... but, you use the the HashSet with unique move instances (instead of the neater move-reuse mechanism).

A more immediate solution is to change the moveTower from being a public method to being a private method, which you should do anyway. There is no need for it to be public. Making it private would also affect the assert in the method.... you assert that the platePair instance is not null, but you do not check the from/using/to instances. That is careless. If you are going to assert, then do it comprehensively. In this case, if the method is changed to be private, I would simply remove the asserts, and move on.... you do trust your own code, right?

PlatePair

Which comes down to the next problem, The PlatePair class. This class should have a number of differences. Firstly, the values should not be Strings, they should be an ENUM, one member for each tower.

public enum Tower {
    A, B, C;
}

public class PlatePair {
    private final Tower source, destination;

    public PlatePair(Tower source, Tower destination) {
        this.source = source;
        this.destination = destination;
    }

    public Tower getSource() {...}
    public Tower getDestination() {...}

}

I would also strongly encourage you to avoid creating so many PlatePair instances.... there are only 6 possible moves that can be made... each Tower can only be the source/destination of 2 possible moves. You should only have 6 PlatePair instances, and they should be immutable, and have good hashCode() and equals() methods.

Also, I don't like the class name PlatePair. It is not a pair of Plates, it is an ordered pair of Towers... a source, and a destination. I would rename it something like Transfer.

Conclusion

The code works, and gets the right answers. It does not read very well, and there are a few gotcha's in the code which mean you have to dig in to the code and understand the 'tricks' you are playing. The documentation/comments are really poor, and this code would fail any formal review in any sane business.

I have taken your code, and restructured it using the ideas I have shown above. This is closer to something that I would consider readable. Note, I have not changed the algorithm at all:

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;

enum Tower {
    A, B, C;

    static {

        // make each tower know what moves are possible from that tower.
        // tower A can have a transfer to towers B, and C.
        // tower B can have a transfer to towers A, and C.
        // tower C can have a transfer to towers A, and B.
        // these 2 transfers per tower are available through the getMove(destination)
        // method for each tower.
        A.setupTransfers(B, C);
        B.setupTransfers(A, C);
        C.setupTransfers(A, B);

    }

    private EnumMap<Tower, Transfer> destinations = null;

    private void setupTransfers(Tower one, Tower two) {
        destinations = new EnumMap<Tower, Transfer>(Tower.class);
        destinations.put(one, new Transfer(this, one));
        destinations.put(two, new Transfer(this, two));
    }

    public Transfer getMove(Tower destination) {
        return destinations.get(destination);
    }
}

final class Transfer {

    private final Tower source;
    private final Tower destination;

    public Transfer(Tower source, Tower destination) {
        this.source = source;
        this.destination = destination;
    }

    public Tower getSource() {
        return source;
    }

    public Tower getDestination() {
        return destination;
    }

    @Override
    public int hashCode() {
        return (31 * source.hashCode()) ^ destination.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj instanceof Transfer) {
            return ((Transfer) obj).source == source
                    && ((Transfer) obj).destination == destination;
        }
        return false;
    }
}

public final class TowerOfHanoi {

    private TowerOfHanoi() {
    }

    /**
     * Solves the Tower of Hanoi problem
     *
     * @param n
     *        The number of plates on the starting tower
     * @return The sequential steps required to solve the problem.
     */
    public static List<Transfer> solve(int n) {
        if (n <= 0)
            throw new IllegalArgumentException("The number of plates " + n
                    + " should be greater than zero.");

        final List<Transfer> moves = new ArrayList<Transfer>();
        moveTowers(n, Tower.A, Tower.B, Tower.C, moves);
        return moves;
    }

    private static void moveTowers(int n, Tower from, Tower using, Tower to,
            List<Transfer> moves) {

        if (n == 0) {
            return;
        }

        // algorithm is:
        // we want to move the 'bottom' tile from the 'from' tower to the 'to'
        // tower.
        // we move everything on top of it to the 'using' tower
        // then we move the tile to the to tower,
        // then we move the things from the using tower back on top of the tile
        // we moved.

        // temporarily move everything on top to the using tower.
        moveTowers(n - 1, from, to, using, moves);
        // move the actual tile.
        moves.add(from.getMove(to));
        // move the temp stuff back on to the tile we just moved.
        moveTowers(n - 1, using, from, to, moves);
    }

    public static void main(String[] args) {
        for (final Transfer getHanoi : solve(4)) {
            System.out.println(getHanoi.getSource() + " : "
                    + getHanoi.getDestination());
        }
    }
}


If the score label is updated while the animation is still running, then
the update is simply ignored. For example, with

[_pointsLabel updateForScore:100];
[_pointsLabel updateForScore:200];

the label will animate to 100 and stay there, instead of animating to 200.

Instead of pre-computing all actions from the current score to the final value,
I would start only a single action that will display the next intermediate score, e.g. from 100 to 110. When that action has completed, start a new action.

This approach solves the problem of simultaneously running actions, and makes
both _isAnimationPlaying and the _actionQueue obsolete. Each time an action is created,
it can check whether the counter has to be incremented or decremented.
The animation is always in steps of 10, e.g. an update from 13 to 51 will
display 13, 23, 33, 43, 51. It would look nicer if multiples of 10 are displayed
where possible, in this case 13, 20, 30, 40, 50, 51.
The animation is too fast. At last on my Simulator it was running so fast that
not all intermediate steps can be recognized. I would add an small delay
between the actions.
The updateForScore: method is not really necessary. I would make score
a (public) property and override the setter method, so that

_pointsLabel.score = newValue;

updates the score and starts the animation.

Then your implementation could look like this:

BZAnimatedScoreLabel.h

@interface BZAnimatedScoreLabel : SKLabelNode
+(BZAnimatedScoreLabel *) labelWithText:(NSString *)text score:(int)score size:(int)fontSize;
@property (nonatomic) int score;
@end

BZAnimatedScoreLabel.m

#import "BZAnimatedScoreLabel.h"

@implementation BZAnimatedScoreLabel {
    SKLabelNode *_scoreLabel;
    int _currentScore; // The currently displayed score
}

#pragma mark - Constants

static NSString *kAnimationKey = @"BZLabelAnimationKey";
static const NSTimeInterval kAnimationDelay = 0.02;

#pragma mark - Initialization

+(BZAnimatedScoreLabel *) labelWithText:(NSString *)text score:(int)score size:(int)fontSize {
    return [[BZAnimatedScoreLabel alloc]initWithText:text score:score size:fontSize];
}

-(instancetype) initWithText:(NSString *)text score:(int)score size:(int)fontSize {
    self = [super initWithFontNamed:@"Arial"];
    if (self) {
        self.text = text;
        self.fontSize = fontSize;
        self.fontColor = [SKColor whiteColor];

        _currentScore = _score = score;
        _scoreLabel = [[SKLabelNode alloc] initWithFontNamed:@"Arial"];
        _scoreLabel.fontSize = fontSize;
        _scoreLabel.fontColor = [SKColor whiteColor];
        _scoreLabel.position = CGPointMake(fontSize * 4, 0);
        _scoreLabel.text = [NSString stringWithFormat:@"%i", score];
        [self addChild:_scoreLabel];
    }
    return self;
}

#pragma mark - Animation

-(void)setScore:(int)score {
    _score = score;
    [self updateDisplay];
}

// Compute next multiple of 10 from _currentScore in the direction of _score:
-(int)computeNextScore {
    int next;
    if (_score > _currentScore) {
        if (_currentScore >= 0) {
            next = ((_currentScore + 10)/ 10) * 10;
        } else {
            next = ((_currentScore + 1)/ 10) * 10;
        }
        if (next > _score) {
            next = _score;
        }
    } else if (_score < _currentScore) {
        if (_currentScore <= 0) {
            next = ((_currentScore - 10) / 10) * 10;
        } else {
            next = ((_currentScore - 1) / 10) * 10;
        }
        if (next < _score) {
            next = _score;
        }
    } else {
        next = _score;
    }
    return next;
}

-(void)updateDisplay {
    if (_score != _currentScore) {
        SKAction *wait = [SKAction waitForDuration:kAnimationDelay];
        SKAction *update = [SKAction runBlock:^() {
            _currentScore = [self computeNextScore];
            _scoreLabel.text = [NSString stringWithFormat:@"%i", _currentScore];
        }];
        SKAction *checkAgain = [SKAction performSelector:@selector(updateDisplay) onTarget:self];
        [self runAction:[SKAction sequence:@[wait, update, checkAgain]] withKey:kAnimationKey];
    } else {
        [self removeActionForKey:kAnimationKey];
    }
}

@end

_currentScore is the currently displayed score, and the computeNextScore
method computes the next value to be displayed. It looks a bit complicated,
but it works correctly for both positive and negative scores.

updateDisplay starts a sequence of three actions (if necessary): wait
is for the delay, update computes the next score to be displayed and
updates the label, and checkAgain causes the updateDisplay method to
be called again.

The sequence action is created with a key. This has two advantages:
The action can be removed, and starting a new action with the same key
will automatically stop the previous action.


Removing Dicts with Null values from Only the End of a List

Some suggestions:

You are using i both inside your list comprehension and outside. This makes the code harder to follow than if the variables were differently named. For example, you could think of the outer i as the count of matching (that is, all None values) dictionaries at the end of the list.
Hungarian notation abbreviations like lst and dct don't tell me anything about what the variables actually are. In an actual application this should be possible, but more context would be needed for that.
You say "remove all dicts with null values", but you neither specify nor test what happens with a dictionary having some None values and some non-None values at the end of the list. As far as I can tell from your implementation you remove only entries with all None values, but it's not clear whether this is the intention.
I would pull out the tuple passed to next as a separate variable for clarity.


Rendering a large collection using BackboneJS and LoDash

You code looks good, I only can give a few suggestions:

I find it more convenient to use ...bind(this) instead of var self = this; - in this case the extra variable is not necessary the code looks better.
Maybe it is better to use an index within the array - in this way the array will not be copied several times. Of course, the JS is highly optimized internally, but it is a good to help it a little.
Rendering 10.000 items is still very CPU consuming process (especially on mobile devices) so maybe use the similar approach that you have used with images and build the next chunk only when the user scrolled down to the end?


Decoding a telephone number that was masked with letters from the respective keys with APL

I am particularly interested in a better way to create the classes variable, [...] this ordering depends obviously on the order of splits.

Because ASCII codes of A..Z come later than those of 0..9, we can't shorten the classes array itself. Instead, we can lengthen it, so that classes becomes simply two copies of 0..9. You can create unused intervals by copying the boundary item that comes after them:

    'BBB' ⍸ 'ABCD'
0 3 3 3

Incorporating it in Telephone:

  splits ← ⎕D, 'AAADGJMPTW'
  classes ← ,⍨ 1 -⍨ ⍳10

Nitpicking: When I need to subtract 1 from an expression, I use ¯1+expr instead of 1-⍨expr because the former reads better to me. This is a personal choice though. Or, if the "subtract 1" appears only for generating 0..n-1 instead of 1..n with ⍳, consider using ⎕IO←0.

Now, splits is creating the interval indices 0..20, and except the first 0, each index is mapped to 0..9,0..9.

interval index: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
class         : 0 1 2 3 4 5 6 7 8 9  0  1  2  3  4  5  6  7  8  9

Do you see the pattern? If you discard the unused interval and take modulo 10, you get the right class! Then you can entirely discard the variable classes and extra indexing:

Telephone ← {
  splits ← 1↓ ⎕D, 'AAADGJMPTW'
  10| splits ⍸ ⍵
}


I notice a very bad (anti-)pattern that you're using. You're polling. "Wake up frequently to check if there's any work, if not go back to sleep". The thread demands to be woken up every 1ms or so. This will cause a big burden on the OS thread scheduler and hinder performance. It also prevents your CPU from going to sleep (low power mode) so the power usage and heat generated by your CPU will greatly increase.

What you should do instead is to have your thread stay asleep until the next time that an event is scheduled to occur. Make sure your sleep has a method of being interrupted in case a new event comes in. Look up "condition variables". (#include <condition_variable>)

Secondly, you're treating std::map as if it's thread-safe. It's not. If the main thread is modifying the map at the same instant that the scheduler thread is checking it, bad things can happen. Spooky bugs that occur intermittently and are impossible to recreate or trace. You need to use a thread-safe data structure (or control access using some kind of locking mechanism, which you'll need anyway for the condition variable) if you're going to share it between multiple threads.

Let me make it clear: don't expose the actual std::map to the event providers. All access must go through methods that enforce proper object locking (and wake up the thread if necessary).

If you want to be able to expand this, you really need to make it its own class with a specific interface -- then you can define the implementation however you wish. The operations could be: add an event, remove an event, scheduling on, scheduling off, list all events, enumerate events one by one, change time of an event, change action of an event, remove all events.


As you yourself noted, you need a function:

def financial_info(acronym):
    company = Share(acronym)

    company_open = float(company.get_open())
    company_current = float(company.get_price())

    if company_open > company_current:
        print(company, " is down for the day. Current price is ", company_current)
    else:
        print(company, " is up for the day! Current price is ", company_current)

    # ...

I just wrote a part of it, you sure are able to finish it :)


Python script which fetches Amazon product details using its API

This should be a short review mainly because your code looks pretty nice.

I don't have any experience with the Amazon API, but from what I can tell you are using it as I would expect it to be used.

The only points that I want to speak on and can nit-pick are:

Your variables asin_regex and isbn_regex are slightly misleading. In Python there is a distinction between regular expression patterns and regular expression objects. The suffix _regex implies that, by itself, the variable can recognize expressions which, in turn, implies the variable is a regular expression object. Because your variables cannot, by themselves, recognize expressions, I would use the suffix _pattern.
Your logic in get_amazon_id is completely fine. Its my personal preference, in this case where you are simply returning inside the if blocks, to just use if statements, no elif or else blocks:

if asin_search:
    return asin_search.group(1)
if isbn_search:
    return isbn_search.group(1)

return None

  The above is strictly personal preference, simply getting another version out there.

However, what I would recommend doing is use a for loop to reduce some of the minor code repetition and make your code more flexible:

for search in asin_search, isbn_search:
    if search:
        return search.group(1)
return None

The above code would be best if, say, for some reason another ID type came out. So, instead of having to add another if statement, all you need to do is add new_id_search to the for loop list.
I would change your regex patterns to use the \w and \d characters:

asin_regex = r'/(\w{10})'
isbn_regex = r'/(\d{10})'

The \d character would just make your currently short regex even shorter, while the \w character helps protect against the case that for some unknown reason the ASIN or ISBN contains lower-case characters.
Finally, I would capitalize the first word of all your comments (unless it is a variable name).


I see two obvious problems:

Your MySQLi queries are vulnerable to sql-injection since you are constructing the queries using string interpolation.  You should use properly parameterized queries with ? placeholders instead.
The business logic is heavily intertwined with the HTML generation.  You would be better off handling the input first (using PHP more like a programming language), writing the order to the database, then when the transaction has successfully completed, proceed to display the output (using PHP as a template language).


Animation that cycles through background colors

The #big and #small divs are actually the same size.  Therefore, I would rename them to #outer and #inner.  You can use the same CSS rules for both.

There's no need to specify the opacity in the stylesheet, since the opacity will be controlled by the jQuery animation.

I'd renumber your classes starting from 0 so that you can take advantage of the modulo operator.  The JavaScript code just looks cleaner with %.

The function-returned-by-a-function would be easier to understand if you make the outer scope into an object.  It also deserves to have a better name than call.

All of the jQuery operations on $('#small') should be done in the same chain.

Clearing the class then calling addClass() is a roundabout way of just setting the class property.

function() { call(); } could just be simplified to call.

function ColorAnimation(speed) {
    var x = 0;
    var self = this;

    this.run = function() {
        x = (x + 1) % 4;
        var y = (x + 1) % 4;
        $('#outer').prop('class', 's' + y);
        $('#inner').prop('class', 's' + x)
                   .text(x + 1)
                   .css({ opacity: 1 })
                   .animate({opacity: 0}, speed, self.run);
    };
};

new ColorAnimation(3000).run();
#outer, #inner {
    width: 100px;
    height: 100px;
    position:relative;
    color:#fff;
}

.s0 {
    background:gray;
}
.s1 {
    background:blue;
}
.s2 {
    background:yellow;
    color:#000;
}
.s3 {
    background:brown;
}


JS composition - Components depend on others

In a case like this I would use mixins (though not everyone agrees when it comes to mixins vs composition). I would write this something like:

let BodyMixin = {
    getPosition:   function(){ /* Returns x and y */ };
    getDimensions: function(){ /* Returns width and height */ };
}

let DrawableMixin = {
   image: function(image) {
        var position   = this.getPosition();
        var dimensions = this.getDimensions();
        // Use image, position and dimensions to draw an image on a canvas
   }
}

function Tree(x, y){
}
Object.assign(Tree.prototype, BodyMixin, DrawableMixin);

Then your call would just be:

tree.image('tree.jpg');

Note: if you are using TypeScript or something similar there are other ways to implement mixins.

-- Update 1:

It might also be worth doing something like:

let BodyMixin = {
    initializeBody:      function(x,y,w,h) { ... };
    ...
}

function Tree(x, y){
    this.initializeBody(x, y, 100, 100);
}
Object.assign(Tree.prototype, BodyMixin, DrawableMixin);


if (el.textContent.indexOf("office is closed" > -1)) {
    el.style.display = "none";
}

Does this help?

Or if you know that hero-action is talking about Office, as in you are confirmed, then you can simply check for the word close rather than checking the whole string.


There's value in factoring the logic out into one or more new functions, even if those functions are only used in a single place, because it can make the code easier to understand and modify.

In a situation like that (when the logic won't be used elsewhere) I often use letfn. The letfn could be either internal or external to the function itself but I see that as a purely stylistic decision.

Here's the ClojureDocs page on letfn. See Pedestal's dataflow logic for a few examples of letfn in use.

On the other hand, there's really no problem with having a top level function that's only used in one place. I like that letfn implicitly communicates the function's scope of relevance, but I don't think either way is objectively superior to the other.


Simple answer: No. Unless if your application only ever runs on 1 thread.

The easiest way to lazy initialise a singleton thread safe would be with a holder pattern. Example from wikipedia:

public class Something {
    private Something() {}

    private static class LazyHolder {
        static final Something INSTANCE = new Something();
    }

    public static Something getInstance() {
        return LazyHolder.INSTANCE;
    }
}

This is thread safe because the java class loader ensures that the INSTANCE is initialised exactly once, when the LazyHolder class is used for the first time.

Since the database you initialise isn't known at compile time in this class you cannot use this pattern. What you can do is a pattern called double-checked locking:

public final class Singleton {
    private static volatile Singleton instance = null;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized(Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

Important here are the synchronized(...) and volatile keywords.
The synchronised part makes sure only 1 thread can execute the construction code. And the volatile ensures that all threads always see all changes to the variable.


Generic merge sort in C++ using a user-defined comparison function or the < operator by default

Avoid a copy by passing by const reference.

[](RandomAccessIterator::value_type const& a, RandomAccessIterator::value_type const& b) { return a < b; }
                                    ^^^^^^                                     ^^^^^^

Don't need an if statatement here:

if (itUpper == last)
    std::copy(itLower, first + m, itResult);
else
    std::copy(itUpper, last, itResult);

One of these ranges will be empty and just do nothing.

std::copy(itLower, first + m, itResult);
std::copy(itUpper, last, itResult);

To avoid a copy (which can be expensive on non POD types). Prefer to use move.

std::move(itLower, first + m, itResult);
std::move(itUpper, last, itResult);

std::move(v.begin(), v.end(), first);

You spend a lot of time creating the temporary array:

std::vector<RandomAccessIterator::value_type> v(last - first);

Basically this causes calls to new for every call to void mergesort(RandomAccessIterator first, RandomAccessIterator last, Compare comp). You can optimize this by allocating the temp space once in void mergesort(RandomAccessIterator first, RandomAccessIterator last) and pass the section of the temp array that recursive function can use.

I know you are trying to be explicit with RandomAccessIterator. But it is more traditional to use single letter for template types. Also there is no compiler validation that your iterator is random accesses (so you are giving a false sense of security to your user).

C++20 should add Concepts (finally). Single letter template types will work well with this.

 template<typename I>
 requires RandomAccessIterator<I>
 void mergesort(I begin, I end){}

For C++ pre 20 You can write:

 template<typename I>
 // requires RandomAccessIterator<I>
 void mergesort(I begin, I end){}

Which provides the same information and when concepts are added you can just remove the comment.


Checking if the access token is valid or expired

You seem to ignore two facts.

The client clock can be out of sync with the server clock.

The transport of the request from client to server takes more then zero time.

Both these cases mean that no matter how hard you try on the client side, there is always a chance that the server will evaluate the token as expired during its processing.
What you should do is have the client take the same action when server refuses the token as you do when your client side validation fails.
In general, client side validation

is not necesary
is not reliable
reduces network traffic
increases user experience

Whereas backend side validation

is necesary
is the only source of truth

Clients should understand and handle possible server side validation errors prior to deploying their own validation logic.


I would first suggest logging the database operation to see what SQL is executed.  EF may not be running the SQL you think it is.

The red flag I see is that you call ToList before the Skip and Take.  Generally in LINQ statements, ToList forces execution immediately.

This suggests your EF code is pulling every record from the table up front, building a list, and then applying the Skip/Take to the list.  If that's the case, the logged SQL should show a select statement without any filtering.

I suspect what you really want to do is run the ToList after the Skip and Take.  This should apply the filtering inside the executed SQL, but the logging will show you for sure.


First suggestion: clean up your code. There are a ton of inconsistencies in variable names, indentation, brackets, defines ...

Variables

I was confused when seeing g_ variables in your game.h file, suggesting that these were global variables yet they are declared as member variables. My guess is that you moved away from global variables (which is a good idea) but forgot to fix the naming. I know it's annoying to change all those names now, but it'll save you a lot of time in the long run and many modern IDE's offer refactoring tools. Keep in mind that full-caps member names (such as FRAMES_PER_SECOND) are used to indicate constants or defines. In another file, Player.h, you use m as prefix. Be consistent, either use the m_ and g_ or m and g prefixes everywhere.

Moving away from global variables is a good idea because they are often quick hacks but often they can do more bad than good in the long run. Imagine declaring g_GameTime as a global variable, and using that in every manager. But when we want a single manager to update at half speed to mimic slow motion, we'll have to do nasty things. So in my opinion it's better just to give the time as a parameter to every manager.

Defines

Header guards should be the first thing in a header file. In game.h this is not the case, so move those ifdef's up to save some compile time and potential compile errors.

Const correctness

If I call a function such as

bool Game::isRectCollision(sf::RectangleShape &sprite1, sf::Sprite &sprite2)

I want to be sure my parameters and base object will not be modified. (If calculating if two rectangles intersect requires non-const parameters (so possibly changing that rectangle), something fishy is going on). The general rule should be to mark everything as const unless it is inpossible:

bool Game::isRectCollision(const sf::RectangleShape &sprite1, const sf::Sprite &sprite2) const

Now, regarding your animation smoothness/stuttering problem. The following while loop is a bit weird:

while(timeSinceLastUpdate > TIME_PER_FRAME)

Since update is inside this loop and render is not, it is possible that we do not update and render the same state of the game again. The other way around: it is possible that we update the game twice but only render once. Both of these scenarios are wrong. The first one because we are going to render the exact same scene again, the second one because we're going to calculate how the scene should look like and then do nothing with the result, but rather calculate it again. For starters, try to replace this second while loop with an if and place the render functions inside of it.


Hackerrank: Count the number of palindromes in a given string

For each position in the string your code checks all substrings that start at that position. For example, for s = 'a2b3bb3443bab' and i = 3, the code checks '3', '3b', '3bb', '3bb3', ..., '3bb3443bab'. That is O(n^2) strings to palindrome check.
Instead, for each position in the string, check for palindomes that are centered on that position. For example, for s = 'a2b3bb3443bab' and i = 3, check the substrings '3', 'b3b', and '2b3bb'.  Stop there, because no other string centered on i = 3 can be a palindrome.  It also needs to check for palindromes with an even length such as at i = 4, where we check 'bb', '3bb3' and stop at 'b3bb34'.  I think it's O(n*p) where p is the average length of a palindrome (which is less than n).  It seems to take about 2/3 as long as you code.
def pcount(s):
    count = 0

    for i in range(len(s)):
        # count the odd-length palindromes
        # centered at s[i]
        j=i
        k=i
        while j>=0 and k<len(s) and s[j] == s[k]:
            count += 1
            j -= 1
            k += 1

        # count the even-length palindromes
        # centered at s[i:i+1]
        j = i
        k = i + 1
        while j>=0 and k<len(s) and s[j] == s[k]:
            count += 1
            j -= 1
            k += 1

    return count


Here's what I would change :

The answer to the question (see 200_success comment) states that the only thing that is hard to spoof is REMOTE_ADDR, so you should put this value first in your array.
I'm not a big fan of your double test (isset and filter_var). I would like to trust that the implementation of filter_var is a good one and that it does test the emptyness of your variable before going any futher, but I'm not sure. Anyway, I'll just keep the test with filter_var .
Not a big fan of your define either, why do you want to use a constant ? I would initialize a variable userIP before the foreach to false, so there's only one test to do after the loop.

One thing that worries me a bit is the existence of a case where filter_var would succeed but inet_pton would fail (for the same value). It should not exist, but if it does, you might exit your loop with userIP equal to false, while there is one valid IP in one of the following server variables. So just to be sure, I would add a test on inet_pton before breaking out of the loop.


No, it is simpler to code than that:

enum Singleton
{
    INSTANCE;

    // instance vars, constructor
    private final Connection connection;

    Singleton()
    {
        // Initialize the connection
        connection = DB.getConnection();
    }

    // Static getter
    public static Singleton getInstance()
    {
        return INSTANCE;
    }

    public Connection getConnection()
    {
        return connection;
    }
}

Then you use can use final Singleton s = Singleton.getInstance(). Note however that since this is an enum you can always access this via Singleton.INSTANCE.

And NEVER do that:

public Singleton getInstance(){
    if(s==null)
        return new Singleton();
    else return s;
}

this is not thread safe! What is more, the new Singleton() value is never assigned to s... (thanks @DaveJarvis for noticing this!)


Computing the distribution of a Jonckheere-Terpstra statistic

I didn't read in it's entirity, but change this line

static int mannwhit(std::vector<int> c, std::vector<int> sizes)

to

static int mannwhit(const std::vector<int>& c,
                    const std::vector<int>& sizes)

This won't speed up your code but you should use

#include <cstdio> //instead of stdio.h

and memset will need to be prefixed as std::memset.

Also ensure you compiler is compiling at 02 and with out debug flags.


I would like to know if the following code is 'good'

For overall quality, I'd give this about a 2 or maybe a 3 (on a scale of 1-10). Honestly, even 3 is being pretty generous though.

#include <iostream>   // C++ IO library code to include.
#include <string>     // C++ string functions.
using namespace std ; // Use standard C++ names for functions.

using namespace std; is generally frowned upon. There are reasons for using a namespace, but doing it globally like this (especially with the stdnamespace) is just a lousy idea.

//====== class declaration.

I'm sort of split on this one. On one hand, vacuous comments like this are generally worse than useless. At the same time, given that it's written exclusively for teaching, it may be excusable to include a few things we'd normally reject, describing basics of how C++ works. This would be a no-no in real code, but under the circumstances it's understandable and (I guess) reasonable.

class Tpacket_list
{public: // functions that are available to code outside the class.

Your teacher seems to be working hard at disproving the usual wisdom about formatting. Most people figure that the exact formatting you choose is less important than using it consistently. This is one of the few I've seen that really does seem to make the code more difficult to read.

    // put the command line into the list.
    Tpacket_list(int param_index, string param) ;
    void print_list() ; // print the list.
    Tpacket_list* find( string target) ;
    int    tell_id() ;
    string tell_payload() ;

The comment here is misleading at best. The code to put the command line into the list is elsewhere (somewhere down in main).

 protected:                //  Data in a class is normally hidden from other code.
    string payload ;       // C++ strings are classes so this is aggregation.
    int id ;               // Such strings are more powerful and easier to use
    Tpacket_list *next ;   //   than the older C string routines, also slower!
} ;

Here we have a real design problem. He's conflating two ideas that should be completely separate: a linked list, and a node in a linked list. To work at all well, a linked list nearly needs to separate the two:

class list {
    struct Node {
        int id;
        std::string param;
        Node *next;

        Node(int param_index, std::string const &p) :
            id(param_index), param(p)
        {}
    }

public:
    list(list const &);
    // ...
private:
    node *list_head;
};

In this case, a node is pretty much just dumb data; the list class has all the real "knowledge" of how to do useful things. Also note that in reality, this should almost certainly be a class template instead of an actual class. Instead of hard-coding an int and a std::string as the types of data being stored, we really want to make those template parameters so we can create a linked list holding any kind of data we want.

Tpacket_list *list_head ;  // Start of linked list, set to 1st item.
Tpacket_list *work_ptr ;   // Work pointer to work along list.

"Daddy, he defined a global!"
"Son, what have I told you about using language like that?"

//====== Class Body =========================================================

//------ Constructor gets called when the class is created. It puts in the
//       payload and sets up the chain of pointers.All this is hideen from
//       the user of the class.

I'll repeat the earlier comment about comments for emphasis: while (barely) acceptable under the circumstances, these would clearly have no place in real code.

Tpacket_list::Tpacket_list(int param_index, string param)
{//--- save information for this parameter.
   id = param_index ;
   payload = param ;
   cout << "    Adding parameter # " << id << ", value = " << payload << endl ;
 //--- form list.
   next = list_head ;
   list_head = this ;
}

This code has quite a problems. First of all, you should generally prefer initializing the members in an initializer list:

Tpacket_list::Tpacket_list(int param_index, string param) :
    id(param_index),
    payload(param)

OTOH, per the earlier comment, this code should really be in Node::Node instead. From the viewpoint of the linked list, this code shouldn't be in a ctor at all. Following the usual conventions for C++, this would be a function named push_front (and it would normally only take one data type as the input -- to store an int and a std::string, we'd put those together into a struct of some sort -- an std::pair, if nothing else.

//------ Print the list.  Note how the function calls the print_list function
//       in the next item in the link list.
//       Function prints from the current link list item to the end.
void Tpacket_list::print_list()
{//---
   cout << "    id = " << id << ",  payload = " << payload << ", length " << payload.length() << " characters."<< endl ;
   if ( next != NULL) // if there is a next item, get it to print itself.
     next->print_list() ;
}

IMO, the very existence of this function is a problem. To print out the contents of a list, we really want to apply an algorithm (e.g., std::copy) to the list (or some subset thereof). To do that, our list should define begin() and end(), which return list iterators. The iterator type should define (at least) operator++ to traverse the list. In our case, the iterator type would be a fairly thin wrapper around a pointer to a node:

class list {
    class Node { /* ... */ };

    // warning: typing this in off the top of my head. It probably has at least a few
    // problems.
    class iterator {
        Node *pos;
    public:
        Node operator*() { return *pos; }
        iterator &operator++() {
            if (NULL == pos)
                return NULL;
            pos = pos -> next;
            return *this;
        }
        bool operator==(iterator const &other) {
            return pos == other.pos;
        }
    };

This way, when we want to print out a list, we can use the same algorithms (and idioms in general) that we can with any of the other containers in the standard library.

//------ Find item in the list.
Tpacket_list* Tpacket_list::find( string target)
{//---
   if ( payload == target)
      return ( this) ;          // return pointer to current object.
   if ( next == NULL)
      return( NULL) ;           // end of list, not match, return NULL.
   //--- if got here there is a valid next.
   return( next->find( target)) ;
}

Again, probably pointless -- instead of a find member function, provide a conforming iterator type so you use use std::find (among other things).

//------ Tell of internal data.
int    Tpacket_list::tell_id()
 { return( id) ;
 }

string Tpacket_list::tell_payload()
 { return( payload) ;
 }

I can't say I like these much, but they're about the only thing so far that isn't obviously/blatantly wrong...

//====== Start program here =================================================

int main(int argc, char *argv[]) // argc = number strings on command line.
                                 // argv is array of strings each holding
                                 //   a parameter.

{//--- Initialize link list with command parameters.
   cout << endl << "  Form link list of command line parameters." << endl ;
   list_head = NULL ;
   int i = 1 ;
   while ( i < argc)
    { new Tpacket_list(i, argv[i]) ;
      i++ ;
    }

Here we see the bad effects of the poor design. This code claims to create (and, incidentally, leak) argc-1 separate Tpacket_lists. In reality, it creates a single linked list, because the ctor does an implicit push_front on the (singular) global linked list represented by the nasty global. For usability we clearly want something like this:

    linked_list<std::pair<int, std::string> > list;

    for (int i=1; i<argc; i++)
        list.push_back(std::make_pair(i, argv[i]));

 //--- print out the list.
   cout << "  Print paramters from head of list the end of list." << endl ;
   if ( list_head != NULL)
        list_head->print_list() ;
   else cout << "   List is empty." << endl ;

Then, to print out the list, we'd have code like:

if (list.empty())
    std::cout << "List is empty.\n";
else
    std::copy(list.begin(), list.end(),
        std::ostream_iterator<std::pair<int, std::string>(std::cout, "\n"));

and of course:

 //--- search for parameters
   cout << "  Find first 0 parameter (working last to first parameter, list head to tail)." << endl ;
   Tpacket_list *found ;
   if ( list_head != NULL)
     { found = list_head->find("0") ;
       if ( found != NULL)
            cout << "    Found target on parameter # " << found->tell_id()  << endl ;
       else cout << "    No \"0\" found." << endl ;
     }

...searching in the linked list would be done with std::find instead of writing our own (clumsy) imitation.

As a final note, since the linked list allocates Nodes dynamically, we almost certainly need to provide a dtor that will delete those nodes. We also want to either provide a copy ctor that will copy the nodes, or else declare the copy ctor privately1 to prevent anybody from copying a linked list at all.

1 In C++11, we could use the =delete syntax to remove it as well, but it may be a bit premature to teach that as normal C++ usage just yet.


Program for helping people practice their maths

Doing something n times

You have a loop asking 10 questions, which you implement like:

question_number = 1
...
while question_number <= 10:
    ...
    question_number = question_number + 1
    ...

This works, but we can do better. The problem with this loop is that it's error-prone. It's three lines of code to express a simple concept, and they're far apart. What if you added a continue before the increment? You'd ask more questions than you meant to.

A better way is just:

for question_number in range(10):
    ...

That loop will iterate 10 times, all in one line of code.

Repetition, repetition, repetition

You have

correct = correct + 1

in three places. Whenever we repeat ourselves, we risk repeating ourselves incorrectly. In this case, we did! For addition questions, we check if the user actually gave us the right answer. For the other two questions, we forgot to check! There's no if statement!

Much better to first determine what the right answer is:

if operation == '+':
    real_answer = num1 + num2
elif operation == '-':
    real_answer = num1 - num2
elif operation == 'x':
    real_answer = num1 * num2

And then just check it in one spot:

if user_answer == real_answer:
    correct += 1

[Advanced] But even this is super repetitive with setting up real_answer, so we can do better still. The value of operation basically defines a function that we need to apply to the two numbers. Let's make that more explicit by actually defining functions:

def add(a, b):
    return a + b

def sub(a, b):
    return a - b

def mul(a, b):
    return a * b

choice = {'+': add, '-': sub, '*': mul}

Now we can do:

real_answer = choice[operation](num1, num2)
if user_answer = real_answer:
    correct += 1

This can be shortened further with the standard library. Python gives us operator which defines all of these functions:

choice = {'+': operator.add,
    '-': operator.sub,
    '*': operator.mul
    }

The advantage of avoiding the repetition is how easy it becomes to add new operators. Let's say we want to test division? We would just have to add one line of code:

choice = {'+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.div  # <== just this
    }

Spacing

The ultimate Python style guide is PEP-8. Please use 4-space tabs throughout, not 8. That is too much spacing. No spacing between a function and the parens:

num_1 = random.randint(1,10)   # this one is good
num_2 = random.randint (1,10)  # this is an extra space

Also see the guidelines regarding variable names (prefer real_answer to realanswer, etc.)