In JavaScript/TypeScript it is custom to place the opening braces at the end of the line instead of on a new line by itself.

Insert a space between control statements and the opening round brackets. (Also don't put round brackets around the expression of a return statement.)

Always use braces even when you only have one line after the statement.

Example:

if (str != null) {
   this.strArray.push(str);
}

Always have a space between the colon and type.

Method names should start with a lower case letter, especially since you should be overriding toString.

There should be a blank line between methods.

The empty constructor is pointless and should be left out.

The Get method is not really a good idea. The fact that your string builder uses an array internally shouldn't influence the interface of the class.

If you do have a Get method like this, then you should consider emulating the signature of a regular array and return undefined instead of null, when the index is out of bounds. That actually would save you the checking of the bounds yourself:

get(nIndex: number): string {
    return this.strArray[nIndex];
}

In IsEmpty the expression this.strArray.length == 0 (should be a === BTW) returns a boolean, so you can return that directly:

isEmpty(): boolean {
    return this.strArray.length === 0;
}

Also this may not be correct way to determine an empty StringBuilder. If the array contained only empty strings, shouldn't the StringBuilder still be consider empty? But this could be covered by the next point.

Append should not only ignore null as a parameter, but also undefined and empty strings, so just do:

append(str: string): void {
    if (!str) {
        this.strArray.push(str);
    }
}

ToArrayString doesn't seem to be a good method name. I'd suggest something like joinToString. Also there is no need to use a variable in there.

joinToString(delimeter: string): string {
    return this.strArray.join(delimeter);
}

And avoid a little bit of duplicate code by having toString call ToArrayString/joinToString.

toString(): string {
    return this.joinToString("");
}


The start of a game in pygame, blitting images to the screen

As noted in the beginners guide, you should convert your image right after loading it. So instead of

tableTex = pygame.transform.scale(pygame.image.load('./Sources/Table.png'), (270, 240))

Do

tableTex = pygame.transform.scale(pygame.image.load('./Sources/Table.png').convert(), (270, 240))

As noted in the guide linked above, this can lead to a speed-up of about a factor 6. The reason is:

  The 'format' that convert() refers to isn't the file format (ie PNG,
  JPEG, GIF), it's what's called the 'pixel format'. This refers to the
  particular way that a surface records individual colors in a specific
  pixel. If the surface format isn't the same as the display format, SDL [what pygame uses underneath]
  will have to convert it on-the-fly for every blit -- a fairly
  time-consuming process. Don't worry too much about the explanation;
  just note that convert() is necessary if you want to get any kind of
  speed out of your blits.


Some possible improvement points:

Splitting out functions for word grouping, padding, and word filtering
Removing unnecessary branching
Moving from fold to self-contained recursive functions that require less post processing
Use a HashSet with a StringComparer for filtering

Using these techniques, and avoiding regexes (like my previous answer), we can get a solution that may be easier to reason about:

    open System.Collections.Generic

    let getWords (str:string) =
        let word rev_chars =
            (rev_chars |> List.rev |> Array.ofList |> String).ToUpper()

        let add_word rev_chars acc =
            if rev_chars <> [] then (word rev_chars) :: acc else acc

        let rec loop (idx:int) (rev_chars:char list) (acc: string list) prev_lower =
            if idx < str.Length then
                let c = str.[idx]
                let rev_chars, acc =
                    match str.[idx] with
                    | ' '                                      -> []             , (add_word rev_chars acc)
                    | c when Char.IsUpper(c)                   -> [c]            , (add_word rev_chars acc)
                    | c                                        -> (c::rev_chars) , acc
                loop (idx + 1) rev_chars acc (Char.IsLower c)
            else
                let acc = add_word rev_chars acc in List.rev acc

        loop 0 [] [] false

    let pad (str:string) len padchar =
        if str.Length < len then str + String(padchar, (len - str.Length)) else str

    // Filter a list of words, if we can 'afford' it, starting from the back
    let filterWords (ignoreList:HashSet<string>) charCount words =
        let rec loop revWords acc =
            match revWords with
            | [] -> acc
            | word::revWords when ignoreList.Contains(word) ->
                let getLen = List.fold (fun len s -> len + String.length s) 0
                let maxLenWithout = (getLen words) + (getLen acc)
                let numOtherParts = List.length revWords + List.length acc
                if maxLenWithout >= charCount && numOtherParts >= charCount then loop revWords acc
                else loop revWords (word::acc)
            | word::revWords -> loop revWords (word::acc)

        loop (List.rev words) []

    let genAbbr (ignoreList:HashSet<string>) padding charCount (str : string) =
        let words = getWords str |> filterWords ignoreList charCount

        // Given a list of words, generate a sequence of abbreviations
        let rec abbrs before (words: string list) : string seq = seq {
                match words with
                | [] -> ()
                | word::words ->
                    for i = 1 to word.Length do
                        let before = before + word.Substring(0, i)
                        yield before + (words |> List.map (fun w -> w.Substring(0, 1)) |> String.concat "")
                    yield! abbrs (before + word) words }

        (abbrs "" words)
        |> Seq.takeWhile (fun s -> s.Length <= charCount)
        |> Seq.maxBy (fun s -> s.Length)
        |> fun s ->
            match padding with | None -> s | Some padchar -> pad s charCount padchar

To call it:

    let ignored = let h = HashSet<string>(StringComparer.OrdinalIgnoreCase) in h.Add("the") |> ignore; h

    ["The Main Test Company"; "Main Test Company"; "The Main Company"; "The Company"; "Company"; "MainCompany"; "The MainCompany"; "MainTestCompany"; "SomeRX"; "SomeCompanyT"]
    |> List.map (fun w -> w,  (genAbbr ignored None 3 w))


Efficiently read a file into a (C) string using POSIX APIs

This is a good project, one that could be very useful in practice. I’ve had two or three C++ blogs over the years, and every time I spin up a new one, I include an updated version of a very old post I wrote about reading an entire file into a string. It’s not an easy problem to solve efficiently, for a number of complicated reasons. Eschewing the standard library and going directly to underlying POSIX API is not a bad idea; one of the sources of inefficiency is the fact that the standard library will buffer everything, meaning you end up with an unnecessary “middle man” between your code and the actual file data.
I am not an expert in the POSIX APIs, so take everything I say in that area with a grain of salt. However, the algorithm itself looks okay; I don’t see anything wrong with it. There are a few things I think are probably unnecessary and useless, but nothing that introduces potential dangers. I’ll get into details about the algorithm as we come to them in the code.
Normally I would start with a design review, but… well, frankly, there doesn’t really look like there’s much in the way of design here. Your focus appears to be on the reading algorithm, and very little else. Which… not a good thing. That’s actually the opposite of how you write good code. And it shows here. To word it another way, the actual file-reading code is probably fine… but to actually use it in practical code (the way it’s currently written) would be difficult, at best.
For example, the iterators return char const*, and there looks like a lot of effort to NUL-terminate the data. So… is it meant to be string data? If so, why isn’t there a c_str() function? Or a conversion to string_view? On the other hand, if it’s not meant to be a string, just raw byte data read from a file, why not use std::byte? Why isn’t there a data() function?
Better yet, why not just read the data directly into an existing container, like std::string (for text data) or std::vector<std::byte> (for binary data)?
But I get it; your focus was on the read algorithm, not making an actually useful interface. That’s fine for experimentation, but when you’re eventually putting this code to use in a real-world library, the place that really needs focus is the public interface… not the low-level reading code. If your public interface sucks, then even if the reading code is the most brilliant code ever, the whole library still sucks for the user. But if your public interface is really good, then even if the reading code sucks… well, you can fix that under the hood, and users of your public interface won’t notice (except for maybe seeing performance gains).
Also, you should really get into the habit of testing your code. And by that I don’t mean “write it, then write a main() function that tries it out and if it all compiles and appears to run and produce correct-looking output, that’s that”. I mean fully unit-testing the code.
So, let’s get into the actual code.
Code review
Slurp.hh
    void *begin_{nullptr};
    void *end_;

The convention in C++ is to put all the type information together. In other words:

void *end_;: This is C style.
void* end_;: This is C++ style. (Well, other than that we try to avoid void* in C++.)

There is an alternative design to consider. Rather than holding two pointers, it might make more sense to hold a pointer and a size. Why? It makes it much easier to maintain and check the class invariant. If you use a pair of pointers, you have to make sure that end_ comes after begin_. But there is no portable way to ensure that (comparing random pointers is UB). On the other hand, if you use a pointer and a size, there is no possible way that the “end” can be before the beginning (assuming the size is unsigned, which is standard practice, but even if it’s signed, it’s trivial to check that the size is greater than zero).
It’s not really a big deal, and two pointers does work just fine in practice. It’s just something I’ve seen experts have opinions on.
I also don’t get why these are void*. void* makes a lot less sense in C++ than it does in C, and in this case… I can’t see the point of it at all. If this is supposed to be character data—a string—then why aren’t these char*? That sure seems to be the intention, what with all the NUL terminating and casting in begin() and end(). If this is supposed to be binary data, then unsigned char* or, better, std::byte* make more sense. void* just doesn’t make sense, not least because you’re just casting it to char* before using it anyway.
Anywho, aside from all that, there doesn’t seem to be a reason why end_ couldn’t also have an initializer.
    Slurp() = delete;

This line is technically unnecessary, because the fact that you have the constructor Slurp(char const[]) means that you have already disabled the default constructor.
Still, it doesn’t hurt, and it does express intent, so I’d leave it.
    Slurp(Slurp&) = delete;
    Slurp &operator=(Slurp) = delete;

These will probably “work”, but if your intention is to disable copying, then they are malformed. They should be:
    Slurp(Slurp const&) = delete;
    auto operator=(Slurp const&) -> Slurp& = delete;
    // or:
    //  Slurp& operator=(Slurp const&) = delete;

Disabling copying makes sense, given that copying will probably be fairly expensive. If someone really wants to copy the data, they can always do something like:
auto const data = Slurp{"input.data"};

auto const data_copy = std::vector(data.begin(), data.end());

But you might consider making the type movable. That could be very handy. It wouldn’t even be hard to do; you just need to make the class aware of a “null” or moved-from state, perhaps like so:
class Slurp
{
private:
    void* begin_ = nullptr;
    void* end_ = nullptr;

public:
    [[gnu::nonnull]] explicit Slurp(char const* path)
    {
        // your existing constructor code...
    }

    Slurp(Slurp&& other) noexcept
    {
        std::ranges::swap(begin_, other.begin_);
        std::ranges::swap(end_, other.end_);
    }

    ~Slurp()
    {
        if (begin_) // note the if test
            std::free(begin_);
    }

    auto operator=(Slurp&& other) noexcept -> Slurp&
    {
        std::ranges::swap(begin_, other.begin_);
        std::ranges::swap(end_, other.end_);
        return *this;
    }

    Slurp(Slurp const&) = delete;
    auto operator=(Slurp const&) -> Slurp& = delete;
};

