Constructors for a class to represent a price in € or $

Starting from:

class Prix
{
    double valeur;
    string monnaie;

    public Prix(double valeur, string monnaie)
    {
        if (monnaie.Equals("€") || monnaie.Equals("$"))
        {
            this.valeur = valeur;
            this.monnaie = monnaie;
        }
        else
        {
            defaultConstr(valeur);
        }
    }

    public Prix(double valeur)
    {
        defaultConstr(valeur);
    }

    private void defaultConstr(double valeur)
    {
        this.valeur = valeur;
        this.monnaie = "€";
    }
}

When you have multiple constructors with similar parameters, it makes sense to keep the construction logic local to one constructor. One approach is to make one constructor call straight through to a second with any extra parameters.

public Prix(double valeur)
    : this(valeur, "€")
{
}

public Prix(double valeur, string monnaie)
{
    ...
}

Alternatively, supplying a default value for optional parameters is possible:

public Prix(double valeur, string monnaie = "€")
{
    ...
}

(see this question for information about the difference between the two)
Having construction logic in one place means that defaultConstr is only being called in one place. This method call can be inlined:

public Prix(double valeur, string monnaie)
{
    if (monnaie.Equals("€") || monnaie.Equals("$"))
    {
        this.valeur = valeur;
        this.monnaie = monnaie;
    }
    else
    {
        this.valeur = valeur;
        this.monnaie = "€";
    }
}

We're now setting valeur in both branches, so that can be factored out:

public Prix(double valeur, string monnaie)
{
    this.valeur = valeur;

    if (monnaie.Equals("€") || monnaie.Equals("$"))
    {
        this.monnaie = monnaie;
    }
    else
    {
        this.monnaie = "€";
    }
}

There is no need to compare against € if that will be assigned anyway:

public Prix(double valeur, string monnaie)
{
    this.valeur = valeur;

    if (monnaie.Equals("$"))
    {
        this.monnaie = monnaie;
    }
    else
    {
        this.monnaie = "€";
    }
}

Next, consider what happens if we have more valid currency symbols, we could end up with code like this:

if (monnaie.Equals("$") || monnaie.Equals("£") || monnaie.Equals("¥") || monnaie.Equals("฿") || monnaie.Equals("₩"))
{
    ...
}

This is getting quite ungainly - it's best to put this into a collection that can be checked against:

class Prix
{
    static HashSet<string> monnaieValid = new HashSet<string>
    {
        "$" // , "£", "¥", "฿", "₩"
    };

    ...

    public Prix(double valeur, string monnaie)
    {
        this.valeur = valeur;

        if (monnaieValid.Contains(monnaie))
        {
            this.monnaie = monnaie;
        }
        else
        {
            this.monnaie = "€";
        }
    }
}

Because the collection of currency symbols is logically a set (no duplicates, unordered), a HashSet<T> is the appropriate choice for the collection. It is static because we don't need every Prix object to have its own HashSet - one shared copy is enough.
It is also advisable to avoid "magic strings" - create a constant for the default currency and use this instead of the literal string:

class Prix
{
    const string MonnaieDefault = "€";

    ...

    public Prix(double valeur)
        : this(valeur, MonnaieDefault)
    {
    }

    public Prix(double valeur, string monnaie)
    {
        this.valeur = valeur;

        if (monnaieValid.Contains(monnaie))
        {
            this.monnaie = monnaie;
        }
        else
        {
            this.monnaie = MonnaieDefault;
        }
    }
}

I would also make a few other small changes to help readability (although this step may be subjective):

Add access modifiers where it's currently implicit
Make fields readonly wherever possible - here no fields are modified after they are initialised, so they can all be made readonly
Use a ternary operator instead of the if statement

Finally, the class looks like this:

public class Prix
{
    private const string MonnaieDefault = "€";

    private static readonly HashSet<string> monnaieValid = new HashSet<string>
    {
        "$"
    };

    private readonly double valeur;
    private readonly string monnaie;

    public Prix(double valeur)
        : this(valeur, MonnaieDefault)
    {
    }

    public Prix(double valeur, string monnaie)
    {
        this.valeur = valeur;
        this.monnaie = monnaieValid.Contains(monnaie) ? monnaie : MonnaieDefault;
    }
}


Checking if a single linked list is a palindrome in C++

I see some things that may help you improve your code.

Omit unused variables

Neither argc nor argv are used in this program and should be eliminated.

Consider the value of simplicity

While your code is correct and likely more efficient, there is often merit in creating a program that is so simple it is obviously defect-free.  Such a routine could be this:

auto bv{lf};
bv.reverse();
return bv == lf;

The advantage to this is that it may be sufficiently fast, depending on your needs.  If it is, then you're done.  If it's not, you can use the code as a benchmark to both verify both the correctness and speed of any alternate versions.

Use the data structure to your advantage

Rather than using a std::vector, it may be better to use std::forward_list for the copy.  Doing so would allow you to do use the push_front() operator which is quite efficient.  That would avoid having to have a std::vector and the possible resizing operations that can occur while adding to it.

Count rather than calculate

Since you're iterating through the list anyway, you could simply count the number of items as you go.  The current code has this somewhat complicated calculation:

int istop = bv.size()/2 + bv.size()%2;

Consider instead that if your code simply increments istop during the copy loop, it could simplify to this:

istop /= 2;

Omit the return in main

Usually, a program that ends main with a non-zero return signifies an error to the operating system.  This program always returns 1 which many operating systems will interpret as an abnormal end to the program.  Simplify your code by simply omitting the return; when main ends without a return, the compiler automatically creates the code equivalent to return 0;.

A worked example

Here's an alternative approach incorporating the ideas above:

template<typename T>
bool isPalindrome(const std::forward_list<T>& lf)
{
    auto iter = lf.begin();
    std::forward_list<decltype(iter)> bv;
    int sz = 0;
    for ( ; iter != lf.end(); ++iter) {
        bv.push_front(iter);
        ++sz;
    }
    sz /= 2;
    iter = lf.begin();
    for (auto it2 = bv.begin(); sz; --sz, ++iter, ++it2) {
        if (**it2 != *iter) return false;
    }
    return true;
}


#include <algorithm>
#include <set>

I don't see anything from <algorithm> or <set> in the code.

using namespace std;

Never do this. Just never do this. But especially never do this in a header.

unordered_map< K, pair<V, list_iterator > > hash;
list<K> ls;

It seems a little inefficient to store the key twice - once in the map and once in the list. If the key is an int, no problem, but what if the key is an expensive type?

One possible solution is to store pointers to the keys in the list. So you have:

std::unordered_map< K, pair<V, list_iterator > > hash;
std::list<K const*> ls;

But that's only one alternative.

int size() { return hash.size(); }
bool empty() { return hash.empty(); }

Both of these functions should be const, and probably both noexcept as well.

void insert(pair<K,V> kv) {
    if (hash.count(kv.first) == 1) {
        auto p = hash[kv.first];
        hash[kv.first] = make_pair(kv.second, p.second);
    } else {
        ls.push_back(kv.first);
        auto it = ls.end(); --it;
        hash.insert( make_pair(kv.first, make_pair(kv.second, it)));
    }
}

There are a lot of inefficiencies in this function, and a lot of problems with exception safety.

Let's start with the inefficiencies, focusing on the case where the key is already in the map. You start by searching the map for the key (to count). And then you search the map for the key again to get the list iterator (using operator[]). And then you search it AGAIN to actually set the value.

Instead, what if you searched it just one time, and used the result from then on. For example:

void insert(std::pair<K,V> kv) {
    auto const p = hash.find(kv.first);
    if (p != hash.end()) {
        p->second.first = std::move(kv.second);
    } else {
        // ...

Now let's look at the exception issues in the second half of the function. First you create the key in the list, which can succeed or fail - if it fails, that's bad, but at least your class's invariants are still valid. Next you create the key, value, iterator set in the map. If that fails, then your class is now in the state where there is a key in the list that is not in the hash table.

Unfortunately, there is no easy fix for this. You are updating two different data structures; either one can fail, so no matter what you do you need to handle the case where the first one succeeds and the second one fails.

You could do something like this:

void insert(std::pair<K,V> kv) {
    auto const p = hash.find(kv.first);
    if (p != hash.end()) {
        p->second.first = std::move(kv.second);
    } else {
        ls.push_back(kv.first);
        try {
            auto it = ls.end(); --it;
            hash.insert( make_pair(kv.first, make_pair(kv.second, it)));
        }
        catch (...) {
            ls.pop_back();
            throw;
        }
    }
}

Or, a little more efficiently:

void insert(std::pair<K,V> kv) {
    auto const p = hash.find(kv.first);
    if (p != hash.end()) {
        p->second.first = std::move(kv.second);
    } else {
        auto const it = ls.insert(ls.end(), kv.first);
        try {
            hash.insert( make_pair(std::move(kv.first), make_pair(std::move(kv.second), it)));
        }
        catch (...) {
            ls.erase(it);
            throw;
        }
    }
}

It might also be worthwhile to create two insert() functions, one that takes std::pair<K, V> const& and doesn't use std::move(), and one that takes std::pair<K, V>&& and uses std::move().

On to erase():

void erase(K key) {
    if (hash.count(key) == 1) {
        auto p = hash[key];
        hash.erase(key);
        ls.erase(p.second);
    }
}

Once again, you are searching the hash map multiple times (once for count(), once for operator[], and once again for erase()). Also, you are taking the key by value, which is unnecessary. You're only reading its value, so you should take it by const&.

A more efficient version of the function might look like this:

void erase(K const& key) {
    auto const p = hash.find(key):
    if (p != hash.end()) {
        ls.erase(p->second.second);
        hash.erase(p);
    }
}

The next two functions have basically the same problems:

void eraseEldest() {
    if(!hash.empty()) {
        K key = ls.front();
        ls.pop_front();
        hash.erase(key);
    }
}

There is no need to copy the key into a variable, then remove it from the list, then use the variable to remove it from the hash table. Do it the other way around, and you avoid copies:

void eraseEldest() {
    if(!hash.empty()) {
        hash.erase(ls.front());
        ls.pop_front();
    }
}

Once again, the next two functions have basically the same problems:

V at(K key) {
    auto p = hash.at(key);
    return p.first;
}

There are loads of unnecessary copies here. First, the key is copied into the function argument, because you don't take it by const&. Then both the key and the value (and a list iterator) are copied into p. Then the value is copied again into the return value.

Let's start at the top.

The key doesn't need to be copied here, because you're just inspecting it's value. You can take it by const&:

V at(K const& key) {

The return value probably doesn't need to be copied either, and if you want to use it like lhm.at(key) = new_value;, it must be a reference. So:

V& at(K const& key) {

Now, in the function, you don't need to copy the result of hash.at(key) - in fact you really shouldn't. You should just take a reference to it:

auto& p = hash.at(key);
return p.first;

But there's really no need for p:

return hash.at(key).first;

Putting it all together:

V& at(K const& key) {
    return hash.at(key).first;
}

For const correctness, you'll need two of these functions, one const and one not:

V& at(K const& key) {
    return hash.at(key).first;
}

V const& at(K const& key) const {
    return hash.at(key).first;
}

And of course, all of the same for operator[].

list<K>& keyList() {
    return ls;
}

This is exceptionally dangerous. You are returning a non-const reference to the key list in your class. You are giving users the freedom to completely break your class's invariants. I can do:

auto& key_list = lhm.keyList();
key_list.clear();
// now lhm.hash is full of dangling list iterators

If you want to return the key list, you should not return it as a non-const reference. Either return it as a const reference or - better - by value. Don't give outsiders access to the guts of your class.


There are few improvements you can do:

Remove the first sec_no = random.randint(0, 10). You are already initializing it inside of the main while loop.
Create a variable that contains minp.lower(). Instead of calculating it over and over - keep it in a variable and avoid code duplication.
Get rid of ncout or att. They are practically saving the same thing, keep only att and change the while and if condition to att > 0.
Add some comments - File comments and function comments.
General python tip: do not write code in main, Use functions. Function for each case, function for main loop, function to check if string is int and the __main__ should look like this:

if __name__ == '__main__':
    main_function()

Except for that - good logic, nice code :)


When you say "points of polygon", I am assuming you are referring to vertices.

I don't think what you have is the fastest. A simple improvement to this could be to divide your matrix in to a grid of p x p cells, where p is a parameter, and classify each grid-cell as completely inside or completely outside of the polygon. This can be done by checking if all the vertices of the grid-cell are inside the polygon. This way, large regions inside grid cells can be directly labeled as inside or outside, without needing to test every point inside the cell against all the edges of the polygon. For the grid-cells that are not completely inside the polygon, you just go by what you are doing. The optimal choice of p depends on the size of polygons you may encounter.

More details about the grid method here (with comparisons to other strategies):
http://erich.realtimerendering.com/ptinpoly/

There could be better ones. I just suggested a simple improvement, which works well in practice.


Modifying the response object for creating and downloading a document

Yes, in ASP.NET WebForms you don't have any nice helper method to hide this. However if you do it often you should make it easier and less error-prone.

public static void WriteDownload(this HttpResponse response, string fileName, byte[] data)
{
    if (String.IsNullOrWhiteSpace(fileName))
        throw new ArgumentException("File name must be specified.", "fileName");

    if (data == null)
        throw new ArgumentNullException("data");

    response.ClearContent();

    response.ContentType = MimeMapping.GetMimeMapping(fileName);
    response.AddHeader("content-disposition",
        String.Format("attachment; filename={0}", fileName));

    response.BinaryWrite(data);
    response.End();
}

It will then be used like this:

Response.WriteDownload(GetFileNameFromTodayDate(".xlsx"), pkg.GetAsByteArray());

Where GetFileNameFromTodayDate() is simply:

private static string GetFileNameFromTodayDate(string extension)
{
    return String.Format("{0:yyyyMMdd}.{1}",
        DateTime.Now, extension.TrimStart(' ', '.');
}

Few more notes:

BufferOutput is true by default, you do not need to repeat it. However I'd consider to set it to false.
If you're using .NET Framework 4.5+ you do not need any function to resolve MIME type otherwise you'd better to resort some helper function but do not hard-code it anywhere.
You do not need Response.Flush() because buffering is on and, moreover, you do not stream anything else before Response.End(), it's just redundant.


Is it good practice to insert data into a table this way?
If by that you mean: is it considered good practice to use prepared statements, and a bind array, then yes. It is. If you mean: "can I consider my code to be good practice", then the answer is no. It's not. Here's why:
function insertTest()
{//needs to go on the next line, PSR standards
    global $db;

The use of functions + global keyword is bad practice. For starters: you have no real way of ensuring that $db will be an instance of PDO. And seeing as you are using a function, why not require the caller to pass a valid DB connection to your function:
function insertTest(PDO $db)
{
}

Now you know what $db will be, with the added benefit of the type-hint, any decent IDE will know, too. So your code is self-explanatory.
Next we have this:
$field_names    = array("id", "first_name", "last_name", "email");
$alias          = array(":id", ":fn", ":ln", ":em");
$assignment     = array(":id" => "2k39dk38dk2k39dk38dk2k39dk38dk2k39dk38dk",
                        ":fn" => "Chris",
                        ":ln" => "Moore",
                        ":em" => "test@gmail.com");

That looks a tad messy, doesn't it. For starters, it's pretty clear to me that $field_names and $alias belong together: for each field in your INSERT, there needs to be a placeholder. Having 2 separate arrays means that someone can add a value to the first, and simply forget about adding a placeholder in the other array. That would break your code. Just write:
$map = [
    'id'         => ':id',
    'first_name' => ':fn',
    'last_name'  => ':ln',
    'email'      => ':email',
];

That addresses that issue. Now you can easily extract the fields you're using (array_keys($map)) and the parameters (array_values($map)). As for the $assignment variable: that really should be an argument that the user passes to your function, so change its signature to:
function inserTest(PDO $db, array $assignment)
{}

In the long run, you'll probably want to turn this function into a method, and define $map as a property, which you can then use to validate $assignment (check if the keys in the array exist in $this->map and throw exceptions if something doesn't quite add up)
Prepared statements are reusable
Another drawback of the way you're using prepared statements in your function is that you're missing out on one of their biggest advantages: prepared statements can be re-used several times:
$stmt = $pdo->prepare('INSERT INTO foo (field1, field2) VALUES (:foo, :bar)');
$stmt->execute([':foo' => 'value 1', ':bar' => 1]);
$stmt->execute([':foo' => 'value 2', ':bar' => 2);

The code above will add 2 rows to the foo table, using the same prepared statement. Creating such a statement in a function, using it and then returning a boolean will GC (garbage collect) the prepared statement, only to create it a second time after when you call the function again. This isn't ideal, obviously.
It might be more useful to harness the power of the PDOStatement instance that PDO::prepare returns.
This can be especially useful if you're using SELECT queries: returning the PDOStatement instance allows the user to fetch the data in a format he sees fit:
$stmt = $obj->getSelectByIdStmt();
$data = [];
foreach ($ids as $id) {
    $stmt->execute([':id' => $id]);
    $objects = [];
    //or PDO::FETCH_ASSOC, PDO::FETCH_CLASS, ...
    while ($row = $stmt->fetch(PDO::FETCH_OBJ) {
        $objects[] = $row;
    }
    $data[$id] = $objects;
}

This is something that is quite hard to abstract into one, comprehensive function/method...
Other niggles:
Your usage of this (badly) named $array variable doesn't really make sense:
$array = array();
$array['table'] = 'users';
$array['field_names'] = $field_names;
$array['alias'] = $alias;
$array['assignment'] = $assignment;

For starters, initializing a variable to an empty array, and then adding keys one by one is a lot more work (to type) than a simple:
$array = [
    'table'       => 'users',
    'field_names' => $field_names,
    'alias'       => $alias,
    'assignment'  => $assignment,
];

Now if you were to pre-format/stringify array values (like $field_names), you could use vsprintf to create your query, but that's something others who work on the same code will hate you for (they really will, trust me, I've been there).
I've already hinted at the possibility of creating a class, which could be used to store things that are, essentially, immutable (like the table name and the field map). But that's a different matter, for now: just start by leaving out the $array variable. There's also no need to assign the format to $q if you're reassigning $q the next statement. Just write:
$q = sprintf(
    'INSERT INTO `%s` (%s) VALUES (%s)',
    'users',
    implode(', ', $field_names),
    implode(', ', $alias)
);

The backticks around the table name imply you're using MySQL, you might want to add the same backticks around your field names (in case some mug decides to call fields "transaction" or "set" - again, I've been there, it happens):
$q = sprintf(
    'INSERT INTO `%s` (`%s`) VALUES (%s)',
    'users',
    implode('`, `', $field_names),
    implode(', ', $alias)
);


At first glance:

The code is a bit difficult to read.  The macros and variable names do not improve readability (using the same names than the problem would help a lot).
If I understand correctly (and I'm honestly not sure) you compute all possible solutions, then use this huge table on the input.
This would be a good idea if the result set was small and the number of 'Q' benefiting from it (much) bigger. (I'd say the order of 10E+7 'Q', give or take an order of magnitude)

A bit deeper:

The sum of weights as a quick elimination is a good idea.

But your algorithm involves this brutal O(m * n²) loop.  This does not inspire confidence in the execution speed.
Also, your main buffer takes 850MB of memory (assuming an int is 32 bits).  That's a LOT of cache misses : another downer.

The way I imagine the algorithm, only 2 arrays of 60 integers are needed (plus bonuses). That's 240 bytes or ~4 to ~8 lines of L0 cache : fast.  As for the work for a given total weight, it should be broadly O(n*log(n))

Reading the problem, a few obvious algorithm optimization steps are presenting themselves.

First, there is no precision that say that pieces weights are different (and if the test is interesting, there should be a fair amount of pieces with identical weights in the input, if only to make room for subtlety).

The weight pieces should be sorted in reverse order and the number of different weights counted.
Note that by starting with the bigger values on each iteration, the test of overflow you will do after each addition will trigger earlier.

Now that you know how many times a weight is used, you only start from it once and multiply the amount of solutions for that starting weight by U. (Repeat for all different weights)

There is also no precision that the total weight cannot be repeated.
I'm assuming that's what your O³ was meant for.
But instead of computing what you don't need, just store the results by total weight in a map (that you will reset for each new set of pieces weights).

And at last, since it's C++11.  You could take advantage of the amount of CPUs and dispatch the test. This part is actually tricky because knowing if you have to divide by (N+Qs) (and have a printer dispatch, the main thread, that centralizes the printing to keep order) or to divide for each Q of an N requires a bit of experiment and tuning.

An example to be clear, with [] being a thread.

[N0 Q01 Q02 Q03 ...] [N1 Q10 ...] per thread, plus [printer dispatch].

or

[N0 Q00] [N0 Q01] [N0 Q02] [N0 Q03] [N1 Q10], plus [printer dispatch].

These are the first ideas but the result should be quite fast.


I prefer a simple cast over as when I don't expect an object to be of any other type. If you do expect this, use as and be sure to check for null.

var comboBox = (ComboBox)sender;
When it makes sense to group code together do so.

if (!comboBox.IsDropDownOpen || !combobox.IsEditable || !combobox.IsReadOnly)
Try to use LINQ where possible.
Place variables close to where they are being used. (textSearch)
Don't overuse var. This is subjective, and there are several discussion about it. (also see comments in the code underneath)
Using continue can make it more difficult to get an overview of the code. In some occasions it is useful, but look at the code below to see how you could replace it with normal if else conditions instead.
Identify redundant code, see what you can eliminate and what you can't. You might have to introduce new intermediate variables. (e.g. textToCompare)

Here is the complete reworked example:

private void OnTextComboBoxPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    var comboBox = (ComboBox)sender;
    if (!comboBox.IsDropDownOpen || !combobox.IsEditable || !combobox.IsReadOnly)
    {
        return;
    }

    foreach (var item in comboBox.Items.Where( i => i != null ))
    {
        string textToCompare = null;

        if (item is string)
        {
            textToCompare = (string)item;
        }
        else if (item is DependencyObject)
        {
            DependencyObject dependencyObjItem = (DependencyObject)item;

            string textMember = TextSearch.GetText(dependencyObjItem);
            if (!string.IsNullOrEmpty(textMember))
            {
                // From this sample, I don't know what the following type is!
                // I wouldn't use var here.
                var selectorFunc = ExpressionHelper.GetMemberFunction(dependencyObjItem, textMember);
                textToCompare = selectorFunc(dependencyObjItem);
            }
        }
        else
        {
            string textSearch = TextSearch.GetTextPath(comboBox);
            if (!string.IsNullOrEmpty(textSearch))
            {
                var selectorFunc = ExpressionHelper.GetMemberFunction(item, textSearch);
                textToCompare = selectorFunc(item);
            }
        }

        if (textToCompare != null && textToCompare.StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))
        {
            SelectItemInComboBox(comboBox, item);
            break;
        }
    }

    e.Handled = true;
}

private void SelectItemInComboBox(ComboBox comboBox, object item)
{
    var comboBoxItem = comboBox.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem;
    comboBoxItem.IsSelected = true;
}

I will leave it up to you as an exercise whether you can further eliminate the duplicate code from selectorFunc, and whether it would be useful.


Adding or Replacing a Page item in a QueryString in C#.

I think that yes this code can be improved.

use a regular expression:

            var newQuery = Regex.Replace(currentQuery, @"(?i)(page=\d*&?)", "").TrimEnd('&');
            if (newQuery.Length > 0)
                newQuery += string.Format("&Page={0}", currentPageNo);
            else
                newQuery = string.Format("Page={0}", currentPageNo);


Using a class might be too much. It all depends of how you want to use your script.

But I think you should take a look at mediainfo help. Issuing:

mediainfo --Inform="Audio;%Encoded_Date%" Filename

outputs only the encoded date value of your audio file, or an empty line if not applicable. Maybe you won't need your script anymore.


A simple implementation of the principle of RSA encryption

1) Real implementation of RSA use the Chinese Remainder Theorem, which greatly improves the performance.

2) The big performance difference between encryption and decryption is a normal thing for RSA. It comes from the fact, that the performance of the modular exponentiation used depends on the number of 1 bits in the exponent. If you either chose the public exponent to be very small (like you are doing in your code, which is insecure btw) or large but with a lot of zeroes in its binary representation (usually e=655537=100...001 is used) public key operations (=encryption) will be fast. The private exponent can not be controlled and will have ~1/2 of its bit set to one, making the decryption a lot slower.


Any help on how to optimize it?

Optimise readability, starting with following the Style Guide for Python Code.
(And yes, this is a useful step in optimising efficiency, too)

(The below reads an ill-tempered diatribe more than a code review, the sole exculpation being the explicit question in the title. (I should look for a well-receives SE resource bound to exist.))

How to write efficient source code for …?
Given a specification that looks ready for implementation,
- write tests shedding a light on correctness.
- fix(!) a limit for the effort to improve efficiency
- define a measure for efficient
(-if applicable, define relevant input data)
- automate measuring efficiency - memory usage is harder to assess than time used
 (use available tools - timeit, for starters)
 (It saves a lot of trouble to include (basic) functional tests here)
 (Don't believe sub-second measurements.
  Measure work completed in a fixed amount of time, not time used for a fixed amount of work.)
- use your first working version to establish a base line
- fix(!) what performance is good enough
- pick alternative implementations, jot down your guesses re. efficiency, measure
- time allowing (see limit above), experiment with improvements


Thread safe lock-free stack using win32 threading primitives

In TSimpleStack::Pop you don't need to check the depth as m_list.Pop() will return null if the stack is empty.

The repeated allocations and frees kind of rub me the wrong way. Instead you can add a CSList m_freeList; member and allocate from that:

DATA_ENTRY* AllocEntry(){
    DATA_ENTRY* result = m_freeList.Pop();
    if(!result)
        result = _aligned_malloc(sizeof(DATA_ENTRY), MEMORY_ALLOCATION_ALIGNMENT);
    return result;
}

void FreeEntry(DATA_ENTRY* entry){
    m_freeList.Push(entry);
}

A destructor to CSList with at least an assert that m_head is empty.

CSList should probably disallow copying and moving. But TSimpleStack should definatley have a copy constructor and assignment operator (plus the move variants) to follow the rule of 3 (5) or disallow them which is saner because it is hard to ensure thread safety when copying/moving.


Please review for performance.

The performance looks fine to me. Some key observations:

It's clear that all nodes must be visited to compute the correct answer, so the solution cannot be better than \$O(n)\$ time.
Traversing in level order as you did will require as much additional space as the number of nodes on the most dense level.
Traversing depth first would require as much additional space as the longest path from root to leaf.

Without knowing in advance the shape of the tree (whether it's deep or wide),
and given TreeNode as defined and no additional helper data structures,
it's not possible to tell whether DFS or BFS is better.
So they are both equally fine, as neither uses space excessively.


Shortest path from U to V using at most k nodes

Algorithm flawed

Your comment here is wrong:

  In the k'th run the floyd-warshall algorithm gives the shortest path with k edges.

In the k'th run, the algorithm gives the shortest path from each node to each other node using intermediate nodes from 0..k.

As an example, suppose you had 10 vertices and wanted to find the shortest path between vertices 0 and 9, with max nodes = 2.  If the shortest path was 0 -> 8 -> 9, you would need to run 9 iterations for k before you would find that path.  Unfortunately, by that time you would have found paths using more than 2 nodes.

Here is an example input for the above case demonstrating the problem:

1
10 3 3
0 8 1
8 9 1
0 9 999

Output: 999

Corrected algorithm

Your idea about iterating k times was good, but you need to compute the correct thing on each loop.  What you should be computing is the shortest path from node 0 to each other node using k or fewer nodes in the path.  To do this, you can still use the same three loops, but like this:

    unsigned int new_g0[number_of_nodes];
    for (int k=2 ; k < limit_of_nodes ; k++) {
        memcpy(new_g0, g, sizeof(new_g0));
        for (int i=1 ; i < number_of_nodes ; i++) {
            for (int j=1 ; j < number_of_nodes ; j++) {
                if (g[0][i] != MAX && g[i][j] != MAX &&
                        g[0][i] + g[i][j] < new_g0[j]) {
                    new_g0[j] = g[0][i] + g[i][j];
                }
            }
        }
        memcpy(g, new_g0, sizeof(new_g0));
    }

The new_g0 array is something I added to avoid modifying the matrix when the loop is still computing the current iteration.  If you modified g[0][j] directly, it could influence another computation in the same loop, causing you to find a path with k+1 nodes instead of k nodes.

The k loop starts at 2 because the original matrix already has the lengths of paths with 2 nodes (the start and end nodes).

While this algorithm is now correct, it has the same run time as your original algorithm, \$O(k*n^2)\$, so it doesn't solve your problem of exceeding the time limit.

Other algorithms

If the number of edges is small compared to the number of vertices, you might be better off using a search algorithm such as a depth first search where you 1) limit the depth and 2) keep track of the best distance so far so you can backtrack immediately whenever you exceed the best distance.

Dijkstra's algorithm is good for finding the shortest path between two nodes, but unfortunately, it is not easy to modify it to also have the constraint that there be at most k nodes in the path.


Renaming the iframe src attribute to facilitate lazy loading

Calling $(this) three times is a bit wasteful.  You can improve that by taking advantage of $.attr(attributeName, function) and by using chaining.

$(function() {
     $('iframe').attr('data-src', function() { return $(this).attr('src'); })
                .removeAttr('src');
});

// For demonstration...
$(function() {
     $('#printout').text($('iframe').attr('data-src'));
});

  data-src=


Code review
Fail
You should ensure your code is at least able to be parsed before you ask for review. I will assume it an oversight (that even your code formater was glaringly pointing out) and review assuming the missing token.
Incomplete
As an exercise the real complexity is in the graph and the neighbors function for which there is no code to evaluate.
The Queue implementation is missing, JS Arrays are queues, using push and shift to move items through the (abstracted) "queue".
Poor style
The code can be written better.

Use const for variables that don`t change
Its a little noisy. Remove redundant code eg while(foo.length > 0) the length property will never be < 0 so while(foo.length) does the same with less
Use appropriate iterators, for(;;) loops only when you need the index, else use the for(of) loop
There is really no need for the variables current and neighbors however neighbors can be argued to help with readability (see rewrite)
The comments are of no useful value.

Never add comments without relevance to the code. Why the many // 1?
Don't state the obvious. // 1 (for break condition)
Comment must be consistent with the naming and abstractions used. // 1 (for adjacency list) don't you mean neighbours?

Bad indentation is the worst possible readability error you can introduce into your source code. If assessing code, unindented blocks are an automatic fail and there is no argument that can ever justify such poor style.
There is a syntax error, the code will not even make it past the parser. A basic requirement for code review. I am not going to point it out as your runtime environment will tell you.

Rewrite
Two acceptable options of the many possible.
function graphBFS(graph, start) {
    const queue = new Queue();
    const visited = new Set([start]);
    queue.enqueue(start);
    while (queue.length) {
        const neighbors = graph.neighbors(queue.dequeue());
        for (const neighbor of neighbors) {
            if (!visited.has(neighbor)) {
                queue.enqueue(neighbor);
                visited.add(neighbor);
            }
        }
    }
}

Or as
function graphBFS(graph, start) {
    const queue = [start], visited = new Set(queue);
    while (queue.length) {
        for (const item of graph.neighbors(queue.shift())) {
            if (!visited.has(item)) {
                queue.push(item);
                visited.add(item);
            }
        }
    }
}

The latter I would score higher as it demonstrates a higher level of understanding of the problem being solved, reduced dependency and thus more portable and reusable, and reduced use of abstraction in favor of consistency.
EG If the function were to be change to depth first you need only change the function graph.neighbors and not rename neighbor 4 times due to strong coupling with the abstract. An item of neighbors is still meaningful as an item of roots (Or whatever you call the forward edge traverse)


Use of mediator design pattern with mailing list implementation

I am not familiar with the Mediator pattern, but I think your code is not complex enough to make good use of the pattern. Take your JavaMailingList and SQLMailingList, what is the difference between those classes ? The value of mailingListId. The implementation of subscribe is exactly the same, you add the same variable to the class. If your MailingListMediator would look like :

public class MailingListMediator {
    private final String mailingListId;
    protected List<MailUser> mailingList;

    public MailingListMediator(String mailingListId) {
        this.mailingList = new ArrayList<MailUser>();
        this.mailingListId = mailingListId;
    }

    public void sendMail(String message){
        for(MailUser mUser:mailingList){
            System.out.println("Mail message: '"+message+"' sent to "+ mUser.getMailId());
        }
    }
    public String subscribe(MailUser mailUser) {
        mailingList.add(mailUser);
        return mailingListId;
    }
}

There is suddenly no need for  JavaMailingList and SQLMailingList.

The same principle apply to YahooUser and GmailUser. Those classes are almost a copy-paste of each other. Same implementation for all the methods and adding the same variable to the class. Why is mailID an attribute in the children classes but not in MailUser? I could repeat the same process that I used for MailingListMediator and I could remove YahooUser and GmailUser.

My conclusion is your code looks like trying to be complicated when in fact it is not. You want to try the Mediator pattern ? Well wait when you will need it, do not force your code into a pattern. Pattern will be useful when you need it, otherwise it will only make your code less readable and harder to maintain.

Since you wanted to implement the Mediator pattern, I will expand more on that part. You do have a mediator pattern implemented. Your "colleagues" do interact between each other through the mediator that is the MailingList. There isn't a MailUser that interact directly with each other, that is the main point of the mediator pattern. Do know that your example is a little weak. I would suggest you, if you really want to test the mediator pattern, try a to code a chat application. This could be a good exercise since you will have a lot of users that will need to communicate, but you don't want the class to be tightly coupled.


Find perfect squares between two numbers

I didn't have a very close look at your solution, but a simple (algorithm-agnostic way) to improve efficiency for this kind of task, is to cache (think about which data structure would suit this task) previously found solutions. For instance consider test 1 being a=1, b=10000 and test 2 exactly (or almost) the same, like for instance a=1 and b=10000 or a=2 and b=9999. You are going to check recompute the whole thing, although you just did that.

p.s.: I'll have a closer look at it if you are still struggling with it when I get home.


Checking an array is sorted in either order efficiently

We could make it better by making it more maintainable by simplifying the code and reducing duplication in the three for-loops. The problem is essentially checking that all successive pairs in the array are either equal or have the same sort order, so let's code it that way:

import static java.lang.Integer.compare;
import static java.lang.Integer.signum;

public static boolean isSorted(final int[] arr) {
    // The order in which the array is.
    // -1: ascending
    //  0: all elements are the same
    //  1: descending
    int arrayOrder = 0;

    for (int i = 0; i < arr.length - 1; i++) {
        // Signum is actually useless, since compare returns -1..1 but
        // we believe the documentation, not the code.
        final int pairOrder = signum(compare(arr[i], arr[i + 1]));

        if (arrayOrder == 0) {
            // All elements so far have been equal. First non-equal pair
            // defines the order expected from the following pairs..
            arrayOrder = pairOrder;
        } else if (pairOrder != arrayOrder && pairOrder != 0) {
            // If any pair is not equal and deviates from array order,
            // the array is not sorted.
            return false;
        }
    }

    return true;
}

Is this more efficient? No. There are more operations inside the for-loop, but we're talking about two equals checks between integers in an O(N) algorithm. If yours takes 4.7s on my laptop, mine takes 5.4s... for 2^31-1 elements.

A benefit in a single for-loop is that we don't need to expose the loop counter outside the loop itself. Code becomes harder to follow and more error prone when the loop counter is modified outside it's logical scope.


Sort algorithm

instead of if len(list_sort)>= 2:, just use else:
I would get rid of all the steps inbetween.
list_sort sounds too much like merge_sort, a method, not like a variable
to prevent surprises when using this algorithm in Python 3, use // for the floor division
you can use the fact 1 // 2 evaluates to False boolean-wise

so it'd end up like:

def merge_sort_list(lost_list):
    """splits the list in two parts until each part is left with one member"""
    x = len(lost_list) // 2
    if not x: # length is 1
        return lost_list
    else:
        return merge(merge_sort(lost_list[:x]), merge_sort(lost_list[x:]))

Merge algorithm

For reuse later, I would use a more generic algorithm using generators, which doesn't alter the items passed into it. This will also help to make it easier to adapt the sorting algorithm for other containers

def merge(left, right):
    try:
        left = iter(left)
        right = iter(right)
        l = next(left)
        r = next(right)
    except StopIteration as exc:
        raise ValueError('left and right should be iterables with at least length 1', exc)
    try:
        while True:
            if l <= r:
                yield l
                l = None
                l = next(left)
            else:
                yield r
                r = next(right)
    except StopIteration:
        yield r if l is None else l  # l is None if left is exhausted
        yield from left
        yield from right
        return

thanks to PeylonRayz for noticing the bug

Alternative version

def merge(left, right):
    try:
        left = iter(left)
        right = iter(right)
        iterators = (
            (next(left), 'left', left),
            (next(right), 'right', right),
        )
    except StopIteration as exc:
        raise ValueError('left and right should be iterables with at least length 1', exc)
    try:
        while True:
            (value, key, iterator), other = min(iterators), max(iterators)
            yield value
            iterators = other, (next(iterator), key, iterator)
    except StopIteration:
        value, key, iterator = other
        yield value
        yield from iterator

I find this alternative version is slightly more elegant, and in case of ex aequo, it keeps left before right. It can be easily adapted to support descending merging

sorting dicts

def merge_sort_dict_keys(items):
    import collections
    sorted_keys = merge_sort_list(list(items.items()))
    return collections.OrderedDict((key, value) for key, value in sorted_keys)

def merge_sort_dict_values(items):
    import collections
    sorted_keys = merge_sort_list(list((value, key) for key, value in items.items()))
    return collections.OrderedDict((key, value) for value, key in sorted_keys)


Lock Using "Interlocked" vs lock Statement ("Monitor")

First and foremost I think your implementation is broken: Interlocked.CompareExchange returns the original value at the location. So in your lock methods you should spin until the original value was Unlocked and not Locked.

As for your first question: Besides that "better" is a very vague term - no I don't think making it a struct is better for the simple reason that you have a mutable structure (it can change it's own state between locked and unlocked) and mutable structs are generally best to be avoided - the value semantics of it can trip you up pretty quick.

For your second question: As per MSDN all Interlocked methods make use of the appropriate barriers.

In general:

I would check that the lock was actually locked in Unlock (and throw if it wasn't) - unlocking an already unlocked lock indicates a potentially serious bug (lock/unlock should always be in matching pairs).
I'd consider implementing IDisposable and check that the lock is not locked when being disposed. Any object owning a lock instance should then dispose of it - this adds another check that the locking/unlocking is done correctly.


Multiply two columns of Census data and groupby

Since you only want to use the total population values for these plots it is not worth adding these columns to your census DataFrame. I would package the plots into a function which creates a temporary DataFrame that is used and then disposed of after the plotting is complete.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
%matplotlib inline

def plot_populations(census, race):
    # Group the data
    race_pops = pd.DataFrame(data={
                                   'State': census['State'],
                                   'Pop': census[race] * census['TotalPop'] / 100
                                  }
                            ).groupby('State')['Pop'].sum().sort_values(ascending=False)

    # Plot the results
    fig, axarr = plt.subplots(2, 2, figsize=(18, 12))
    fig.suptitle("{} population in all 52 states".format(race), fontsize=18)
    for ix, ax in enumerate(axarr.reshape(-1)):
        data = race_pops.iloc[ix*len(race_pops)//4:(ix+1)*len(race_pops)//4]
        sns.barplot(x=data.values, y=data.index, ax=ax)
        if ix % 2 != 0: ax.set_ylabel('')

census = pd.read_csv("acs2015_census_tract_data.csv")

races = ['Hispanic', 'White', 'Black', 'Native', 'Asian', 'Pacific']
# current racial population being plotted
race = races[0]

plot_populations(census, race)


Some recommendations just looking at the style of the code:

It would benefit from being run through pycodestyle, flake8 and/or similar tools to be more idiomatic. This would make the code easier to read for anyone familiar with Python.
Timing code should not be part of your program. External tools like time can handle that.
Use argparse rather than input to make the program scriptable. The script should not stop anywhere to ask for input.
The Alphabet and 25 in this code are good candidates for configuration or parameters.
You can remove all of a list of characters from a string in a single command.


As a review, the code needs some work with regard separation of concerns. A single function shouldn't get user input, get a URL and write to a file. If you try to write unit tests for it, you'll quickly see it's better to split the functionality.

With regard to the problem, try something as follows:

import urllib2

url = 'http://www.uniprot.org/uniprot/P57052.txt'
response = urllib2.urlopen(url)
with open('output.txt', 'w') as f:
    f.write(response.read())

I hope this helps.


Performance difference between declaring Regex inside or outside of often-called method.

I would go with the former unless you profile your code and it tells you that the constructor for Regex is using a significant amount of time.

Creating the Regex inside your method makes the clear statement that this given Regex is being used by only this method.  The compiler doesn't care, but someone maintaining your code in the future might care.

Running a profiler is necessary for really optimizing your code.  There are some things that are always likely to be bad (O(n^3) algorithms for instance), but I've learned by experience that I can't tell just by looking where the time is being wasted in my code.  Profile it and see what you learn.

If your profiling results tell you that the constructor of Regex is using too much time, then definitely move it outside the method.  If you do that though, you should add comments explaining why.  (Keep thinking about the poor person maintaining your code in the future, it just might be you.)


Using LINQ to perform a LEFT OUTER JOIN in 2 DataTables (Multiples criteria)

DataTables are quite powefull and offer lots of the real database functionality. Also as far as joins are concerned a few things are possible and I'm of the opinion that if someone uses DataTables he also should use the functionality they offer ;-)

It this case using DataTable joins your example could look like this:

DataSet ds = new DataSet();

DataTable dt1 = new DataTable();
dt1.Columns.Add("Key");
dt1.Columns.Add("Key2");
dt1.Columns.Add("Data1");
dt1.Columns.Add("Data2");

dt1.Rows.Add(new object[] { "01", "ZZ", "DATA1_AAAA", "DATA2_AAAA" });
dt1.Rows.Add(new object[] { "02", "ZZ", "DATA1_BBBB", "DATA2_BBBB" });

DataTable dt2 = new DataTable();
dt2.Columns.Add("Key");
dt2.Columns.Add("Key2");
dt2.Columns.Add("Data3");
dt2.Columns.Add("Data4");

dt2.Rows.Add(new object[] { "01", "ZZ", "DATA3_AAAA", "DATA4_AAAA" });
dt2.Rows.Add(new object[] { "01", "ZZ", "DATA3_BBBB", "DATA4_BBBB" });
dt2.Rows.Add(new object[] { "01", "ZZ", "DATA3_CCCC", "DATA4_CCCC" });
dt2.Rows.Add(new object[] { "01", "ZZ", "DATA3_DDDD", "DATA4_DDDD" });
//dt2.Rows.Add(new object[] { "02", "ZZ", "DATA5_DDDD", "DATA4_DDDD" });

ds.Tables.Add(dt1);
ds.Tables.Add(dt2);

// specify the relations between the data tables
DataRelation drel = new DataRelation(
    "MyJoin",
    new DataColumn[] { dt1.Columns["Key"], dt1.Columns["Key2"] },
    new DataColumn[] { dt2.Columns["Key"], dt2.Columns["Key2"]});

ds.Relations.Add(drel);

DataTable jt = new DataTable("JoinedTable");
jt.Columns.Add("Key");
jt.Columns.Add("Key2");
jt.Columns.Add("Data1");
jt.Columns.Add("Data2");
jt.Columns.Add("Data3");
jt.Columns.Add("Data4");
ds.Tables.Add(jt);

// create the result table
foreach (DataRow row in dt1.Rows)
{
    var childRows = row.GetChildRows("MyJoin");
    // mimics left join
    var hasChildRows = childRows.Length > 0;
    if (!hasChildRows)
    {
        jt.Rows.Add(row["Key"], row["Key2"], row["Data1"], row["Data2"], null, null);
        continue;
    }

    foreach (var child in childRows)
    {
        jt.Rows.Add(row["Key"], row["Key2"], row["Data1"], row["Data2"], child["Data3"], child["Data4"]);
    }
}

jt.Rows.Dump(); // LINQPad dump

As far as your code is concerned I'm not happy with the Koncat method because it modifies the ItemArray that belongs to the DataRow instead of creating a new result.

You actually don't need it because LINQ already has a such a method that you could use like this:

dr1.ItemArray
.Concat(result.Any() ? result.First().ItemArray: Enumerable.Empty<object>())
.ToArray());

It's not necessary to call the FirstOrDefault method two times. It's better to just check if the result has Any rows and then get the First one and its ItemArray or otherwise an empty IEnumerable, finally you turn it into an array and you're done:

var vLINQ = vDT1.AsEnumerable()
    .GroupJoin(
        vDT2.AsEnumerable(),
        dr1 => new { key1 = dr1["Key"], key2 = dr1["Key2"] },
        dr2 => new { key1 = dr2["Key"], key2 = dr2["Key2"] },
        (dr1, result) =>
            dr1.ItemArray
            .Concat(result.Any() ? result.First().ItemArray: Enumerable.Empty<object>())
            .ToArray());

or if you can use C# 6 even shorter with the ?. and ?? operators

dr1.ItemArray
.Concat(result.FirstOrDefault()?.ItemArray ?? Enumerable.Empty<object>())
.ToArray());


Chain of Responsibility Design pattern in C++

Design Pattern Comments
It works as a chain of responsibility (and the point of patterns is that they are not exact and are chained depending on exact need).
BUT saying that I think you could have done it better in this situation.

Your descent of the the chain is manual and repeated in any every class.
This should be automated in the base class. Each derived class should simply perform the action that you wan them too.
This will remove programmer error when a new developer creates a chaining task.
Your creation of the chain elements is not consistent. It would be easier to have a setTask() method then force every new task to join the chain rather than force every class to have a boiler plate constructor (that can be done incorrectly).
You do not always want to chain all the way to the end.
On of the handlers should be able to say I have done the final processing stop searching the chain.
No memory management (but that was covered by @Mantosh Jumar).
Also note using smart pointers helps you with another design pattern (Separation of Concerns).

I would have started like this:
class HelpInterface
{
        // Private virtual function.
        // You don't want it called directly as it just does the action
        // None of the chaining.
        virtual bool getHelp(int iHelpConstant) = 0;
        // Note it returns bool.
        // true indicates I have done it all.
        // Do not activate any more tasks in the chain.
        // false indicates try the next item in the chain.

        // Always have a next pointer in all HelpInterface
        std::unique_ptr<HelpInterface>   next;

    public:

        // Need  virtual destructor to make sure memory management is done
        // done correctly. As elements are destroyed via a pointer to the
        // base class.
        virtual ~HelpInterface() {}

        // Chain the getHelp.
        // But stop if it returns true (or we are the last element
        // in the chain.
        void activateHelp(int iHelpConstant)
        {
            if (!getHelp(iHelpConstant) && next)
            {
                next->activateHelp(iHelpConstant);
            }
        }

        void setNextTask(std::unique_ptr<HelpInterface>&& nextElement)
        {
            next = std::move(nextElement);
        }

};

Now you can create the chain like this:
int main()
{
    std::unique_ptr<HelpInterface> app    = std::make_unique<Application>();
    std::unique_ptr<HelpInterface> ilayer = std::make_unique<IntermediateLayer>();
    std::unique_ptr<HelpInterface> fend   = std::make_unique<FrontEnd>();

    iLayer->setNextTask(std::move(app));
    fend->setNextTask(std::move(iLayer));

    fend->getHelp(GENERAL_HELP);
    fend->getHelp(INTERMEDIATE_LAYER_HELP);
}

General Coding comments
A tiny bit lazy here.
using std::cout;
using std::endl;

But these are used so often I will not complain. I would have preferred it if you had not polluted the global namespace for everybody (in this file).
All caps identifier are by tradition reserved for macros. Macros have no regard for scope so you are putting yourself in a dangerous position using all caps for constants.
const int FRONT_END_HELP = 0;
const int INTERMEDIATE_LAYER_HELP = 1;
const int GENERAL_HELP = 2;

Also could have used an enumerate. I personally would have done.
enum HelperTypes { FrontEndHelp, IntermediateLayerHelp, GeneralHelp};

Doing it this way, makes the compiler generate the actual numbers (so there is no chance that somebody accidentally puts two identical numbers into the list). Also if you change your getHelp() signature to use the enum people can not accidentally pass an integer, as the compiler will spot that and force them to use the correct type.
A base class with virtual members. Must usually have a virtual destructor.
class HelpInterface
{
protected :
    HelpInterface * Successor;
public:
    virtual void getHelp(int iHelpConstant) = 0;
};

Also in C++ never us RAW pointers (there are some exceptions). But RAW pointers do not convey ownership. If you don't know the ownership then you don't know who is responsible for deleting the object. One of the most important concepts in C++ (over C) is the concept of ownership (RAII being more important). We should always know who owns a pointer so we know who is going to clean it up. Smart pointers are the usuall technique of indicating ownership (or using references to indicate the passing of a reference with no ownership transfer).
The * is part of the type. So put the * by the type when declaring pointers.
 HelpInterface*     successor;   // object (anything you can get an address of)
                                 // this includes functions. Should have an
                                 // initial lower case letter.

 // User defined types have an initial uppercase letter.
 // This helps you distinguish Types from objects.

You use at least two different styles of bracing:
class HelpInterface
{                                       // Brace on the next line.

class FrontEnd : public HelpInterface { // Brace on the same line.

Pick one and be consistent.
Note: You can use different styles in different places.
class X
{                 // Style for classes.

    int func() {  // Style for code.

    }
};

Personally I always put the '{' on a new line by itself. Others find this wastes vertical space. I buy a big monitor and keep my functions relatively short.
Use default parameters to avoid this situation.
        FrontEnd(HelpInterface * s){ Successor = s;}
        FrontEnd(){ Successor = NULL;}

Can be replaced with:
        FrontEnd(HelpInterface* successor = nullptr)
            : successor(successor) // Note:  member and parameter name the same.
        {}

You have plenty of space between operators here:
    if (FRONT_END_HELP == iHelpConstant)    {

But here they are all packed together. Space is your frined use it.
        cout<<"This is the front end, don't you like it ?\n"<<endl;

Don't use std::endl unless you want to force a flush. This is rarely the case. std::cin and std::cout are linked. If user input is required the cout is automatically flushed so the user can see any questions (or output). Excessive flushing severly degrades performance.
The most hidious of things ever:
    system("Pause");

Stop using it.
Try.
    std::cout << "Hit Enter to continue\n";
    std::string line;
    std::getline(std::cin, line);

This is portable.


Capturing the positions of "start" and "end" markers in a multi-line string

If you are certain that there is exactly one match, then you don't need to iterate.  You could write:

start, end = re.search('start.*ends?', sstring, re.DOTALL).span()

To note:

Take advantage of re.DOTALL so that the regex can span multiple lines.
Use match.span() and destructuring assignment to get both the start and end in one statement.
The [s]? after start is, from a mechanical viewpoint, useless.  You might want to keep it just for symmetry.

The spacing in print (something) is kind of weird; print(something) would be more conventional.


Getting and posting data use PHP OOP and MySQLi

No, this isn't the right way to use OOP or MySQLi.

First of all, you only provide two methods to access your wrapped mysqli instance: one to get data, one to post data.

This hides a lot of useful and necessary functions. You can't even use prepared statements with your code, making it incredibly insecure.

You also didn't really gain anything with your functions. With your functions, your code is:

$query = "SELECT * FROM USERS WHERE user_country='India'";
$data = $db->get_data($query);
  if($data){
    while($row=$data->fetch_assoc()){
      echo 'User Name: ':.$row["user_name"].' Age: '.$row["age"];
    }
  }

Without your functions it would be:

$query = "SELECT * FROM USERS WHERE user_country='India'";
$data = $db->query($query);
  if($data){
    while($row=$data->fetch_assoc()){
      echo 'User Name: ':.$row["user_name"].' Age: '.$row["age"];
    }
$data->free();

It's essentially the same code, making your functions unnecessary.

If you do want to wrap mysqli - which may not actually be necessary in your case -, make sure that you:

provide all the needed functionalities.
actually improve mysqli (make it easier to use, add functionalities, ...).
keep the interface as close to that of mysqli as possible, to make it easier to use.

Instead of wrapping mysqli, it may make sense to aim for less abstract methods. For example, you may have a UserDAO, which may have methods such as selectByCountry.


Implementing Addition, subtraction, multiplication, division of numbers of different base and give result in desired base:

For the conversion to base ten, you can just use the normal int function. It takes as a second argument a base (as int). In this case the first argument is required to be a string (so it has exactly the same interface as your convert_to_base_10 function.

For the convert_from_base_10 function, I would do something closer to this answer. It is recursive, which should be fine here (unless you convert numbers with more than a thousand digits in binary, because one thousand is the default maximum recursion depth in Python). It is also a lot easier to read, IMO.

Finally, your calculation functions all proceed after the same scheme:

Convert the inputs to decimal
Calculate the result in decimal
Convert to the desired base

For this you could define a decorator that can wrap the actual calculation, which can then just assume everything is in base ten. So I would do:

def digit_to_char(digit):
    if digit < 10:
        return str(digit)
    return chr(ord('a') + digit - 10)

def str_base(number,base):
    if number < 0:
        return '-' + str_base(-number, base)
    d, m = divmod(number, base)
    if d > 0:
        return str_base(d, base) + digit_to_char(m)
    return digit_to_char(m)

def calculate_in_decimal(func):
    def wrapper(n1, b1, n2, b2, b):
        n1_10 = int(n1, b1)
        n2_10 = int(n2, b2)
        ans = func(n1_10, n2_10)
        return str_base(ans, b)

# Use it like this:
@calculate_in_decimal
def addition(n1, n2):
    return n1 + n2

# Or use the operator module:
import operator
multiplication = calculate_in_decimal(operator.mul)
subtraction = calculate_in_decimal(operator.sub)

Note that I also fixed a bug, you wrote:

n1_10 = convert_to_base_10(n1,b1)
n2_10 = convert_to_base_10(n1,b1)

Where it should be:

n1_10 = convert_to_base_10(n1,b1)
n2_10 = convert_to_base_10(n2,b2)


Seems basically reasonable. Some English nits: You said "nominator and denominator," when the English terms are "numerator and denominator." You also seem to be using the word "evaluate(s)" as a noun (something like "precipitate" in chemistry), when I think the word you meant was more like "value(s)."

struct Node {
    Node(std::string const parameter, double const evaluate) {
        this -> parameter = parameter;
        this -> evaluate = evaluate;
    }

    std::string parameter;
    double evaluate;
};

Write this->x, not this -> x, for the same reason you write st.x and not st . x. But in fact, this constructor would be better written as either
struct Node {
    explicit Node(const std::string& p, double v) : parameter(p), value(v) {}
    std::string parameter;
    double value;
};

or simply
struct Node {
    std::string parameter;
    double value;
};

since simple aggregates can already be initialized with e.g. Node{"a", 2}. Notice that I'm passing std::string by const reference, because it is expensive to copy.
You could actually rewrite all of the helper functions and data structures to use C++17 std::string_view instead of std::string, as long as all the stringviews referred to the original long-lived strings from equations and queries which you are appropriately careful not to modify. This would be an "advanced" idea, though, and probably wouldn't even buy you any speed in this case where all your strings seem to be 1 character long.

for (auto& query : queries) — Use for (const auto& query : queries) to indicate that the const-qualification is on purpose; or use auto&& in generic code if you just want something that always works. I don't see any reason to use specifically auto& to get a specifically const-qualified result.

        if (visited.find(child.parameter) == visited.end()) {
            accumulated *= child.evaluate;

            if (child.parameter == denominator) {
                return true;
            }

            if (solve_equation(child.parameter, denominator, accumulated, visited)) {
                return true;

            } else {
                accumulated /= child.evaluate;
            }
        }

This if-else ladder is indeed confusing. I would write it like this:
        if (visited.find(child.parameter) != visited.end()) {
            // we have already visited this node; skip it
        } else if (child.parameter == denominator) {
            // we've reached our destination node and resolved the query
            accumulated *= child.value;
            return true;
        } else if (solve_equation(child.parameter, denominator, accumulated, visited)) {
            // this node is on a path that resolves the query
            accumulated *= child.value;
            return true;
        } else {
            // this node is not involved in the solution; do nothing
        }

The most confusing part of the original ladder was
            } else {
                accumulated /= child.evaluate;
            }

That line is really just undoing the multiplication hidden at the top of the loop. But the multiplication is done one scope higher than it is undone, which violates most programmers' intuition. It would have been a simple fix to write
        if (visited.find(child.parameter) == visited.end()) {
            accumulated *= child.evaluate;
            if (child.parameter == denominator) {
                return true;
            }
            if (solve_equation(child.parameter, denominator, accumulated, visited)) {
                return true;
            }
            accumulated /= child.evaluate;
        }

thus visually indicating the symmetry between *= and /=.

bool solve_equation(std::string const nominator,
    std::string const denominator, double& accumulated,
    std::set<string>& visited)

Consider whether visited should be a data member of class Solution.
Passing by const value is always a bug; you left off the &. If you used west const style, you could use these git grep lines to find such bugs: https://quuxplusone.github.io/blog/2019/01/03/const-is-a-contract/
Consider whether the return type of this function should be std::pair<bool, double>; or, in C++17, std::optional<double>.
Put it all together and you get a C++14 signature like
std::pair<bool, double> solve_equation(const std::string& numerator,
                                       const std::string& denominator);

or a C++17 signature like
std::optional<double> solve_equation(std::string_view numerator,
                                     std::string_view denominator);

You have methods named both calcEquation and solve_equation. Admittedly, the name calcEquation is just flat wrong; it should be something like solve_equations (plural). But, given that you aren't allowed to change the public name, personally I would go with calcEquation and calcSingleEquation — reusing the same verb instead of a near-synonym, and emphasizing that this function calculates for a single equation, since I don't have the option of adding an s to pluralize the public name.


Overall it looks good, I would just have some minor comments. In any case please have a look at the official Ericsson guidance.

Use macro ?MODULE instead of repeating sb.
In Erlang function names are usually_with_underscores rather than camelCasing. There are some exceptions, even in OTP applications, but in general underscores help to distinguish functions from variable names, which are usually CamelCased. The same holds for atom names.
I would usually put a code like this: [First | Rest] = Clients directly to the function argument to make it shorter, e.g.: tryAttend([First | Rest] = Clients, Barbers, BarberShopPID) ->
NewC and NewB aren't very descriptive. I would rather use NClients if NewClients are too long for you.
When accessing the head and tail of a list the names of variables are usually H and T, unless you want a specific name for the head, in which case the tail is just T or Tail, e.g. [H|T] = Clients or [First|T] = Clients. It's a convention which you will notice when reading someone else's code.
When spawning process with a function that doesn't need to be exported for its own sake try to use fun, e.g.: spawn(fun() -> barber(First, BarberShopPID) end). It's better to not expose functions that are not meant to be called from outside. And if you do have to export a function like that, then it's better to put it into a separate export with an additional comment, e.g. %% Internal API.
Didn't you want to write MAX_SEATS rather than MAX_SITS? :)


Using the numpy module for numerical computations is often better as the code is generally simpler and much faster. Here is a version adapted to use numpy:

from typing import List
import numpy as np
Matrix = np.matrix

MOD = 10 ** 9 + 7

def power(mat: Matrix, n: int) -> Matrix:
    res = np.identity(len(mat), dtype=np.int64)

    while n:
        if n & 1:
            np.matmul(res, mat, out=res)
            res %= MOD

        np.matmul(mat, mat, out=mat)
        mat %= MOD # Required for numpy if you want correct results
        n >>= 1

    return res

def fib(n: int) -> int:
    if n == 0:
        return 0

    magic = np.matrix([[1, 1], [1, 0]], dtype=np.int64)
    mat = power(magic, n - 1)
    return mat[0,0]

if __name__ == '__main__':
    print(fib(10 ** 18))

As you can see, using numpy reduce significantly the size of the code since it provide primitive for creating and computing matrices (eg. matrix multiplication).
Numpy is also faster since it uses fast native code to perform the computations. However, here, your matrices are too small so that numpy can provide any speed-up.
Also note that numpy as a downside: it does not support large integers as python does. So, the code above works well as long as you do not increase too much the value of MOD. You can use dtype=object to force numpy to support large integers but it will be slower (especially on bigger matrices).

Besides using numpy, you can also specialize your code to compute 2x2 matrices much faster in this specific case. Here is the result:

from typing import List
Matrix = List[List[int]]

MOD = 10 ** 9 + 7

def identity_2x2() -> Matrix:
    return [1, 0, 0, 1]

def multiply_2x2(mat1: Matrix, mat2: Matrix, copy: Matrix) -> None:
    a00, a01, a10, a11 = mat1
    b00, b01, b10, b11 = mat2

    copy[0] = (a00 * b00 + a01 * b10) % MOD
    copy[1] = (a00 * b01 + a01 * b11) % MOD
    copy[2] = (a10 * b00 + a11 * b10) % MOD
    copy[3] = (a10 * b01 + a11 * b11) % MOD

def power_2x2(mat: Matrix, n: int) -> Matrix:
    res = identity_2x2()

    while n:
        if n & 1:
            multiply_2x2(res, mat, res)

        multiply_2x2(mat, mat, mat)

        n >>= 1

    return res

def fib(n: int) -> int:
    if n == 0:
        return 0

    magic = [1, 1, 1, 0]
    mat = power_2x2(magic, n - 1)
    return mat[0]

if __name__ == '__main__':
    print(fib(10 ** 18))

This is faster because the default interpreter (CPython) executes loops very slowly, so it is better to avoid them as much as possible. It is also faster because no additional list is created.

Please note that if you want your code to run faster, you could use the PyPy interpreter.


CodeIgniter AJAX messages submission security issue

First of all you should use site_url() in your jquery code instead of base_url() as it provides url flexibility. For more info visit http://codeigniter.com/user_guide/helpers/url_helper.html

And in your controller code i suggest you to use bulk insert instead of loop insert. So you may use this piece of code:

foreach( $pieces as $user_id2)
{
    $insert_arr[] = array('user_id1'=> $user_id, 'user_id2'=> $user_id2, 'message'=>$msg);
}

$this->db->insert_batch('messages', $insert_arr);


Because it's a framework static methods are used as my preferred method to access a class from multiple classes without having to worry about creating variables of instances that I either have to remember globally or re-instantiating the class constantly.

I don't do php, but I'll give this one a try.

Being a framework shouldn't be a reason to prefer static methods everywhere.

The Observer Pattern can be depicted as follows:

  I've taken a look at the SPL Listener/Observer model but found that it doesn't work when using static methods.

There's a reason for that. If I read the code correctly, then when you have a class called SubjectA, and register 3 observers statically, every single instance of SubjectA will have the 3 observers registered; this is unlikely to be the intended behavior (not to mention threading issues), and it's only happening because of the static stuff.1

It looks like your Listeners class is intended to be used in object composition, like, you'll create a Car class that has a Listeners instance, and you'll register listeners for an Explode event. Then you might have a Dog class that has a[nother] Listeners instance, and you'll register listeners for a Bark event. If I assessed the situation correctly, that will give you a barking Car and an exploding Dog, on top of the expected events.

1 that is, if static in php has the same meaning as static in c#, which I'm assuming here.


Using "Generics" to implement "Unit Of Work"

Trying to not promote low-level transaction implementation in initial design,
IDbContext is the place for db-transactions.
 public interface IDbContext
 {
      void Commit();
      void Rollback();
 }

Using “Generics” to implement “Unit Of Work”

public interface IUnitOfWork<T> where T: IDbContext
{
   T DbContext { get; }
}

Now the async version of IUnitOfWork
public interface IAsyncUnitOfWork: IUnitOfWork<IDbContext>
{
    Task CommitAsync(CancellationToken cancellationToken);
    Task BeginTransactionAsync(CancellationToken cancellationToken);
}

Trying to implement abstract system with our setup.
public abstract class AbstractUnitOfWork: IAsyncUnitOfWork
{
  public abstract IDbContext DbContext {get; set; }

  public AbstractUnitOfWork(IDbContext context)
  {
    DbContext = context;
  }

  public abstract Task BeginTransactionAsync(CancellationToken cancellationToken);
  public abstract Task CommitAsync(CancellationToken cancellationToken);
}


More specific types are available for an eight bit number, such as uint8_t
static keyword is dangerous (when used as an output buffer) and results in weird behaviour if your method is called twice
The arithmetic can be replaced with a more simple & (bitwise AND)

void to_binary(uint8_t x, char *output) {
    *output++ = '0';
    *output++ = 'b';
    for (int mask = 1<<CHAR_BIT-1; mask!=0 ; mask>>=1) {
        *output++ = x & mask ? '1':'0';
    }
    *output = 0; // null terminate the string
}


First a bit of nitpicking:

Naming conventions:

Please read the Capitalization Conventions by Microsoft. Method names will always be capitalized:

generateCode() becomes GenerateCode()

Your private fields (globals in your code) should be lower case: letters and numbers.

The var keyword:

From the C# Programming Guide:

  The var keyword can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code.

So lines like:

string[] RL = new string[9];

would become:

var RL = new string[9];

Separation of concerns:

From the method that generates the code, you set the value of the textbox. This is not a good practice reagarding maintenance of your code. What if you want to use that method somewhere else?

Assign the value of the method to a variable in the click event of the button and assign that value to the textbox.

private string GenerateCode()
{
    //...
}

private void Generate_Click(object sender, RoutedEventArgs e)
{
    var code = GenerateCode();
    YourTextBox.Text = code;
}

And is there a specific reason why your code returns the RL array?

The initialisation of your arrays could also be made simpler:

private readonly char[] letters= "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
private readonly char[] numbers = "01234567489".ToCharArray();

The answer of austin wernli already provides a nice solution, I have written another way of achieving this. This method uses only one loop and no if statements:

private readonly char[] _letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
private readonly char[] _numbers = "01234567489".ToCharArray();
private readonly Random _random = new Random();

private string GenerateCode()
{
    var parts = new string[4];

    for (var i = 0; i < 4; i++)
    {
        parts[i] = String.Format("{0}{1}{2}{3}", _numbers[_random.Next(0, _numbers.Length)], _letters[_random.Next(0, _letters.Length)], _numbers[_random.Next(0, _numbers.Length)], _letters[_random.Next(0, _letters.Length)]);
    }

    return String.Join("-", parts);
}

Example usage:

private void Generate_Click(object sender, RoutedEventArgs e)
{
    YourTextBox.Text = GenerateCode();
}

This can be a bit simplified by generating an extension method to get a random element from the array:

The extension method:

public static class Extensions
{
    private static readonly Random Random = new Random();

    public static char GetRandom(this char[] collection)
    {
        return collection[Random.Next(0, collection.Length)];
    }
}

The method:

private string GenerateCode()
{
    var parts = new string[4];

    for (var i = 0; i < 4; i++)
    {
        parts[i] = String.Format("{0}{1}{2}{3}", _numbers.GetRandom(), _letters.GetRandom(), _numbers.GetRandom(), _letters.GetRandom());
    }

    return String.Join("-", parts);
}


Determining if a sequence is a palindrome

Following is my solution. It's much less code. It also handles the case of string literals correctly (e.g., is_palindrome("aba")).

In modern C++ (11 and onward), there is no need to differentiate predicate and non-predicate versions of generic algorithms. The fact that the standard library does overload predicate and non-predicate versions is simply due to historical reasons. See this S.O. topic for details.

#include <functional>
#include <iterator>
#include <utility>

template <typename Iterator, typename Pred = std::equal_to<void>>
bool is_palindrome(Iterator beg, Iterator end, Pred pred = Pred{}) {
  if (beg == end) return true;
  end = std::prev(end);
  if (beg == end) return true;
  do {
    if (! pred(*beg++, *end--)) return false;
  }
  while (beg != end && beg != std::next(end));
  return true;
}

template <typename T, typename Pred = std::equal_to<void>>
bool is_palindrome(const T& x, Pred pred = Pred{}) {
  return is_palindrome(std::begin(x), std::end(x), std::move(pred));
}

template <std::size_t n, typename Pred = std::equal_to<void>>
bool is_palindrome(const char (&x)[n], Pred pred = Pred{}) {
  return is_palindrome(x, x + n - 1, std::move(pred));
}


It is a good Idea to create a generic object model that may represent an XML document. Therefore, the .Net Framework already contains such models: XmlDocument and XDocument.

I would really suggest to use them.

Some comments to your code:

Methods and properties usually start with a capital letter in C#.
The method getChild throws an exception if no element was found. Consider to return null instead because it is not an exceptional use case and returning null is more flexible.
The field subList could be read-only.
C# has the concept of Properties which should be used instead of get* and set* methods

buildObject.setName(startNode.Name);
buildObject.setValue(startNode.InnerText);

The code above does not produce the expected result because InnerText is not just the inner text of the current node but the text of the current and all sub nodes. The following XML for example:

<xml>
    <test>
        <blub>foo</blub>
        <blub>bar</blub>
    </test>
</xml>

Produces something like:

XmlObject(Name: xml, Value: foobar)
    XmlObject(Name: test, Value foobar)
        XmlObject(Name: blub, Value foo)
        XmlObject(Name: blub, Value bar)


Negation detection in sentiment analysis

Here are a few suggestions on how to improve the code:
State the intent
What is the purpose of the function? What is the input, what is the output? In human words, what does the algorithm do? A docstring answering those basic questions would be helpful. A series of concise unit tests would be great.
I ran the function to have a look at the output:
>>> text = "The weather is not good."
>>> result = negate_sequence(self=None, text=text)
>>> print(result)

['the', 'weather', 'the weather', 'is', 'weather is', 'the weather is', 'not', 'is not',
'weather is not', 'not_good', 'not not_good', 'is not not_good']

This doesn't ring a bell with me, so I stopped trying to understand the purpose.
Avoid stateful loops
Iteration i is coupled to iteration i-1 by the negation variable, this makes the logic hard to understand and error prone. If you work on bigrams/trigrams, I'd create a list of bigrams/trigrams and iterate over the tuples. This decouples the iterations.
Breakup long functions
This has almost endless benefits, as a starting point see this article. Some possibilities:

Have the text broken up into all lowercase and without punctuation by extract_words(text)
Have the list of trigrams created by make_trigrams(words)
Inspect the trigrams by process(trigrams)
If needed, have some kind of aggregate(results)

Once this is done, I guess we are much better to prepared to identify bugs and to further improve functionality.


Extracting a sentence containing a specific word from a longer text

There are a few things of interest with your solution. Firstly, it is a very literal implementation of the problem to solve, and I worry that it is too literal. For example, are you sure that sentences end with just a period .? Is it not a period and some whitespace? Is a URL like example.com two sentences?

The second issue I have is the blind trust you have in the inputs. You happily convert the input text to lower-case (too often, actually), but you do not convert the word to lower-case. If someone gives an upper-case word, you'll never find it.

I would prefer a more zen approach, using regular expressions... actually, just a split, and some Java 8 niceness.

private static final Pattern END_OF_SENTENCE = Pattern.compile("\\.\\s+");

public static String getSentence(String text, String word) {
    final String lcword = word.toLowerCase();
    return END_OF_SENTENCE.splitAsStream(text)
            .filter(s -> s.toLowerCase().contains(lcword))
            .findAny()
            .orElse(null);
}

Why is that better? Well, it streams the text in the form of sentences, and then finds the first match in a sentence. If there are no sentences, it matches the whole thing.

Note that the same principles can be used with a non-streaming approach. Split by sentences, then find the first match.

In an android environment, you could do:

private static final Pattern END_OF_SENTENCE = Pattern.compile("\\.\\s+");

public static String getSentence(String text, String word) {
    final String lcword = word.toLowerCase();
    for (String sentence : END_OF_SENTENCE.split(text)) {
        if (sentence.toLowerCase().contains(lcword)) {
            return sentence;
        }
    }
    return null;
}

Note that the results from the above code may, or may not include the terminating period. If the match is in the last sentence of a text, and that text ends with a period, then the period may be returned as part of the result. If there is a match in the middle of the text, then the period will not be included.


First: in the book 'Refactoring' by Martin Fowler,  one of the code smells is "Obsession with elementary types". And the advice is to create/take out variables and move them to another class.

Array is an elementary type. The resolution is to create an entity class Settings and set member variables $lvl,$xp,$nxtlevel.

Second: global $db; transfer through object.

Using global variables is bad practice. If you want to use a Database you should create an object for Database access. Best practice use DI. For PHP one such library is php-di.

Your code may look like this:

<?php

  class LevelingSystem {

  private $settings;
  private $db;

  function __construct(SettingsEntity $settings, DBInterface $db ){
    $this->settings=$settings;
    $this->db = $db;
  }

  public function setxp($setxp) {
    $result =  $this
                ->db
                ->prepare("UPDATE user_atri SET totalxp =totalxp+" . $setxp . " WHERE id=1")
                ->execute();

    if(!$result) {
       throw new Exception('DB error');  //you can send your exception
    }

    return $this;
  }

  public function calcSettings() {
   $xp = $this->getxp();
   $nxtlevel = $this->settings->getNxtlevel();
   $lvl = $this->settings->getLvl();

   while ($xp >= $nxtlevel) {
        $lvl += 1;
        $xp = $xp - $nxtlevel;
        $nxtlevel = round($nxtlevel * 1.6);
    }

     $this->settings
     ->setlvl($lvl)
     ->setXp($xp)
     ->setNxtlevel($nxtlevel);

     return $this;
  }

  public function getLvl() {
      return $this->settings->getLvl();
  }

  private function getxp() {
    $totalxp = $db
                ->prepare("SELECT totalxp FROM user_atri where id=1")
                ->execute()
                ->fetch(PDO::FETCH_ASSOC);

    if(!isset($totalxp["totalxp"])) {
       throw new Exception('Some DB error'); //you can send your exception
    }

    return $totalxp["totalxp"];
  }
}


I agree with you that the if-first-three-lines predicate is not needed. I like Massa's solution, https://codegolf.stackexchange.com/questions/139900/first-they-came/140247#140204 :

print(' they came for '.join(
    ["First"]
    + [f"the {i}s, and I did not speak out-\nBecause I was not a {i}.\n\nThen"
       for i in ['Socialist', 'Trade Unionist', 'Jew']]
    + ['me-and there was no one left to speak for me.']))

It says everything additively, without subtracting any special cases. Perhaps you'd like to port that approach.


Bush Wanderer - code intended for teaching

Because the code you write is to be used for teaching, the importance is not on performance, but on correctness and readability and understandability (comphrensiveness?).

So basically...

Add comments! Explain each step, so that the kids are gonna see the code, think "what does it do", and they can read it right there!
Don't use dx and dy, use more explanatory variables!

Let's combine them:

  if dx == x and dy == y:
    if moves == 1:
      print('You died in', moves,'move!')
    elif moves > 1 or moves == 0:
      print('You died in', moves,'moves!')
    break
  elif cx == x and cy == y:
    if moves == 1:
      print('You won in', moves,'move!')
    elif moves > 1 or moves == 0:
      print('You won in', moves,'moves!')
    break

This is hard to understand. dx and dy were hard to grasp at first - when doing games programming, usually dx and dy are "delta-x" and "delta-y", to calculate object velocity.

But it's dragon x y and chest x y here!

So just call it that.

  if dragon_x == x and dragon_y == y:
    if moves == 1:
      print('You died in', moves,'move!')
    elif moves > 1 or moves == 0:
      print('You died in', moves,'moves!')
    break
  elif chest_x == x and chest_y == y:
    if moves == 1:
      print('You won in', moves,'move!')
    elif moves > 1 or moves == 0:
      print('You won in', moves,'moves!')
    break

Next, I'd usually tell you to split this up into functions. But maybe these kids don't know functions yet, and it's remarkably frustrating to be shown "the solution" when "the solution" consists of "this magic trick I didn't teach you yet, haha".

Use comments instead, and be sure to teach them what a comment is and what its for. If you have to review homework, a comment might be all you get to understand their code.

  #check for loss by comparing dragon and player location
  if dragon_x == x and dragon_y == y:
    if moves == 1:
      print('You died in', moves,'move!')
    elif moves > 1 or moves == 0:
      print('You died in', moves,'moves!')
    break
  #else, check for victory by comparing chest and player location
  elif chest_x == x and chest_y == y:
    if moves == 1:
      print('You won in', moves,'move!')
    elif moves > 1 or moves == 0:
      print('You won in', moves,'moves!')
    break

Note that function names make good comments. Instead of checkForVictory() we just put #check for victory. I recommend you start comments with why, and then with how. How-comments should eventually be removed (you can read the code), and why-comments should stay, but when learning how to program, having the explanation next to the code just helps. It also promotes micro problem-solution flow (in my opinion), which is what you need later if you want to split up code into smaller chunks or problems.

And this loop here...

  for i in range(grid):
      if i == dy and i == y:
        for u in range(grid):
          if u == dx:
            print('@ ', end='')
          elif u == x:
            print('x ', end='')
          else:
            print('# ', end='')
        print()
      elif i == y:
          print('# '*x, end="")
          print('x ', end="")
          print('# '*((grid-x)-1))
      elif i == dy:
          print('# '*dx, end="")
          print('@ ', end="")
          print('# '*((grid-dx)-1))
      else:
        for i in range(grid):
          print('# ', end="")
        print()

Is mighty confusing. There is no easily discernible pattern to it. If you had to explain the thought process that went into each step, what would you say? (Teacher, I don't understand, how did you create this?)

Here's mine:

per tile:
  print dragon if dragon is on tile
  print player if player is on tile
  print empty tile if nobody is on tile

Those are the requirements, next up is realizing that if we have a grid, we ought to do it by row and columns:

for each row
  for each column
    if the dragon is on that tile
     print dragon
    else if the player is on that tile
     print player
    else
     print empty tile
  print new line, to go to next row

And then translate to python (untested)

for i in range(grid)
  for u in range(grid)
    if i == dragon_y and u == dragon_x:
     print('@ ', end='')
    elif i == player_y and u == player_x:
     print('x ', end='')
    else:
     print('# ', end='')
  print()

Another reason for this is that if you were to get a question like, "how do we add mountains, where the dragon can wander, but the player can't?", you'd be stumped. Or at least I would be, if I had to add mountains into your display code. It's all about clever tricks with multiplying strings. You'd have to alter ALL your cases. Or if there were two dragons, because, you know, hard mode. Again, it would take you a major overhaul.

I'd just make a simple change:

for each row
  for each column
    if there is a dragon on that tile
     print dragon
    else if the player is on that tile
     print player
    else if that tile is a mountain
     print mountain
    else
     print empty tile
  print new line, to go to next row

and it supports mountains and multiple dragons!

Possibly the best thing you could do is take another look at your code, and remove the python element from it. Start in English, and convert that to python. I bet that's what the kids will be doing.

Using an approach like this, the code is going to be a lot shorter and easy to understand. Yes, it's slower by doing all the checks all the time. But for these kids, it's probably going to be more important that they understand the code, than that it runs three times as fast. Computers these days are forgiving, and you can always teach them better optimizations later.

Plus, if they were to shy away from programming because the code is too complex, that'd be a darn shame.

And get comfortable with your code before the lesson. It would be best if you could do live editing in the classroom.

As for industry standards...

  for i in range(grid):
      if i == dy and i == y:
        for u in range(grid):
          if u == dx:
            print('@ ', end='')
          elif u == x:
            print('x ', end='')
          else:
            print('# ', end='')
        print()
      elif i == y:
          print('# '*x, end="")
          print('x ', end="")
          print('# '*((grid-x)-1))
      elif i == dy:
          print('# '*dx, end="")
          print('@ ', end="")
          print('# '*((grid-dx)-1))
      else:
        for i in range(grid):
          print('# ', end="")
        print()

Extract to printGrid.

  m = input('Which way would you like to move?(N,E,S or W)').lower()

  if m == 'n' and y > 0:
      y = y-1
  elif m == 'e' and x < (grid-1):
      x = x+1
  elif m == 's' and y < (grid-1):
      y = y+1
  elif m == 'w' and x >0:
      x = x-1
  else:
      print('Invalid move')

  moves = moves + 1

Extract to pickMove, and use a while loop to make sure that the move counter (moves) doesn't go up if you make a bad move.

Encapsulate conditionals by putting checks like dy == y and dx == x into either a function isDragonEatingPlayer (naming is hard) or just a temporary variable of some sorts.


Haskell/Yesod - Butchering use of MaybeT

I'd suggest these points to simplify your code:

Make everything that returns Maybe something into MaybeT, and as close to the origin as possible. This will make composition of your functions much easier. For example:

lookupIdGetParam :: (PathPiece (Key a), MonadHandler m) => Text -> MaybeT m (Key a)
lookupIdGetParam name = liftM fromPathPiece (MaybeT $ lookupGetParam name)

Notice using MaybeT just at lookupGetParam, then we don't need to duplicate MaybeT's functionality in the case expression.

This also helps you to avoid complicated code with two nested monads (such as SqlPersistT m (Maybe MarketingCampaigns)) and then complex and hard-to-read operations on them like fmap join (mapM ...).
MaybeT . fmap Just is equivalent to lift.
Whenever applicable, use functions from MonadPlus. Not just mzero (which is here equivalent to Nothing) and mplus, there are also some other very useful ones such as mfilter or guard. Like in:

fetchCampaigns :: MonadHandler m => Key User -> Key Dealership -> MaybeT (SqlPersistT m) MarketingCampaigns
fetchCampaigns userKey dealershipKey = do
  enabled <- lift $ campaignsEnabled userKey dealershipKey
  guard enabled
  lift $ getCampaigns dealershipKey

Something to try out, I'm not sure if this will help you, but it might: Instead of a function that returns a Bool in a monad, return MaybeT MyMonad () such that original False corresponds to a failure in MaybeT and True to a () value. To be specific, instead of isDiscountEligible, you could have

checkDiscountElegible :: MonadHandler m => Key Vehicle -> MaybeT (SqlPersistT m) ()
checkDiscountElegible vehicleKey = do
  vehicle <- MaybeT (get vehicleKey)
  hasDiscount <- vehicleHasDiscount <$> (MaybeT . get $ vehicleManufacturer vehicle)
                                    <*> pure vehicle
  guard hasDiscount

The idea is that this will make these functions composable with the other MaybeT ... ones, and avoid the tedious M.fromMaybe False <$> runMaybeT.

In other words, in MaybeT m Bool there are two failure modes: One failing within the monad, and another returning False. If you know from the beginning that they're both equivalent, just collapse them instead of keeping the distinction.

Disclaimer: I haven't tried to compile any of the above, so there might be syntax errors, but hopefully the meaning is clear.


The most obvious point is probably that the standard library already includes std::shuffle, so there's little point in creating your own.

If you do decide to write your own shuffle, you probably want to look up the Fisher-Yates Shuffle algorithm. What you're doing right now can introduce biases (actually, it introduces a couple of different biases in entirely different ways).

If you're going to generate random numbers in C++, you're generally better off using the "new" generators found in <random> instead of using srand/rand from <stdlib.h>/<cstdlib>.

Probably also want to use the standard distribution classes instead of rolling your own with the modulus operator (that's one of your current sources of bias1).

Even if you do insist on writing your own and using srand/rand, you must call srand only once, probably when your program starts, not separately each time you're going to use some random numbers.
I advise against using std::endl. Most of the time (including this case) printing a new-line ('\n') will do what you want, and frequently be substantially faster. In addition to writing a new-line, std::endl flushes the stream, which is almost never necessary or desirable.
Instead of:

std::cout << "Word found in " << count
          << " guess" << (count>1?"es":"")

I'd rather use:

std::cout << "Word found in " << count
      << (count > 1 ? "guesses" : "guess";

At least to me, this makes it somewhat easier to follow what's going on (and a trade between easier to read and saving half a dozen bytes of string constant seems pretty easy to me, at least most of the time).
Finally, Add the appropriate includes for the features you use.

std::string => #include <string>
std::srand() => #include <cstdlib>
std::time() => #include <ctime>
srand() => #include <stdlib.h>      // Note the difference between C++ and C version.
time() => #include <time.h>

1. consider a generator that produced 0, 1, or 2 and you used %2 to get only 0 or 1. You'd get 1 only when the generator produced 1, but you'd get 0 when it produced either 0 or 2, so assuming the generator produced 0, 1, and 2 equally frequently, your output would be 0 about twice as often as it was 1. With larger ranges, the bias tends to be less extreme (and less visible) but the same basic mechanism causes the same basic problem.