C++ heap CPS: Continuation Passing Style with Recursion

Code Review

Use standard library data structures! In this case std::list.
Iterators are the usual way of traversing a C++ container, so use those too (they also allow us to not care which data structure is being used).
Use std::size_t or even std::container<T>::size_type for indexing. An int is signed, and won't necessarily cover the correct range to be indexed.
lenK and lenKheap return doubles, but should presumably return the index type.

template<class IteratorT>
std::size_t length(IteratorT begin, IteratorT end, std::size_t totalLength = 0) {
    return (begin == end) ? totalLength : length(std::next(begin), end, totalLength + 1);
}

using F = std::function<std::size_t(std::size_t)>;

template<class IteratorT>
std::size_t lengthK(IteratorT begin, IteratorT end, F k = [] (std::size_t a) { return a; }) {
    return (begin == end) ? k(0) : lengthK(std::next(begin), end, [k] (std::size_t a) { return k(a + 1); });
}

...

    auto list = std::vector<int>{ 0, 1, 2, 3 };

    std::cout << length(list.begin(), list.end()) << std::endl;
    std::cout << lengthK(list.begin(), list.end()) << std::endl;

Note that the stack overflow that happens with long lists is due to the depth of recursion. std::function may already be using the heap to allocate memory. As such, there's not much point in using unique_ptr.

In theory we could use the type hiding already present in std::function, rather than defining a separate inheritance hierarchy, and do something like this:

template<class IteratorT>
std::size_t lengthKHeap(IteratorT begin, IteratorT end, std::unique_ptr<F>&& k = std::make_unique<F>([] (std::size_t a) { return a; })) {
    return (begin == end) ? (*k)(0) : lengthKHeap(std::next(begin), end, std::make_unique<F>([k = std::move(k)](std::size_t a) { return (*k)(a + 1); }));
}

However, this doesn't compile. Although lambda capture by move was added in C++14, std::function is still required to be copyable. We can use a dodgy work-around storing the parameters in a shared pointer like this:

// hideous hack from here: https://stackoverflow.com/a/20846873/673679
template<class F>
auto make_copyable_function(F&& f) {
    auto spf = std::make_shared<std::decay_t<F>>(std::forward<F>(f));
    return [spf] (auto&&... args) -> decltype(auto) { return (*spf)(decltype(args)(args)...); };
}

template<class IteratorT>
std::size_t lengthKHeap(IteratorT begin, IteratorT end, std::unique_ptr<F>&& k = std::make_unique<F>([] (std::size_t a) { return a; })) {
    return (begin == end) ? (*k)(0) : lengthKHeap(std::next(begin), end, std::make_unique<F>(make_copyable_function([k = std::move(k)](std::size_t a) { return (*k)(a + 1); })));
}

But as mentioned, this doesn't help avoid the stack overflow.

Deviations

Things become much more interesting if we stop using recursion and store a vector of functions instead. This allows us to make the control flow explicit (which appears to be one of the main points of using continuations). e.g.:

using NodeT = std::function<void()>;

struct Then {

    void add(NodeT node) {
        m_nodes.push_back(std::move(node));
    }

    void operator()() const {
        for (auto& n : m_nodes)
            n();
    }

private:

    std::vector<NodeT> m_nodes;
};

...

    auto i = 0;
    auto increment = [&] () { ++i; };

    auto then = Then();

    for (auto _ : list)
        then.add(increment);

    then();

    std::cout << i << std::endl;

Counting the elements in a list isn't a good example, but I've actually found this pattern of composing functions very helpful for writing lexers / parsers. By defining some more classes to go with Then (Or, ZeroOrOne, ZeroOrMore, etc.) and some operator overloading, it's possible to build up an entire tree of parsing / lexing functions with code that's very close to a simple statement of the language grammar. Which is pretty cool (if not technically continuations).

Of course, there's also asychronously oriented composition stuff using std::future, but I've not been keeping up with what's going on in the C++ standard with that lately.

facebook version.
blog series on avoiding allocations.

Full Code

#include <functional>
#include <memory>

template<class IteratorT>
std::size_t length(IteratorT begin, IteratorT end, std::size_t totalLength = 0) {
    return (begin == end) ? totalLength : length(std::next(begin), end, totalLength + 1);
}

using F = std::function<std::size_t(std::size_t)>;

template<class IteratorT>
std::size_t lengthK(IteratorT begin, IteratorT end, F k = [] (std::size_t a) { return a; }) {
    return (begin == end) ? k(0) : lengthK(std::next(begin), end, [k] (std::size_t a) { return k(a + 1); });
}

// hideous hack from here: https://stackoverflow.com/a/20846873/673679
template<class F>
auto make_copyable_function(F&& f) {
    auto spf = std::make_shared<std::decay_t<F>>(std::forward<F>(f));
    return [spf] (auto&&... args) -> decltype(auto) { return (*spf)(decltype(args)(args)...); };
}

template<class IteratorT>
std::size_t lengthKHeap(IteratorT begin, IteratorT end, std::unique_ptr<F>&& k = std::make_unique<F>([] (std::size_t a) { return a; })) {
    return (begin == end) ? (*k)(0) : lengthKHeap(std::next(begin), end, std::make_unique<F>(make_copyable_function([k = std::move(k)](std::size_t a) { return (*k)(a + 1); })));
}

#include <functional>
#include <vector>

using NodeT = std::function<void()>;

struct Then {

    void add(NodeT node) {
        m_nodes.push_back(std::move(node));
    }

    void operator()() const {
        for (auto& n : m_nodes)
            n();
    }

private:

    std::vector<NodeT> m_nodes;
};

#include <list>
#include <vector>
#include <iostream>

int main() {

    {
        auto const list = std::vector<int>{ 0, 1, 2, 3 };

        {
            std::cout << length(list.begin(), list.end()) << std::endl;
            std::cout << lengthK(list.begin(), list.end()) << std::endl;
            std::cout << lengthKHeap(list.begin(), list.end()) << std::endl;
        }

        {
            auto i = 0;
            auto increment = [&] () { ++i; };

            auto then = Then();

            for (auto _ : list)
                then.add(increment);

            then();

            std::cout << i << std::endl;
        }
    }
}


Remapping Heading Angle to Coordinates to Move By

I'll separate this into two sections: readability and maintainability. I'm not exactly sure of the usage, so I don't feel I can comment on that.
Readability
Personally, I think the largest burden on the cleanliness of this code, is the comments. I think they're too large and there's too many.
One way to improve this, is PHPDocs. Just like JavaDocs, they help organize the functionality of code properties.
Another way to reduce them is to make your variables as meaningful as possible. What exactly is $deg? What kind of degree is it? Same principle for $xdeg and $x.
Breaking apart one large method into several smaller functions can also improve the cleanliness, not to mention the benefits of modularized code and improved organization.
One last note: I see a lot of numbers. What's the decision behind these numbers. Making some of the numbers in map(180,360,180,0 constants or variables at the top can help readers understand the meaning.
Maintainability
You code is very simple (as in it takes care of one thing), and I think this is the greatest tool to avoiding confusion in the future.
Having well documented code is also great, just make sure your wording is clear and concise. Sometimes referencing to other code in the comments can help. Explain why, not how.
I don't think there's too much else you can do to future-proof this!


Well you've written you don't like it, but why?  Is this ever used with relevantly large input?  If so, you might have to consider allocating the right size of data frame from the start and assign the values afterwards.

If not, I can only see some small things that could be a little bit more succinct, and perhaps np.ones_like(df) instead of with df.loc[:,:] ... but otherwise this seems fine?

Like the following removes a bit of duplicated code, but is not inherently better:

def suffixed_columns(df, suffix):
    return ["{}{}".format(column, suffix) for column in df.columns]

def constants(df):
    return pd.DataFrame(np.ones_like(df), index=df.index, columns=suffixed_columns(df, "_Int"))

def lag(df, n):
    new_df = df.shift(n)
    new_df.columns = suffixed_columns(df, "_Lag{:02d}".format(n))
    return new_df

def lagged_dataframe(df, lags=1):
    return pd.concat([df, constants(df)] + [lag(df, i) for i in range(1, lags + 1)], axis=1)


Simplifying logic of overlapping predicates

It seems to me that the primary role of the programmer is to write clear and correct code and that it's largely the job of the compiler to turn that into efficient machine code.  With that said, it seems to me that the first fun() version is both clear and effective in that it avoids the needless overhead of computing conditions that don't need to be computed, and is sufficiently clear about the results of each predicate.

Your gun() version separates the predicates from the actions using an intermediary Triple and while it produces the same result, it makes the job of interpreting the code (for a human) a little bit harder. So I would advocate not doing it that way.

If you'd like to reduce the repetition, the way to do that would be to create subfunctions such as this:

void do123(int x) {
    fun1(x);
    fun2(x);
    fun3(x);
}

Once this is done, the multiple if statements become a bit shorter and easier to read, although at some possible expense in clarity.

If the predicates and functions are dealing solely with integers it doesn't much matter, but if they are dealing with larger items, and particularly objects with constructors and destructors, it would be helpful to use references and const as much as possible to avoid useless object copies.


Vulkan and Opengl swapable rendering backend

First of all: OpenGL and Vulkan work very differently in some parts. In the following i assume you are already familiar with vulkan.

IDrawable

There would probably some problems arise with the current design. You cannot just render something like that in vulkan, a vulkan drawable cannot implement the draw() function without that you maintain any global state (which you hopefully don't want, one of the strengths of vulkan is that you don't need that anymore and therefore gain things like threadsafety and a more reliable api performance). You would at least need a command buffer to record into, but this would change the meaning of the draw interface on different backends (immediate rendering on opengl vs recording on vulkan), which is bad. Additionally, in this case every drawable would change the bound pipeline (another thing that can be optimized using vulkan). In the end it would maybe make sense to handle drawing entirely in the renderer and maybe only expose things like material and vertices from the drawable.
Every drawable could e.g. own a Buffer object which is an interface that might be a vulkan or an opengl buffer and managed by the renderer (those are the parts where one could really nicely abstract opengl and vulkan).
In the end this also drives away the need for this rather smelly tag-based polymorphism pattern, and allows to model things in a easier, more natural way (which is usually a good sign). When you render using e.g. vulkan there should not be any opengl drawables around (should there? not a sign if there could be...) so there is no need to use this tag checking.

Templates