Being able to very cheaply moved the slurped data around could be very handy indeed.
    [[gnu::nonnull]] Slurp(const char path[]);

Writing functions that look like they take arrays like this is a really bad idea. (Except for main(), which is just special in a lot of ways.) I’ve lost count of the number of newbies who think that this actually takes an array argument, and then think they can do sizeof(path) / sizeof(path[0]) to get the number of elements. Yes, you and I and other experts know what’s really going on, but you shouldn’t be writing code that’s only readable by experts. Down that path lies madness.
On the other hand Slurp(const char* path) or Slurp(char const* path) are unlikely to confuse beginners, and, really, tell the truth of what’s going on much better.
As a general rule, all constructors that take a single argument should be marked explicit (unless you have a damn good reason not to). Yes, explicit should really be the default, but that ship sailed a long time ago.
In addition to this constructor, it would help usability if you could use strings or—even better—actual paths with this class. It would be trivial to do, too:
explicit Slurp(std::string const& path) :
    Slurp{path.c_str()}
{}

explicit Slurp(std::filesystem::path const& path) :
    Slurp{path.c_str()}
{}

Now this next bit is going to get really complicated. Brace yourself.
gnu::const on non-static member functions
    [[gnu::const, gnu::returns_nonnull]] const char *begin() const noexcept;

The issue here the gnu::const attribute. I am not a GCC expert, but from my understanding of gnu::const, it sure seems like using it for a member function is an absolutely terrible, and dangerous, idea.
Here’s why.
gnu::const means that a function’s output depends ONLY on the function’s arguments. And I mean ONLY. The function’s behaviour cannot be affected by anything else; it doesn’t matter what state the rest of the program happens to be in (well, I mean, the state has to be valid… if the abstract machine’s state is kerfuckt, then all bets are off in any case), the function’s return value will ALWAYS be the same, given the same arguments.
This makes sense for, say, a function like: auto twice(int i) { return i * 2; }. It doesn’t matter what’s going on with the rest of the program, like how many exceptions are in flight or how many files are open or how much memory has been allocated. So long as the function can complete without UB (for example, there is no stack overflow), then it will ALWAYS return the same result for the same arguments. twice(32) will ALWAYS return 64. ALWAYS. GCC can use that information to optimize. For example, if you call twice(14) a million times in your program, GCC might cache the result of the first call, and then replace every other call with just loading that cached value.
So far none of this sounds problematic, I suppose. Well, now let’s talk about non-static member functions.
There is a very important key feature of non-static class member functions: the implicit this.
You see, every non-static class member function has a hidden this argument. We usually pretend it’s the first argument (but it doesn’t actually have to be, in reality, it’s usually passed in a specific register), so your begin() function actually looks like begin(Slurp const*):
// what you write:
auto Slurp::begin() const noexcept -> char const*
{
    return begin_;
}

// what the compiler actually implements:
auto Slurp__begin(Slurp const* this) noexcept -> char const*
{
    return this->begin_;
}

Normally, this isn’t something you need to think about.
However… remember what gnu::const means. It means that begin() will ALWAYS return the same result, when called with the same argument.
So let’s imagine you write this:
auto const s = Slurp{"data.file"};

auto p1 = s.begin();
auto p2 = s.begin();
auto p3 = s.begin();
auto p4 = s.begin();
auto p5 = s.begin();

The above is theoretically:
auto const s = Slurp{"data.file"};

auto p1 = Slurp__begin(&s);
auto p2 = Slurp__begin(&s);
auto p3 = Slurp__begin(&s);
auto p4 = Slurp__begin(&s);
auto p5 = Slurp__begin(&s);

But since begin() is gnu::const, once we know the result of calling it with address of s, we can assume that will ALWAYS be the result of calling it with that address. So the compiler could do:
auto p1 = Slurp__begin(&s);
auto p2 = p1;
auto p3 = p1;
auto p4 = p1;
auto p5 = p1;

(And it probably will.)
So far no problems. There is currently no way for the value of begin_ to change once a Slurp object has been constructed, so the above code is a perfectly valid optimization.
However, suppose you implemented moving—or copying, or any way to change the data in a Slurp object. Then you wrote this:
auto const s = Slurp{"data.file"};

auto p1 = s.begin();
auto p2 = s.begin();

s = Slurp{"other.file"};    // this line will construct a new Slurp,
                            // and REPLACE the internals of `s` with the
                            // new data

auto p3 = s.begin();
auto p4 = s.begin();

Now the address of s hasn’t changed… but it’s internal data—in particular, the value of begin_—has changed. The compiler sees the above code as:
auto const s = Slurp{"data.file"};

auto p1 = Slurp__begin(&s);
auto p2 = Slurp__begin(&s);

s = Slurp{"other.file"};

auto p3 = Slurp__begin(&s);
auto p4 = Slurp__begin(&s);

And it does the optimization:
auto const s = Slurp{"data.file"};

auto p1 = Slurp__begin(&s);
auto p2 = p1;

s = Slurp{"other.file"};

auto p3 = p1;
auto p4 = p1;

Except after the move assignment, p1 is now a dangling pointer. Which means p3 and p4 are dangling pointers, too.
This is a disaster.
Now you may be thinking: “Meh, no problem; my class is non-copyable, non-movable, and immutable. This problem doesn’t affect me.”
Wanna bet?
Remember, gnu::const isn’t about the object. It’s about the arguments to the function. In the example above, the object’s internals changed, but the address of the object didn’t, so the argument to begin() didn’t either, and that was the problem. So if the object’s internals can’t possibly change… no problem, right?
Wrong.
Because even if it is impossible to change the internals of an object, it is still possible to create an object… destroy it… then create a whole new object at the same memory address… and it is the address that matters. Because that is what is being used as the function argument to begin().
Here’s just one example of how that could happen:
auto s = std::optional<Slurp>{std::in_place, "data.file"};

auto p1 = s->begin();
auto p2 = s->begin();

s.emplace("other.file");    // destroys contained Slurp object, then
                            // constructs a new one in the same place... so it
                            // has the same address

auto p3 = s->begin();
auto p4 = s->begin();

Which eventually optimizes to:
auto s = std::optional<Slurp>{std::in_place, "data.file"};

auto p1 = s->begin();
auto p2 = p1;

s.emplace("other.file");

auto p3 = p1;
auto p4 = p1;

And ends up with the same problem.
But you don’t even need std::optional! This problem could be triggered with even this code:
auto f()
{
    auto s = Slurp{"data.file"};

    auto p = s.begin();
}

auto some_other_function()
{
    f();
    f();
}

What might happen above is the first call to f() happens to place s at some address on the stack… then when f() ends, s is destroyed… then f() is called again and just happens to place the new s at the same address on the stack. But of course, the allocation done within the Slurp constructor (the posix_memalign() call) may be entirely different. So p SHOULD have two entirely different values with the two successive calls to f() even though the address of s (and thus, the argument passed to begin()) is the same for both calls. But gnu::const says it won’t; gnu::const says that if the argument is the same, the result is the same.
Once again: catastrophe.
To get a clearer view of why, imagine the calls to f() are inlined. Inlining isn’t necessary to trigger the problem, but it helps illustrate. If the calls are inlined, some_other_function() will look like:
auto some_other_function()
{
    {
        auto s = Slurp{"data.file"};

        auto p = s.begin();

        // s is destroyed here
    }

    {
        auto s = Slurp{"data.file"};

        auto p = s.begin();

        // s is destroyed here
    }
}

After the first s is destroyed, the second s may very well be constructed at the exact same location… let’s call it STACK_ADDRESS. So:
auto some_other_function()
{
    {
        auto s = Slurp{"data.file"};

        auto p = Slurp__begin(STACK_ADDRESS);

        // s is destroyed here
    }

    {
        auto s = Slurp{"data.file"};

        auto p = Slurp__begin(STACK_ADDRESS);

        // s is destroyed here
    }
}

The two calls to begin() are identical, and gnu::const promises that that means the result will be identical, so the compiler might do:
auto some_other_function()
{
    auto __p_inlined = static_cast<char const*>(nullptr);

    {
        auto s = Slurp{"data.file"};

        __p_inlined = Slurp__begin(STACK_ADDRESS);
        auto p = __p_inlined;

        // s is destroyed here
    }

    {
        auto s = Slurp{"data.file"};

        auto p = __p_inlined;

        // s is destroyed here
    }
}

And, boom.
Whew, that was a long digression. The tl;dr is “don’t use gnu::const for (non-static) member functions”… but I think it’s important to understand why.
And, really, it seems kinda pointless in modern C++. If it is possible for a function to be gnu::const, then it is almost certainly also possible for it to be constexpr… in which case the compiler can optimize it far more aggressively than it could possibly optimize a function that is merely gnu::const (but not wholly visible).
Slurp.cc
using namespace std;

Never, ever do this at file scope. No, not even in a non-header file. Just use std::.
#define ERROR_IF(CONDITION) do {\
        if (__builtin_expect((CONDITION), false))\
            throw system_error(errno, system_category());\
    } while (false)

#define ERROR_IF_POSIX(POSIX_PREFIXED_FUNCTION_CALL) do {\
        const int error_number = posix_##POSIX_PREFIXED_FUNCTION_CALL;\
        if (__builtin_expect(error_number, 0))\
            throw system_error(error_number, system_category());\
    } while (false)

Avoid macros. There’s no good reason for them here. Inlined functions will be just as efficient… not that it really matters, because these are error cases after all. For example:
namespace {

auto error_if(int result)
{
    if (result != 0) [[unlikely]]
        throw std::system_error{errno, std::system_category()};
}

auto error_if_posix(int error_number)
{
    if (error_number != 0) [[unlikely]]
        throw std::system_error{error_number, std::system_category()};
}

} // anonymous namespace

Slurp::Slurp(char const* path)
{
    // ... [snip] ...

    error_if_posix(::posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL));

    struct ::stat file_statistics{};
    error_if(::fstat(fd, &file_statistics));

    // ... etc.

But even that’s not really great, because it just obfuscates the function’s logic. I don’t see how it’s really an improvement over:
Slurp::Slurp(char const* path)
{
    // ... [snip] ...

    if (auto const res = ::posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL); res != 0) [[unlikely]]
        throw std::system_error{res, std::system_category()};

    struct ::stat file_statistics{};
    if (auto const res = ::fstat(fd, &file_statistics); res != 0) [[unlikely]]
        throw std::system_error{errno, std::system_category()};

    // ... etc.

The only thing I might do is maybe avoid repeating std::system_category by doing:
namespace {

auto posix_error(int err)
{
    return std::system_error{err, std::system_category()};
}

} // anonymous namespace

Slurp::Slurp(char const* path)
{
    // ... [snip] ...

    if (auto const res = ::posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL); res != 0) [[unlikely]]
        throw posix_error(res);

    auto file_statistics = ::stat{};
    if (auto const res = ::fstat(fd, &file_statistics); res != 0) [[unlikely]]
        throw posix_error(errno);

    // ... etc.

I just don’t see the benefit of hiding the throws. Yes, I get that it is somewhat ugly to have to check the return code every function call… but this is a C API; that’s just the nature of the game.
If you really don’t want all that ugly C-ish code, the right move is to properly wrap the API… not to obfuscate your logic by hiding it behind macros. For example:
Slurp::Slurp(char const* path)
{
    auto const fd = posix::open(path, O_RDONLY);

    posix::fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);

    auto const file_statistics = posix::fstat(fd);

    // ... etc.

(Note that implied is that each call above throws on failure, like a good C++ API should.)
But it’s really an all-or-nothing deal. Either completely wrap the API into a proper C++ API, so the usage just looks like regular C++… which maintainers of the code should be familiar with. Or use the C API as-is—don’t hide it behind macros—so people who actually know the POSIX API inside and out can look at your code and immediately spot what’s going on (and any potential problems). Going half-way just annoys both parties, with no real benefits.
    class FileDescriptor {
        const int fd_;
    public:
        FileDescriptor(int fd) : fd_{fd} {ERROR_IF(fd_ == -1);}
        ~FileDescriptor() {close(fd_);}
        [[gnu::const]] operator int() const noexcept {return fd_;}
    };

This is a really useful class! Rather than burying it as an implementation detail, it could be part of a public API. You’d need to flesh it out a bit (and make it non-copyable, but perhaps movable), but it’s pretty cool.
FileDescriptor fd{open(path, O_RDONLY)};

This goes back to the “never use using namespace std;” rule: function names like open() are extremely common, and there is a very high chance of conflict between the POSIX function, and some function you might put in your class in the future. If that were to happen, if you are lucky, you’ll get a compile error… but I’ve seen cases where behaviour subtly changes because the wrong function is called.
To make sure you get the right function, you should explicitly qualify it. In this case, because it’s a POSIX function that doesn’t exist in a namespace, you have to use ::open().
You should do this for all the POSIX functions.
constexpr char32_t NullChar = U'\0';

I’m a little baffled by the logic here.
Okay, so you want the data to be null-terminated. Fine, sure. But… you’re treating the data as an array of char… not char32_t. So… huh?
The only thing I can figure is that you’re imagining that maybe someone might possibly want to reinterpret_cast the char const* to char32_t const*, and treat the data as a UTF-32 NUL-terminated string. That seems a pretty odd thing to presume. And it’s even odder when you consider that the Slurp class doesn’t even model a NUL-terminated string in any sense. There is no c_str() function, for example. Even if there were, it’s hard to see why it should return a char32_t const* and not a char const*.
Aside from being odd, it may also be wrong. You are aligning the memory according to file_statistics.st_blksize… not alignof(char32_t). In other words, if you’re thinking that you can just reinterpret_cast the result of begin() to a char32_t const* and treat it as a UTF-32 string… you may be in for a nasty surprise when your program crashes due to a a misaligned read. Or, possibly, just garbled text (that is probably illegal Unicode). (And all this is assuming the endianness of the UTF-32 data is correct.)
I mean, if you really wanted to read file data as a UTF-32 string, why wouldn’t you read it into a std::u32string? Similarly, if you want a regular string, why not read it directly into a std::string? In either case, all the allocation and alignment headaches are taken care of, and the NUL termination is automatic. And if you want binary data, why not read directly into a std::vector<std::byte>?
I’ll be getting back to that idea later.
ERROR_IF_POSIX(memalign(&begin_, blksize, bufsize));

Honestly, I don’t see the point of this.
Okay, I get that the file you’re reading probably has a preferred block size, and if you were mem-mapping the file, or reading it directly from storage, then yes, you’d need aligned memory. But you’re doing neither.
Internally, when you open the file (and specify the access characteristics via posix_fadvise()) a buffer gets created. (I think you can avoid this by using direct input, but that’s beyond the scope here. mmap() is another way to avoid the buffer, but that’s another beast altogether.) Then you are reading from that buffer into your program’s memory space. Now, the buffer needs to be aligned to the block size of the file, so that the file can be read efficiently a block at a time. But your memory… the memory you allocate to read the file data (from the buffer) into… that does not need to be aligned to the block size of the file… because with that memory, you are not reading directly from the file, you are reading memory-to-memory (from the kernel’s buffer, to your array).
Follow? Block-alignment only matters for the initial read of the file from the device. THAT needs to be block-aligned. But unless you’re doing direct input, that’s happening in the kernel (usually), and then read() copies from that buffer to your desired location. Once the data is already in RAM, it’s just a memory-to-memory copy… which is just a rep stosb or some SSE or AVX operation. That doesn’t need to be aligned.⁕
⁕ (Ugh, in order to make this not too absurdly long, I have to gloss over or outright ignore a lot of hyper-technical details, so I know there are nerds out there just champing at the bit to “akshually…” me in the comments. Okay, yes, the data does need to be aligned for super-fast memory-to-memory transfer… both the source and destination data, with penalties for not being aligned varying depending on your processor architecture. HOWEVER… the default C++ allocator in any serious-grade standard library is almost certainly already aligning every allocation to take advantage of those efficiencies by default. So unless you’re doing something “clever”, you don’t need to worry about it.)
In other words, you’re wasting your time using posix_memalign(). You gain nothing from it. You could just as well be using malloc() or new.
Which brings us back again to the idea of reading directly into std::string or std::vector<std::byte>. But let me postpone that for a bit more, because we’re almost at the end of the code, so let’s get through that first.
ERROR_IF_POSIX(madvise(begin_, bufsize, POSIX_MADV_SEQUENTIAL));

I’ll admit that I don’t understand how this call isn’t failing. I thought posix_madvise() was only for memory-mapped memory. I would have guessed you’d get a EBADF from trying to use it on random memory. TIL, I guess.
But I do suspect the call is just being ignored. My understanding of POSIX_MADV_SEQUENTIAL is that it signals to the kernel to make a larger look-ahead buffer… which makes sense if you’re mem-mapping a file into memory, but is just nonsense for RAM. (Where you gonna put the look-ahead buffer for RAM? Super-duper-RAM?)
ERROR_IF(read(fd, begin_, fsize) == -1);

read() can fail spuriously for a number of reasons, like a signal interrupting it, and end up doing only a partial read. You can’t just write a read() call like this; you need to call it in a loop and keep doing reads until you’ve read fsize bytes in total or until read() returns zero.
memcpy(end_, &NullChar, sizeof NullChar); // ensure null termination

I mean… why not just std::fill_n(end, 4, 0);? It would probably be faster. (Unless your optimizer is smart enough to transform that memcpy() into a memset(), in which case it will probably be equally fast.)
Reading directly into containers
Okay, the biggest problem with Slurp is that it’s a specialized type. Even if it had a perfect interface, it’s still not a string. If I need a std::string, which is very common, then I’ll be forced to copy the entire Slurp object into a std::string. What a waste.
What if you just read the file’s contents directly into a std::string. Or, if it’s binary data, into a std::vector<std::byte>. Remember, there is no need to use posix_memalign() to specially align the memory to the original file’s preferred block size. The default allocator will align things just fine. So you can just use standard containers.
(But, FYI, even if the default allocator didn’t align things just fine, it would still be a better solution to use a custom allocator, and standard containers, rather that rolling your own, half-assed container.)
For example, to read into a string (note: untested, rough code):
auto read_into_string(std::filesystem::path const& path)
{
    // file_descriptor is a class basically identical to yours
    auto const fd = file_descriptor{::open(path.c_str(), O_RDONLY)};

    // get the file size from the file descriptor
    auto const file_size = [&]
    {
        struct ::stat fstats{};
        if (auto const res = ::fstat(fd, &fstats); res != 0)
            throw std::system_error{errno, std::system_category()};
        return fstats.st_size;
    }();

    // create the string we'll be reading into
    auto s = std::string{};
    s.resize(file_size);

    // this is the read loop
    auto pos = std::string::size_type{};
    while (true)
    {
        auto const last_read = ::read(fd, s.data() + pos, s.size() - pos);
        if (last_read < 0)
            throw std::system_error{errno, std::system_category()};
        else if (last_read == 0)
            break;

        // this should never happen
        if (last_read > (s.size() - pos)) [[unlikely]]
            throw std::runtime_error{"more data in file than file size"};

        pos += last_read;
    }

    // this should never happen
    if (pos != s.size()) [[unlikely]]
        throw std::runtime_error{"failed to read entire file"};

    return s;
}

And the usage:
auto const string_data = read_into_string("file.txt");

And string_data is a std::string.
The only thing that I suspect might make this code slower than your code, and only for very, very large files, is that there is no way (AFAIK) to allocate a std::string without initializing its contents. In other words, s.resize(n) doesn’t does just allocate n bytes (internally), it also zeros those bytes… which is a total waste of time for us. You shouldn’t have this inefficiency if you’re reading binary data into a std::vector<std::byte> (for which the code is otherwise identical).
But even that std::string inefficiency should be tolerable (unless your files are huge), because you get the benefit of actually having an honest-to-goodness string. Which basically works everywhere, and which many APIs specifically need, in one form or another.
And, frankly, I seriously doubt you’ll even notice it, because, again, unless you’re dealing with huge files, the cost of that zeroing will be completely dwarfed by the I/O costs.
Anywho, this is getting way too long, and I’ve been sitting on it for days, so, I’ll just go ahead and publish what I’ve got.


Small code duplication

The two constructors of DataCache have duplicated code:

DataCache() {
    dataMap = new HashMap<K, DataValue<V>>();
    mTimeout = mDefaultTimeout;
}

DataCache(long timeoutMinutes) {
    dataMap = new HashMap<K, DataValue<V>>();
    mTimeout = timeoutMinutes;
}

The difference between the default constructor and the second one is the use of a default timeout value. It would be better to invoke the second constructor from the default one to avoid duplication:

DataCache() {
    this(mDefaultTimeout);
}

DataCache(long timeoutMinutes) {
    dataMap = new HashMap<K, DataValue<V>>();
    mTimeout = timeoutMinutes;
}

Logic of code

You have a DataValue class that holds the time at which it was inserted in the map. For the map itself, this should be transparent: it doesn't know what the value is doing to find out if it's outdated or not. The field long insertTime goes in that direction.

But then, you are using

long diff = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - data.insertTime);

inside the map itself. This means that, somehow the map has figured it out: it knows that the values are following the current system time to know if they're outdated or not. So this couples the map with the logic of the expiration of the value.

I would suggest creating a method isExpired(timeOut) inside the class DataValue, that will tell if a given value is expired or not based on the current timeout.

private final class DataValue<T> {
    public T value;
    private long insertTime;

    DataValue(T value) {
        this.value = value;
        insertTime = System.currentTimeMillis();
    }

    public boolean isExpired(long timeOut) {
        return TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - insertTime) >= timeOut;
    }

}

Note that, in the mean time, I also made the insertTime variable private because, now, the map doesn't need to know that information. The advantage of that approach is that, someday, if you decide not to rely on System.currentTimeMillis() but on something else entirely (reading info from a file, always return true, etc.), you just need to change that single method.