I am not sure your use of templates is optimal. In this case (although you just write the type Window in both cases) the both Windows are actually totally different types and therefore could not be changed at runtime. This means if you want to change the renderer you have to change the code
somewhere which is probably not what you want (The same for the Renderer class).
It would make more sense to have something like virtual (or even abstract) Renderer and Window interfaces that are then implemented by {Vulkan, GL}Window/Renderer. But doing this for renderer already drives away the need to do this for window at all, which is (at least for me) code smell anyways, the Window class should not changed dependent on the renderer used. In the case described you would need the Backend class anymore. You could of course use the Backend and the Render class but then, at least don't use templates (and I am not sure if there is enough to abstract from the both rendering apis that would justify a separate Renderer class).

Modern C++

You use C++17 features (and compile using this flag) so i assume you want to write modern C++. If so use the (great) features modern C++ gives you:

Use enum class Tag instead of enum Tag for type safety and less name pollution
Use the override keyword for functions that implement virtual ones
Use references where a nullptr is not a valid argument. Unless Renderer::draw(nullptr) has a special meaning and is therefore handled (which would proably be bad interface design) you should use a reference. Same for Window and Backend.
Window(Renderer) copies the renderer which is probably a bad idea. The renderer will be a heavy class which lots of state (which should probably not be copyable in the first place), use move semantics in a case like this. Additionally it would be nice to separate Window and Renderer, prefer to build a Renderer on top of a Window and not the other way around (how should the Renderer know to which Window it should render?). A draw method makes much sense in a Renderer but not so much in a Window (although there are many Window abstractions like this, this will lead to design issues later).

Also: No matter in which stage code is, don't name your classes something like D. And IMO Vulkan isn't a really good name either, choose something like VulkanBackend instead (same of OpenGL).

Those were just some first things that came to my mind (there are of course also things done right in your code i did not mention), there is probably more to say about it. An abstraction like this is really hard to build and (as a small - maybe opinionated - side note) it probably makes more sense to focus on one of the both api's if you do not absolutely need both since they are really different (at least in some, critical places like the rendering - plan global calls vs command buffer recording).


Find all words beginning with a given prefix

Sentinel could simply be None instead of a "custom" object.
You don't need chain either: just set the sentinel manually at the end of the for loop.
If using Python 3, you can use yield from ... instead of from ...: yield.

def insert(tree, word):
    for letter in word:
        tree = tree.setdefault(letter, {})
    tree[None] = {}  # or = None, it doesn't matter

def words_beginning_with(start, tree):
    for letter in start:
        try:
            tree = tree[letter]
        except KeyError:
            return
    for word in _all_words(tree):
        yield start + word

def _all_words(tree, start=''):
    for letter, tree in tree.items():
        if letter is None:
            yield start
        else:
            yield from _all_words(tree, start + letter):


Code hygiene

What is $("#serial")?  Did you mean $("#manual").empty() instead?

You are sloppy in localizing your variables.  a, b, j, k, c, l, lastValue, and max (the one in the $manual.on('change') handler) are all global.  All of them are horribly named.  Furthermore, I recommend eliminating unnecessary variables.

Take care to end your statements with a semicolon.  It's considered good practice even though the language doesn't require them.

Performance

There are two major problems.

The first issue is that it is much more efficient to append a giant string all at once than to manipulate the DOM an element at a time.

The second problem is that you are defining a change handler within a change handler.  That means the #manual element gets regenerated more and more frantically with each change in the first two columns.

function pad(str, max) {
    str = str.toString();
    return str.length < max ? pad("0" + str, max) : str;
}

$('#manual').on('change', function() {
    var autoOptions = '';
    var lastValue = +$(this).find('option').last().val();
    for (var i = 1 + +$(this).val(); i <= lastValue; i++) {
        // Should i be padded to 7 digits?
        autoOptions += '<option value="' + i + '">' + i + '</option>';
    }

    $('#automatic').html(autoOptions);
});