In the same way, I would move the

data.value = null;

logic, that reinitializes the value to a method inside the DataValue class, and make value private.

Constants

In Java, a constant, like your mDefaultTimeout should be both static and final. Also, it should be written in uppercase. So instead, I would have

private static final long DEFAULT_TIMEOUT = 15;

Note that you could add a comment to specify the unit for which 15 refers to (Is it seconds? minutes?).

Namings

Why are you prefixing all your variables by m? This does not really follow the Java naming conventions. It would be preferable to have

private long timeout = 0;


Firstly I would change all the occurances of

}

if(!i && c.indexOf(...

to

 } else if(c.indexOf(...

To me there doesn't seem to be any difference logically and its cleaner.

Second I would use regexes for the urls (I'm sure someone will comment on how regexes aren't needed/ too slow yadda yadda.)

var regexFBprofile = /^(http\:\/\/)?(www\.)?facebook\.com\/profile\.php\?id=/;
var regexLinkedIn = /^(http\:\/\/)?(www\.)?linkedin\.com\/in\//;
var regexMySpace = /^(http\:\/\/)?(www\.)?myspace\.com/;
var regexTwitter = /^(http\:\/\/)?(www\.)?twitter\.com\//;

another small thing:

re = / /g;
contacts = contacts.replace re, "");

with:

contacts[i].trim();

http://jsfiddle.net/96Gk6/34/


Lists' intersection keeping elements' order

This function deletes from the first list all the elements not contained in the intersection, thus returning what you want:

f[l_List]:= DeleteCases[First@l, Except[Alternatives @@ (Intersection @@ l)]]

f[{{1, 2, 3, 4, 5}, {1, 2, 3, 4}, {2, 3, 4, 5}}]
->{2,3,4}

f[{{5, 7, 6, 3}, {5, 6, 1, 3}}]
->{5,6,3}


Finding the longest path in an equally-weighted tree

(defn farthest [edg current-node entry-node len]
    (let [
        farthest-key (atom current-node)
        farthest-val (atom len)
        ]
        (do
            (dorun
                (map
                    (fn [n]
                        ...
                    )
                    (aget edg current-node)
                )
            )

            [@farthest-key @farthest-val]
        )
    )
)

Put )s and ] on the same line as the expression they close.
Put the first let-binding and [ on the same line.
You can use doseq instead of (dorun (map ...))
You can drop the do, since let has an implicit do around its body

E.g.,

(defn farthest [edg current-node entry-node len]
  (let [farthest-key (atom current-node)
        farthest-val (atom len)]
    (doseq [n (aget edg current-node)]
      ...)
    [@farthest-key @farthest-val]))

But also, think functional:

You don't need atoms (e.g., use reduce to find the maximum path, rather than an imperative loop).
Don't use arrays.  Use Clojure's persistent data structures instead.  For example, represent the tree as a map from node ids to a set connected nodes.


You are missing a second part of the diff.

I've added the missing part, renamed the variables a bit to make it easier to work with, and added some comments.

DELIMITER $$

DROP PROCEDURE IF EXISTS JSON_OBJECT_DIFF $$

CREATE PROCEDURE JSON_OBJECT_DIFF(IN a JSON, IN b JSON, INOUT aResult JSON, INOUT bResult JSON)
BEGIN
    DECLARE aKeys, bKeys JSON;
    DECLARE currentKey, currentKeyPath TEXT;
    DECLARE aVal, bVal JSON;
    DECLARE aKeysLength, bKeysLength, aHasKey, bHasKey INT;
    DECLARE i INT DEFAULT 0;

    SELECT JSON_KEYS(a) INTO aKeys;
    SELECT JSON_KEYS(b) INTO bKeys;
    SELECT JSON_LENGTH(aKeys) INTO aKeysLength;
    SELECT JSON_LENGTH(bKeys) INTO bKeysLength;

    # Iterate keys in `a` as `currentKey`:
    # * If exists in `b` and !=, insert `a(currentKey)` and `b(currentKey)` into `aResult` and `bResult`
    # * If does not exist in `b`, insert `a(currentKey)` into `aResult`

    WHILE i < aKeysLength DO
        SELECT JSON_EXTRACT(aKeys, CONCAT('$[', i, ']')) INTO currentKey; /* Already quoted */
        SELECT CONCAT('$.', currentKey) INTO currentKeyPath;
        SELECT JSON_EXTRACT(a, currentKeyPath) INTO aVal;

        SELECT JSON_CONTAINS_PATH(b, 'one', currentKeyPath) INTO bHasKey;

        IF bHasKey = 1 THEN
            SELECT JSON_EXTRACT(b, currentKeyPath) INTO bVal;

            IF aVal != bVal THEN
                SELECT JSON_INSERT(aResult, currentKeyPath, aVal) INTO aResult;
                SELECT JSON_INSERT(bResult, currentKeyPath, bVal) INTO bResult;
            end if;
        ELSE
            SELECT JSON_INSERT(aResult, currentKeyPath, aVal) INTO aResult;
        END IF;

        SET i = i + 1;
    END WHILE;

    # Iterate keys in `b` as `currentKey`:
    # * If does not exist in `a`, insert `b(currentKey)` into `bResult`

    SET i = 0;
    WHILE i < bKeysLength DO
        SELECT JSON_EXTRACT(bKeys, CONCAT('$[', i, ']')) INTO currentKey; /* Already quoted */
        SELECT CONCAT('$.', currentKey) INTO currentKeyPath;

        SELECT JSON_CONTAINS_PATH(a, 'one', currentKeyPath) INTO aHasKey;

        IF aHasKey = 0 THEN
            SELECT JSON_EXTRACT(b, currentKeyPath) INTO bVal;
            SELECT JSON_INSERT(bResult, currentKeyPath, bVal) INTO bResult;
        END IF;

        SET i = i + 1;
    END WHILE;
END $$


Presenting collections for code generation

can it be improved?

Looks good to me.

Ship it.

The program accomplishes its goals, and it is clear. The length seems about right for what it does.


Your code looks very good for me, what I found are just some minor improvements:

You do not need to inherit from object so you can just do class temp:
I would suggest to change temporary class name to something else since when you do print(type(x)) I would rather see something more informative than <class '__main__.create_number_class.<locals>.temp'>. I would suggest to add another argument for your method called className and set it dynamically as shown here
New lines after each method would be appreciated since it would make code more readable


Code style is not the problem. The expectation is that a new coder uses the in house style guides when writing.

I think the problem is that you missed an important assumption.

The test case passes one argument, however that does not mean that the function you are given will have only one argument.

Thus maybe (I am just guessing) if you wrote...

const alternate = fn => {
    let odd = false;
    return (...args) => (odd = !odd) ? fn(...args) : undefined;
};

Also though not stated there could have been an expectation that it not throw on bad input. Thus first vet the input function.

const alternate = fn => {
    let odd = false;
    return typeof fn === "function" ?
        (...args) => odd = !odd ? fn(...args) : undefined :
        () => {};
}

or

function alternate (fn) {
    if (typeof fn === "function") {
        let odd = false;
        return (...args) => odd = !odd ? fn(...args) : undefined;
    }
    return () => {};
}

As the documentation does not say anything about throwing an error the safer bet is to silently deal with bad input


Binary searching the turning point of a function

Don't use using namespace std; Writing std:: a few times isn't that bad, and it helps keep the std lib types identifiable in your code.

Don't use globals so much. It is much better to limit the scope of variables to where they are needed and pass them around (possibly by reference) when needed. Usernumber for example is only used when filling the array, So something like this is much better:

for (int u = 0; u < arraysize; u++) {
    long long number;
    std::cin >> number;
    userArray.push_back(number);
}

vectorsum has a vector passed by value, this will copy the entire vector. instead you'll want to pass by const ref:

int vectorsum(const std::vector<long long>& userVector) {
    int ans = std::accumulate(userVector.begin(), userVector.end(), 0);
    return ans;
}

You don't really need this function at all though, you can keep a running total instead and save yourself the loop.

You keep rebuilding the vectors over and over again, you don't even need to do that. Instead you only need to keep track of the sum of the current subarray you are testing and how many subarrays you have built already.

You can also keep track of the largest subarray sum and pass it back as new upperbound. This will reduce the iteration time once the options have been narrowed down somewhat because then you will never try 2 numbers that will create the same partition.

long long isPossible(const std::vector<long long> &user_array, long long max_sum, int max_number_subarrays) {

    long long running_sum = 0;
    long long largest_sum = 0;
    int subarray_count = 0;
    for (auto current : userArray) {
        if (running_sum + current <= max_sum) {
            running_sum += current;
        } else {
            if(running_sum > largest_sum)
                 largest_sum = running_sum;

            running_sum = current;

            subarray_count++;
            if(subarray_count > max_number_subarrays)
                return -1; //early out

        }
    }

    return largest_sum;
}

and in the while loop.

while (left + 1 != right) { //Binary search
    middle = ceil((left + right) / 2);
    long long result = isPossible(userArray, middle, numberofsubarrays)
    if (result >= 0) {
        right = result;
    }
    else {
        left = middle;
    }
}
std::cout << right << endl;

You can initialize left with the largest number in the input Because if it was less than at least one sub array sum will be larger than it.

right can be initialized with the sum of the array where every element is in a single subarray.

int left = 0;
int right = 0;

for (int u = 0; u < arraysize; u++) {
    long long number;
    std::cin >> number;
    userArray.push_back(number);

    if(left < number)
        left = number;
    right+= number;
}


I don't think you get much benefit from using the IDbConnection. What I do is just use connection in my repository and use IoC just for the IRepository. The other problem with your code is that there is nothing disposing your connection. Since it's a console app it might not be a big deal, but typically you want to open a connection, do a bunch of work and then close it. If this was a web app for instance you'd run out of pools in your connection pool. Typically you want your IoC being the one to new up instances of classes, not pass in one you already created.


Instead of resetting the massOnBridge, you can declare it inside the body of the for loop:

for (int i = 0; i < totalCars; i++) {
    int massOnBridge = 0;
    ...

It is a good practice to keep a scope of a variable as narrow as possible.
There are a lot of comments in your code that tell what the code does. Instead, you should try to write a self-documenting code. You can increase modularity and clarity of your code by using separate methods for separate tasks. For instance,

// gets the sum of the masses on the bridge
for (int j = 0; j < carsOnBridge.size(); j++) {
     massOnBridge += carsOnBridge.get(j);
}

looks like a very good candidate for a separate method:

/**
  * Computes the sum of elements of {@code aList}.
  * @param aList A list of integers. Must not contain {@code null} elements.
  *              Must be non-{@code null}.
  * @return The sum of elements of the given list.
  */
private static int getSum(List<Integer> aList) {
    int sum = 0;
    for (int value : aList) {
         sum += value;
    }
    return sum;
 }

Having one long method(main in your case) that does everything is a bad practice.


Initializing multiple variables with different types using parallel calls

I've been doing something similar to your await Task.WhenAll, though not often enough to think about a shorter way of doing it. However, I've recently come to doubt the necessity of it.

Note that there is almost zero difference in the effective behavior of this code:

var t1 = SomethingAsync();
var t2 = OtherAsync();
await Task.WhenAll(t1, t2);
var r1 = await t1;
var r2 = await t2;

and this code:

var t1 = SomethingAsync();
var t2 = OtherAsync();
var r1 = await t1;
var r2 = await t2;

In both cases, the tasks are started. In both cases, the tasks run in the background as much as possible. In both cases, the method won't finish until both tasks are done, assuming they succeed.

If only task t1 fails, both cases will throw its exception. The first version will first wait for task t2 to finish, the second version will not. This may make a difference, but usually won't.

If only task t2 fails, both cases will throw its exception, although the second version will execute a little more code first; this difference is very unlikely to make a practical difference.

If both tasks fail, both cases will throw the exception of t1 and swallow the one of t2, see here: https://blogs.msdn.microsoft.com/seteplia/2018/02/14/one-user-scenario-to-rule-them-all/ down at "Exception Handling".

So if I don't mind the swallowed exceptions, I would simply omit the WhenAll completely, which makes your utility method redundant.

That said, it would make a good place to attach code that prevents the swallowing of the exception, if that is what you want. Given that, I like your idea, but it can be improved: you can make a tuple of tasks directly awaitable. The GetAwaiter method that the compiler implicitly calls may be an extension method. That would result in this code:

static class ParallelTasksExtensions
{
    static TaskAwaiter<(T1, T2)> GetAwaiter<T1, T2>(this (Task<T1>, Task<T2>) tasks)
    {
        return AwaitAndPackage().GetAwaiter();

        async Task<(T1, T2)> AwaitAndPackage()
        {
            await Task.WhenAll(tasks.Item1, tasks.Item2);
            return (await tasks.Item1, await tasks.Item2);
        }
    }
}

(Warning: untested.)

Now you can just write await (t1, t2) directly. You can then proceed to overload for more arguments, of course.

Or instead you can install the TaskTupleAwaiter NuGet package, which contains exactly this code already. See also the enhancement request that led to this.


Showing unapproved comments in a discussion system

What about something like this:

sealed abstract class CommentVisibility {
  def shallShow(comment: Comment): Boolean
}

object CommentVisibility {
  case object HideUnapproved
  case object ShowUnapproved
  case class ShowAllByUser(userId)
}

Usage:

renderPage(page, CommentVisibility.ShowUnapproved)

That's easy to understand :-) And can be amended to include e.g. showing/hiding comments with too many flags. (One would add another case class, perhaps using the Composite design pattern)

And reminds of CSS I think: "visibility: hidden / visible"


You have four cases and each of them behaves differently, so you actually need to have four different branches. But you can simplify your code by extracting the checks into variables and using nested ifs:

public string CallKey
{
    get
    {
        bool callKeyEmpty = string.IsNullOrEmpty(CALLKEY);
        bool asCallKeyEmpty = string.IsNullOrEmpty(AS_CALL_KEY);

        if (callKeyEmpty)
        {
            if (asCallKeyEmpty)
                return "";
            else
                return AS_CALL_KEY.Trim();
        }
        else
        {
            if (asCallKeyEmpty)
                return CALLKEY.Trim();
            else
            {
                if (AS_CALL_KEY.Trim() != CALLKEY.Trim())
                    _error = true;
                return AS_CALL_KEY.Trim();
            }
        }
    }
}

As an added benefit, you can now remove the “this never happens” part.


Filtering from a file to show information

Since you are using jquery, you can use its built in each function to loop through the json results, which will eliminate the need for the size function.
i = index, v = values
$.each(data,function(i,v){
   $("#list_box").append("<option value='"+v.idgrupo+"'>"+v.nome+"</option>");
})


Complete graph traversal algorithm in Prolog

Consider describing what a transition is:

list_transition(List, (E1->E2)) :-
        select(E1, List, Rest),
        member(E2, Rest).

Example query:

?- list_transition([0,1,2], T).
T = (0->1) ;
T = (0->2) ;
T = (1->0) ;
T = (1->2) ;
T = (2->0) ;
T = (2->1) ;
false.

And to get all transitions:

?- findall(T, list_transition([0,1,2], T), Transitions).
Transitions = [ (0->1), (0->2), (1->0), (1->2), (2->0), (2->1)].


Integer factoring in C using GMP for numbers

You can improve the readability of your code, your indentation is great but you have magic numbers and the variable names aren't very clear. You probably wouldn't need comments if your variable names were clear and you had symbolic constants rather than numbers.

Magic Numbers:

You have a lot of raw numbers : 65536, 10u, 128u, 1ul, 2ul ...

For example you can have a symbolic constant CHARACTER_BUFFER_SIZE for 65536. Using the gcc compiler you would write your constant as

#define CHARACTER_BUFFER_SIZE 65536

When compiling with g++ you would use

static const CHARACTER_BUFFER_SIZE = 65536;

this would change the first 2 lines in main to

    char str[CHARACTER_BUFFER_SIZE];
    char bas[CHARACTER_BUFFER_SIZE];

If you use this number often, it makes it easier to change the value by just changing it where you define the constant. It also makes the code easier to read. The standard for symbolic constants in C and C++ is all caps with '_' between words.

Function Names:
Underscore in function names is a lot less common than it used to be, Camel Case is more common

next_prime => nextPrime
prev_prime => prevPrime

Variable Names:

The base variable name is almost understandable, but what kind of base, does it provide a starting point for the function, or is it a numeric base like Octal, Hex or Decimal?

It's really not clear from the code what x is.

In main() what are the variables str (almost obvious), bas, n, p, base?

Future Flexibility:

You main could be a little more flexible, currently you can only redirect input and a output, you could use command switches in your to select input and output files as well. In main it is possible to add a couple of FILE * variable to make it a little more general

    FILE *inputFile = stdin;
    FILE *outputFile = stdout;

    while(fscanf(inputFile, "%s %s", str, bas) != EOF) {
        ...
        mpz_out_str(outputFile, 10u, &base);


You can also use unfoldTree (or unfoldTreeM here) to build Data.Tree:

import Control.Monad
import System.Directory
import System.FilePath
import Data.Tree

dirTree :: FilePath -> IO (Tree FilePath)
dirTree root = unfoldTreeM step (root,root)
    where step (f,c) = do
            fs <- getDirectoryContents f
            ds <- filterM doesDirectoryExist fs
            return (c, [(f </> d, d) | d <- ds, d /= "." && d /= ".."])

main :: IO ()
main = do
  t <- dirTree "."
  putStrLn $ drawTree t

Update: As Björn Lindqvist correctly noted in his edit suggestion, my use of doesDirectoryExist doesn't work here (it uses directory names instead of directory paths).

The correct version of dirTree would be:

dirTree :: FilePath -> IO (Tree FilePath)
dirTree root = unfoldTreeM step (root,root)
    where step (p, c) = do
            isDirectory <- doesDirectoryExist p
            fs <- if isDirectory then getDirectoryContents p else return []
            return (c, [(p </> f, f) | f <- fs, f `notElem` [".", ".."]])


ReactJS Calling an API and rendering results

Here is the code after refactor some changes that i think should be good to follow:

use let instead of var.
I have used style2 as a state as its changing.
Used arrow function instead of bind.
Prefer destructuring.

import React from "react";
import "./App.css";
import axios from "axios";

let Style = {
  marginRight: "22px"
};

const API_CALL = "xxx";

class SearchForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "",
      errorValue: "",
      countryCode: "",
      VATNumber: "",
      valid: false,
      name: "",
      address: "",
      isLoading: false,
      isSubmitted: false,
      Style2: { display: "none" }
    };
  }

  renderField() {
    return (
      <form onSubmit={this.handleSubmit}>
        Search VAT:
        <input type="text" onChange={this.handleChange} style={Style} />
        <input type="submit" value="Submit" />
      </form>
    );
  }

  render() {
    const {
      Style2 = {},
      countryCode = "",
      VATNumber = "",
      valid = false,
      name = "",
      address = "",
      isLoading = false,
      isSubmitted = false,
      errorValue = ""
    } = this.state;
    return (

Reference: EE100247019

        {this.renderField()}

        <Loader loading={isLoading} />
        {isSubmitted && (
          <Result
            country={countryCode}
            number={VATNumber}
            name={name}
            address={address}
            error={errorValue}
            valid={valid}
            loading={isLoading}
            style={Style2}
          />
        )}

    );
  }

  handleChange = event => this.setState({ value: event.target.value.trim() });

  handleSubmit = event => {
    this.setState(({ Style2 }) => ({
      isLoading: true,
      isSubmitted: false,
      Style2: {
        ...Style2,
        listStyleType: "none",
        textAlign: "left",
        display: "block",
        border: "1px solid white",
        marginTop: "50px"
      }
    }));
    axios
      .get(API_CALL + this.state.value)
      .then(
        ({
          data: {
            CountryCode = "",
            VATNumber = "",
            Name = "",
            Address = "",
            Valid = false
          } = {}
        } = {}) =>
          this.setState({
            countryCode: CountryCode,
            VATNumber: VATNumber,
            name: Name,
            address: Address,
            valid: Valid,
            isLoading: false,
            isSubmitted: true
          })
      )
      .catch(error =>
        this.setState({
          valid: false,
          errorValue: this.state.value,
          isLoading: false,
          isSubmitted: true
        })
      );

    event.preventDefault();
  };
}

const Loader = ({ loading = false } = {}) =>
  loading ? null :
 Loading ...
;

const Result = ({
  valid = false,
  error = "",
  style = {},
  country = "",
  number = "",
  name = "",
  address = ""
} = {}) => {
  if (!valid) {
    return (

        Invalid value "{error}"

        Please enter valid VAT Number

    );
  } else {
    return (

          Country code:
          {country}

          VAT Number:
          {number}

          Product name:
          {name}

        Address:
        {address}

    );
  }
}

export default SearchForm;


VBA script that copies data from one workbook to another

Option Explicit

The counter variables were never declared.

MSDN Option Explicit Statement:

  Note Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear.

Goto Statement

Goto Statement are best reserved for error handling.

MSDN Goto Statement:

  Note Too many GoTo statements can make code difficult to read and debug. Use structured control statements ( Do...Loop, For...Next, If...Then...Else, Select Case ) whenever possible.

ID Lookups

Using nested loops over multiple lists comparing unique values (IDs) is very inefficient.  Use a Dictionary. They are optimised to reference IDs stored as Key/Value pairs.

K Loop

        Debug.Print "k is "; k
        'Go to 14, because we want to keep the first 14 weeks (columns)
        If counter < 14 Then
            counter = counter + 1
            GoTo NextIteration
        End If
        counter = counter + 1
        dests.Cells(j, k).Value2 = copys.Cells(i, k).Value2
 NextIteration:
        Next k