$("#game, #camp").on('change', function() {
    var gameCamp = pad($('#game').val(), 2) +
                   pad($('#camp').val(), 2);

    var manualOptions = '';
    for (var i = 1; i <= 200; i++) {
        var iii = pad(i, 3);
        manualOptions += '<option value="' + gameCamp + iii + '">' + gameCamp + iii + '</option>';
    }
    $('#manual').html(manualOptions)
                .change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select id="game">
    <option value="01">01</option>
    <option value="02">02</option>
    <option value="03">03</option>
    <option value="04">04</option>
    <option value="05">05</option>
    <option value="06">06</option>
    <option value="07">07</option>
</select>

<select id="camp">
    <option value="11">11</option>
    <option value="22">22</option>
    <option value="33">33</option>
    <option value="44">44</option>
    <option value="55">55</option>
    <option value="66">66</option>
    <option value="77">77</option>
</select>

<select id="manual"></select>
<select id="automatic"></select>


This looks reasonable and idiomatic to me.

I don't recognise the reduction strategy, though. Specifically, the line

red (App a b) = App (red a) (red b)

looks like you're not reducing to a normal form, and you might be reducing, say, one redex in the function and one in the argument. This may be intentional on your part, but if it isn't, maybe take a look here for a brief overview of reduction strategies, or here for more detail.

I haven't looked at de Bruijn indices in a while, so I wouldn't be able to promise that your implementation is correct. Nothing untoward comes to mind, though.

About the style–and this is really nitpicking–in the subs definition you might use simply a instead of the cumbersome abstraction. And I'd have indented the | one more space. (See? Nitpicking.)


Style

Almost all the naming of the parameters and methods are good.
RsaProcessor() sounds like a noun. Based on the naming guidlines you should use verbs or verb phrases to name your methods. Maybe a simple name like Process() would be sufficient here.

In the RsaProcessor() method I would suggest to introduce as Boolean forEncryption. In this way the meaning of this line

_engine.Init(!key.IsPrivate, key);

will be obvious.

private byte[] Process(byte[] data, int offset, int length, AsymmetricKeyParameter key)
{
    Boolean forEncryption = !key.IsPrivate;

    _engine.Init(forEncryption , key);

    var blockSize = _engine.GetInputBlockSize();

    var result = new List<byte>();
    for (var i = offset; i < offset+length; i += blockSize)
    {
        var currentSize = Math.Min(blockSize, offset + length - i);
        result.AddRange(_engine.ProcessBlock(data, i, currentSize));
    }
    return result.ToArray();
}

Otherwise your code seems to look good.

Regarding your Unsure about the certinaty parameter See https://stackoverflow.com/a/3087161/2655508

  The RSA key generation requires prime numbers. However, it's impossible to generate absolute prime numbers. Like any other crypto libraries, BC uses probable prime numbers. The certainty indicate how certain you want the number to be prime. Anything above 80 will slow down key generation considerably.


I tried this in VS2019 and I needed to #include <string> in order to compile.

Then I get a warning for the line

long product_of_primes = 600851475143;

which says

  truncation from __int64 to long

which means that long is not enough to hold that number. Since it's positive, I changed that to unsigned long long.

For the remaining review, I'll go through your code from top to bottom, trying to understand it. Whenever I find something, I'll point it out.

If you change

  // Holds the prime factors.
  std::vector<int> primes;

to

std::vector<int> prime_factors;

you can get rid of the comment and the variable becomes self-explaining.

The method

int get_prime_above(int i = 1)

IMHO should not support a default value. As you see in your code, you're calling it with

int current_prime = get_prime_above(1);

and seeing a call with the default value

int current_prime = get_prime_above();

would not make sense to the reader.

Another open question is: which prime above i will the method return? Just any? The next? At this point of understanding and from the comment, I'd propose the name

next_prime_after(int i)

At the same time, I'd change the parameter i to minimum.

I stumbled over the line

while (target_number > 1) {

because I was expecting some other number increasing towards that target. However, your code reduces target_number to become 1. Given that target_number is a product of prime numbers, I would call it product_of_primes instead. Again, you can now remove the comment for that variable.

Again, you need a comment to explain what a variable means:

// Does the target divide by the prime evenly?
long result = product_of_primes % (long)current_prime;

Note that the comment asks a yes/no question, which is why I would expect a boolean. However, the result is a long. Also, the cast to (long) seems redundant. My proposal:

bool is_divisor = 0 == product_of_primes % current_prime;

This also changes the conditional statement to

if (!is_divisor) {

so the comment here is redundant, so it can be removed:

// If not, move on to the next prime.
current_prime = next_prime_after(current_prime);

In order to simplify the branch we have now:

if (!is_divisor) {
    current_prime = next_prime_after(current_prime);
    continue;
}

you can initialize current_prime to 1 and then call next_prime_after() at the beginning of the loop like this:

int current_prime = 1;
while (product_of_primes > 1) {
    current_prime = next_prime_after(current_prime);
    bool is_divisor = 0 == product_of_primes % current_prime;
    if (!is_divisor) continue;
    ...
    current_prime = 1

product_of_primes = (long)product_of_primes / (long)current_prime;

This IMHO has redundant casts and can be simplified to

product_of_primes = product_of_primes / current_prime;

   This, however, will change the result from 71 to the correct value expected by Project Euler to complete the challenge.

current_prime = 1;

IMHO, you don't need to restart at the beginning, since you'll not find prime factors lower than the one you already found.

However, it will not change performance significantly.

Instead of reversing

std::reverse(prime_factors.begin(), prime_factors.end());

you can simply get the last element of the vector

std::cout << "Largest prime: " + std::to_string(prime_factors.back()) << std::endl;

or (my preferred option in this case) sort in descending order

std::sort(prime_factors.begin(), prime_factors.end(), std::greater<int>());

---- Dunno, the horizonal rulers stop working in this line

Woah, this is ugly:

if (current_number <= minimum) {
  current_number++;
  continue;

This can simply be replaced by

int current_number = minimum + 1;

And in consequence the loop can be re-written as

int next_prime_after(int minimum) {
    int current_number = minimum + 1;
    while (!is_prime(current_number)) {
        current_number++;
    }
    return current_number;
}

In that same method, we probably get a performance benefit of a factor of 2 if you move to odd numbers.

int next_prime_after(int minimum) {
    int current_number = minimum + 1;
    current_number += minimum % 2; // ensure odd number
    while (!is_prime(current_number)) {
        current_number += 2;
    }
    return current_number;
}

A had a WTF moment here:

float result = ((float)number / (float)tmp);
// If the result has decimals, it doesn't divide equally
// so return false.
if (!has_decimals(result)) {

Why? Because you already did a proper divisability check somewhere else (cited from the original code):

// Does the target divide by the prime evenly?
long result = target_number % (long) current_prime;

That way, you can get rid of the whole method has_decimals().

for (int tmp = number - 1; tmp > 1; tmp--) {

When you learned dividing numbers in school, did you start by dividing an arbiotrary number like 56 by it's predecessor 55 to check if it is a prime factor? Certainly not. So let's not do it in your code as well. Go simple: check if 56 is divisable by 2.

Oh, and BTW: if you can't divide 56 by 2, you can also not divide it by anything > 28, right? Make a huge performance impact of a factor ~10.

bool is_prime(int number) {
    for (int divisor = 2; divisor < number/2; divisor++) {
        bool is_divisor = 0 == number % divisor;
        if (is_divisor) {
            return false;
        }
    }
    return true;
}

This could be reduced to sqrt(2) instead of number/2 if you think about it.

Starting at 3 and testing odd numbers only will increase by another factor of 2:

bool is_prime(int number) {
    if (number % 2 == 0) return false;
    for (int divisor = 3; divisor < number/2; divisor+=2) {
        bool is_divisor = 0 == number % divisor;
        if (is_divisor) {
            return false;
        }
    }
    return true;
}

For this Project Euler question, int prime factors see to be good enough. For general purpose factorization, you should consider at least long.

My final proposal for you

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include "fibonacci.h"
#include <limits>

int next_prime_after(long minimum);
bool is_prime(long number);

int main() {

    unsigned long long product_of_primes = 600851475143;
    std::vector<int> prime_factors;

    int current_prime = 1;
    while (product_of_primes > 1) {
        current_prime = next_prime_after(current_prime);
        bool is_divisor = 0 == product_of_primes % current_prime;
        if (!is_divisor) continue;

        prime_factors.push_back(current_prime);
        product_of_primes = product_of_primes / current_prime;
        current_prime--;
    }

    std::sort(prime_factors.begin(), prime_factors.end(), std::greater<int>());
    std::cout << "Largest prime: " + std::to_string(prime_factors[0]) << std::endl;
}

/**
 * Get the next prime number above minimum.
 * @param minimum
 * @return
 */
int next_prime_after(long minimum) {
    long current_number = minimum + 1;
    current_number += minimum % 2; // ensure odd number
    while (!is_prime(current_number)) {
        current_number += 2;
    }
    return current_number;
}

/**
 * Is the given number a prime?
 * @param number
 * @return bool
 */
bool is_prime(long number) {
    if (number % 2 == 0) return false;
    for (long divisor = 3; divisor < number/2; divisor+=2) {
        bool is_divisor = 0 == number % divisor;
        if (is_divisor) {
            return false;
        }
    }
    return true;
}

Summary

I hope you agree with my proposals and see that the resulting code is

easier to read
bug fixed
faster by a factor of ~100 (measured using QueryPerformanceCounter())


struct Fork {
    std::mutex mux;
};
std::vector<Fork*> forks;

I think the problem you want to solve by using pointers here is that a std::mutex is not copyable nor movable. By using raw owning pointers, you'll get a bunch of unpleasant properties. For example, you have to implement a destructor, and might have to worry about exception safety.

Typically, using smart pointers instead of raw owning pointers is a better idea, since it avoids many of those unpleasant side-effects. But the original problem can be solved differently:

std::vector<std::mutex> forks; // data member
DiningPhilosopher(..) // constructor
  : // ...
  , forks(5)
{}

This uses a vector constructor that constructs 5 std::mutex in-place. It therefore does not require that the value type is movable. You cannot resize such a vector, though, nor can you add new entries via push_back etc, even if there's space left (capacity > size). If you have a fixed number of forks, you could use a std::array as well.

If you need to add more forks later, or need to resize:

std::vector<std::unique_ptr<std::mutex>> forks;
DiningPhilosopher(..) // constructor
  : // ...
  , forks(5)
{
    for(auto& fork : forks) fork = std::make_unique<std::mutex>();
}

make_unique is C++14, but can be easily implemented in C++11 as well.
It is also possible to use std::generate_n:

DiningPhilosopher(..) // constructor
  : // ...
{
    std::generate_n(std::back_inserter(forks), 5
                    []{ return std::make_unique<std::mutex>(); });
}

threads.push_back(std::thread(&DiningPhilosopher::Philosopher, this, i));

This can be replaced by the slightly simpler:

threads.emplace_back(&DiningPhilosopher::Philosopher, this, i);

Or even:

threads.push_back([this, i]{ Philosopher(i); });

std::for_each(threads.begin(),threads.end(), std::mem_fn(&std::thread::join));

alternative:

for(auto& t : threads) t.join();

One might argue about the use of "raw loops", but you don't need the position of each thread (the iterator) here. Therefore, I'd say that a for-each loop is fine as well; and it's shorter.

void Philosopher(int id)

The name of this function surprised me when I encountered &DiningPhilosopher::Philosopher earlier. It almost looked like a data member, since it's not formulated as a verb. From a code organization perspective, I think it should be earlier in the code, before the functions it calls. This allows a top-down reading from the higher to lower level functions.

 std::cout << "Philosopher "<< id << " is eating" << std::endl;
 this->Think(id);
 std::cout << "Philosopher "<< id << " has finished eating" << std::endl;

The philosopher thinks while they're eating? Ok, I think it is code reuse, but the name confused me. Why not introduce an intermediary function wait_for_random_time that is used to implement both thinking and (the actual) eating? Similarly, the function Eat doesn't just let a philosopher eat. It does more (waiting to eat etc.)

int sleep_for_random_time() {
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<double> dist(1000, 4000);

    return dist(mt);
}

glampert has already criticised the name of this function in his answer, the fact that it repeatedly creates a random_device as well as a mt19937, and the usage of double.

I'd also like to point out that creating both generators seems strange to me: First you get a (potentially pseudo-)random number from one random number generator (the random_device). Then, you use it to seed another random number generator, to create a pseudo-random number. The second step is unnecessary, if you trust the quality of your random_device implementation enough: It either produces true random numbers, or - and that's the Quality Of Implementation aspect - evenly distributed pseudo-random numbers. The following should be sufficient:

int sleep_for_random_time() {
    std::random_device rd;
    std::uniform_int_distribution<int> dist(1000, 4000);
    return dist(rd);
}

The original code followed a common pattern of creating pseudo-random numbers. Typically, one does not use the random device to create all random numbers because it is slow (it might run out of entropy, too, depending on the implementation). You'd therefore use it only once to initialize a single mersenne twister. Successive requests for pseudo-random numbers would use this single mersenne twister to produce pseudo-random numbers. For example:

 int sleep_for_random_time() {
     static std::mt19937 mt{ std::random_device{}() };
     std::uniform_int_distribution<int> dist(1000, 4000);
     return dist(mt);
 }

Arguably, even the distribution should be static, to allow recycling unused bits of the output of the generator. As Deduplicator points out, there could/should be one generator per thread. The above code uses one shared generator, which is not thread-safe, since dist(mt) modifies the state of the (now shared) generator. There are several ways to make this thread-safe, one of them is:

 int sleep_for_random_time() {
     thread_local std::mt19937 mt{ std::random_device{}() };
     std::uniform_int_distribution<int> dist(1000, 4000);
     return dist(mt);
 }

This associates an individual mersenne twister for each thread. Each of them is created once, for the lifetime of the thread.

this->Think(id);

Again this line, but this time in isolation. First, why is there a this? It seems to be used whenever you call a member function. Why?

Additionally, the id is currently unnecessary. If it was not, there should be a way IMHO to make sure that each philosopher thinks for themselves. Something like

Think();

should be sufficient; however it requires an object to represent each philosopher. Since you already have a thread object for each philosopher, that seems possible and simple to realize. These objects could also get (read-only!) access to the options such as numOfEating.


List with no sequential repeats (where possible)

Here's an alternate way to do it. It doesn't involve modifying and reversing the existing list. Instead, it first groups and counts the items, then yields the one that wasn't printed last time and still needs to be yielded the most times. I'm not sure about actual runtime for large lists, but as long as the number of distinct items in the list is small, the reorderings and searches should run very fast.

public static IEnumerable<T> WithoutDupes<T>(this IEnumerable<T> source) where T : IEquatable<T>
{
    var sourceGroups = source.GroupBy(x => x).Select(x => new GroupCount<T>(x)).ToList();
    T last = default(T);
    bool hasLast = false;
    while (sourceGroups.Count > 0)
    {
        sourceGroups = sourceGroups.OrderByDescending(x => x.Count - x.CountOutputted).ToList();
        var group = (hasLast ? sourceGroups.FirstOrDefault(x => !last.Equals(x.Value)) : null) ?? sourceGroups[0];

        yield return group.Value;
        group.CountOutputted++;
        if (group.CountOutputted == group.Count)
        {
            sourceGroups.Remove(group);
        }
        last = group.Value;
        hasLast = true;
    }
}
private class GroupCount<T>
{
    public T Value { get; private set; }
    public int Count { get; private set; }
    public int CountOutputted { get; set; }
    public GroupCount(IGrouping<T, T> grouping)
    {
        this.Value = grouping.Key;
        this.Count = grouping.Count();
    }
}

As example output, with your input, it produces this list (note how it handles the impossible case: puts the extra T's at the end)

T, G, T, G, T, G, T, G, T, G, T, M, T, M, T, G, T, G, T, M, T, M, T, G, T, T, T, T


Implementing a c++ Kafka producer based on librdkafka

It would be more useful (and typical) for CodeReview if you'd post the entire code for the class, starting with the class definition and then the method definitions, rather than starting with one of the methods and then two more and then the class definition.

For example, your declaration for

void publish(std::string &message);

looks wrong. If you mean to take message by reference for efficiency, it should be const std::string& message. On the other hand, if it is semantically important that publish is going to modify its argument (an "out-parameter"), it would be traditional to pass the argument by pointer, or (better) return it by value.

std::string s;
kp.publish(s);  // confusing — is `s` modified?
kp.publish(&s);  // OK, informs the caller that something wacky is going on
s = kp.publish();  // best way to return a value

However, I strongly suspect from context that what's going on here is actually that publish wants to take ownership of s's heap-allocated buffer of chars. Ownership transfer is represented in C++ by plain old pass-by-value:

void publish(std::string s);

std::string s;
kp.publish(s);  // publish a copy of `s`, don't modify the original
kp.publish(std::move(s));  // publish `s` and let the original be trashed

The parts of the code you posted don't use m_run at all, so theoretically you could eliminate it.

At least, you should explain why it's an int. We only ever see it assigned the values 0 and 1, which strongly implies to me that m_run ought to be a bool.

Without seeing the code of your destructor, we can't tell whether your copy-constructor and move-constructor are doing the right thing or not.

But from what I know about librdkafka, I am reasonably confident that your copy-constructor is incorrect. Your destructor should be calling rd_kafka_topic_destroy to balance out the call to rd_kafka_topic_new in your constructor; so, if I write

kafka_publisher kp1(brokers, topicname);
kafka_publisher kp2 = kp1;
// destroy kp2
// destroy kp1

the two destructors will each call rd_kafka_topic_destroy, meaning you'll destroy the topic twice; but you only created it once! So you've got a double-free bug here.

My understanding is that librdkafka objects should be handled by unique_ptr in C++. "Copying" a pointer to a librdkafka object (such as a topic) is not generally possible. (Alternatively, you could use shared_ptr; but that seems like overkill.)

kafka_publisher(const std::string &brokers,
                const std::string &topic);

should be marked explicit.

std::string msg = "Failed to initialize Kafka configuration. Caused by ";
throw std::invalid_argument(msg.append(m_errstr));

strikes me as unnecessarily confusing. Try to avoid having multiple side-effects on the same line of C++ code. Either add lines until you have one side-effect per line:

std::string msg = "Failed to initialize Kafka configuration. Caused by ";
msg += m_errstr;
throw std::invalid_argument(msg);

or eliminate side-effects until you have one side-effect per line:

throw std::invalid_argument("Failed to initialize Kafka configuration. Caused by " + m_errstr);

I would also caution that rd_kafka_conf_set can probably fail for plenty of reasons that would not be best described as "invalid argument." In production code you'd probably just wrap up the return value in a custom exception type (throw KafkaException(return_code)) and let the higher-level code deal with it if it wanted to.


Create a view with a thick inner border that has a gradient

Nitpick: It is "Bezier", not "Beizer".

Setting the background color

  backgroundColor = UIColor.clear

can be shortened to

backgroundColor = .clear

because the type is inferred from the context. But why do you force the
view to be fully transparent at all? Shouldn't that be left to the
designer to configure in the interface builder? Unless there is a special
reason I would just remove that from the init methods.

Your view has three characteristic properties: the outer and inner
gradient color, and the width of the border. The values of those
properties are spread in the code: width and outer gradient color are
arguments in

addGradientInnerBorder(width: 8, color: UIColor.orange)

and passed around, while the inner color is directly set in

gradient.colors = [color.cgColor, UIColor.white.cgColor]

I would define properties instead:

class InnerGradientBorderView: UIView {

    let borderWidth: CGFloat = 8.0
    let outerColor = UIColor.orange
    let innerColor = UIColor.white

    // ...
}

so that they are easily identified and modified.
Even better: Use @IBInspectable and @IBDesignable

@IBDesignable
class InnerGradientBorderView: UIView {

    @IBInspectable var borderWidth: CGFloat = 8.0 {
        didSet {
            setNeedsLayout()
        }
    }
    @IBInspectable var outerColor: UIColor = .orange {
        didSet {
            setNeedsLayout()
        }
    }
    @IBInspectable var innerColor: UIColor = .white {
        didSet {
            setNeedsLayout()
        }
    }

    // ...
}

so that they can be configured directly in the interface builder,
with a live preview (compare IBInspectable / IBDesignable:

Closing a path automatically adds a line segment from the last point
to the first point of the current path segment, i.e. the final
addLine(to:) in addClosedPathForPoints() is not needed, and it
suffices to pass 4 points to the function.

Also I would not make the return value optional. Passing a wrong number
of arguments is a programming error and should be detect early in the
development instead of silently ignored:

func addClosedPathForPoints(points: [CGPoint]) -> UIBezierPath {
    assert(points.count == 4)

    let path = UIBezierPath()
    path.move(to: points[0])
    path.addLine(to: points[1])
    path.addLine(to: points[2])
    path.addLine(to: points[3])
    path.close()

    return path
}

Instead of completely re-creating all gradient layers in
layoutSubviews() it might be more efficient to create them once
(when the view is initialized), and only update the frame and mask layer
when the layout changes.

Then your class would look like this:

@IBDesignable
class InnerGradientBorderView: UIView {

    @IBInspectable var borderWidth: CGFloat = 8.0 {
        didSet {
            setNeedsLayout()
        }
    }
    @IBInspectable var outerColor: UIColor = .orange {
        didSet {
            createGradients()
            setNeedsLayout()
        }
    }
    @IBInspectable var innerColor: UIColor = .white {
        didSet {
            createGradients()
            setNeedsLayout()
        }
    }

    var topGradient, leftGradient, rightGradient, bottomGradient: CAGradientLayer!

    override init(frame: CGRect) {
        super.init(frame: frame)
        createGradients()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        createGradients()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        layoutGradients()
    }

    func createGradients() {
        topGradient = createGradient(gradientPoints: [CGPoint(x: 0, y: 0), CGPoint(x: 0, y: 1)])
        leftGradient = createGradient(gradientPoints: [CGPoint(x: 0, y: 0), CGPoint(x: 1, y: 0)])
        rightGradient = createGradient(gradientPoints: [CGPoint(x: 1, y: 0), CGPoint(x: 0, y: 0)])
        bottomGradient = createGradient(gradientPoints: [CGPoint(x: 0, y: 1), CGPoint(x: 0, y: 0)])

        layer.addSublayer(topGradient)
        layer.addSublayer(leftGradient)
        layer.addSublayer(rightGradient)
        layer.addSublayer(bottomGradient)
    }

    func createGradient(gradientPoints: [CGPoint]) -> CAGradientLayer {
        let gradient = CAGradientLayer()
        gradient.colors = [outerColor.cgColor, innerColor.cgColor]
        gradient.startPoint = gradientPoints[0]
        gradient.endPoint = gradientPoints[1]
        return gradient
    }

    func layoutGradients() {
        let topLeftO = CGPoint(x: 0, y: 0)
        let topLeftI = CGPoint(x: borderWidth, y: borderWidth)

        let topRightO = CGPoint(x: frame.width, y: 0)
        let topRightI = CGPoint(x: frame.width - borderWidth, y: borderWidth)

        let bottomLeftO = CGPoint(x: 0, y: frame.height)
        let bottomLeftI = CGPoint(x: borderWidth, y: frame.height - borderWidth)

        let bottomRightO = CGPoint(x: frame.width, y: frame.height)
        let bottomRightI = CGPoint(x: frame.width - borderWidth, y: frame.height - borderWidth)

        layoutGradient(gradient: topGradient, points: [topLeftO, topLeftI, topRightI, topRightO])
        layoutGradient(gradient: leftGradient, points: [topLeftO, topLeftI, bottomLeftI, bottomLeftO])
        layoutGradient(gradient: rightGradient, points: [topRightO, topRightI, bottomRightI, bottomRightO])
        layoutGradient(gradient: bottomGradient, points: [bottomLeftO, bottomLeftI, bottomRightI, bottomRightO])
    }

    func layoutGradient(gradient: CAGradientLayer, points: [CGPoint]) {
        let path = UIBezierPath()
        path.move(to: points[0])
        path.addLine(to: points[1])
        path.addLine(to: points[2])
        path.addLine(to: points[3])
        path.close()

        gradient.frame = path.bounds
        gradient.bounds = path.bounds

        if let shapeMask = gradient.mask as? CAShapeLayer {
            // Update mask.
            shapeMask.path = path.cgPath
        } else {
            // Create and set mask.
            let shapeMask = CAShapeLayer()
            shapeMask.path = path.cgPath
            gradient.mask = shapeMask
        }
    }
}

But this is not yet perfect! The problem is that the sublayers do not
animate correctly if the view's position or size changes, e.g.
when rotating the device.
You'll notice that clearly in the iOS Simulator if you activate
"Debug -> Slow Animations":

The solution is to embed the call to layoutGradients()
into a Core Animation transaction so that the frame and mask changes are
synchronized with the view layer's animation, see for example

How do you animate the sublayers of the layer of a UIView during a UIView animation? on Stack Overflow.

Applied to our situation (and translated to Swift) that becomes:

    override func layoutSubviews() {
        super.layoutSubviews()

        if let animation = layer.animation(forKey: "position") {
            CATransaction.begin()
            CATransaction.setAnimationDuration(animation.duration)
            CATransaction.setAnimationTimingFunction(animation.timingFunction)

            let frameAnimation = CABasicAnimation(keyPath: "frame")
            topGradient.add(frameAnimation, forKey: "frame")
            leftGradient.add(frameAnimation, forKey: "frame")
            rightGradient.add(frameAnimation, forKey: "frame")
            bottomGradient.add(frameAnimation, forKey: "frame")

            let pathAnimation = CABasicAnimation(keyPath: "path")
            topGradient.mask?.add(pathAnimation, forKey: "path")
            leftGradient.mask?.add(pathAnimation, forKey: "path")
            rightGradient.mask?.add(pathAnimation, forKey: "path")
            bottomGradient.mask?.add(pathAnimation, forKey: "path")

            layoutGradients()
            CATransaction.commit()
        } else {
            layoutGradients()
        }
    }

And now it animates perfectly:


Tough List Comprehension Split Letters and Numbers

Padraic Cunningham nailed the shortest form in his comment:

" ".join(x for x in s.split() if not x.isdigit()) + " | " + "".join(sorted(x for x in s if x.isdigit()))

Explanation:

x for x in s.split() if not x.isdigit() -- the list of words that don't have digits. Note that the split method without parameters uses space as the separator.
x for x in s if x.isdigit() -- the list of digits extracted from the string, unsorted
From the above 2 it's easy to combine to get the desired result.

Although this is short, it checks every letter twice, first using not x.isdigit() to get only the letters and then x.isdigit() to get only the digits. We could improve that by using a helper function to partition the list of words on the outcome of x.isdigit(), like this:

def partition(pred, iterable):
    trues = []
    falses = []
    for item in iterable:
        if pred(item):
            trues.append(item)
        else:
            falses.append(item)
    return trues, falses

nums, words = partition(str.isdigit, s.split())
' '.join(words) + ' | ' + ''.join(sorted(''.join(nums)))

Of course, this is much more than one line...


This is simpler:

#include <stdint.h> // #include <cstdint> in C++

void write_bit_32b(uint32_t *num, uint8_t pos, bool val)
{

        *num &= ~(UINT32_C(1) << pos);
        *num |= (uint32_t)val << pos;
}

Use fixed-width integers if you can (see above).

Use int main(void):

C17::6.11.6:

  Function declarators The use of function declarators with empty
  parentheses (not prototype-format parameter type declarators) is an
  obsolescent feature.

This may be interesting to you:

https://stackoverflow.com/q/47981/6872717


Magento MySQL search based on phone number

you haven't missed anything (the code works as intended), but you can improve the performance a bit and make it more readable (for someone who is used to PHP and MySQL).

I've modified your code and added comments where necessary.
As on of the comments requested, I'll add a bit more detail.

The most important thing is the select query. As it was originally you had to performed another query for every row from the original query in order to get the corresponding parent_id from the customer_address_entity table. You should avoid doing this because it is not very efficient.

The modified query selects everything you need in one go using a JOIN statement. The JOIN statement allows you to perform a SELECT on both tables that were joined, but you have to specify which column you want from each table, that's why the original SELECT value becomes SELECT customer_address_entity_varchar.value.

When looping the return results in order to assign them to a new array, like you're doing below, it's useful to now that:
a. Using $found_customers[]['entity_id'] instead of $found_customers[$position]['entity_id'] has the same results, because the $array[] notation in PHP makes it so that every assignment appends that assignment to the end of the array, auto-incrementing the index.
b. Since you want to transfer all the data from $row into $found_customers, you can simply do $found_customers[] = $row and it will have the same effect in this case.
c. (Optional) A simple quality of life trick, use mysqli_fetch_assoc' instead of 'mysqli_fetch_array'. Whenvar_dump`ing you won't see the same values twice for each row (one with and index and one with the key, as seen in the comments), only once, with the key.

$position = 0;

while($row = mysqli_fetch_array($response)) {

    $found_customers[$position]['entity_id']    = $row['entity_id'];
    $found_customers[$position]['value']        = $row['value'];

    $position++;
}

If you want to have unique values for a column (as requested in the comments), one way to do it is to GROUP BY that column. The downside is that you will lose the data contained in the duplicate results.

<?php

DEFINE ('DB_HOST',      'localhost');
DEFINE ('DB_USER',      'theuser');
DEFINE ('DB_PASSWORD',  'thepassword');
DEFINE ('DB_NAME',      'magento');

$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

$search_query = "5555555555";

// find customers with matching phone numbers
/* This is probably the most important part: using a JOIN.
   It will save you having to do a separate query for each customer */

$query = "SELECT customer_address_entity_varchar.value, customer_address_entity_varchar.entity_id, customer_address_entity.parent_id
          FROM customer_address_entity_varchar
          JOIN customer_address_entity
              ON customer_address_entity_varchar.entity_id = customer_address_entity.entity_id
          WHERE customer_address_entity_varchar.value = $search_query
          GROUP BY customer_address_entity.parent_id
          LIMIT 100";

$response = mysqli_query($dbc, $query);

// save found phone numbers to $found_customers array
$found_customers = array();

/* in PHP you can just use $found_customers[] and it will auto-increment
 no need to use $position */

/* also, since your select query on selects 3 columns, you can assign the results directly */

while($row = mysqli_fetch_assoc($response)) {
    $found_customers[] = $row;
}

/* The foreach loop is no longer necessary because the initial query  (now with a JOIN) returns all the required data */

var_dump($found_customers);

?>


XMLHttpRequest with cancel, timeout and retry option

First of all, there's already a fetch function that's already available in most modern browsers. If you care about IE, there's also a polyfill for it. With that out of the way, we can ignore the first part of your code and focus on the second part of the code.

While it's perfectly fine JS, having very long argument lists is horrible. As a developer, you have to evaluate which arguments take priority and come first. As a consumer, you have to remember which ones come first. I suggest turning your options into an object. You can use Object.assign to merge a defaults object.

With regards to your control flow, you can simplify the retry routine by simply calling fetchWithRetry recursively, passing it the retries remaining. Since this operates on just promises and promises cannot be cancelled, this version's abort bails out when abort is called during the delay or after the request, not immediately.

const fetchWithRetry = (userOptions) => {
  let abort = false;
  const options = {
    url: '',
    options: {},
    cancel: {},
    retries: 3,
    retryDelay: 1000,
    ...userOptions
  };

  // Add an abort to the cancel object.
  cancel.abort = () => { abort = true };

  // Abort or proceed?
  return abort ? Promise.reject('aborted') : fetch(options.url).then(response => {

      // Reject because of abort
    return abort ? Promise.reject('aborted')

      // Response is good
      : response.ok ? Promise.resolve(response.text())

      // Retries exceeded
      : !options.retries ? Promise.reject('retries exceeded')

      // Retry with one less retry
      : new Promise((resolve, reject){
          setTimeout(() => {

            // We use the returned promise's resolve and reject as
            // callback so that the nested call propagates backwards.
            fetchWithRetry({ ...options, retries: retries - 1 }).then(resolve, reject);
          }, options.retryDelay);

        });
  });
}


Use Math.abs()

 public static int lastDigit(int x) {
      return Math.abs(x % 10);
 }


setDict() is a bit of a misnomer; loadDict() would be more accurate.  Since the loaded dictionary becomes part of the global state, it would be more appropriate to make it an instance variable than a static variable.  If loading fails, you shouldn't just print a stack trace and attempt to continue execution — that defeats the purpose of exceptions.  In general, if you don't have a good way to handle an exception, just propagate it (by declaring throws IOException).

Your technique for checking whether a word consists solely of a limited set of characters is to do repeated string replacement.  That would cause a lot of temporary objects to be allocated and discarded.  A more appropriate tool to use would be a regular expression match (using Pattern.compile("^[bikn]*$"), for example).

Since this is a filtering exercise, it would be more eloquently written using Stream<String>.filter(Predicate) instead of List<String>.

Although String args[] is syntactically valid, String[] args is considered more idiomatic in Java, since String[] is considered the type.

Suggested solution

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class BrokenKeyboard {
    public static Predicate<String> typableUsing(String availableKeys) {
        // CAVEAT: availableKeys is assumed not to contain regex metacharacters
        // such as ^ [ ] - \
        return Pattern.compile("^[" + availableKeys + "]*$").asPredicate();
    }

    public static Stream<String> dictionary(File f) throws IOException {
        return Files.lines(f.toPath());
    }

    public static void main(String[] args) throws IOException {
        System.out.println(
            BrokenKeyboard.dictionary(new File(args[1]))
                          .filter(BrokenKeyboard.typableUsing(args[0]))
                          .collect(Collectors.joining(", "))
        );
    }
}

It is possible to resolve the caveat using Pattern.quote().  I'll leave it as an exercise to the reader.  =)


Implementation of Equals and GetHashCode for base class

I think you are overcomplicating things you can say simple this:

    public abstract class Entity<TKey> where TKey : struct
    {
        public abstract TKey Key { get; }

        protected bool Equals(Entity<TKey> other)
        {
            return Key.Equals(other.Key);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            var asThis = obj as Entity<TKey>;
            return asThis != null && Equals(asThis);
        }

        public override int GetHashCode()
        {
            return Key.GetHashCode();
        }
    }

No need the type magic
A key cannot be null and it should be a ValueType
An Equals and GetHashCode implementation should be symmetric and fast (your solution is slow and i'm not sure it is symmetric or not)


That seems like a lot of code for very little purpose. It's allowing you to write

IntRandom<int> r(17, 42);
int i = r.Next();

instead of the no-helpers version,

std::mt19937 g(std::random_device{}());
std::uniform_int_distribution<int> dist(17, 42);
int i = dist(g);

Some people would say that that's not worth the 77 lines of code.

Two small problems with your code, related to your use of random_device: First, you're using only 32 bits of entropy to seed your entire Mersenne Twister; it would be better to use as many bits as the mt19937 has bits of state. However, doing this correctly is needlessly difficult in C++17, so you get a pass on it for now.

Second, your RandomBase class keeps a member of type random_device. This might be problematic, because a random_device is essentially an open file handle to /dev/urandom. If you create a lot of RandomBase objects at once, you might find yourself running out of file handles.

Oh, and a third problem is that random_device is non-copyable and non-movable; so your RandomBase is also non-movable. That could actually be pretty bad, depending on how you want to use it.

You could fix the random_device issues by removing the random_device data member, and instead providing a method like this:

void RandomBase::reseed() {
    std::random_device rd;
    m_RandomGenerator.seed(rd());  // TODO: better seeding
}

This keeps the random_device alive (and /dev/urandom open) only as long as it's needed; and it removes the data member from the class so that the class becomes movable and even copyable.

You could also reduce duplication by using templates and type-aliases, something like this:

template<class Distribution>
class dist_and_gen {
    std::mt19937 m_g;
    Distribution m_dist;

    template<class... Args>
    explicit constexpr dist_and_gen(Args&&...) :
        m_dist(std::forward<Args>(args)...) {}

    auto next() { return m_dist(m_g); }
    auto params() const { return m_dist.params(); }
};

template<class T> using IntRandom =
    dist_and_gen<std::uniform_int_distribution<T>>;
template<class T> using FloatRandom =
    dist_and_gen<std::uniform_float_distribution<T>>;
template<class T> using BoolRandom =
    dist_and_gen<std::bernoulli_distribution<T>>;

This version loses some of the details, such as your custom-named accessors for the parameters; but it preserves a lot of the details "accidentally". For example, I didn't try to preserve your BoolRandom::BoolRandom() default constructor; but it turns out that it just works anyway, thanks to the default constructor of the standard bernoulli_distribution.


Parsing mathematical expressions in Reverse Polish Notation

I'm not quite sure what you're asking for, but I was bored so I typed this up anyway. Hopefully it helps. ;-)

Working from the outside in:

Invocation

if __name__ == '__main__':
    print('Press ^C to exit')
    try:
        main()
    except KeyboardInterrupt:
        pass
    # For some reason my Windows raises EOF on ^C...
    except EOFError:
        print()
    print('Goodbye!')

This is all fine, but it probably should be in the main() function, and you just write

if __name__ == '__main__':
    main()

Mostly, this is a matter of convention, but also, it's handy to have a function that can be run from another Python script that will just do everything.

Organizing the driver code

The process of evaluating an RPN expression is something that makes a lot of sense to put as its own function. That's a self-contained task you could easily want to reuse elsewhere. So I would suggest making a function evaluate_rpn(expr) which does exactly that. You can then use this function in your main loop as follows:

def main():
    print(...)
    try:
        while True:
            try:
                print(evaluate_rpn(input('> ')))
            except CalculatorError as e:
                print(e)
    except KeyboardInterrupt:
    # and so on

Evaluating

This new evaluate_rpn() function is going to do mostly the same thing as your call() function currently does, except that instead of prompting using input(), it will take a string argument, and instead of printing the result, it will return it. Let me pick on a few things in that function, though.

Let the stack just be a stack

stack = []
pop = make_pop(stack)

The only real purpose of make_pop is to make it so that you get a CalculatorError instead of an IndexError when a function or operator doesn't have enough arguments. But I don't think it makes sense to do that. See, stack is just a stack. (Well, a list that is serving as a stack.) It knows nothing of numbers or arguments or calculators and really has no business raising a CalculatorError. The code in evaluate_rpn() is the thing that knows it is a calculator. That's where you should be raising CalculatorErrors. So instead of using make_pop, just watch for IndexErrors during the evaluation, catch them, and raise a CalculatorError in the handling code. As a side effect you won't need make_pop() anymore; you can just dispense with it entirely.

try:
    a = pop()
    b = pop()
except IndexError:
    raise CalculatorError(...)

Do tokenization the easy way

Your input strings consist of tokens (numbers, operators, functions) separated by whitespace, right? There's a built-in method to split a whitespace-separated string: string.split(). You don't need to bother with a buffer, or with iterating through the string's characters.

for token in calculation.split():
    # and so on

Don't overuse variables

You don't really have to save a and b and return_value separately; you only use them once each.

if token in TOKENS:
    try:
        stack.append(TOKENS[token](stack.pop(), stack.pop())
    except ZeroDivisionError:
        raise CalculatorError(...)
    except IndexError: # from a couple paragraphs ago
        # and so on

If different parts of this expression could raise the same type of error, then that would be a good reason to break it down, so that you could tell exactly where a given error comes from. But that's not an issue here. You'll only ever get ZeroDivisionErrors for one reason.

Same goes for the float-parsing part:

else:
    try:
        stack.append(float(token))
    except ValueError:
        raise CalculatorError(...)

For complicated sequences of code, you have to make a subjective judgement about where to use variables and where not to in order to make the code as clear as possible. But in this case, I think most programmers would agree that the variables are fairly unnecessary.

Let output formatting be controlled by the formatting routines

Evaluating an RPN expression doesn't include formatting - in particular, deciding whether the result is an integer or not is a separate task from just getting the result in the first place. So at the end of evaluate_rpn, just return a float. When you print it, instead of print(result) you can do

print('{:g}'.format(result))

and it will automatically strip trailing zeros as needed. Of course, this does display large numbers in scientific notation (2.89146e+07); if that's a problem, then you might have to do your own formatting.

Use descriptive variable names

Your TOKENS list doesn't actually contain tokens; it contains operators, and could be generalized to contain functions. So I'd suggest naming it OPERATORS or some such thing.

Allowing arbitrary numbers of arguments

This is really more about adding a feature than reviewing your existing code, but I might as well point you in the right direction. All you have to do is store the number of arguments a function or operator requires, in addition to the code that actually evaluates the operator. For example,

OPERATORS = {
    '+':    (2, lambda x, y: x + y),
    'sqrt': (1, math.sqrt),
    # and so on
}

Then, when you invoke an operator, instead of hard-coding two arguments like you did or like I did above,

stack.append(OPERATORS[token](stack.pop(), stack.pop())

you can check how many operands the operator requires,

n_operands, evaluator = OPERATORS[token]

pop that many from the top of your stack,

# these two lines together are like a "multipop"
operands = reversed(stack[-n_operands:])
del stack[-n_operands:]

and evaluate the operator with those operands,

stack.append(evaluator(*operands))

I leave it to you to figure out the best way to put try/except blocks around this code.

Actually, the way I've done it here has a problem dealing with the case where n_operands is zero (this would happen if you include constants or zero-argument functions in the list of operators). To get around that, you can use the following:

n_operands, evaluator = OPERATORS[token]
stack.append(evaluator(*[stack.pop() for _ in range(n_operands)]))

Instead of chopping off the whole end of the list, as in the previous method, this one pops off the last n_operands elements one at a time.


Query to find instances of two types of events occurring more than one second apart

I don't think your code is correct.

select top 1, without any kind of order by clause selects an essentially random record from a table, so unless you know that there can be only one event with the right EventTypeId you may be missing event combinations that are relevant.

If I understand the problem correctly, I think you need something more like this:

select A.BusinessObjectId from
( select BusinessObjectId, min(DateEvent) as min, max(DateEvent) as max
  from CustomEvent where EventTypeId = 11
  group by BusinessObjectId
) as A
inner join
( select BusinessObjectId, min(DateEvent) as min, max(DateEvent) as max
  from CustomEvent where EventTypeId = 10
  group by BusinessObjectId
) as B on A.BusinessObjectId = B.BusinessObjectId
where datediff( second, A.min, B.max ) > 1 or datediff( second, B.min, A.max ) > 1
group by A.BusinessObjectId

I have not included the six month restriction.


builtin

you can use some parts of the standard library:

math.hypot for the distance function
collections.defaultdict for the frisbees_held
itertools.combinations for generating the combinations in the distance matrix

imports:

from itertools import combinations, islice
from collections import namedtuple, defaultdict
from math import hypot

players

you can use a class, or even a namedtuple to represent a player, to simplify the building of the distance matrix

Player = namedtuple('Player', 'name x y range')
players = [[152, 213, 276], [274, 259, 151], [40, 57, 130], [203, 87, 189], [43, 182, 163]]
players = [Player(i, x, y, range_) for i, (x, y, range_) in enumerate(players)]

[Player(name=0, x=152, y=213, range=276),
 Player(name=1, x=274, y=259, range=151),
 Player(name=2, x=40, y=57, range=130),
 Player(name=3, x=203, y=87, range=189),
 Player(name=4, x=43, y=182, range=163)]

distance matrix

you calculate the distance between the players a few times, you can reduce that by doing something like this:

def distance_generator(players):
    for p1, p2 in combinations(players, 2):
        dist = hypot((p1.x - p2.x), (p1.y - p2.y))
        if dist < p1.range:
            yield p1, p2, dist
        if dist < p2.range:
            yield p2, p1, dist

here a dict of dicts might be a more appropriate data structure than a list of lists

def build_distance_matrix(players):
    distance_matrix = defaultdict(dict)
    for p1, p2, dist in distance_generator(players):
        distance_matrix[p1.name][p2.name] = dist
    return dict(distance_matrix)

{
    0:
    {
        1: 130.38404810405297,
        2: 192.04166214652486,
        3: 135.9301291105103,
        4: 113.3225485064645,
    },
    1: {0: 130.38404810405297},
    3: {
        0: 135.9301291105103,
        1: 186.07794065928394,
        2: 165.73774464496614,
        4: 186.07794065928394,
    },
     4: {0: 113.3225485064645, 2: 125.03599481749245},
     2: {4: 125.03599481749245},
}

throwing

you can model a game as an endless series of people throwing the frisbee to eachother. The min(...) you use is the correct way to do this, but can be formatted clearer

def game(distance_matrix, start_player):
    frisbees_held = defaultdict(int)
    target = start_player
    while True:
        frisbees_held[target] += 1
        targets = distance_matrix[target]
        yield target
        target = min(
            targets,
            key=lambda x: (
                frisbees_held[x], # number times held
                -targets[x], # furthest
                x # lowest index
            )
        )

final selection

then you can use the nth itertools recipe

def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(islice(iterable, n, None), default)

def frisbees(friends, numberOfPasses, startingPlayer):
    players = [Player(i, x, y, range_) for i, (x, y, range_) in enumerate(friends)]
    distance_matrix = build_distance_matrix(players)
    g = game(distance_matrix, startingPlayer)
    return nth(g, numberOfPasses)


A small note on naming:

Being new to your code base, I have no idea what MIF represents and worse, IF looks a lot like if and it confuses my eyes. As a rule of thumb, don't abbreviate names. Spell them out so that the maintainer coming behind you understands what everything is.


Bug: no null character
printf("%s\n", result); fails as result does not point to a string.  That data lacks a null character and is short, by 1 of allocated memory needed.
// char *output = malloc(output_len);
char *output = malloc(output_len +1);
output[output_len] = '\0';

Similar problem with decryptor.
No protection against non-A-Z characters
I'd expect only encrypting/decrypting when the input[] is an A-Z.
I suspect code may generate output[i] == 0 for select inputs, rendering the string short.

Pedantic bug: Negative char
When input[i] < 0, isupper(input[i]) is UB.  Better to access the string via an unsigned char * for is...().
A negative char value also messes-up mod().  When x < 0, x % n code does not perform a Euclidean mod.


Naming
You code's naming conventions are very inconsistent (which possibly reflects the fact that you've taken bits of it from different sources).  Generally speaking, I expect local variables to follow a camelCasing naming convention.  Your current approach ends up with lines like this:
catch (Exception StreamException)

Which honestly at first glance made me ask the question 'have they done something funky with exception filters'.
Exceptions
You don't actually do anything with any of the exceptions that you catch.  If you don't need to access the variable, then you can simply catch the exception:
catch (Exception)

Typically you'd also want to try to avoid catching base exception.  It suggests that you don't really know what exceptions can be thrown.  Sometimes it's the right thing to do, but more often than not you should be catching more specific exceptions so that you can take more appropriate action.
When you're done, you're done
Your thread function in your server contains an endless loop.  This works whilst the client is behaving, but falls apart once you encounter an error.  Within the loop, you're catching all exceptions and responding by closing the socket:
catch (Exception StreamException)
{
    Console.WriteLine("Connection from a client closed.");
    ClientSocket.Close();
}

Best case, the second time you call Close, it throws an exception and the thread function crashes.  Worst case, the Close doesn't throw an exception and you don't notice that the thread function is in an endless loop, eating processor time.
Once you've closed the connection, you should return from the thread function to prevent the pointless spinning.


Documenting and commenting code using xml tags

Only focusing on the code...no, not really, I will say something regarding the xml doc as well.

xml documentation should tell the truth, because this is what another developer reads. Seeing e.g ''' Gets the description of the current document one wouldn't expect that this property has a setter as well.
''' Creates a new XT document object isn't true either, because it is used to create a new Document object. If you have another class named XTDocument inheriting from the Document object then the doc would be ok.
Although VB.NET is case insensitive one should stick to the .NET Naming Guidelines. This means method parameters should be named using camelCase casing.
While we are at naming things, please don't use hungarian notation. Prefixing a variable with its type or with what one thinks is its type is frowned upon nowadays. What value does the o in oPropertySets add ? Having intellisense and stuff just makes it superflous. In the time of VB 6 one could say that it is easier to see the type of the variable, but nowadays one just hoovers with his mouse over the variables name and see its type.
Comments shouldn't tell what the code is doing. This should be done by the code itself by using meaningful names. Comments should always tell why the code is written like it is. As an example, please take a look at my answer here.
Nowadays (sorry I need to use this term often, because the code looks like it is ported from VB 6) we use Return someValue instead of assigning the returning values to the properties name.
Not only because it is more clear but in VB.NET this Description = oDescriptionProperty.Value will call the setter of the Description property. Hence calling the getter will call the setter as well which can lead to dangerous, because hidden, sideeffects.


i have given basic question about the efficient way to sort user-defined object

If you really care about performance, you should measure it. Experience shows that there are many subtle influences to performance, that make it hard to reliably predict it.

Instead of using a std::set, you could try sorting the array directly. It is less code, less memory and probably faster: std::set typically is implemented as a tree, and will allocate each node separately. When inserting elements not in order, the resulting nodes will most likely be scattered in memory. Iterating over such a set might be slower than iterating over a contiguous array or even over a set where the elements have been inserted in order. (Not that it would matter much with the small sample size in this program.)

std::set also provides guarantees that you don't need here: Stability of references/iterator, unique elements, "fast" insertion not just at the end, "fast" removal of elements.

Interestingly, because std::set guarantees unique elements, it might be an incorrect choice in this context. Students will not be inserted into the set if there's already a student with the same midTermScore when using your current definition of operator<. Live example You should either use a total order for the std::set or use a data structure that can contain multiple equivalent elements (equivalent with respect to the order) like std::multiset.

For example, instead of

std::set<Student> sorted;

for (auto&& i : a)
{
    sorted.insert(i); // O(N*log(size() + N))
}

you could sort the original array:

std::sort(begin(a), end(a));

(that is std::begin and std::end, but I'm using ADL because I'm lazy)

friend bool operator<(Student const & a, Student const & b)
{
    return a.midTermScore > b.midTermScore;
}

I don't think it's a good idea to define an operator< for a type that does not provide a total order. We could try to introduce equality between two students by using (a == b) <=> (!(a<b) && !(b<a))  (I'm using <=> as is equivalent to here). But this notion of equality is strange, since we expect (a == b) => (a.studentName == b.studentName).

After looking at the code again, I think it's even a worse idea to define the (canonical) operator< for a type be mean greater than.

Therefore, I'd rather use a function, function object type or lambda to introduce this order. For example, using std::sort from above:

auto const larger_midTermScore =
    [](Student const& a, Student const& b)
    { return a.midTermScore > b.midTermScore; }

std::sort(begin(a), end(a), larger_midTermScore);

I you want to use a std::set, you could impose that order on the set as follows:

class larger_midTermScore {
private:
    static auto tie_in_order(Student const& a)
    -> decltype(std::tie(a.midTermScore, a.grade, a.studentName)) {
        return std::tie(a.midTermScore, a.grade, a.studentName);
    }
public:
    bool operator() const (Student const& a, Student const& b) {
        return tie_in_order(a) < tie_in_order(b);
    }
};

// in the main function:
std::set<Student, larger_midTermScore> sorted(begin(a), end(a));

I'm being lazy again by using std::tuple to define a lexicographical comparison of the data members of Student. Include the <tuple> header.

std::string studentName;
int midTermScore;
char grade;

The type Student might have invariants that you should protect.
For example, 'A' <= grade <= 'F' etc. Also, it is unclear (because not documented nor enforced by encapsulation) if there is a maximum length for studentName. The display algorithm suggests there is one.


The fun thing about these kinds of libraries is that they're fun to implement. The sad thing about them is that they aren't really fun to work with. You will beg for markup-like syntax in the long run.

But anyways,

div: function(props, children) {
    return this.h('div', props, children);
},
label: function(props, children) {
    return this.h('label', props, children);
},
input: function(props, children) {
    return this.h('input', props, children);
},
button: function(props, children) {
    return this.h('button', props, children);
},
li: function(props, children) {
    return this.h('li', props, children);
}

This can be simplified into a list of element names. You can run through it and assign a function to DOM for each name.

['div', 'li', ...].forEach(elementName => {
  DOM[elementName] = function(props, children){
    return this.h(elementName, props, children);
  };
});

As for your h function, you should guard for-in with hasOwnProperty to avoid iterating over prototype elements. Alternatively, you can use Object.keys and forEach. Also, silencing errors is terrible when debugging. If the user passed in something not an array, best inform them immediately. In the following code, it only catches on falsy values. Anything else, like a non-array or something will throw because forEach expects an array.

h: function(tagName, props, children) {
    var element = document.createElement(tagName);

    Object.keys(props || []).forEach( prop => {
      element[prop] = props[prop];
    });

    (children || []).forEach(child => {
      element.appendChild(child);
    });

    return element;
},


Printing a list to a file then reassembling said list

Forewords

Let's break down the problem once more:

you have a text and want to extract individual words out of it;
with these words, you want to build a list of unique ones.
you replace each word by its position in the list of uniques;
and write these positions and the list of uniques into two files.

After that, an other part can read both files and rebuild the original text.

Now let's get back to the code and put everything into a function to organize things a bit and allow for better reusability and testing. One function for the text to files: def split_sentence(text, filename_indexes, filename_uniques): and one for the files to text: def build_sentence(filename_indexes, filename_uniques):. You can see that by giving meaningful names to parameters, we can get a better grasp at what they are used for.

Text to file

Let's iterate over each part of the algorithm and see what can be improved. Remember, we are defining:

def split_sentence(text, filename_indexes, filename_uniques):

Improving

Extract individual words from a text

sentencelist = []

# split the text
words = text.split()

# for each word in the line:
for word in words:
    sentencelist.append(word)

Each "thing" that you can place after in in a for loop (such as words here) is an iterable. And building a list by appending elements from an iterable into a for loop is a waste of time: the list constructor already does the exact same thing. So, at the very least, you should do words = text.split(); sentencelist = list(words).

But here, words is not only an iterable, it is also already a list. So you don't need to copy it over. The only thing you need is:

    sentence_list = text.split()

Build a list of unique words

uniqueword =[]
for i in range(0,len(sentencelist)):
    if not sentencelist[i] in uniqueword:#<--- creates list of unique words
        uniqueword.append(sentencelist[i])
    else:
        i+=1

So many things done wrong here:

The else: i+=1 part is useless as i, being the iteration variable, is overwritten at each loop iteration. And since you perform no extra operation with it after incrementing it, you can drop these two lines.
range(0, len(sentencelist)): as 0 is the default start of a range, it is common practice to not specify it.
for i in range(len(sentencelist)): ... sentencelist[i] ...: this is a code smell. Unless you have a truly good reason to do that, it is faster, more Pythonic and more readable to iterate over the elements directly rather than using their indices. So use for element in sentencelist: ... element ... instead. If you really need the index, you can still use enumerate.
uniqueword = []; for element in sentencelist: if ...: uniqueword.append(element): again this is unefficient and rather un-Pythonic. Use a list-comprehension instead. Except you can't here because you need the partially built list to check for existence of the current element. But:

All in all, we could discuss about ways to improve this for loop, but that would be missing the point: you don't need it. There is a data structure in Python that is meant for holding unique elements: set. Whenever you try to insert an elemnt in a set, if the element is already present then nothing happens. Since you will need a list for its indexes latter on, you will need to convert it back:

    unique_words = list(set(sentence_list))

Compute the position of each word in the list of uniques

positionlist = []
for i in range(0,len(sentencelist)):
    positionlist.append(uniqueword.index(sentencelist[i]))#<-- finds the index of the unique words in the sentence and appends them to positionlist

I already talked about it a bit above, but you should convert this loop into a list-comprehension; iterating over the elements rather than the indices:

    positions = [unique_words.index(word) for word in sentence_list]

You then have this code:

wordvals = []
end=False
im = 0
while True:
    try:
        wordvals.append(uniqueword[im])
        im+=1
    except:
        break

That I don't understand. You are copying uniqueword into wordvals. For one, this can be done using wordvals = list(uniqueword). For two, this is useless as you already have the list (uniqueword) and you don't modify any of these two lists. So just stick to using uniqueword and avoid unnecessary computation.

Write to files

First off, you should get into the habit of using with when you use open. You do it in your second snippet but not in the first. Second, closeing the file is done automaticaly by with so you don't need to do it manually aftewards.

The "%s\n" % item syntax is the old-style formatting syntax which is superseeded by the format function and the str.format method of strings. And the upcoming "f-strings" in Python 3.6 will make it even more easy to use. So write '{}\n'.format(item) instead for now and f'{item}\n' in Python 3.6. This has the added advantage that, if item is a tuple, your code won't crash.

But, in Python 3 (which I guess you are using, judging by your print calls), you can use the print function to write into files and use its full potential of features: automatic conversion of anything into a string and newlines at the end of each call:

    with open(filename_indexes, 'w') as f:
        for position in positions:
            print(position, file=f)
    with open(filename_uniques, 'w') as f:
        for word in unique_words:
            print(word, file=f)

Improving (again)

Now that we reduced the visual clutter of the function down to 9 lines, let's focus on the complexity of the algorithm.

Splitting the text and getting the unique words out of it can't really be reduced. But when you build the list of indices, you perform an \$O(n)\$ lookup into unique_words for each word in sentence_list: you end up with an overall complexity of \$O(n^2)\$. You can do better.

You don't really need the indices of the words. All you need is a unique value associated to each unique word. So you will need a data structure to hold such association and a way to generate enough unique values. You already know how to generate n unique values: range(n). And to associate one of them to each word, you will need a dictionary. Also the zip function will help in the process of making pairs:

unique_words = set(sentence_list)
lookup_table = dict(zip(unique_words, range(len(unique_words))))

That way, you can replace unique_words.index(word) which is \$O(n)\$ by lookup_table[word] which is \$O(1)\$. Unfortunately, this means that you will have to sort the words in lookup_table by their associated value if you want to be able to reconstruct the text properly. Luckily, sorted, the standard function to sort elements of a container, can help us doing so. It accepts a key parameter which is a function that will be called with each value that should return its "index" in the resulting sorted sequence. Here we’ll make use of the get method on dictionaries that return the element associated to the given value. In the case of lookup table, it will return the unique number associated to each word:

for word in sorted(lookup_table, key=lookup_table.get):
    print(word, file=f)

The whole code for the text to file transformation can thus become:

def split_sentence(text, filename_indexes, filename_uniques):
    words = text.split()
    uniques = set(words)
    lookup_table = dict(zip(uniques, range(len(uniques))))
    positions = [lookup_table[word] for word in words]

    with open(filename_indexes, 'w') as f:
        for position in positions:
            print(position, file=f)
    with open(filename_uniques, 'w') as f:
        for word in sorted(lookup_table, key=lookup_table.get):
            print(word, file=f)

File to text transformation

First, the line wv=f.read().splitlines() is underindented and cannot possibly work as the file will be closed by the time you try to read it.

Second, f.read().splitlines() is neat as it removes newlines characters at the end of each line but it has the disadvantage of copying the file in memory twice: once when reading it, and once when building the list of lines. You can achieve pretty much the same using a list-comprehension and half the amount of memory. List-comprehensions also have the advantage that you can perform any operation while building the list, such as converting a string into a number:

def build_sentence(filename_indexes, filename_uniques):
    with open(filename_indexes) as f:
        positions = [int(line) for line in f]
    with open(filename_uniques) as f:
        words = [line.strip() for line in f]

    for index in positions:
        print(words[index], '', end='')

But you can go further and transform the number into a word as well; granted that you already have your list of words:

def build_sentence(filename_indexes, filename_uniques):
    with open(filename_uniques) as f:
        words = [line.strip() for line in f]
    with open(filename_indexes) as f:
        sentence = [words[int(line)] for line in f]

    for word in sentence:
        print(word, '', end='')

Lastly, you shouldn't compute a value and print it in the same function: return the value, if the caller want it printed, it will print it. But if the responsibility of your functions is to compute and return a value only, it is much more reusable than if they also tried to print it.

So you will need to find a way to build a string out of each word in sentence by inserting a space between each of them. You could try to do it in a loop, starting with an empty list and concatenating words and spaces. But again, that would be terribly inneficient and completely un-Pythonic. Instead use str.join(iterable) that will do the exact same thing: concatenate every elements in iterable and inserting str between each. Here you would need ' '.join(sentence).

But you can do even better by not creating the sentence list in the first place and let join combine the words and the spaces as the lines are read from the file:

def build_sentence(filename_indexes, filename_uniques):
    with open(filename_uniques) as f:
        words = [line.strip() for line in f]
    with open(filename_indexes) as f:
        return ' '.join(words[int(line)] for line in f)


A regex pattern that matches all forms of integers and decimal numbers in Python

Your expression looks just fine, maybe we would slightly modify that to:
^[+-]?((\d+(\.\d+)?)|(\.\d+))$

for failing these samples, 3., 4., for instance, just in case maybe such samples might be undesired. Other than that, you have some capturing groups that I'm guessing you'd like to keep those.

Test the capturing groups with re.finditer
import re

regex = r"^[+-]?((\d+(\.\d+)?)|(\.\d+))$"

test_str = ("0.00000\n"
    "0.00\n"
    "-200\n"
    "+200\n"
    "200\n"
    "200.2\n"
    "-200.2\n"
    "+200.2\n"
    ".000\n"
    ".1\n"
    ".2\n"
    "3.\n"
    ".")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

Test with re.findall
import re

regex = r"^[+-]?((\d+(\.\d+)?)|(\.\d+))$"

test_str = ("0.00000\n"
    "0.00\n"
    "-200\n"
    "+200\n"
    "200\n"
    "200.2\n"
    "-200.2\n"
    "+200.2\n"
    ".000\n"
    ".1\n"
    ".2\n"
    "3.\n"
    ".")

print(re.findall(regex, test_str, re.MULTILINE))

The expression is explained on the top right panel of this demo, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs step by step, if you like.

RegEx Circuit
jex.im visualizes regular expressions:


Script to get available IP automatically

Not sure if it's any better as a class...

#!/usr/bin/env python

import getpass
import requests

from orionsdk import SwisClient
from requests.packages.urllib3.exceptions import InsecureRequestWarning

class Subnet_Explorer(dict):
    def __init__(self, npm_server, auth, dns, verify, **kwargs):
        super(Subnet_Explorer, self).__init__(**kwargs)
        self.update(
            npm_server = npm_server,
            auth = auth,
            dns = dns,
            server_navn = input('Skriv inn DNS navn: '),
            swis = SwisClient(npm_server, auth['username'], auth['password'])
        )

        if verify == False:
            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

    def directed_exploration(self, subnets):
        """
        Yields tuple of IP and DNS addresses from select subnets
        """
        unexplored_subnets = subnets.keys()
        while True:
            print("Unexplored Subnets: {unexplored_subnets}".format(
                unexplored_subnets = unexplored_subnets))
            inp = input("Skriv in Subnet: ")

            if not unexplored_subnets or inp not in unexplored_subnets:
                print("Det er ikke et subnet, velg en fra listen.")
                break

            unexplored_subnets.remove(inp)
            ipaddr = self['swis'].invoke('IPAM.SubnetManagement',
                                      'GetFirstAvailableIp',
                                      subnets[inp][0],
                                      subnets[inp][1])
            dns = self['swis'].invoke('IPAM.IPAddressManagement',
                                   'AddDnsARecord',
                                   self['server_navn'],
                                   ipaddr,
                                   self['dns']['ip'],
                                   self['dns']['sone'])

            yield ipaddr, self['server_navn']

if __name__ == '__main__':
    """
    Running as a script within this block, eg. someone ran;

        python script_name.py --args

    to get here, usually.
    """

    auth = {
        'username': 'jnk',
        'password': getpass.getpass(),
    }

    dns = {
        'ip': '10.96.17.4',
        'sone': 'yy.dd',
    }

    subnet_explorer = Subnet_Explorer(
        npm_server = 'mw-solarwinds.yy.dd',
        auth = auth,
        dns = dns,
        verify = False)

    exploration = subnet_explorer.directed_exploration(
        subnets = {
            'ka-windows': ['10.112.12.0', '24'],
            'ka-linux': ['10.112.10.0', '24'],
            'ka-exa-mgmt': ['10.112.26.0', '28']
        })

    print("--------------")
    for ipaddr, server_navn in exploration:
        print("IP: {ipaddr} > DNS: {server_navn}".format(
            ipaddr = ipaddr,
            server_navn = server_navn))
    print("--------------")

... though perhaps ya see some things ya like. Regardless ya may want to consider is adding some argparse stuff after the if __name__ == '__main__': line. And probably best to use anything from above modifications with care as I may have made things a bit more messy by turning towards classes.

Is there a reason for setting dns = swis.invoke(...) when it's not being used for anything?


I tried keeping your approach, although I would've made it an infinite lazy sequence. Yours is probably a better idea, since you still have the infinite sequence (mapping to range as you did) and you can map it to other non-linear sequences too.

(def targets  ;; This is more readable for me
  (sorted-map
    3 "fizz",
    5 "buzz",
    7 "baz"))

(defn fizzbuzz [targets n]  ;; Pass the targets here! Commas aren't very common in args lists
  (let [matches (keep (fn [[f w]]  ;; Destructuring is nice :P
                        (when (zero? (mod n f)) w))  ;; Got rid of your helper function
                      targets)]  ;; ^ Use 'zero?' instead of '(= 0 ...)'
    (if (empty? matches)  ;; Use 'empty?' instead of '(= 0 (count ...))'
      (str n)
      (apply str matches))))  ;; I prefer apply here, but seen both

;;;;; EXAMPLE
(map (partial fizzbuzz targets) (range 1 20))
   => ("1" "2" "fizz" "4" "buzz" "fizz" "baz" "8" "fizz" "buzz" "11" "fizz" "13" "baz" "fizzbuzz" "16" "17" "fizz" "19" "buzz")

There's an even more idiomatic way to rewrite the (if (empty? matches)...) bit:

(if matches
  (apply str matches)
  (str n))

Lazy sequence style. Consider fizzbuzz and targets are already defined:

(defn lazy-fizzbuzz
  ([targets n]
    (lazy-seq
      (cons (fizzbuzz targets n)
            (lazy-fizzbuzz targets (inc n)))))
  ([targets]
    (lazy-fizzbuzz targets 1)))

;;;;; EXAMPLES
(take 20 (lazy-fizzbuzz targets))
   => ("1" "2" "fizz" "4" "buzz" "fizz" "baz" "8" "fizz" "buzz" "11" "fizz" "13" "baz" "fizzbuzz" "16" "17" "fizz" "19" "buzz")

;; You can also specify an initial n
(take 20 (lazy-fizzbuzz targets 20))
   => ("buzz" "fizzbaz" "22" "23" "fizz" "buzz" "26" "fizz" "baz" "29" "fizzbuzz" "31" "32" "fizz" "34" "buzzbaz" "fizz" "37" "38" "fizz")

;; which is the same as...
(take 20 (drop 19 (lazy-fizzbuzz targets)))
   => ("buzz" "fizzbaz" "22" "23" "fizz" "buzz" "26" "fizz" "baz" "29" "fizzbuzz" "31" "32" "fizz" "34" "buzzbaz" "fizz" "37" "38" "fizz")


The logical solution here is to sort the data in order, then scan it looking ahead for the partner that has the right difference to the target. Slicing, and combinations, etc. are not going to be the most efficient algorithm.

A sort with \$O(n \log n)\$ scaling, and a simple 'look ahead' to find a potential pairing, will be much, much faster.

If your data has duplicates, then you will need to look for multiple matches for the correct difference.

Consider doing a binary search for the target value, which will still leave you at an overall performance of \$O(n \log n)\$ algorithm


Optimizing and clarifying nested list appending

Using a list comprehension means you can eliminate all local variables:

size_variants = [{'size': size} for size in sizes_list]

Generally, anything of the form:

<new list initialization>
for <variable> in <list>:
    <new list>.append(<variable>)

can be written much more cleanly in list comprehension form.

Edit: If you want to extend an already existing list, and you have something like a nested list, then you'll probably want to use itertools.chain:

import itertools
x = [1, 2, 3]
y = [[4, 5], [6, 7, 8], [9, 10]
x = x + [i for i in itertools.chain.from_iterable(y)]

which will have x == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].


You can use Array#group_by to produce a hash keyed by status. Then follow that by a map to collect the counts. You'll get an array of key/value pairs, so use Hash[] to make that into a proper hash:

def batch_status
  counts = self.batch_details.group_by(&:status).map { |k, v| [k, v.count] }
  Hash[counts]
end

Alternatively, you can use use your current approach, just shortened a bit

def batch_status
  self.batch_details.reduce({}) do |counts, details|
    counts[details.status] = (counts[details.status] || 0) + 1
  end
end

Edit: Completely overlooked the "count" key. I muddies the picture a little, but you could do something like this for code blocks 1 and 2 above

def batch_status
  counts = self.batch_details.group_by(&:status).map { |k, v| [k, v.count] }
  counts << ["count", self.batch_details.count]
  Hash[counts]
end

and

def batch_status
  counts = { "count" => self.self.batch_details.count }
  self.batch_details.reduce(counts) do |counts, details|
    counts[details.status] = (counts[details.status] || 0) + 1
    counts
  end
end

Or, as Cary Swoveland suggests:

def batch_status
  counts = { "count" => self.self.batch_details.count }
  counts.default = 0
  self.batch_details.reduce(counts) do |counts, details|
    counts[details.status] += 1
    counts
  end
end

Which cleans it up nicely. Further cleanup could be done by using each_with_object in place of reduce:

def batch_status
  counts = { "count" => self.self.batch_details.count }
  counts.default = 0
  self.batch_details.each_with_object(counts) do |counts, details|
    counts[details.status] += 1
  end
end