Why would you not just start K at 14?????

Refactored Code

Using a Dictionary to store value Arrays by key ID, this code took 11.27 seconds to transfer 10K rows x 12 Columns of data.  I better computer would easily cut that time in helf.  My IndexedArray Class takes about 0.6 seconds per 10K Rows x 7 Columns.

Sub TransferDataToForecast2()
    Dim r As Long, c As Long
    Dim Key As Variant, Values As Variant
    Dim strPath As String
    Dim dicID As Object
    Set dicID = CreateObject("Scripting.Dictionary")

    'Get user to select target workbook
    strPath = BrowseForFile("Select the DM Forecast file you want to update")
    If strPath = vbNullString Then Exit Sub

    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    With ActiveWorkbook.ActiveSheet                   'Worksheet that contains the data to be copied

        For r = 2 To .Cells(Rows.Count, 3).End(xlUp).Row
            If Len(Trim(.Cells(r, 3).Value2)) > 0 Then
                Key = Replace(.Cells(r, 3).Value2, "_", "") & "|" & .Cells(r, 4).Value2
                If dicID.Exists(Key) Then
                    Debug.Print "Duplicate ID Found:"; .Name; " - "; .Cells(r, 3).Address
                Else
                    ' Add the ID and Array of Values
                    Values = .Range(.Cells(r, 14), .Cells(r, .Columns.Count).End(xlToLeft)).Value
                    dicID.Add Key, Values
                End If
            End If
        Next
    End With

    With Workbooks.Open(strPath).Worksheets(1)
        For r = 2 To .Cells(.Rows.Count, 3).End(xlUp).Row
            If Len(Trim(.Cells(r, 3).Value2)) > 0 Then
                Key = Replace(.Cells(r, 3).Value2, "_", "") & "|" & .Cells(r, 4).Value2
                If dicID.Exists(Key) Then
                    Values = dicID(Key)
                    .Cells(r, 14).Resize(1, UBound(Values, 2)).Value2 = Values
                End If
            End If
        Next
    End With

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

    MsgBox ("Data has been transferred.")
End Sub


Though your code would suffice for the current task, I would create a fully (or partially) functioning Tree class, so that it may be used later. Another class will handle the display. This is what the Tree class would look like:

public class Tree<T> {

    private Node rootNode;

    public Tree() {
        rootNode = null;
    }

    public Tree(T rootValue) {
        rootNode = new Node(rootValue);
    }

    public Node getRootNode() {
        return rootNode;
    }

    public Node createNewNode(T value) {
        return new Node(value);
    }

    class Node {

        private T value;
        public Node left = null;
        public Node right = null;

        Node(T value) {
            this.value = value;
        }

        public T getValue() {
            return value;
        }

        public void setValue(T value) {
            this.value = value;
        }

    }

}

This is an extremely basic Tree class that has very basic functions, but it gets the job done. Later, when you need more functions for the Tree class, you can easily go and add it. Explanation of the class:

The default constructor (Tree()) will just set the root node to null.
The other constructor will take the argument and create a new Node with the value of the argument.
The getRootNode() method is to get the root Node, so that you can get the other Nodes like so:

// example
Tree tree = new Tree(10);
// initialization of values
Node someNode = tree.getRootNode().left.right/*etc*/;

The createNewNode(T value) method provides indirect access to the otherwise inaccessible (at least outside the package) Node(T value) constructor. Though this isn't necessary, as you can make the Node's constructor public, it is good practice for later.
The Node class is a simple class that represents a node with a left and right node, as well as its value:

The value is a private variable, so getters and setters are required to access it. Again, though you can just make value public, it is better practice not do so.
I made the left and right variables public, just for easier usage. Though it differs from good practice, there are some cases where there are exceptions (some programmers may disagree with this statement).

Now, for the printing component:

Since I redesigned the Tree class completely, we have to change your method as well. Just to do exactly what your code does, here is the new method:

public <T> void LevelOrderQueue(Tree<T> tree) {
    if (tree != null) {
        Tree<T>.Node rootNode = tree.getRootNode();
        if (rootNode != null) {
            Queue<Tree<T>.Node> queue = new LinkedList<>();
            int levelNodes = 0;
            queue.add(rootNode);
            while (!queue.isEmpty()) {
                levelNodes = queue.size();
                while (levelNodes > 0) {
                    Tree<T>.Node node = queue.remove();
                    System.out.println(node.getValue());
                    if (node.left != null) {
                        queue.add(node.left);
                    }
                    if (node.right != null) {
                        queue.add(node.right);
                    }
                    levelNodes--;
                }
                System.out.println();
            }
        }
    }

}

Note some changes:

The method now takes a Tree<T> object instead of a Node object.
This method has two checks for null; the first one to check for the tree, and the second one for the root node.
I added braces for if statements. The reason for this is because the lack of braces may cause horrible, hard-to-spot bugs that might frustrate you for days. I can't find the post which I wrote about this in more detail, but I will post it up once I find it. (EDIT: Found it! Read here)
I added generics to your Queue initialization.
I removed the Node cast. This is not necessary when generics are used.
I changed naming. Variable names like node and queue are easier to understand than n and q.
I changed System.out.println(""); to System.out.println();. There is a println() method that takes no arguments.
I changed System.out.println(""+n.data); to System.out.println(node.value);. The beginning "" is not necessary because System.out.println() automatically converts what is given into a String, via the toString() method defined by the class (or whatever class before it in the inheritance chain that has it defined).
I added more space between some individual keywords, variable names, braces, parentheses etc.: this is for better readability, and to follow the Java conventions. If you are not sure of them, just search up "Java Conventions" on google.
I removed empty lines. You may re-add them where you like them; I like my code that way.


I think this replicates the logic:

price = @booking_request.guests * @table_offer.price_cents / 100
@remaining = @coupon.current_amount - price
@coupon.current_amount = @remaining
@price_to_play = @remaining >= 0 ? 0 : -@remaining
coupon.save

Note that I avoid setting @price_to_play to a value and changing it afterwards, that kind of variable re-using makes code harder to understand.


Python making call list for C++ executable

Putting an open() function inside a list comprehension seems a bit iffy to me, especially since you don't seem to close it anywhere.

List comprehensions are generally better than for loops.

The config_file name is a bit misleading, as it's the filename, not the file object.

So alternative code would be:

config_file_name = directory + file_prefix + ".txt"
with  open(config_file_name) as config_file:
    config_list_split = [config_item for config in config_file for config_item in config.split()]

This is less transparent, but performance-wise I would expect it to be better than a for-loop.


Checking if two strings are permutations (anagrams) in Python

From Sumit Raj's 2015 article 10 Neat Python Tricks Beginners Should Know, which I would classify as "more pythonic":

from collections import Counter
def is_anagram(str1, str2):
    return Counter(str1) == Counter(str2)
>>> is_anagram('abcd','dbca')
True
>>> is_anagram('abcd','dbaa')
False


C++ program to remove duplicate characters from string

From the tests we are if we are only looking for repeating chars, not duplicate e.g. we can transform "ABBA" into "ABA"  (and not "AB"). Then we can use something like:

void removeRepeatingChars(char* s){
  if(!s[0]){                  // Check for enpty string
    return;                   // Notning to do per definition
  }

  int last=0;                 // Store position of last seen character  thats not a duplicate

  for(int i = 1; s[i] ; i++){ // Loop over all characters and
    if(s[i] != s[last]){      // check if current character is not a dupllicate.
      last++;                 // If so increment the position of last non duplicate and
      s[last] = s[i];         // copy the currentcharacter to this position.
    }                         // Else go to next char.
  }
  s[++last] = '\0';           // Add string terminator at the end.
}

If not you need to store each seen character and add this check so we get something like.

for(int i = 1; s[i] ; i++){
  if(s[i] != s[last] && !sceen[s[i]]){
      last++;
      s[last] = s[i];
      seen[s[i]] = true;
  }
}

Observe that we use that we can modify the string how ever we like on chars we already have checked in order to do the whole operation in place.


Well, for one thing, the python code is using a set for its amicable_pair_set, where-as you're using a large vector and setting the n'th element to n when you need to add to the set.  It's a reasonable way to imitate a set, if your scheme doesn't have a set library; however, this situation doesn't need true set semantics.  You can use a simple list instead, so your named let becomes:

(let loop ((res '())
           (i 0))
      (cond
       ((= i n) (reduce + 0 res))
       ((and (< (vector-ref sums i) n) (not (= (vector-ref sums i) i))
         (= (vector-ref sums (vector-ref sums i)) i))
    (loop (cons i res) (+ 1 i)))
       (else
    (loop res (+ i 1)))))

This keeps it close to the python code, but you could go a step further and have res be an integer accumulator, adding to it instead of consing to it, getting rid of the need to add the list at the end.  Of course, the same optimization could be made to the python version as well.

Unfortunately, I've optimized the part of the code that runs quick :-).  The real work is being done above, when the sums vector is being populated.  Since that is a pretty direct translation, I would chalk it up to chibi's implementation of scheme versus whatever implementation of python you're using (PyPy, for instance, is probably going to be faster).  I use racket-scheme which is jit compiled.  Calling your code returns an answer in ~680ms for me.  Calling it with the default python 2.7.3 compiler gives me a result in ~1400ms.

Here's a version which only calculates the sum of its proper divisors for the numbers that are needed, and then stores them for future use.  Basically memoizing the results.  The first run is slightly faster for me ~30ms, and then subsequent runs return in less than 1ms.

(define d
  (let ((cache (make-vector 10000 #f)))
    (lambda (n)
      (or (vector-ref cache n)
      (let ((val (reduce + 0 (filter (lambda (d) (= 0 (remainder n d)))
                     (iota (quotient n 2) 1)))))
        (vector-set! cache n val)
        val)))))

(define (sum-of-amicable-pairs n)
  (let loop ((a 0)
         (sum 0))
    (if (< a n)
      (let ((b (d a)))
        (loop (+ a 1)
          (if (and (< a b n) (= (d b) a))
              (+ sum a b)
              sum)))
      sum)))

(time (sum-of-amicable-pairs 10000))


The best I've got is:
FROM ubuntu:20.04

ENV DEBIAN_FRONTEND=noninteractive
ARG TZ=Asia/Jerusalem
ARG USERNAME=yotam
RUN apt-get update; \
    apt-get dist-upgrade -y && \
    apt-get autoremove -y && \
    apt-get autoclean -y && \
    apt-get install -y vim tmux bash-completion shellcheck ssh git pylint flake8 python sudo expect curl cmake build-essential python3-dev golang npm openjdk-11-jre exuberant-ctags && \
    useradd -m -s /bin/bash $USERNAME && \
    usermod -aG sudo $USERNAME && \
    echo vim-anywhere > /etc/hostname

WORKDIR /home/$USERNAME
COPY .vimrc .
RUN mkdir -p ./.vim/pack/plugins/start
WORKDIR /home/$USERNAME/.vim/pack/plugins/start
RUN git clone https://github.com/tpope/vim-fugitive.git/ && \
    git clone --depth 1 https://github.com/dense-analysis/ale.git && \
    git clone https://github.com/ycm-core/YouCompleteMe.git
WORKDIR /home/$USERNAME/.vim/pack/plugins/start/YouCompleteMe
RUN git submodule update --init --recursive && \
    python3 install.py --all && \
    chown -R $USERNAME:$USERNAME /home/$USERNAME && \
    PASSWORD=$(openssl rand -base64 16 | tr -d "=") && \
    echo "$USERNAME:$PASSWORD" | chpasswd && \
    echo $PASSWORD
WORKDIR /home/$USERNAME
USER $USERNAME

This gives me only minor advantages which are:

The password is echoed at the end of the build and is easier to find in the output.
The return to the homedir at the end is more what you'd intuitively expect.


Flood-clearing routine for a JavaFx Minesweeper

Iterating through adjacents

There are two main approaches to take while iterating through the neighbors in Minesweeper.

The first and most common option is to use a nested for loop:

for (int y = -1; y <= 1; y++) {
    for (int x = -1; x <= 1; x++) {
        if (x == 0 && y == 0) {
            continue; // We don't want to consider the field itself as a neighbor
        }
        increaseAdjacentMineCounter(mineX + x, mineY + y);
    }
}

The second approach, and the one that I normally use and like better, is to use an array to define which fields should be used as your neighbors.

int[][] neighbors = {{ -1, -1 }, { -1, 0 }, { -1, 1 }, { 0, -1 },
    { 0, 1 }, { 1, -1 }, { 1, 0 }, { 1, 1 }};
for (int[] neighbor : neighbors) {
    int x = neighbor[0];
    int y = neighbor[1];
    increaseAdjacentMineCounter(mineX + x, mineY + y);
}

The reason for why I like the second approach better is because it becomes more data-oriented. You can change the way you consider neighbors without changing your code. Changing the way your neighbors are considered can be a bit entertaining but very confusing :)


I'm assuming that this is basically a pointer exercise rather than a real piece of code that you're planning to use.  If it's the latter, please reconsider -- there are STL containers that do this better and safer.  As to your question about the for loop, there's nothing wrong with that if you're using pointers.  In fact it's a pretty common idiom in C.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  I don't know that you're doing that, but the use of vector in the definition of Node suggests it.

Use nullptr

Every instance of 0 in your code would probably more correctly be encoded as nullptr as defined in C++11.  If you're using an older compiler, you can use NULL instead which will more clearly indicate to readers of your code that these are pointers.

Reconsider the interface

If this is a pointer exercise, that's fine, but if you actually intend to use this for something, you should probably reconsider the interface.  Specifically, passing around raw pointers is not generally a good idea in C++.  Better would be to use unique_ptr (C++11) or auto_ptr (C++03).

Also the version of remove() that takes a linked list node pointer as an argument is a very dangerous thing to have in an interface.  Knowledge of a node's structure would be better encapsulated within the class and not revealed as part of the interface.

Use better names

Having DLList as the name of a class implementing a doubly-linked list makes sense, but having that actually be the name of an individual node in such a list does not.  Instead of DList and DLList, it would be much easier to interpret your code if they were named DLList and DLListNode.  Also the function add suggests that the node is added to the end, but the code actually prepends this to the list which is, at best, confusing.

Simplify remove(Node* n)

The remove(Node *n) is more complex than it needs to be.  It could be rewritten as:

void remove(Node* n)
{
    for(DLListNode* i=first; i!=nullptr; i=i->next)
    {
        if(n==i->val)
        {
            i->prev->next = i->next;
            i->next->prev = i->prev;
            break;
        }
    }
}

Note that this still has a bug just like the original.  What happens if i->prev or i->next are null pointers?  You should handle those cases.

A similar simplification could be done for the other remove functions.

Don't leak memory

Your program uses new but not delete which is a surefire recipe for memory leaks.

Be explicit about whether your container owns contained objects

It's not clear (because there are not comments) whether the contained Node objects should be destroyed or not when either of the two remove functions is called.

Define a destructor

Because you have a constructor, you really should define a destructor as well.  See the note above about leaking memory.

Consider using an anchor node

Much of the special-case checking for null pointers in your code would disappear if you defined an anchor or head node in the constructor.  In that case, there would always be one node and you wouldn't have to check for null pointers quite as often.


Speaking from a straight Java perspective, one thing you can do is change your loop header. You evaluate the power every iteration and could do something like:

for (int i = 0, end = Math.pow(2, n); i < end; i++)

You also use standard String concatenation which is slow because once compiled, when you concatenate two strings a StringBuffer is created, and both strings are added to it, and then resulting string is returned. You save a step by using a StringBuffer from the get go which would you replace B = ""; with B = new StringBuffer(); (of course changing it's type accordingly). Instead of adding strings to you call insert (which can be chained) like B.insert(0, "1")

You're appending a char ('0' or '1') which you evaluate with modular division, you can just prepend it like B.insert(0, (temp % 2)) and save that entire if.

I probably said more than I should have for homework, but you appear to have already solved your problem and so I was just giving advice in addition to that.

EDIT

My solution would be as follows:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number >> ");
        int value = in.nextInt();
        in.close();
        Binary binary = new Binary(value);
        System.out.println(binary.getResult());
    }
}

class Binary {
    private int value = 0;
    private StringBuilder binaryValues;

    public Binary(int value) {
        this.value = value;
        this.binaryValues = new StringBuilder();
        this.process();
    }

    private void process() {
        for (int i = 0, end = (1 << this.value); i < end; i++) {
            StringBuilder binary = new StringBuilder(Integer.toString(i, 2));
            while (binary.length() < this.value)
                binary.insert(0, 0);
            this.binaryValues.append(binary).append("\n");
        }
    }

    public String getResult() {
        return this.binaryValues.toString();
    }
}

Maybe not shorter but no need to rewrite binary number generation when it's built in.


Overloading __getitem__() for two key types in Python

From Python 3.3, the collections module added collections.ChainMap.
Utilizing this class can simplify your code.
You should probably make self.a_ids and self.b_ids a list. And index to get which one you want, such as self.ids[0]. This list is created when using ChainMap anyway too.

And so I'd change your code to something more like:

from collections import ChainMap

class UserList:
    def __init__(self, users):
        self._lookup = ChainMap({}, {})
        self.ids = self._lookup.maps
        for user in users:
            self.ids[0][user['a_id']] = user
            self.ids[1][user['b_id']] = user

    def __contains__(self, some_id):
        return some_id in self._lookup

    def __getitem__(self, some_id):
        return self._lookup[some_id]

Alternately, you could subclass ChainMap, and not need to write any of the methods.

from collections import ChainMap

class UserList(ChainMap):
    def __init__(self, users):
        super().__init__({}, {})
        for user in users:
            self.maps[0][user['a_id']] = user
            self.maps[1][user['b_id']] = user

However, at that point, there's not much benefit to using a class. And so I'd just use a raw ChainMap.


Bug: If, during the "pick a sigil" part of the game setup, player 1 simply presses <ENTER>, the game will play empty-string vs. "X". It looks bad.

Your code has several problems. Let's start with the most basic:

You are not using Python idiom for structuring your code. Please see this page (one of many duckduck search results) for an example and explanation. You should be using:

if __name__ == '__main__':
    play_game()

(for some value of play_game().)
You are not using descriptive names for your functions. What does func_1 do?
You are not using functions to organize your code. From about line 7 down to the definition of make_a_move you have a bunch of code that is just executed in-line. That should be a setup_game() function, or some such.
Your logic is confused. Consider this code:

#sets the players name
if (player_1 == "" or player_2 == ""):
  if (player_1 == ""):
    player_1 = "Player 1"
  if (player_2 == ""):
    player_2 = "Player 2"
else:
  pass

What are the real possibilities here? If player one's name is empty, you
need to set it:

if (player_1 == ""):
    player_1 = "Player 1"

Likewise for player 2:

if (player_2 == ""):
    player_2 = "Player 2"

All the rest of that code is just noise.
You are not using standard Python functions. Consider:

square_values = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]

Is there a standard Python function that returns a range of values? Why, yes! There is!

square_values = range(1, 10) # integers, not strings
# or
square_values = map(str, range(1, 10))
# or
square_values = [str(n) for n in range(1, 10)]

Not a code problem, but a logic problem: why use player 1 and player 2? You ask for their names, and then the sigil they should use. Why not simply call them 'Player X' and 'Player O' all the way through? You could eliminate a lot of code that way.
Your code does not have "basic elegance" of structure. This is hard to quantify, but I would say that basic elegance requires that your control structures be used in as natural a fashion as possible. Consider this:

while (status_main == True):
      func_1(player_1, player_1_pick)
      func_1(player_2, player_2_pick)

This fails on many levels. First, comparing a boolean with True in a conditional expression is stupid. It's a boolean! Just use it:

while (status_main):

Next, using parens like this is a Java/C thing. Not required, nor recommended, in Python:

while status_main:
    func_1(player_1, player_1_pick)
    func_1(player_2, player_2_pick)

Next, what does status_main even mean? How about keep_playing instead?

while keep_playing:
    func_1(player_1, player_1_pick)
    func_1(player_2, player_2_pick)

But honestly, why not do the checking in the while loop, instead of relying on a global variable set who-knows-where?

while not game_over():
    func_1(player_1, player_1_pick)
    func_1(player_2, player_2_pick)

And, since all you are doing is alternating between player X and player O, why not include that in the loop. You can use that to insert a check for a win after each turn:

curr, next = 'O', 'X'

while not game_over():
    curr, next = next, curr
    take_turn(curr)

print("Winner is", curr)  # Note that winner is in curr, if winner

There are other problems like this. Look for your no_wins variable: almost every place it gets used looks inelegant. And calling a function won't help - you really need to think how to get rid of that variable. Here's hint: simplify your code. Move some logic out of the "bottom" functions and up into the "middle" and "top" functions.


Identify the Length of the Longest Substring Without Repeating Characters

LinkedBlockingQueue is not the best choice. It's based on a linked list, which lacks spacial locality. An continuous array-backed queue would be more efficient (there're a few options in the standard library).
 if (substringCharacters.size() > longestSubstringLength) {
     longestSubstringLength = substringCharacters.size();
 }

I'd use the Math.max method here.
You can avoid using the queue altogether. You can keep the leftmost index of the current "window" and the set instead.


Generating permutation of indices from seed ID

Use your words

Let's start with what you're actually accomplishing in all those if statements. It looks like what you're doing is incrementing each index by the number of smaller indices, for each possible such count.

That translates itself naturally to using arrays:

uchar index[5] = {(id / 32760) % 16,
                  (id / 2184) % 15,
                  (id / 156) % 14,
                  (id / 12) % 13,
                  (id / 1) % 12};

And writing that idea as a loop:

// for each index
for (int i=1; i<5; ++i) {
    // for each possible count of smaller indices
    for (int cnt=1; cnt<=i; ++cnt) {
       // count the number of smaller indices
       int k=0;
       for (int j=0; j<i; ++j) {
           k += (index[i] >= index[j]);
       }

       // and increment if necessary
       if (k >= cnt) {
           ++index[i];
       }
    }
}

This can be translated into the sort-of-more/sort-of-less readable (YMMV) C++11 version:

for (int& i : index) {
    for (int cnt=1; cnt <= std::distance(index, &i); ++cnt) {
        i += std::count_if(index, &i, [i](int j){return i >= j; }) >= cnt;
    }
}


Predicate testing for equality that returns the common element

Soon after I posted this, I went for a walk and realized that this is the perfect opportunity to use reduce. I'm kind of embarrassed that I didn't see it originally, but this was my train of thought that lead me to what I'm much happier with.

First, I tried a simple reduction. This was pretty simple, although still a little verbose:

(defn =?2 [& args]
  (reduce (fn [acc n]
              (if (= n acc)
                n
                (reduced nil)))
          (first args)
          (rest args)))

I decided that this was probably simple enough to use a function macro for. Normally I don't like using them for reductions, but there's not much going on here:

(defn =?3 [& args]
  (reduce #(if (= % %2) % (reduced nil))
          (first args)
          (rest args)))

I don't like using explicit calls to first and rest, as I find they're usually neater when they're implicit in a deconstruction. I decided to deconstruct the arguments instead:

(defn =?4 [& [arg & rest-args]]
  (reduce #(if (= % %2) % (reduced nil))
          arg
          rest-args))

Then I checked what = uses, and found that it just uses multiple argument lists, so I tried that. This strikes me as the more idiomatic solution:

(defn =?5
  ([] nil)
  ([arg] arg)
  ([arg & args]
   (reduce #(if (= % %2) % (reduced nil))
           arg
           args)))

I'm torn between 4 and 5, but I think that both are a significant improvement.


First calculator in c++, tips for optimisation

You should avoid using namespace std.

The code in the prompt function is not indented.

You should avoid using endl unless absolutely necessary (use a \n instead).  endl will flush the output buffer which can be a big performance hit.

You don't have a break statement for the default case of your switch statement.  While not required here, it can lead to problems in the future if additional cases are added after the default and the break is not added.

Declaring uninitialized variables within a switch statement is legal, but can lead to confusion.  Usually when variables are declared under a case, the code of the case is enclosed within { curly brackets }.  For example, the a and b variables, which are used in most of the cases, could be declared before the switch.


Sum of number's quotients when divided by exact powers of 2

It's great that you found a closed form to generate the results.  Shame that it was by search rather than by reasoning.  (i/GCD(i, 2^n) is simply i shifted right until it's odd, so we get the sequence (in binary) 1**,** 10, 11, 100, 101, 110, 111, 1100, ...  You can see that every other value is divided by 2, every fourth value divided by 4 and so on; that allows you to arrive at the closed form fairly quickly.

I'll note that the numerator and denominator have a common factor of 4, so could be reduced to \$\frac{4^n+2}3\$.

Now to the code:

<bits/stdc++.h> is non-portable, and extremely wasteful.  Include only the headers that are needed; in this case just <iostream>.

Instead of using a preprocessor #define for a constant integer, always prefer to use a C++ constant.  Macros don't respect context.

Avoid using namespace std;.  It doesn't even save you typing, once the unnecessary stdio operations are removed.

The typedefs are misleading: the name u64 suggests that unsigned long happens to be 64 bits on your particular target, but it also suggests that you've written brittle code that depends on that assumption (and all the other typedefs appear to be unused).  For this code, I think we really should be using std::uint_fast64_t from <cstdint>.

Moving on to main(): as hinted earlier, std::ios_base::sync_with_stdio() and std::cin::tie() are pointless, given that we're not using the C standard streams, so should be omitted.  Also, there's no checking that streaming from std::cin was successful; that's easily fixed.

Now we need to look at pawa().  Given that we only ever call it with a equal to 4, then we can make a special-purpose function rather than a general modpow() - let's call it exp4mod() (meaning exponentiation base 4, modulo 1000000007).

For values of b less than 15, the result is less than 1000000007, so that is easily computed as 1u << (2*b).  Values of 15 or more can be reduced using the identity \$4^{14a+b} = (4^{14})^a4^b\$, and then we can use a standard binary exponentiation for the first part and a shift for the second.

All that said, it's unclear why the exponentiation must be done modulo 1000000007 - the description says that the result be reduced modulo such a number.  So perhaps there's a logic error there, and we really need to be reducing modulo 3000000021 (having reduced the fraction so we divide by 3)?

Here's the version I ended up with, having made the recommended changes (and modifying main() not to require input):

#include <cstdint>
#include <iostream>

using u64 = std::uint_fast64_t;

static u64 modpow(u64 x, u64 y, u64 mod)
{
    u64 result = 1;
    while (y) {
        if (y%2) {
            result = result * x % mod;
        }
        x = x * x % mod;
        y /= 2;
    }

    return result;
}

static u64 exp4mod(u64 x)
{
    static auto const mod = 3000000021;
    static auto const chunk_size = 16;

    static const u64 one = 1;
    static auto const residue = (one << 2*chunk_size) % mod; // 4^15%mod = 73741817

    const auto a = x / chunk_size;
    const auto b = x % chunk_size;
    return (modpow(residue, a, mod) << (2 * b)) % mod;
}

int main()
{
    for (u64 n = 0;  n < 35;  ++n)
        std::cout << n << ": " << (exp4mod(n) + 2) / 3 << '\n';
}


Convert list of dictionaries to iterable list

Does the scipy.sparse.coo_matrix() function accept three different lists as parameters?

Maybe I'm missing something but your "fastest" method is not actually the fastest, since you'd still need some conversion to parse it to the function anyhow.
I think your timing is off

  For this one z = [tuple(el.values()) for el in x] you say:

  evaluate each line as a tuple of the dictionary values. Comparable in speed with something like [[el['id'], el['y'], el['values']] for el in x].

I have tested this myself, and it seems the second suggestion is 2 times as fast as the first method.

Setup: x = [{'id':random.randint(0,5),'y':random.randint(0,5), 'value':random.randint(0,500)}]*100000

z = [tuple(el.values()) for el in x]
3.070572477

z1 = [[el['id'], el['y'], el['value']] for el in x]
1.5449943620000006

This could also be a generator

def gen_vals(d):
    for el in d:
        yield [el['id'], el['y'], el['value']]

However this did not improve speed, but just to bounce some ideas around

Setup: x = [{'id':random.randint(0,5),'y':random.randint(0,5), 'value':random.randint(0,500)}]*100000

z1 = [el['id'] for el in x]; z2 = [el['y'] for el in x]; z3 = [el['value'] for el in x]
1.244481049000001

z1 = [[el['id'], el['y'], el['value']] for el in x]
1.5449943620000006

z1 = list(gen_vals(x))
1.8347137390000015

z1 = [a for a in gen_vals(x)]
2.018111815000001

Timing code for reference

import timeit as ti
import random

def gen_vals(d):
    for el in d:
        yield [el['id'], el['y'], el['value']]

# SETUP
x = [{'id':random.randint(0,5),'y':random.randint(0,5), 'value':random.randint(0,500)}]*100000
print("Setup: x = [{'id':random.randint(0,5),'y':random.randint(0,5), 'value':random.randint(0,500)}]*100000")

print("z = [tuple(el.values()) for el in x]")
print(ti.timeit("z = [tuple(el.values()) for el in x]",
          setup="from __main__ import x",
          number=100))

print("z = pd.DataFrame(x)")
print(ti.timeit("z = pd.DataFrame(x)",
          setup="import pandas as pd; from __main__ import x",
          number=100))

print("z1 = [el['id'] for el in x]; z2 = [el['y'] for el in x]; z3 = [el['value'] for el in x]")
print(ti.timeit("z1 = [el['id'] for el in x]; z2 = [el['y'] for el in x]; z3 = [el['value'] for el in x]",
          setup="from __main__ import x",
          number=100))

print("z1 = [[el['id'], el['y'], el['value']] for el in x]")
print(ti.timeit("z1 = [[el['id'], el['y'], el['value']] for el in x]",
          setup="from __main__ import x",
          number=100))

print("z1 = list(gen_vals(x))")
print(ti.timeit("z1 = list(gen_vals(x))",
          setup="from __main__ import x, gen_vals",
          number=100))

print("z1 = [a for a in gen_vals(x)]")
print(ti.timeit("z1 = [a for a in gen_vals(x)]",
          setup="from __main__ import x, gen_vals",
          number=100))


Vowels in a String are in Alphabetical Order

Since vowels is a constant for your program, the convention would be that its name is in all uppercase, like VOWELS.
Take great care when uppercasing Strings:

final char[] chars = candidate.toUpperCase().toCharArray();

Uppercasing a String depends on the locale. By not specifying a locale, you are relying on the default locale of the JVM, which may cause problems for Turkish users (for example). It would be better to specify the ROOT locale:

final char[] chars = candidate.toUpperCase(Locale.ROOT).toCharArray();

I'm not a big fan of inversing the conditions in an if:

if (-1 != lookupIndex) {

The following would be easier to read:

if (lookupIndex != -1) {

In fact, it would be even better to not check against -1 but test that the result is positive:

if (lookupIndex >= 0) {

It decouples the fact that indexOf returns -1 from what you really want to test, which is that the index was found.
I think returning true when there is no vowels is the least surprising result: when there are no vowels, then they all are in the right order. Throwing an exception would be a bad idea: no vowels in a String is not a real exceptional condition.


Is there a more readable way to write this add to a list only if the element not exists? (perfectionistic)

I don't think it is necessary to create a method; the code seems atomic enough (SRP).

But I would refactor the code to make it clearer, and to avoid enumerating the categories twice:

foreach (var summaryOdd in odds)
{
    string eventId = summaryOdd.Championship;
    var category = categories.FirstOrDefault(cat => cat.Name == eventId);
    if(category == null)
    {
        category = new PlacedCategory
        {
            Name = eventId,
        };
        categories.Add(category);
    }
}


ActiveRecord object for billing and shipping addresses

Solution still relying on callbacks

validations in rails accept a "condition" option:

validates :shipping_address, presence: true, unless: :ship_to_billing_address?

for simplicity and consistency, i would advise to use a "real" attribute instead of a virtual one for ship_to_billing_address (attributes accessor generated from boolean columns integrate nicely with checkboxes, and rails automatically generates a ship_to_billing_address? method).

In order to ease access to the shipping address, you could either override the shipping_address method :

def shipping_address
  ship_to_billing_address? ? billing_address : super
end

...or create another method, if you fear overrides. Problem is, this approach could induce confusion (modifying in place a shipping address that is in fact a billing address without knowing it, for instance)

Solution without callbacks

Have an eye on DCI architecture. Some gems implement it. Using multiple form objects with different validation rules is another option.