Which is the better way to return a new instance of a boost intrusive_ptr

When in doubt, be explicit.  While both of the functions given will work, the second expresses programmer intent more clearly.  Adding a comment along the lines of "This will call intrusive_ptr's implicit constructor" to the first can help, though at that point it's more concise to call the constructor directly.  Returning a raw pointer and relying on the implicit constructor for intrusive_ptr may also be viewed as a mistake introduced by changing the declaration of MyFactory() but forgetting its definition.  Relying on implicit constructors may also make the code harder to debug and maintain because by default, the constructor for intrusive_ptr increments the retain count in Foo.  Calling it explicitly gives you the benefit of being able to search for "FooPtr(" when trying to track down every place a Foo is  retained.  Also, if the Foo constructor initializes its retain count to 1, you may be introducing a memory leak by relying on the implicit constructor.  Explicitly specifying FooPtr(new Foo(a, b, c), false) would prevent this.


You should not catch exceptions and discard them silently. This code has no chance of throwing an exception, therefore you should just let the exception bubble up and let someone else catch it. If it should ever happen.
Your variable names don't express their intention. The word temp should not be used at all, you mix terminology between languages and locale. Sometimes you put the j at the beginning of the name, sometimes at the end; this is inconsistent.
Declare your variables as late as possible (json).
Declare your variables in the smallest possible scope (tempj).
Method names in Java start with a lowercase letter.
Don't declare throws Exception when your code doesn't actually do that.
It is unusual that the languages set actually contains null. So in general you should leave out the if (language != null) check.

After following all these hints, the code may look like this:

public String createLanguagesJson(Set<Locale> languages) {
    JSONArray array = new JSONArray();
    for (Locale language : languages) {
        array.put(new JSONObject()
                .put("lcode", language.toLanguageTag())
                .put("ldisplay", language.getDisplayName()));
    }

    return new JSONObject()
            .put("root", array)
            .toString();
}


Starting with the low-hanging fruit: A variable called 'temp' is a big sign that you can do better. If you were to set up your code so that it returned a new list rather than modifying it in place, you could do this:

alist[:i-1] = insertionsort(alist[:i-1])

The rest of your code assumes that we will be working on the original, but the easiest fix for that is to make a copy at the earliest opportunity. If you do that early (and with an appropriate comment), and you don't need the original list anymore (you don't), then you can reuse the name alist without losing clarity. Unfortunately, copying the list is bad for performance, but readability needs to come first. But way down the bottom, I will point out a bigger improvement that will mean we don't actually have to choose between performance and readability here.

You can also eliminate that i: Python allows negative indices to all builtin sequences, which are defined to count from the back. So the above line is just:

alist[:-1] = insertionsort(alist[:-1])

and the condition above it can test against len(alist) explicitly.

In your second loop, you use four lines to swap two list elements. This can be more idiomatically done in one line using tuple assignment:

alist[k], alist[k-1] = alist[k-1], alist[k]

But we can do better even then this - we don't need to do all these swaps at all. Instead, find where the last element should go, and put it directly there. This is exactly the type of job the bisect module is good for:

candidate = alist.pop()
bisect.insort(alist, candidate)

And this replaces the whole second while loop.

So so far we have:

def insertionsort(alist):
    # work on a copy instead of the original
    alist = alist[:]

    if len(alist) > 2:
        alist[:-1] = insertionsort(alist[:-1])

    candidate = alist.pop()
    bisect.insort(alist, candidate)

    return alist

A = [4, 1, 6, 3, 9, 10]
A = insertionsort(A)

print(A)

I said before that copying is potentially bad for performance (each copy takes time). And we're doing a lot of it. This line:

alist[:-1] = insertionsort(alist[:-1])

makes a new list containing all but the last element, which the recursive call will promptly clone (in its entirety). So that's two copies for each element after the second. It would be better if we could tell the recursive call to only treat up to a certain point in the list, and everything after that. To do this, we put the bulk of the code into a helper function:

def insertionsort(alist):
    def sort_helper(alist, hi):
        if hi > 1:
            sort_helper(alist, hi-1)

        candidate = alist.pop(hi)
        bisect.insort(alist, candidate, hi=hi)

    alist = alist[:]
    sort_helper(alist, len(alist)-1)
    return alist

A = [4, 1, 6, 3, 9, 10]
A = insertionsort(A)

print(A)

Note that the first condition changed from testing a length to testing a position, and that the helper function works completely in-place. This makes one copy, in the outer function. You can also change it back to an in-place sort like your original code by deleting two lines, and it will make zero copies. This is probably the best a recursive insertion sort can be.


First step to making the code look good is proper indentation. JSBeautifier can do that for you.
Next is consistency. If you use jQuery, you can go all-out with jQuery to make it as neat and uniform. Of course, you can do vanilla JS if you want to for optimization.
Then remove duplicate code or code that does the same thing over and over again.
Watch out for missed vars. This can make variables to globals which isn't good.
When declaring, follow this order:

variables
functions
"prep code" like initializers, code to fill arrays, fetching values etc.
actual operation of the function

The rest are commented so keep a sharp eye. Can't really debug the code but the idea of what to do are there:

function getTweets(user) {

    //cache an object if it's to be used more than once
    var container = $('.container').html('

'),

        //put the url up here so it does not clutter the getJSON below
        //i prefer using single quotes than double quotes for a cleaner look
        url = 'https://twitter.com/statuses/user_timeline.json?screen_name=' + user + '&callback=?&count=50';

    $.getJSON(url, function (data) {

        //it's logical to only put things where they are needed
        //in this case, the following variables are only needed
        //when the callback completes
        var date = {
            Sun: 'Sunday, ',
            Sat: 'Saturday, ',
            Mon: 'Monday, ',
            Tue: 'Tuesday, ',
            Wed: 'Wednesday, ',
            Fri: 'Friday, ',
            Thu: 'Thursday, '
        },
            width = Math.floor(($(window).width() - 200) / 225),
            col = [],
            small = 0,
            articleArray = $('article');

        //prep codes after vars
        while(col.length < width) {
            col.push(0)
        };

        //consistency and ease, use jQuery instead.
        $.each(data, function (i, value) {
            //watch out for missed "vars"
            var day = date[value.created_at.match(/\w+/)[0]],
                //shorthand notation for creating a variable, appending it to the container directly
                //we can hand it over to a reference to do more on it
                art = $('
').appendTo(container);
            value.text = value.text.replace(/(http[s]*:\/\/[\w/\.]+)/, '$1')
            value.created_at = value.created_at.replace(/(\+\d+)/g, '').replace(/\w+/, day);
            art.html('
' + value.user.name + '
' + value.created_at + '
' + value.text + '
');
        });

        container.css({
            width : col.length * 225 - 5,
            height : col[small]
        })

        //using the built in each to loop through DOM
        articleArray.each(function (i, article) {
            $(article).css({
                'top': col[small],
                'left': small * 225
            });
            col[small] += article.clientHeight + 5;
            for(var j = 0; j < width; j++) {
                if(col[j] < col[small]) {
                    small = j
                }
            }
        }).fadeIn(); //chain whenever necessary

        //using context to limit the scope of the selector search
        $('.loading', container).fadeOut();
    });
}


Much like elclanrs' solution, just slightly more "plain"

$(function () {
  var classes = ['index', 'grid', 'type'],
      url = window.location.href.toLowerCase();
  for(var i = 0, l = classes.length ; i < l ; i++ ) {
    if(url.indexOf(classes[i]) !== -1) {
      $('.' + classes[i]).addClass('active');
      break; // only first matching class is considered
    }
  }
});


Here are some things that may help you improve your code.

Omit C prolog and epilog if possible

The part you have correctly labeled "C prologue" in your code is used by the compiler to be able to access local variables.  However both inputs and outputs to this assembly routine are in registers, so no stack manipulations are needed.  For that reason, we can eliminate both in this code.

Don't push/pop registers you don't alter

In the addDen routine, the rdi register is pushed and then popped off the stack, but not altered by the routine.  As a result, neither push nor pop are required and both could be omitted.

Avoid subroutine calls

Subroutine calls are not good for fast assembly code.  Your addDen code doesn't need to be a subroutine -- it can be placed inline, avoiding the overhead of a subroutine call.

Reduce jumps per loop iteration

The code as currently structured has both a comparison and conditional jump and also an unconditional jmp .whileLoop that both occur within each loop iteration.  Better practice is to minimize the number of jumps within each loop; ideally one should strive to reduce it to exactly one.

Use direct memory access for instructions

The current code uses this instruction sequence

    movss xmm8, [One]
    movss xmm9, [rdi]
    divss xmm8, xmm9

However, the divss instruction can use memory directly as a source, so we can shorten this to:

    movss xmm8, [One]
    divss xmm8, [rdi]

This saves us a register (xmm9) and some time.

Avoid compare instructions if practical

The current code uses cmp rsi, 0 but that's not really needed since the dec esi at the end of the loop already sets up the zero flag.  Putting all of the previous hints together, a revised routine looks like this:

section .data
    harmonicMean2:
        cvtsi2ss xmm0, rsi        ; xmm0 = len = numerator
        movss xmm10, [Zero]       ; xmm10 = denominator
        inc rsi
        jmp .testzero
    .more:
        movss xmm8, [One]
        divss xmm8, [rdi]
        add rdi, 4
        addss xmm10, xmm8
    .testzero:
        dec rsi
        jnz .more
        divss xmm0, xmm10
        ret

Take advantage of SIMD where practical

SIMD stands for Single Instruction, Multiple Data which allows the CPU to execute multiple operations in parallel, speeding up the routine.  Because your code calculate reciprocals of each data item in the list, we can do that calculation in parallel (4 at a time using SSE) and save some time.  If there aren't 4 data items, we can drop back to a simple serial approach as with what you've already written.  Here's one way to write such a routine:

section .data
    One dd 1.0, 1.0, 1.0, 1.0

section .data
    harmonicMeanP:
        cvtsi2ss xmm0, rsi      ; xmm0 = len = numerator
        xorps xmm10, xmm10      ; xmm10 = denominator = 0
        mov rax, rsi
        shr rax, 2
        jz .single
        movups  xmm9, [One]     ; Loads series of 1s in
    .doquad:
        movaps  xmm8, xmm9      ; copy those ones
        divps   xmm8, [rdi]     ; fetch 4 floats
        add rdi, 16
        addps   xmm10, xmm8

        dec rax
        jnz .doquad
        movaps  xmm8, xmm10         ; copy xmm10
        shufps  xmm8, xmm10, $04E   ; swap low and high halves
        addps   xmm8, xmm10         ; sum now in xmm8
        movaps  xmm10, xmm8         ; copy xmm8
        shufps  xmm10, xmm8, $0B1   ; swap pairs into xmm10
        addps   xmm10, xmm8         ; now have 4 copies of sum in xmm10
        and rsi, 3                  ; less than 4 left
    .single:
        inc rsi
        jmp .testzero
    .more:
        movss xmm8, [One]
        divss xmm8, [rdi]
        add rdi, 4
        addss xmm10, xmm8
    .testzero:
        dec rsi
        jnz .more
        divss xmm0, xmm10
        ret

Test your results

With assembly language code like this, as with much code, the two things one generally looks for are correctness and speed.

Correctness

Although the algorithm is essentially identical in all versions, there is subtle difference that is inherent with the addition of floating point numbers.  Specifically, with floating point numbers, adding a large number to a small number can lead to loss of precision.  In extreme cases, if a is very large and b is very small, we can have a + b = a which is obviously incorrect for non-zero values of b.  (See the oft-cited and still excellent What Every Computer Scientist Should Know About Floating-Point Arithmetic, by David Goldberg for a readable technical discussion for why this is so.)  This can affect the harmonic mean calculations.  For example, if we calculate the harmonic mean of the numbers \$1 \cdots 100000\$, in that order, the correct value is approximately 8271.198621.  However, the original code reports 8270.716797 which is off by a bit.  The reason is that by the time we get to 100000, we're adding a very small number (1e-5) to a relatively much bigger number of about 12.09.  One can use doubles instead of floats here, but while that helps, it only postpones the inevitable when dealing with floating point addition. Numerical analysis is important with these kinds of calculations to assure that the answers are as accurate as they need to be.

Speed

The desire for speed can sometimes conflict with the other goal of correctness, but in this case, we can serve both interests.  When the calculation is parallelized, the effect is that we calculate 4 reciprocals and add 4 results at a time to 4 separate sums.  Because the SSE instructions take about the same amount of time to do one division as to do four in parallel (or 8 in parallel if you can use SSE2 or newer) the results are obtained about 4x as quickly (or 8x with SSE2).  This is where the real speed dividends are, and there's also potentially a small increase in accuracy because each sum is only (roughly) 25% of the total sum (given randomly distributed numbers as input), the loss of precision is slightly reduced.
Here is the C++ program I used to test all variations, including a pure C++ variant that uses doubles for calculation instead of float.

drivemean.cpp

The following code was used to evaluate the various versions for both speed and accuracy.  The stopwatch.h code from this question and was designed for exactly this kind of purpose.

    #include <algorithm>
    #include <iostream>
    #include <iomanip>
    #include "stopwatch.h"

    extern "C" float harmonicMean(float *arr, unsigned len);
    extern "C" float harmonicMean2(float *arr, unsigned len);
    extern "C" float harmonicMeanP(float *arr, unsigned len);
    float hmean(float *arr, unsigned len)
    {
        double sum = 0;
        double n = len;
        for ( ; len; --len, ++arr)
            sum += 1.0/(*arr);
        return n/sum;
    }

    struct MeanTest
    {
        float (*calc)(float *, unsigned);
        std::string name;
    };

    static MeanTest test[]{
        {harmonicMean, "original" },
        {harmonicMean2, "tweaked" },
        {harmonicMeanP, "parallel" },
        {hmean, "C++ double" },
        {nullptr, ""},
    };

    int main()
    {
        const unsigned arrlen{100000};
        const unsigned iterations{1000};
        float nums[arrlen];
        float hm;

        std::iota(nums, nums+arrlen, 1);

        Stopwatch<std::chrono::milliseconds> sw;
        for (MeanTest *t = test; t->calc != nullptr; ++t) {
            sw.start();
            for (unsigned i = iterations; i; --i)
                hm = t->calc(nums, arrlen);
            sw.stop();
            std::cout << std::setprecision(10) << hm << ", "
                << t->name << " time = " << sw.elapsed() << " ms\n";
        }
    }

Results

    8270.716797, original time = 496 ms
    8270.716797, tweaked time = 431 ms
    8271.209961, parallel time = 108 ms
    8271.198242, C++ double time = 675 ms

As you can see, the C++ version was slowest, but most accurate (only off by about 0.0004) but the parallel version was second most accurate but 4x faster than the next fastest.

Using SSE2 instructions would allow one to approach 8x faster and would also allow for some simplification in the use of the shufps instruction.  I'll leave that fun for you.


This is sophisticated for a first attempt, but today would be a great day to break yourself of bad habits.  Your code is full of them.

Start with:  format your code using standard formatting conventions.  We understand code more easily if it is vertical, and your code is horizontal.

Let's go through this line by line.

static void Main(string[] args)
{

Programs that do everything in Main are programs that cannot be easily refactored or re-used.  Main should create an object that represents the program and then execute it.

    Random GenRandom = new Random();

Follow C# naming conventions. Locals get camelCase names.  This should be

    Random random = new Random();

    int t = 0, r, c1 = random.Next(1, 6), c2 = random.Next(1, 6), c3 = random.Next(1, 6), c4 = random.Next(1, 6);

Though this style is legal, it's considered poor style.  Declare and initialize variables one per line.  Give your variables meaningful names.  You will not die younger if you spend time typing turn instead of t.  This should be:

    int turn = 0;
    int digit;
    int cell1 = random.Next(1, 6);
    int cell2 = random.Next(1, 6);
    int cell3 = random.Next(1, 6);
    int cell4 = random.Next(1, 6);

Moving on:

    bool w = false;

Same deal:

    bool hasWon = false;

Moving on:

    string Input, Code = Convert.ToString(c1);
    Code += c2;
    Code += c3;
    Code += c4;

Again, one per line.

We now see that we have the same data in two places: the locals c1, c2, c3, c4 which are never used again and Code.  It is time for our first refactoring.  What we want is:

string code = GenerateCode();

Let's implement that:

static Random random = new Random();
static string GenerateCode()
{
  return random.Next(1, 6).ToString() +
    random.Next(1, 6).ToString()
    random.Next(1, 6).ToString()
    random.Next(1, 6).ToString();
}

And we remove random, c1, and so on, from our method.

All right, where were we? We now have:

    string input;
    string code = GenerateCode();

Moving on:

    while (t != 8) {

First, bad form in the disco brace style.  Second, eight?  Where did eight come from? Rewrite it:

const int maximumTurns = 8;
while (turn != maximumTurns)
{

Moving on:

  t++;

I find increment operators distasteful.

  turn += 1;

Much nicer.

    Unepic:

OH THE PAIN.  Do not write unstructured code in C#; it is 2018, not 1972.

        Console.Clear();

The first line I don't object to! :-)  But as we'll see, it should be in a method of its own.

        Console.WriteLine("You have {0} turn(s) left.",9-t);

Better would be:

        Console.WriteLine($"You have {maximumTurns + 1 - turn} turn(s) left.");

Because now if you change maximumTurns to 7, you only have to change the code in one place, not many.

Better still, make a helper function:

static string Plural(int x, string s)
{
  return x == 1 ? s : s + "s";
}

and then

        int remainingTurns = maximumTurns - 1 - turn;
        Console.WriteLine($"You have {remainingTurns} {Plural(remainingTurns, "turn")} left.");

And then move that into a helper.

Moving on:

        Console.WriteLine("Guess the code E.g 1561: ");

Eschew Latinisms. Should be:

        Console.WriteLine("Guess the code (for example, 1561): ");

Now we come into a section that demands refactoring:

        input = Console.ReadLine();

Fine so far...

        if (input.Length != 4) goto Unepic; // Checks if input is 4 characters long

Do not write comments that repeat what is plainly evident in the code. And do not use spaghetti logic.

        try { Convert.ToInt16(Input); Convert.ToString(Input); } catch (FormatException) { goto Unepic; } // Checks if input is only numbers

Do not re-invent the wheel; TryParse already exists:

    int number; // In C# 7 you can use a discard instead.
    bool valid = int.TryParse(input, out number);

How should we structure this whole thing better? What we want is:

    if (!ValidInput(input)) goto Unepic;

So write that:

static bool ValidateInput(string input)
{
  int number;
  return input.Length == 4 && int.TryParse(input, out number);
}

Moving on:

        if (Input == Code) { w = true; goto End; }; // Checks if you've won

There's a feral semi at the end there. Remove it.

Again, when you are writing comments that are obvious, ask yourself "how could I rewrite the code so that the comment was unnecessary?"  Like this:

        if (input == code)
        {
          hasWon = true;
          goto End;
        }

We'll address the goto later.

        if (Input.Contains("0") || Input.Contains("7") || Input.Contains("8") || Input.Contains("9")) { goto Unepic; } // Checks if it has any digits that are 0 or above 7

Why is this check here? It should be in ValidateInput.  Put it there!

We then have a little loop:

        r = -1;
        while (r != 3)
        {
            r++;
            if (Input[r] == Code[r]) Console.Write(1); else Console.Write(0); // Checks if a digit of the input is equal to a digit of the code
        }

Again, put it in a method.

static void WriteHints(string input, string code)
{

The normal way we would write this loop is:

  for (int i = 0; i < input.Length; i += 1)
    Console.Write(input[i] == code[i] ? 1 : 0;
}

Finishing up the game loop:

        Console.WriteLine();
        Console.Write("Press any key to continue.");
        Console.ReadKey(true);

Why make the user press a key here?  But again, it could be put into a helper method.

    }
    End:;
    Console.Clear();

Again, I'm fine with this but we'll come back to the goto later.

    if (w == true) { Console.WriteLine("You won! The code you guessed was {0}.", Code); } else { Console.WriteLine("You lost! The code you couldnt guess was {0}.",Code); };

Writing if (w == true) is a sure sign of newbie code.  w is already either true or false; you don't have to say "if it is true that w is true" and you don't have to say "if w is true" -- just say "if w".

And again, this could go into a helper.

Now, let's look at your main loop as I have refactored it, all together

static void Main(string[] args)
{
    int turn = 0;
    bool hasWon = false;
    string code = GenerateCode();
    string input;
    const int maximumTurns = 8;
    while (turn != maximumTurns)
    {
      turn += 1;
    Unepic:
      PromptUserForInput(maximumTurns, turn);
      input = Console.ReadLine();
      if (!ValidInput(input)) goto Unepic;
      if (input == code)
      {
        hasWon = true;
        goto End;
      }
      WriteHints(input, code);
      PromptUserToPressKey();
    }
    End:;
    PrintWinOrLoseMessage(hasWon, code);
}

This is already one million times easier to read but we are not done.

The first thing we notice is that we do some work to ensure that turn is not incremented if the user did a bad input. That's great! But the code does not read like that intent.  Let's rewrite it so it does.

    int turn = 1; // not zero!
    while (turn <= maximumTurns) // not !=
    {
    Unepic:
      PromptUserForInput(maximumTurns, turn);
      input = Console.ReadLine();
      if (!ValidInput(input)) goto Unepic;
      if (input == code)
      {
        hasWon = true;
        goto End;
      }
      WriteHints(input, code);
      PromptUserToPressKey();
      turn += 1;
    }

Now turn is only ever incremented after the user has put in a good guess, and the code doesn't need to initialize turn to the wrong value so that it can be incremented later.

Now we notice that the goto Unepic and goto End are continue and break:

    while (turn <= maximumTurns)
    {
      PromptUserForInput(maximumTurns, turn);
      input = Console.ReadLine();
      if (!ValidInput(input))
        continue;
      if (input == code)
      {
        hasWon = true;
        break;
      }
      WriteHints(input, code);
      PromptUserToPressKey();
      turn += 1;
    }

Look at how much easier to understand my version is compared to yours.  Anyone, even a non-coder, could look at this thing and just read it like English.  "while the turn is less than or equal to the maximum turns, prompt the user for input, then read the line from the console, then validate the input..."

That is what you must strive for in your code.  Always be asking yourself how could I make this easier to understand? How could I make this read more like a description of my intentions?

Could we do better?  Sure.  We actually have two loops written as one.  There's the loop that gets valid user input, and there's the loop that runs the game.  Make that explicit:

    while (turn <= maximumTurns)
    {
      do
      {
        PromptUserForInput(maximumTurns, turn);
        input = Console.ReadLine();
      }
      while(!ValidInput(input));
      if (input == code)
      {
        hasWon = true;
        break;
      }
      WriteHints(input, code);
      PromptUserToPressKey();
      turn += 1;
    }

And now we see another opportunity for helper methods. Move the inner loop to a helper!  Move the winning check to a helper:

    while (turn <= maximumTurns)
    {
      input = ObtainValidatedInput(maximumTurns, turn);
      hasWon = CheckForWin(input, code);
      if (hasWon)
        break;
      WriteHints(input, code);
      PromptUserToPressKey();
      turn += 1;
    }

Were I writing your code from scratch, I would make it considerably more abstract than even the version I've given you here.  My main would be:

static void Main()
{
  var game = new Game();
  game.Start();
  while (!game.IsOver)
    game.ExecuteTurn();
  game.End();
}

Try writing your code starting from this template.  Notice how clear and logical it forces your code to be when you start from a position of the code reading like an abstract description of the workflow.  Make every method like this, where you can read the logical workflow right out of a half dozen lines of code.  Get in good habits while you are still a beginner.


Converting a c# enum into a list to be sent to the client

Yes, use linq extensions:

public static List<clientEnum> EnumToclientEnum<T>()
{
    var type = typeof(T);
    if (!type.IsEnum) throw new NotSupportedException();
    return Enum.GetValues(type).Select(x => new clientEnum { Key = (int)x, Value = x.ToString() }).ToList();
}

In your original code (as well as in Abbas's answer) enum value is being converted to string and then this string  is parsed back to get the value. That makes no sense.


This looks good, nice work! I do think Uniprot is a bit long, but mostly because of comments.

"""
Gets the UNIPROT XML or HTML, very bad code.... Cant come up with a better one yet :(
"""

No need to criticise yourself in docstrings. Aside from everything else, this makes your comment too long without information. If it's really that bad, people will notice! Just stick with explaining unclear aspects to the code, or giving context to why the code does what it does. Other unnecessary comments:

    Initialize stuff

Most people familiar with classes will know what __init__ does. Also avoid vague language like "stuff". Initialise parameters would tell you slightly more, initialise uniid or even Unification ID. I obviously made that up, but only that last one adds information (telling the user what a uniid is).

    :return:

I'm not familiar with the docstring convention you're using, but does it really insist on including return lines even when they're blank? Not to mention the fact that you do return things from two of these functions, but your docstring claims otherwise. Either remove it or make the return lines accurate.

Next, you only ever use uniid to do this:

    "http://www.uniprot.org/uniprot/%s.xml" % self.uniid

Why not just initialise the URL in __init__ instead then?

def __init__(self, uniid):
    self.url = uniid.upper("http://www.uniprot.org/uniprot/%s" % self.uniid)

Now you can use self.url and self.url + '.xml' instead. Still on __init__, is there any need to initialise soup? Or even to store it as an attribute at all? You only need to return it from the function. Like you do with websoup. If there's an advantage to keeping it, why not do the same with websoup? You may have good reason, but if there's inconsistent treatment in your code you should comment it for the sake of clarity.

Next, you use a couple magic numbers in your code. Magic numbers are basically when you put numbers into code but it's not really clear from context what they mean or why they have to be that value.

    if xmlpage.getcode() != 200:

This is presumable a success code that the page returns? But it would be more readable like this:

    if xmlpage.getcode() != Uniprot.SUCCESS_CODE:

This is a constant value now, that you'd define as part of the class here:

class Uniprot:

    SUCCESS_CODE = 200

Neater and more readable, it makes perfect sense now (not that your initial case was the most egregious). Similarly, you set timeout to 2 in both cases. This is clearer to follow since timeout=2 is quite readable. But it's better organised if you put this as a class constant or even a value in __init__ that defaults to 2. Either way, it allows a user to change the value. What if they have woefully slow internet? Allowing them access makes the class more useful.

Your file reading seems a bit messy. I can't even tell why you're using such a complex method to check if the file is empty after reading it. So let's start with what I do know. All your file reading can be reduced to this:

    filename = "{}/{}/UNIPROT/{}.html".format(DATA_DIR,
                                              FASTA_OBJECT.organism(),
                                              FASTA_OBJECT.accession()))
    with open(filename) as f:
        uniprotxml = f.read()

format is the newer string formatting function that's recommended over the old % formatting. with is a way of opening files that will always ensure they are closed properly, no matter what. It's also generally recommended. And f.read() just reads the whole file as a string in one go. No need to iterate over the file to read line by line and add that to uniprotxml.

Also you're using recursion to retry. But that's a messy solution. Instead consider using a loop, and call either return or break to end the loop when you get a successful result, but otherwise loop indefinitely (or for a limited number of tries).


Acceptable way of using jQuery methods in Angular directives

I see no reason not to use JQuery animations. If you want to have your app pure angular, use angular animations.

The main issue usually being nagged about is view (dom) manipulation code in the controller, so the directive is the way to go, for sure.

The event broadcast is overkill though, just put the onclick in the directive too :) unless you are planning to put the link outside of <div class="toggle"....


Prime factorization of a natural number greater than 1

Method names

You should try to make the name of your methods are descriptive as possible, without being too long:

user_input should first be userInput according to Java naming conventions. But it is difficult to tell what the method does by just looking at its name: it surely involves the user input but we don't know how and why. In this case, the purpose of the method is to retrieve a number to factor. A possible name would be getNumberToFactor or askNumberToFactor, although I would prefer the first variant because it describes what the method does and does not care of how it does it: in the future, you might expand this code and read the number from a file for example; the method's purpose would still be the same, and its name wouldn't change.
checkPrime could be renamed isPrime: generally, boolean-returning methods have a name starting with is (or has).
primes is fine: it returns a list of prime numbers and it is well described that this name. (Perhaps getPrimes() but this is a matter of opinion)
array is misleading. One would assume that it makes an array of something when it fact, this is the prime method making the factorization. It would be better to name it primeFactors and make it clear that this method makes the prime factorization of the given parameter.

Programming to an interface

It is a good idea to program to an interface. This means, trying to avoid the implementing classes and work only on the interfaces. In this case, you are passing ArrayList when you should be passing List:

           //  v--v
private static List<Integer> primes() {
    List<Integer> primeList = new ArrayList<>();
 // ^--^
    for (int x = 1; x < 10000; x++){
        if (checkPrime(x))
            primeList.add(x);
    }
    return primeList;
}

    Map<Integer, Integer> counter = new HashMap<>();
//  ^-^

Separated logic

You have reasonably well separated the code into methods, but the main array is missing its main ingredient. This method is the central-point for making the prime factorization. Therefore, it is that method that should direcly return a Map<Integer, Integer> of the prime factors with their exponent.

Currently, this code is separated in two unrelated blocks:

private static ArrayList<Integer> array(int x) {
    // return list of primes dividing x
}

public static void main(String [] args) {
    ArrayList<Integer> temp = array(user_input());
    HashMap<Integer, Integer> counter = new HashMap<>();
    // process that list and turn it into a Map
}

Note that separating this code actually hides you from an optimization you can make: you don't need to have a list of all primes factors with duplicate values. You can just construct the Map directly, without having that temporary list:

private static Map<Integer, Integer> primeFactors(int x) {
    Map<Integer, Integer> primeFactors = new HashMap<>();
    ArrayList<Integer> listOfPrime = primes();
    for (int i : listOfPrime) {
        for (int j = x; j % i == 0; j /= i) {
            if (primeFactors.get(i) != null) {
                primeFactors.put(i, primeFactors.get(i) + 1);
            } else {
                primeFactors.put(i, 1);
            }
        }
    }
    return primeFactors;
}

If you're using Java 8, you can make this even simpler by replacing the updating of the map with counter.merge(i, 1, Integer::sum);:

private static Map<Integer, Integer> array(int x) {
    Map<Integer, Integer> counter = new HashMap<>();
    ArrayList<Integer> listOfPrime = primes();
    for (int i : listOfPrime) {
        for (int j = x; j % i == 0; j /= i) {
            counter.merge(i, 1, Integer::sum);
        }
    }
    return counter;
}

Avoid concatenating Strings with +=

In the following loop

for (int key : counter.keySet()) {
    primeFactors += counter.get(key) == 1 ? "(prime)" + key + " x "
            : "(prime)" + key + "^" + counter.get(key) + " x ";
}

you are concatenating the primeFactors variables with +=. This is not a good practice because it creates a lot of Strings in memory. It would be better to use a StringBuilder for this task and append each part with append(...).

Also, I don't see the need to print (prime) each time: you know it's a prime already since we're doing the prime factorization.

If you're using Java 8, you can actually use StringJoiner instead: this will also enable you to get rid of the

primeFactors.substring(0, primeFactors.length() - 3)

at the end. This class is designed to join Strings together with a separator:

StringJoiner sj = new StringJoiner(" ");
for (int key : counter.keySet()) {
    sj.add(counter.get(key) == 1 ? key + " x" : key + "^" + counter.get(key) + " x");
}
System.out.println(sj.toString());


(I'm assuming the code will be changed according to the comments. Otherwise it won't run with the given example graph)

Performance issues:

Comparing lists as in while X != V involves looping through the lists. Also, the condition is not very useful because the lists only become equal in the special case when the algorithm visits the vertices in numerical order. You could as well use while True because the exception you are catching will occur when there are no vertices left to explore.
The w not in X check also loops through X. Making X a set would help with that.
After visiting each vertex, the for loops go through all the edges from all visited vertices, computing the tentative distances. That's a lot of repeated work. The usual approach is to compute the tentative distances only from the vertex just visited to its neighbors and store them in a data structure that allows querying the minimum distance. In Python the heapq module is available to help with that.

Implementation using heapq:

from heapq import heappush, heappop

def Dijkstra(graph, start):
    A = [None] * len(graph)
    queue = [(0, start)]
    while queue:
        path_len, v = heappop(queue)
        if A[v] is None: # v is unvisited
            A[v] = path_len
            for w, edge_len in graph[v].items():
                if A[w] is None:
                    heappush(queue, (path_len + edge_len, w))

    # to give same result as original, assign zero distance to unreachable vertices
    return [0 if x is None else x for x in A]


Disjoint set implementation as linked list

#include <assert.h> // for assert
#include <string.h> // for memset

#include <iostream>

using namespace std;

// OMIT these as not very useful. Anyway, don't needlessly expose globals.

long NodeAddress[9999] = {0};
int n=0;

/* I've kept the class names for now, for the sake of recognition, but
   they've each got different problems.

ListSet does a poor job of describing the class' purpose.
Since its purpose is to generate, find, and merge disjoint sets,
call it something like DisjointSetSource.

Item is too generic and not very descriptive of the class' function. It represents a disjoint set, but to reserve the name DisjointSet for its exported opaque equivalent, just call it Set, or since it's represented as a linked list of member nodes, maybe SetNodeList or SetMemberList.

node is also very generic, but it's a little more apt. Also, it's name should be capitalized by convention and for consistency. So, Node is OK, but better might be Member or since it's main features are to refer to its parent list and successor, call it ListMember.
*/

class ListSet {
private:
    typedef int ValueType;
    struct Item;

/* There's a non-trivial smattering of node and item processing cluttering up the ListMember methods. They really want to be full-fledged classes with a constructor, (possibly) destructor, and (possibly) mutators. Item needs write access to node::next and ListMember needs write access to itemPtr, so I'd keep the node members public. */

    struct node {
        ValueType val;
        node *next;
        Item *itemPtr;

// So, add:

        node (const ValueType& a);
        ~node ();
     };

    struct Item {

// So, add:

        Item(node *shd) : hd(shd), tl(shd) {}
        void append(const Item*);
        // returns head node as "sign of life"
        node* remove(node* old);
    private:
        node *hd, *tl;
    };

/* Avoid exposing nodeAddress, especially as a global. It SHOULD use std::vec for dynamic growth or std::map if values are sparse. Wrap this in accessors to stay flexible, especially WRT ValueType, opening the door for (re)templatizing as in the originally posted code. */

private:
    node* nodeAddress[9999];

public:

    void setNodeAddress(const ValueType& a, node* shd) {
        nodeAddress[a] = shd;
    }

    node* getNodeAddress(const ValueType& a) {
        return nodeAddress[a];
    }

    // removeAll requires or maybe IS a third form of nodeAddress accessor

/* Why does a ListSet object ever need to be created?
   When the original implementation used the global NodeAddress as its state,
   all functions could be static and no ListSet instance ever created.
   This would also be true if NodeAddress was a static member.

Yet, it was easy enough to improve on the design by making nodeAddress a normal data member. This provides a useful purpose for multiple ListSet instances.
   Each managing its own disjoint sets, completely independently.
   All the more reason to pull NodeAddress out of the API, where it is just noise. See main.
*/

    ListSet() {
        // zero out nodeAddress in some type appropriate way
        memset(nodeAddress, 0, sizeof(nodeAddress));
    }

    ~ListSet() {
        removeAll();
    }

/* "long" is too general a type to use for "handles" like the return type, here. Better to make up a unique fictitious type:
*/

    class DisjointSet;

    DisjointSet* exportSet(Item* result) { return (DisjointSet*) result; }
    Item* importSet(DisjointSet* input) { return (Item*) input; }

/* Use camelCase or under_scoring to makemultiwordnamesreadable. */

    DisjointSet* makeSet(const ValueType& a);
    DisjointSet* find (const ValueType& a);
    void remove(const ValueType& a);
    void removeAll();

// Use suffix word rather than breaking lowercase convention to get around reserved words

    void unionSets (const ValueType& a1, const ValueType& a2) {
        DisjointSet* s1 = find(a1);
        DisjointSet* s2 = find(a2);
        if (s1 && s2) {
            (void) unionSets(s1, s2);
        }
        // else error?
    }

    DisjointSet* unionSets (DisjointSet* s1, DisjointSet* s2);
};

ListSet::DisjointSet* ListSet::makeSet (const ValueType& a) {
    assert(!getNodeAddress(a));
    node *shd = new node(a);
    Item *newSet = new Item(shd);
    setNodeAddress(a, shd);
    shd->itemPtr = newSet;
    return exportSet(newSet);
}

ListSet::DisjointSet* ListSet::find (const ValueType& a) {
    node* ptr = getNodeAddress(a);
    if (ptr)
        return exportSet(ptr->itemPtr);
    // else error?
    return 0;
}

/* This used to be needlessly confusing with lines like:

Item *set2 = ptr1->itemPtr;
Item *set1 = ptr2->itemPtr;

I'm really still not sure the revision, below maintains the original intent, because of the set1/set2 naming confusion, but it does what the old code did.

Aside from avoiding such confused naming, use of an Item method
makes this code much easier to read. */

ListSet::DisjointSet* ListSet::unionSets (DisjointSet* s1, DisjointSet* s2) {
    Item *set1 = importSet(s1);
    Item *set2 = importSet(s2);

    set2->append(set1);
    delete set1;
}

void ListSet::Item::append (const Item* other) {
    //join the tail of the set to head of the other set
    tl->next = other->hd;
    tl = other->tl;
    for (node* cur = other->hd; cur; cur = cur->next) {
        cur->itemPtr = this;
    }
}

ListSet::node::node (const ValueType& a) : val(a), next(0), itemPtr(0)
{ }

/* Here's mutator code that allows values to be incrementally dropped as operations continue.
Note that after "union(1,2); union(2,3); remove(2);",
1 and 3 are still considered to be in the same set.
*/

// Returns hd as a sign of life -- null if empty/dead.
ListSet::node* ListSet::Item::remove(node* old) {
    if (old == hd) {
        if (old == tl) {
            assert(! old->next);
            return 0;
        }
        assert(old->next);
        hd = old->next;
    } else {
        node* prev;
        for (prev = hd; prev->next != old; prev = prev->next) {
            assert(prev->next);
            ;
        }
        if (old == tl) {
            assert(! old->next);
            //
            tl = prev;
            prev->next = 0;
        } else {
            assert(old->next);
            prev->next = old->next;
        }
    }
    return hd;
}

ListSet::node::~node() {
    if (itemPtr) {
        if (! itemPtr->remove(this)) {
            // Don't leak an empty set.
            delete itemPtr;
        }
    }
}

void ListSet::remove(const ValueType& a) {
    node* ptr = getNodeAddress(a);
    if (ptr) {
        setNodeAddress(a, 0);
        delete ptr;
    }
    // else error?
}

void ListSet::removeAll() {
    assert( 0 ); // TBD
    // This just needs to iterate over nodeAddress
    // and call delete on each remaining node*.
}

/* There's no reason to expose anything other than the original elements
   (raw numbers), the ListSet and the DisjointSets it returned.
   So don't clutter the interface with Item*s disguised as longs,
   node*s disguised (indistinguishably) as longs, or NodeAddress.
   A cleaner, safer API results:

int main () {

    ListSet a;
    ListSet::DisjointSet *s1, *s2, *s3, *s4;
    s1 = a.makeSet(13);
    s2 = a.makeSet(25);
    s3 = a.makeSet(45);
    s4 = a.makeSet(65);

    /* If this really needs to work, either define a stream io operator
       for our DisjointSet type or let it get dumped as a hex value. */
    cout<<s1<<' '<<s2<<' '<<s3<<' '<<s4 <<endl;

    cout<<"a.find(65): "<<a.find(65) <<endl;
    cout<<"a.find(45): "<<a.find(45) <<endl;
    cout<<"a.Union(65, 45) "<<endl;

    // The next line is a safer way to express a.unionSets(s3, s4);
    // which may crash if s3 or s4 had been previously merged/deleted,
    // but it's also a little slower.
    a.unionSets(65, 45);

    cout<<"a.find(65): "<<a.find(65) <<endl;
    cout<<"a.find(45): "<<a.find(45) <<endl;
}


Counting matrix elements that have "4" or "5" as a neighbor

This is how you could write your code efficiently in base R:

offset <- function(x, v_offset = 0L, h_offset = 0L) {
   stopifnot(h_offset %in% -1:1, v_offset %in% -1:1)
   nr <- nrow(x)
   nc <- ncol(x)
   if (h_offset == +1L) x <- cbind(x[, -1], -99L)
   if (h_offset == -1L) x <- cbind(-99L, x[, -nc])
   if (v_offset == +1L) x <- rbind(x[-1, ], -99L)
   if (v_offset == -1L) x <- rbind(-99L, x[-nr, ])
   x
}

getNeighbours <- function(x, functionof) {
   v_offsets <- c(-1, -1, -1,  0,  0, +1, +1, +1)
   h_offsets <- c(-1,  0, +1, -1, +1, -1,  0, +1)
   neigh_x   <- Map(offset, list(x), v_offsets, h_offsets)
   kc   <- Reduce(`+`, Map(function(x) x == 4L, neigh_x))
   ks   <- Reduce(`+`, Map(function(x) x == 5L, neigh_x))
   kpre <- 0
   functionof(kc, ks, kpre)
}

It builds a list (neigh_x) of eight matrices in memory, one for each neighboring position. Instead of four loops, you are down to a single loop (8 iterations) wherever you see Map or Reduce, everything else uses vectorized operations.

Testing the code:

health <- matrix(1, 5, 5)
health[1, 1] <- 4
test_fun <- function(kc, ks, kpre) 2 * (kc + ks + kpre)

getNeighbours(health, functionof = test_fun)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    0    2    0    0    0
# [2,]    2    2    0    0    0
# [3,]    0    0    0    0    0
# [4,]    0    0    0    0    0
# [5,]    0    0    0    0    0


The implementation you have will forever consume one thread from the ThreadPool. That's not the end of the world, but not ideal either. An easy solution would be to use an overload of Task.Factory.StartNew that accepts a TaskCreationOptions argument, and specify TaskCreationOptions.LongRunning. That will let the system handle it appropriately. Another option would be starting a new thread yourself.

In the task delegate (the code inside StartNew()) I would put a global try/catch block. Any exceptions that might be thrown in there will cause your process to be killed. At the very least you'd want to log those somewhere just so you have some idea what's going on.

I think you're going to Dispose() the IsStopping event on the first time through the loop, then try to use it on the second time through, which will probably cause an exception. I would just remove the AutoResetEvent entirely and use CancellationTokenSource instead. You can use TokenSource.Token.WaitHandle.WaitOne() to wait on instead of the AutoResetEvent. This also has the benefit that when Stop() is called, any pending wait will end immediately.

I would make the Interval property a TimeSpan instead of an int. It's just more clear to users what it means - they don't have to wonder whether it's seconds, milliseconds, or what.


Calculation of Hamming distance between two adjacency lists

First what you want is not the Hamming distance but the Levenshtein distance (the Hamming distance in fact assumes that the two strings (in this case lists) have the same size).
Computing the Levenshtein distance is not trivial and to build an efficient algorithm you need to use the dynamic programming (otherwise you can come up with a recursive algorithm that is less efficient).

The approach is the following:
A list can be transformed in a second one by applying tree different operations to an element: insert, remove, modify.

With this in mind we design the algorithm as follow:
we keep a matrix M where

M[i][j] = distance between the first i-th elms of the the first list and the first j-th elems of the second list.

Thus, the first row of the matrix represents the distance between an empty list and the second list if you consider only the first i-th elements. Thus it has to initialized as follow:

for i in range(len(l1)):
    M[0][i] = i

because we can always transform a list to the empty one by dropping all the elements (so i operations).

Similarly first column also  is initialized in the same way:

for i in range(len(l2)):
    M[i][0] = i

At this point to compute the distance between the first i elements of l1 and the first j elements of l2 we have to consider which is the operation that will transform l1 to l2 with fewer operations. So we take the minimum between

the number of operations to transform l1[0:i-1] into l2[0:j] + 1 (the added 1 is the cost for this operation which is the deletion)
the number of operations that we had to perform to transform l1[0:i] into l2[0:j-1] + 1 (this represent the insertion operation)
and the number of operations to transform l1[0:i-1] into l2[0:j-1]. Summing 1 if l1[i] != l2[j] (we have to substitute te element), 0 otherwise.

This translated into formula is:

M[i][j] = min(M[i-1][j] + 1, M[i][j-1] + 1, M[i-1][j-1] + 1 if l1[i]==l2[j] else 0

Implementing everything in java is:

public static int editDistance(List<String> l1, List<String> l2)
{
    int[][] M = new int[l1.size()][l2.size()];
    for(int i = 0; i < l2.size();i++)
        M[0][i] = i;
    for(int i = 0; i < l1.size(); i++)
        M[i][0] = i;

    for(int i = 1; i < l1.size(); i++)
    {
        for(int j = 1; j < l2.size(); j++)
        {
            int substitute = 0;
            if(!l1.get(i).equals(l2.get(j)))
                substitute = 1;

            int minRemoveAdd = Math.min(M[i - 1][j] + 1, M[i][j - 1] + 1);
            M[i][j] = Math.min(minRemoveAdd, M[i-1][j-1] + substitute);
        }
    }
    return M[l1.size() - 1][l2.size() - 1];
}


helper method returning a call to itself

Using a delegate to allow the method to return another call to itself.

You don't necessarily need a delegate to allow another call to itself. For example:

public class SimpleCalculation
{
    private int result;

    public int Result
    {
        get { return result; }
    }

    public SimpleCalculation Add(int i)
    {
        result += i;
        return this;
    }

    public SimpleCalculation Subtract(int i)
    {
        result -= i;
        return this;
    }
}

//Usage:
var sc = new SimpleCalculation();
sc.Add(5).Subtract(2);
Console.WriteLine(sc.Result); //Writes '3' to the screen

I'm not saying your code is wrong, only saying that you don't need delegates to achieve this. Also this:

//using (var repo = new Data.Repository(true))
//{
//    repo.AddClient(sender.Name, true);
//}
//using (var repo = new Data.Repository(true))
//{
//    repo.AddMessageType<T>();
//}
//using (var repo = new Data.Repository(true))
//{
//    repo.AddRegistration<T>(this.name, sender.Name);
//}

Could also be rewritten as:

using (var repo = new Data.Repository(true))
{
    repo.AddClient(sender.Name, true);
    repo.AddMessageType<T>();
    repo.AddRegistration<T>(this.name, sender.Name);
}

I don't know if you already knew or tried this but I'm just pointing it out as a possibility. But I agree with you: experimenting with code is fun! :)


d20pfsrd Discord Bot Scraper Abstraction and Deployment

Here's how I would do it. Move the logic about which pages a parser consumes into the code for said parser. Also organizing your helper files into objects could reduce complexity in terms of the number of variables you pass around but that's more a matter of personal preference.
class SpecificPageParser {
    match(url) {
        return (
           url.startswith('https://www.d20pfsrd.com/magic/') &&
           !url.endsWith('/magic/')
        );
    }
    format(response) {
        // do your parsing stuff
        const formatted = {...response,'extra':'info'};
        return formatted;
    }
}

const responders = [new SpecificPageParser(),new SomeOtherParser()];

async function getPage(msg, url){
    try {
        const responder = responders.find(responder=>responder.match(url));
        if (!responder) return;
        const response = await axios.get(url);
        const message = responder.format(response);
        sendMessage(message, msg);
    }
    catch(error) {
        console.error(error);
    }
  }
```


Note: benchmarking C++ code over a fixed, compiler provided sample can lead to the optimizer removing all relevant code and/or replacing it by a precalculated result. The only reason this didn't happen in your test was that GCC gave up because of the complexity and not enough hints.

Implementation

I and v are declared with auto storage class. This causes them to be placed on the stack on most platforms, for which they might be too large (2 * 100000 * 8 Bytes = 1.6 MB, for comparison: standard max stack size on windows is 1 MiB). This might crash the program or cause any number of undefined behaviors.
Also, double I[numSamples]; and double v[numSamples]; would require numSamples to be a compile time constant (e.g. const or constexpr) by the C++ standard (GCC seems not to mind, though).
Checking array/loop bounds: All loop bounds are off by one (<= instead of <), which in turn causes array accesses to be out of bounds by 1 or even 2. This is undefined behavior, and can lead to crashes! (Also, it means you've run 1001 loops of the C++ code, instead of the 1000 mentioned, slightly skewing the comparison.)
A lot of variables could be made const and/or constexpr. Doing so might help the compiler optimize your code, as it gets more information to work with/doesn't have to deduce the const-ness by itself (which can be costly).
Unnecessary header #includes: contents from <iostream>, <stdio.h> and <array> are never used!
Prefer to include the adapted C++ headers over plain C headers (<cmath> and <cstdio> instead of <math.h> and <stdio.h>).
using namespace std; is considered bad practice and should be avoided.
Try to refactor code into smaller, independent units. This helps humans for readability and compilers for deducing useful traits for optimization.
Along the same line: Try to restrict variables to the smallest scope needed. Again, this helps human readers as much as compilers, as now we only have to consider them where they are reachable.
Your code still uses a lot of magic numbers. Try to extract them into appropriately named variables, so other readers of your code can reason about them easier.

Optimization

Your current code is not structured well enough for the optimizer. Why? If it could reason about it perfectly, it would remove all the code (as there are no observable side effects), running in near 0ms!

Declaring all possible variables const and moving them to the smallest scope possible helps quite a bit. Even better: Refactor the code into functions (and maybe classes) with proper const annotations!

Just this alone allowed MSVC and GCC to recognize that the whole calculations aren't needed (as they don't cause side effects by themselves), so they removed them and run-time went down to ~24 microseconds on my machine.

To get relevant results, we now need to fool the compiler a bit: Adding a little side effect (num_calls in the code below) and taking the number of loops to run as a command line argument were enough for MSVC and GCC (and clang, though not ICC). Now runtime (with all calculations!) went down from ~14 seconds (original) to ~12.5 seconds (again on my machine).

  Note: The code below has some changes that, while possibly benefiting benchmark performance, are differences to the original:

  Results of all the simulation steps aren't stored. Instead, only the latest result is kept. (The stores would probably be optimized out anyways, as they wouldn't be read from.)
  The input impulse is generated on the fly (instead of being read from an array). This causes the optimizer to generate better code for this case (no memory reads, just a branch that the hardware can predict well). I don't think the impact is large (as contiguous array accesses would be prefetched anyways), but still to be noted.
  The number of benchmark loops to run is taken from the command line arguments (argument #1). This is done to fool the optimizer into not removing/precalculating the actual calls (as it can't know how often it will run).
  To cause a visible side effect, I needed to report the number of simulation steps made. Since I had to print them anyways, I added a small snippet to measure the benchmark time and print it as well.
  I renamed a lot of variables. This was more for my understanding (and readability). For some variables, I couldn't deduce their intents, so their names remained unchanged. I also didn't move the magic numbers into variables, as I don't know what they are referring to. (I know scientific code usually tries to use formula symbols as names, but those were too similar for me to reason about, especially since I'm not too versed into that specific field.)

#include <iostream>
#include <cmath>
#include <chrono>

uint32_t num_calls = 0; // to fool optimizer

namespace constants
{
    constexpr const auto time_step = 0.01;
    constexpr const auto num_samples = 100000;

    constexpr const auto initial_voltage = -65.0;
    constexpr const auto reference_voltage = -65.0;

    constexpr const auto membrane_surface = 4000.0;  // [um^2] surface area of the membrane
    constexpr const auto membrane_capacitance_density = 1.0;   // [uF/cm^2] membrane capacitance density
    constexpr const auto membrane_capacitance = membrane_capacitance_density * membrane_surface * 1e-8;   // [uF] membrane capacitance

    constexpr const auto GNa = 120.0;
    constexpr const auto GK = 36.0;
    constexpr const auto GL = 0.3;
    constexpr const auto ENa = 125.0;
    constexpr const auto EK = -55.0;
    constexpr const auto EL = -25.0;

    constexpr const auto sodium_conductance = GNa * membrane_surface * 1e-8;// Na conductance [mS]
    constexpr const auto kalium_conductance = GK * membrane_surface * 1e-8;  // K conductance [mS]
    constexpr const auto leak_conductance = GL * membrane_surface * 1e-8;  // leak conductance [mS]
}

class simulation
{
    double membrane_potential;
    double m;
    double h;
    double n;

    double step_m(const double delta_time) const
    {
        const auto voltage_difference = membrane_potential - constants::reference_voltage;

        const auto aM = 0.1 * (voltage_difference - 25.0) / (1.0 - exp(-(voltage_difference - 25.0) / 10.0));
        const auto bM = 4.0 * exp(-voltage_difference / 18.0);

        auto const derivative_m = (1.0 - m) * aM - m * bM;

        return (m + derivative_m * delta_time);
    }

    double step_h(const double delta_time) const
    {
        const auto voltage_difference = membrane_potential - constants::reference_voltage;

        const auto aH = 0.07 * exp(-voltage_difference / 20.0);
        const auto bH = 1.0 / (1.0 + exp(-(voltage_difference - 30.0) / 10.0));

        auto const derivative_h = (1.0 - h) * aH - h * bH;

        return h + derivative_h * delta_time;
    }

    double step_n(const double delta_time) const
    {
        const auto voltage_difference = membrane_potential - constants::reference_voltage;

        const auto aN = 0.01 * (voltage_difference - 10.0) / (1.0 - exp(-(voltage_difference - 10.0) / 10.0));
        const auto bN = 0.125 * exp(-voltage_difference / 80.0);

        auto const derivative_n = (1.0 - n) * aN - n * bN;

        return n + derivative_n * delta_time;
    }

    double step_membrane_potential(const double time, const double stimulus) const
    {
        const auto sodium_current = constants::sodium_conductance * m*m*m * h * (constants::ENa - membrane_potential);
        const auto kalium_current = constants::kalium_conductance * n*n*n*n * (constants::EK - membrane_potential);
        const auto leak_current = constants::leak_conductance * (constants::EL - membrane_potential);

        auto const derivative_potential = (sodium_current + kalium_current + leak_current + stimulus) / constants::membrane_capacitance;

        return membrane_potential + derivative_potential * time;
    }
public:
    simulation(const double initial_potential, const double initial_m, const double initial_h, const double initial_n) : membrane_potential(initial_potential), m(initial_m), h(initial_h), n(initial_n) {}

    void step(const double delta_time, const double current_stimulus)
    {
        membrane_potential = step_membrane_potential(delta_time, current_stimulus);
        m = step_m(delta_time);
        h = step_h(delta_time);
        n = step_n(delta_time);

        ++num_calls; // to fool optimizer
    }

    double latest_potential() const
    {
        return membrane_potential;
    }
};

void run_simulation()
{
    auto sim = simulation{ constants::initial_voltage, 0, 0, 0 };

    for (auto j = 0; j < constants::num_samples; j++) {
        auto stimulus = 0.0;
        if (j >= 25000 && j <= 75000) stimulus = 0.01;

        sim.step(constants::time_step, stimulus);
    }
}

int main(int argc, char *argv[])
{
    using seconds = std::chrono::duration<double, std::ratio<1, 1>>;

    if(argc < 2)
    {
        std::cerr << "requires number of benchmarking loops as command line argument #1";
        return 1;
    }

    const auto num_loops = atoi(argv[1]);

    const auto start_time = std::chrono::high_resolution_clock::now();

    for (auto loop = 0; loop < num_loops; ++loop) {
        run_simulation();
    }

    const auto end_time = std::chrono::high_resolution_clock::now();
    const auto time_taken = std::chrono::duration_cast<seconds>(end_time - start_time);

    std::cout << "time taken: " << time_taken.count() << "s\n";
    std::cout << "number of loops: " << num_loops << "\n";
    std::cout << "number of simulation steps: " << (num_calls / num_loops) << "\n"; // to fool optimizer
}

Further optimization possibilities?

All compilers produce reasonable ILP (instruction level parallelism) assembly (if still fooled). There doesn't seem to be much to improve upon.
Multithreading also doesn't seem like it would be helping for this problem, as the simulation steps are dependent on previous results.
The bottleneck seems to be the exp function call, so a faster implementation might help (that's why I tried ICC, but that one is too smart and removes the calculations as a whole -.-).


The block

for (int i = 0; i < _roiY1; i++)
{
    for (int j = 0; j < newWidth; j++)
    {
        channel_gr[i*newWidth + j] = clipLevel;
    }
}

can be made more concise by using std::fill.

std::fill(channel_gr, channel_gr+_roiY1*newWidth, cliplevel);

I won't vouch for better performance though.


Sorting an array in C++ using Bubble sort

Some notes:

I would avoid running a loop while changing i inside, it is very unclear to the reader. I prefer using two nested loops.
The swap can be done in one step less
I would initialize a size variable and use it throughout the code instead of hard-coding 6.
Printing the array to the console should be in a separate function (as well as the sorting function really).

#include<iostream>

int main(){
    const int sz = 6;
    int arr[sz] = {5,2,3,7,2,6};
    do{
        swapped = false;
        for(int i = 1;i < sz; i++){
            if(arr[i] < arr[i-1]){
                int tmp = arr[i];
                arr[i] = arr[i-1];
                arr[i-1] = tmp;
                swapped = true;
            }
        }
    } while(swapped);
    print_array(arr, sz);
}


ES6 class that generates an area where you can draw on a page

The first weird thing I saw in your code is the use of the $(fun).

This jQuery function is used to execute code when the DOM is ready.

I think it should be better to remove all this calls and instead instantiate the class itself in a function executed after the DOM is ready.

That helps to follow the code properly.

// here you declare the class
class MyClassThatUseDOM {
    constructor(selector) {
        this.myElement = $(selector);
    }
}

$(function(){

    // here you instantiate the class
    // when the DOM is ready and all selector
    // will properly match.
    const myObj = new MyClassThatUseDOM("#theselector");

});

As the element $(selector) or $(this.selector) are used may times it is best to save in an instance variable:

this.element = $(selector);

And then access always from this variable, instead of continue to search it with jQuery.

The following method have some issue for me:

createChessBoard() {
    var id = this.selector;
    $(function() {
        $(id + " tr:nth-child(even) td:nth-child(even)").addClass("black-tile");
        $(id + " tr:nth-child(odd) td:nth-child(odd)").addClass("grey-tile");
    });
}

Maybe if you remove the $(func) part as I suggested in my first point the code will be more clear.

But let's discuss what we have now.

You use a variable id to save the selector, but id is more specific term than selector. It could confuse some developer.

A selector for jQuery is anything is a valid css selector, like a tag name, a css class name or even and id.

Please pay attention to the names you use for your variables.

In this case you can do something like:

let _selector = this.selector

As you can see you understand that you just assign a private variable, here.

Use of var is not wrong, but we have let.

Similar considerations for:

var bname = $(this.selector).css("border");

About the method:

createRandowDraw() {
    this.clearBoard();
    let mat = $(this.selector + " td");
    let max = mat.length;
    for (let i = 0; i < max; i++) {
        let num = Math.floor(Math.random(2) * 2);
        if (num && num <= 1)
            $(mat[i]).addClass("tile-active");
    }
}

Here you could use jQuery API to simplify your code:

createRandowDraw() {
    this.clearBoard();
    $(this.selector + " td").each(function(i, mat){
        let num = Math.floor(Math.random(2) * 2);
        if (num && num <= 1) {
           $(mat).addClass("tile-active");
        }
    });
}

Or in a plain javascript fashion by using filter and forEach.


Faster way to concat dataframes with different columns vertically

Yep, you can do this in one line, no need to create other lists or empty dataframes when concat will cover your use-case entirely:

import pandas as pd
# to artificially fill a dataframe
import random

# for the purpose of transparency, here's how the dataframes were constructed
a_cols = list('ABCD')
b_cols = list('ACYZ')
a_index = [f'2018-10-{i}' for i in range(16, 21)]
b_index = [f'2018-10-{i}' for i in range(21, 23)]

# creation of the two dataframes
a = pd.DataFrame([{col: random.randint(0, 10) for col in a_cols} for i in a_index], index=a_index)
            A  B  C  D
2018-10-16  6  8  7  4
2018-10-17  5  6  2  5
2018-10-18  4  1  6  5
2018-10-19  4  3  7  9
2018-10-20  7  6  7  5

b = pd.DataFrame([{col: random.randint(0, 10) for col in b_cols} for i in b_index], index=b_index)
            A  C  Y   Z
2018-10-21  1  9  4  10
2018-10-22  1  6  4   6

# and here's your function call
pd.concat([a, b], axis=0, sort=True)
            A    B  C    D    Y     Z
2018-10-16  6  8.0  7  4.0  NaN   NaN
2018-10-17  5  6.0  2  5.0  NaN   NaN
2018-10-18  4  1.0  6  5.0  NaN   NaN
2018-10-19  4  3.0  7  9.0  NaN   NaN
2018-10-20  7  6.0  7  5.0  NaN   NaN
2018-10-21  1  NaN  9  NaN  4.0  10.0
2018-10-22  1  NaN  6  NaN  4.0   6.0

Now the only issue would be the RAM you have at your disposal, and since that wasn't mentioned, I'm assuming this is sufficient. If you are looking for a more memory-optimized solution, we would have to see how those frames are created, since pandas will always load the entire structure into RAM


I'd change the code so that every implicit constant value is an argument in the constructor, with default values.

In addition, I guess this excel application is the COM API for Excel, so perhaps a better approach would be using the IDisposable interface and implementation.

I changed the typo and now the inner method's name is ExcelScanInternal (and not ExcelScanIntenal).

So the result looks like this (I didn't compile it, so it might have syntax errors):

public class MyRange
{
    public string @From { get; set; }
    public string @To { get; set; }
}

public class ExcelReader : IDisposable
{
    Application _excelApp;
    string _fileName;
    MyRange _scanRange;

    public ExcelReader() : this ("the_file_name", new MyRange{From = "A1", To = "B2"})
    {
    }

    public ExcelReader(string fileName, MyRange scanRange)
    {
        if (null == fileName) throw new ArgumentNullException("fileName");
        _fileName = fileName;
        if (null == scanRange) throw new ArgumentNullException("scanRange");
        _scanRange = scanRange;
        _excelApp = new Application();
    }

    public string ExcelOpenSpreadsheets(string sheetName)
    {
        string _txt = string.Empty;
        try
        {
            Workbook workBook = _excelApp.Workbooks.Open(_fileName,....);
            _txt = ExcelScanInternal(workBook, sheetName);
        }

        catch
        {
            //
            // Deal with exceptions.
            //
        }
        return _txt;
    }

    private string ExcelScanInternal(Workbook workBookIn, string sheetName)
    {
        Worksheet sheet = workBookIn.Sheets[sheetName] as Worksheet;

        Range a1 = sheet.get_Range(_scanRange.From, _scanRange.To);
        if (a1 != null)
        {
            string formattedText = a1.Text;
        }

        return formattedText;
    }

    public void Dispose()
    {
        _excelApp.Quit();
    }
}


MVC4 approach to checking authorization after POST

Authorising actions should be done by your business layer or whatever you want to call it. Your web layer need only say this person is authenticated and is trying to perform this action:

public ActionResult Edit(FtpTrackViewModel ftptrackVM)
{
    if (ModelState.IsValid)
    {
        var requestingUserName = User.Identity.Name.Split('\\')[1]);
        someFtpTrackService.UpdateExpirationDate(ftptrackVM, requestingUserName);
        return RedirectToAction("Index");
    }
    return View(ftptrackVM);
}

Then it's the job of your service to check the user can do the action that the web layer is asking:

public class SomeFtpTrackService
{
    public SomeFtpTrackService(/* dependencies */)
    {
        // set up dependencies (assign to fields)
    }

    public void UpdateExpirationDate(FtpTrackViewModel ftpTrack, string userName)
    {
        var track = db.FtpTracks.Find(ftptrackVM.guid);
        if (track.DomainUserName != userName)
        {
            // throw new ...
        }
        // ...
    }
}

Not that I've Pascal cased domainUserName to DomainUserName. I've treated user and name as separate words here (userName) but if you implement full authentication on the site, you might find you move towards an actual username (one word).

Having said all of the above, the chance of someone randomly changing a GUID and getting another entity is infinitesimally small.


Python Turtle - Olympic flag re-creation

Your function kind-of works as intended, except the obvious deviation occurring at the crossings of rings. However, you can only draw the logo at one specific size and you need a heck of a lot of code to do it.

Let's start with a little clean-up and I'll explain the how and the why afterwards:

import turtle

OFFSET = 165
HALF_OFFSET = OFFSET/2
BORDER = 10
UPPER_LINE = 0
LOWER_LINE = UPPER_LINE - (HALF_OFFSET + BORDER/4)

def draw_circle(turtle, x=0, y=0, width=10, color="black", size=75):
    """
    Take a turtle, draw a circle.
    Takes 6 arguments, including the turtle.

    turtle: The turtle to use. Save the world, re-use your turtle.
    x: X coordinate offset from 0
    y: Y coordinate offset from 0
    width: width of the border of the ring
    color: color of the ring
    size: size of the ring
    """
    turtle.up()
    turtle.goto(x, y)
    turtle.down()
    turtle.width(width)
    turtle.color(color)
    turtle.circle(size)

def main():
    t = turtle.Pen()
    draw_circle(t, -OFFSET, UPPER_LINE, BORDER, "blue")
    draw_circle(t)
    draw_circle(t, OFFSET, UPPER_LINE, BORDER, "red")
    draw_circle(t, -HALF_OFFSET, LOWER_LINE, BORDER, "yellow")
    draw_circle(t, HALF_OFFSET, LOWER_LINE, BORDER, "green")

    input("Press any key...")

if __name__ == "__main__":
    main()

Which, apart from the input part, does exactly the same thing as your code does. That part halts the program so you can actually enjoy the creation on your screen before the rings disappear again. I've also removed the reset(), since it wasn't necessary.

I apologize for the poor naming, but at least it adheres to PEP8. Consistency is good, re-inventing the wheel unnecessary so just follow the same convention as everyone else. Keeps code readable for most developers at the same time. Good, no?

First, I've reduced the amount of functions. A lot. How? By using arguments. I can even use default arguments to save a lot of duplication. You can see this most of all in the second call to draw_circle, where a black circle is drawn with standard dimensions.

Note that many arguments are read from a value set at the top, which is calculated frome one single value: OFFSET. By changing one value, all other values scale with it.

This improves re-usability and readability by a lot. Your future self will thank you.

Another way to improve re-usability is with the following standard technique:

if __name__ == "__main__":
    main()

If you dive deeper into Python, you'll start encountering special variables like __name__. In this case, __name__ allows us to see whether a piece of code was included from somewhere else or executed directly. Now, everything inside main will only be executed whenever you call the function directly and not when it's included in a different file.

Now, assuming I have 2 scripts, CR_162598.py and foo.py. CR_162598.py is the cleaned-up version of your code. foo.py could look like this:

import turtle
from CR_162498 import draw_circle

t = turtle.Pen()
draw_circle(t, 50, 50)

input("Press any key...")

And all of a sudden, a black ring appears at coordinates 50, 50. Now, you can re-use your code without actually touching your old code. All you need to know is you can use the function draw_circle from the file CR_162498 and what arguments it takes. Noticed the docstring on top of the function? It's there for (among others) exactly that reason. Telling your user (or future self) how to use the function.

On default arguments:
Default arguments (default parameter values) help with setting a default ring. If we 'just want a ring' and don't care about it's size and color, simply calling the function will do. They are the values used if no other values are provided. Basically, giving a default gives you the option of making that parameter optional instead of obligatory. If it's missing, the function will simply take it's default instead.

Note: size is probably your radius, diameter or a value derived from either of those. Renaming it to something more sensible would be beneficial.


Write output file, collating groups of up to 7 input lines

You should avoid writing code with exception-handling altogether.  Usually, when you want to write a fancy loop in Python, the itertools module is your friend.  In this case, I would take advantage of itertools.groupby() to form groups of lines, assisted by itertools.count() to provide the line numbers.

import itertools

def chunks(iterable, n):
    i = itertools.count()
    for _, group in itertools.groupby(iterable, lambda _: next(i) // n):
        yield group

with open('data.txt') as read_f, open('new_data.txt', 'w') as write_f:
    for group in chunks(read_f, 7):
        print(' '.join(line.rstrip() for line in group), file=write_f)

A few other minor changes:

You only need one with block to open both files.
line.rstrip() is more convenient than lambda x: x.replace("\n", '')
print(…, file=write_file) is slightly more elegant than write_file.write(… + '\n').


Remove redundant comments
You added a lot of comments to the code, but many of them are not very useful. Comments should be used to explain what the code does if this is not clear from reading the code itself. But for example:
std::queue<Task> _toDo;

I can see just from this line of code that this is a queue of tasks to be done, so the comment you wrote doesn't add any new information to this. Adding unnecessary comments just increases the noise to signal ratio, and actually makes the code less readable.
Avoid starting names with underscores
The C++ standard reserves some names starting with underscores. Unless you want to learn the exact rules, I recommend you don't start any names with an underscore, but instead use the prefix m_ or a single underscore as a suffix.
Avoid manually locking and unlocking mutexes
I recommed you just use a lock guard without std::defer_lock_t to lock those regions of code that need exclusive access to the data structures. So in MainThread(), I would write:
while (true) {
    std::function<void(void)> task;

    {
        std::unique_lock lock{_mutex};
        _signal.wait_for(lock, []{ return _stop || !_toDo.empty(); });

        if (_stop && _toDo.empty())
            break;

        task = std::move(_toDo.front());
        _toDo.pop();
    }

    task();
}

Notify without the lock held
While your code is correct, it is slightly more efficient to call notify_one() if you don't hold the lock. So for example, in the destructor you can write:
~WorkerThread() {
    {
        std::unique_lock lock{_mutex};
        _stop = true;
    }

    _signal.notify_one();
    _thread.join();
}


The selector for all edit_buttons can be expressed as a single selector $('div#personal_info button.edit_button').

I am tempted to rewrite the code to use closure scope to cache the selector values e.g.

// Iterate using each to define cached values for selectors within a
// closure scope
$('.edit_button, .save_button, .cancel_button').each(function() {
  var button = $(this);
  // select all elements that need be toggled on click
  var toggled = $([
    button,
    button.siblings('button'),
    $('div#personal_info button.edit_button').
       not(button.parent().find('button.edit_button'))
  ]);
  // toggle each element separetely on click as the first element in a selector
  // defines the target visiblity of a no parameter .toggle()
  button.click(function() {
    toggled.each(
      function() {
        $(this).toggle();
      });
    });
});

The benefit of it is that less traversing is needed. Unfortunately the toggle method didn't work quite as I imagined it would when there are both hidden and shown elements in the selector when using jQuery 1.6.2.

The above code is available through jsFiddle

From a maintenance/cleanliness point of view I'm a bit wary how this piece of code merges the concerns of

Hiding all edit actions
Showing all edit actions
Displaying save and cancel actions for a specific edit action
Hiding save and cancel actions for a specific edit action

The result of all these goals leads to astonishment that is higher than the least possible. I don't really know what a good name for that function would be?

Also how and where are the event handlers for onclick events of .save_button and .cancel_button defined?


Breaking up a PHP class between a master class and subclasses

Coding standards
I'm not going into details here. But there are coding standards psr-1 tot psr-4. I would advice you to follow them.
Another quick remark: if you need something, ask for it. And if you cant do it, throw an exception. This code shows exactly what I mean:
  public function insert($cfg)
  {
    // Specific to this class
    if ( is_array($cfg) &&
      isset($cfg['parts'], $cfg['id_tiers']) &&
      \bbn\str\text::is_number($cfg['parts']) &&
      ($cfg['parts'] > 0) ){
      return parent::insert($cfg);
    }
    $this->error("Problème dans la configuration pour l'insertion");
  }

In order to be able to do something, you need parts, id_tiers. parts needs to be a number larger then 10. So ask it:
public function insert($parts, $tiers)
{
    if (!is_number($parts)) throw new IllegalArgumeInvalidArgumentExceptionntException('parts needs to be a number');

    if ($parts < 0) throw new InvalidArgumentException('parts needs to be larger then 0');

    //do the actual inserting
}

But the problem you had to solve with that nifty && stuff is that you are extending a Link that extends a Company. And that is how I come to my conclusion:
I don't think you understand the concept of 'OO'. You use words like interface, class, protected and that's it.
Encapsulate everything
What you did is create one GODObject. It knows all, does all and will eventually break all. A good thing to start is to define all your Domain Models. Domain Models are defined by state, and are nearly always stored in some persisting storage (e.g. a Database).
Domain Models
Domain Models represent state and give us a set of tools to easily access that state. A Domain model is by definition stupid:
class MyDomainModel
{
    private $attribute;

    public function getAttribute()
    {
        return $this->attribute;
    }

    public function setAttribute($value)
    {
        $this->attribute = $value;
    }
}

It gives you a set of tools to pass around state. In your case, there will be multiple Domain models:

Company
Shareholder
Representative
Warrantor
Office
...

A Shareholder and a Representative will probably be special cases of a User:
class User
{
    private $name;
    /** getter + setter for name */
}

class Shareholder extends User
{
    private $someShareholderStuff;
}

class Representative extends User
{
    private $someRepresentativeStuff;
}

That makes sense. Your code doesnt, here is why:
A link is a Company and implements the a _list. A Shareholder is a link (and thus also a Company). A Company has multiple Shareholders. Thus, a Company has multiple Companies. And just sounds strange.
What is beging done? And who is doing it?
This is a mistake a lot of people make. They add methods to the wrong class. This comes from the 'We use MVC and cram everything into either a Model, a View or a Controller'. And they end up writing code like this:
class User extends BasicModel
{
    public function sendRegistrationMail()
    {
        $this->mailer->sendEmail($this->email, 'Lorem Ipsum registration');
    }
}

and use it
$user->sendRegistrationMail();

Some might event argue that there is nothing wrong with this code. But lets look at what is going on. Somewhere down the road, the USer Object - that was a simple representation of state - learned how to use the MailerInterface. And now everytime we create a User, we also need a Mailer to pass to the constructor. The target has become the actor.
Much better code would be:
$mailer->sendEmail($email, $user);

The Email and the User care less about how the email is send. They don't even know an email is send. They shouldn't, they are but dum objects that represent state.
I want my constructors to be protected
This reminds me of the Singleton anti-pattern. If you don't want multiple instances to be created, then don't create multiple instances. Same goes for your Shareholder class. If you don't want it to be created outside a given context, then don't. Code doesn't magically appear.
And think of testing. One day you will have to stub a Shareholder, and then writing new Shareholder('name'); without the app complaining will be heaven.


Linq C# pulling from table row into input fields

Your use of linq is fine.

You may consider using a more descriptive variable than a, such as patient

You should pass any query parameters likely to change as variables. Consider:

var patientID = 1198;
var detail = from patient in da.tblPatients
             where patient.ID == patientID
             select patient;

I find the form population logic and database design to be a touch more troubling. txtFirstName.Text = d.FirstName is perfectly fine. DOB, which I assume to be date of birth should be stored and used as a Date rather than a String.

If you are unable to change the data-layer, at least convert it to a Date for use using Date.Parse or similar.

Your try block is lazy coding. Check the results from your dob.IndexOf and 'dob.Substring' calls rather than relying on catching an error -- be defensive in your code. Consider the following:

DateTime dob = DateTime.MinValue;
if (DateTime.TryParse(d.DOB, dob))
{
    ddlDOBMonth.SelectedValue = dob.Month.ToString();
    ddlDOBDay.SelectedValue = dob.Day.ToString();
    ddlDOBYear.SelectedValue = dob.Year.ToString();
}


Find all words that satisfy unknown letters (Hangman)

The solution would indeed be much simpler using regular expressions.  The trick is to build the regular expression dynamically, using a negated character class like [^unwanted] to represent any character other than u, n, w, a, n, t, e, or d.

I'd suggest writing this function to return a generator expression, such that it yields matching words from WORD_LIST as it finds them, rather than waiting until all of the processing is complete.

import re

def words_like(search, without_letters='', preclude_revealed_letters=True):
    forbidden_letters = set(without_letters)
    if preclude_revealed_letters:
        forbidden_letters.update(c for c in search if c != '?')
    regex = re.compile(
        search.replace('?', '[^' + ''.join(forbidden_letters) + ']'),
        re.IGNORECASE
    )
    return filter(regex.fullmatch, WORD_LIST)

This assumes that search consists only of letters and question marks, and contains no regex metacharacters such as ..

(Note that regex.fullmatch() was added in Python 3.4.  For earlier versions of Python, use regex.match, and append a $ to the regex.)


Function that multiplies all numbers between "a" and "b" with do loop

You can use a do loop without using set!.

(define (product-of-range x y)
  (do ((result 1 (* result i))
       (i x (+ i 1)))
      ((> i y) result)))


Getting all likes from a specific user on a news wall with fewer graph API calls

Interesting / fun question.

I don't think there is much to improve there to reduce the API call count.

From a once over, these are some things you might want to look at:

forEach is still slower than the good old for loop, not sure that matters for you.
Don't use console.log in production code
Don't keep commented out code in production code
Does it make sense to keep comparing to my_user_id if you already found a match ? It is not like you could like the same post twice ? (One more (better) argument to not use forEach here)
my_user_id -> myUserId -> id , always apply lowerCamelCase plus keep it simple

Not relevant after comment

You say you are using the likes edge in your comment, so you might want to mention that in your example ex: url = /123/posts/likes ?
If post.likes is not set while using the likes edge, then something serious is going on , consider an early 'return callback(count);`
Same thing for if (response.data)


When you are looping over the keys a and values elements[a] of a dictionary, use the items method to loop over both at the same time:

for a, value in elements.items():
    for (b, c), d in value:

(If I knew what these values represented, I would pick a better name than value.)
The code here doesn't use the keys, it only uses the values. So use the values method instead:

for value in elements.values():
    for (b, c), d in value:

The code doesn't use b or d either. It is conventional to use the name _ for unused variables:

for (_, c), _ in value:

A double iteration over some lists and then over the elements of those lists can be combined into a single iteration using itertools.chain.from_iterable:

from itertools import chain
for (_, c), _ in chain.from_iterable(elements.values()):

The repeated calls to max can become a single call taking a generator expression:

values = chain.from_iterable(elements.values())
max_abs_c = max(abs(c) for (_, c), _ in values)

It's common to worry whether code is "Pythonic" but it is better to think in terms of general principles (clarity, simplicity, maintainability, testability, usability, efficiency, etc.) that apply to code in any language.


Decrease execution time in updating rows in PHP

You can replace the outer loop with a simple test:

if (array_key_exists($row2['person'], $array)) {
    $value = $array[$row2['person']];
}

Next, the inner loop can be replaced with a single merge:

$row2 = array_merge($row2, $value);

After some small refactorings, the code would look like this:

while ($row2 = pg_fetch_assoc($result2))
{
    if (array_key_exists($row2['person'], $array)) {
        fputcsv($fp, array_merge($row2, $array[$row2['person']]));
    }
}


How about this?

mac_address = mac_address[19:].translate(str.maketrans("", "", "\n':")).strip()


Mysql multiple queries from one PHP file

I can't say how the queries should be built for the other 7 that you haven't posted, but I think I've identified enough commonalities in your design intent to exercise the D.R.Y. principle.

While it is always best to minimize total calls to the database, it seems you are struggling to package all of the queries into one.  I'll suggest implementing mysqli_multi_query() for your case with the noticeable benefit being maintainability.  I am assuming that your $datefilter value is 100% validated/secure and is safe to place into your queries (versus being a raw user input).  I should also note that if any of your queries experience a syntax error, the loop will break, the html table will close early, and you will see details about the erring query.

The following method can be modified to allow blank rows and/or group headings withing the html table -- just write that portion between the do{ and if($result... lines.

Untested Code:

// $datefilter MUST be validated/trustworthy as prepared statements are not in use.
$queries['KickOff']="SELECT actualstart AS `Time`,League,'KO' AS Label,HomeTeam,AwayTeam FROM livescores WHERE actualstart>='$datefilter'";
$queries['HalfTime']="SELECT actualhalftime AS `Time`,League,'HT' AS Label,HomeTeam,AwayTeam FROM livescores WHERE actualhalftime>='$datefilter'";
$queries['Fulltime']="SELECT actualft AS `Time`,League,'FT' AS Label,HomeTeam,AwayTeam FROM livescores WHERE actualft>='$datefilter'";
// ... ~7 more queries entries here

echo "
";
if(mysqli_multi_query($mysqli,implode(';',$queries))){
    do{
        if($result=mysqli_store_result($mysqli)){
            while($row=mysqli_fetch_assoc($result)){
                echo "
{$row['Time']}	{$row['League']}	{$row['Label}	{$row['HomeTeam']} v {$row['AwayTeam']}
";
            }
            mysqli_free_result($result);
        }
    } while(next($queries) && mysqli_more_results($mysqli) && mysqli_next_result($mysqli));
}
echo "
";
if($mysqli_error=mysqli_error($mysqli)){
    echo "
Error occurred on ",key($queries);
    // echo " Query: ",current($queries),"Syntax Error:
$mysqli_error
";  // developer-only details
    echo "
";
}

A link to my previous work that I am leveraging for this answer.


Playing a sound depending on the currently displayed flash card image

You shouldn't determine the sound to play from the image displayed.  Instead you should use the same piece of information to set both the image name and the sound path.

Create a property of your ViewController to keep track of the card number that is being displayed:

var displayedCard = 1

and set it whenever you assign a new image to the imageView:

// if the tapped view is a UIImageView then set it to imageview
if (gesture.view as? UIImageView) != nil {
    if segControl.selectedSegmentIndex == 0 && segControl2.selectedSegmentIndex == 0 {
        imageView.image = UIImage(named: "card\(number)")
        displayedCard = number
        number = number % 26 + 1
    }
    else if segControl.selectedSegmentIndex == 0 && segControl2.selectedSegmentIndex == 1 {
        imageView.image = UIImage(named: "upper\(number)")
        displayedCard = number
        number = number % 26 + 1
    }

Then use it to create the String you pass to URL(fileWithPath:):

// create the soundPath using displayedCard
let letter = String(UnicodeScalar(96 + displayedCard)!)
let soundPath = Bundle.main.path(forResource: "\(letter)Sound.m4a", ofType:nil)!

do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: soundPath))
    audioPlayer.play()
} catch {
    print("Couldn't load sound file")
}


First, since you are concerned about naming: this class doesn't really handle, manage, or control anything.  It does two things: queries a database, and makes those results available via a TryGet interface.  In fact, you could split it into two classes, LocaleLoader and Locale.  Though I wonder if "locale" is even the correct term since there is no locale supplied (like "en-us"), it's more of a string table.  On the topic of naming, "_localeKeyValue" is not very good; it describes the implementation and not the purpose.  Something like "Strings" would be better.  Even "_localeDict" would be an improvement.

As noted in the comments, the ConcurrentDictionary is unnecessary; Dictionary supports concurrent readers as long as there are no writers.  In your case, all reading occurs after all writing.

@paparazzo is right about checking for no results being unnecessary.  The result is the same, it's no faster, and it's more code.

Consider allowing the constructor to be passed in a database connection to use.  This makes it more flexible and removes a dependency.

TryGetLocale: are you really getting a locale?  I think you are getting a string, translation, or localization.  Without seeing how this code is used, I question the usefulness of the TryGet-style interface.  For (what I imagine to be) my similar code, I like to just return the key if it's not found.  Something like:

public String GetString(String key)
{
    String value;
    return _localeKeyValue.TryGetValue(key, out value) ? value : key;
}

This means that when the code encounters an untranslated string it's obvious to the devs and testers what is missing.  The other possibility would be to throw an exception when you can't find the key, but on the off-chance that you ship software with a missing string it's better for the user to see a message box like "IMG_CONVERSION_JPEG_SUCCESS" than "Illegal argument: key".


Use case of nesting an enum into a struct

In my opinion nothing indicate the use of enum.
According to my understanding your object provides the following functionalities from consumer perspective:

Provide two factory methods one for Ascending and another for Descending
Provide custom string representation (abbreviation) for these

From the public interface point of view the following implementation is equivalent with yours
public struct OrderDirection
{
    private readonly string _direction;
    private OrderDirection(string direction)
    {
        _direction = direction;
    }

    public override string ToString() => _direction;

    public static OrderDirection Ascending = new OrderDirection("asc");
    public static OrderDirection Descending = new OrderDirection("desc");
}


How could I have approached this responsive image gallery differently?

The most important bit here is the resize handler, since it fires many times per scroll.

//Run on document ready
$(function () {

    // Cache the slider jQuery object
    var slider = $('#slider');

    // Pass in the existing reference. Explanation after the code
    activateSlider(slider);

    // Move out the debouncing function outside the resize handler
    // so that the function isn't recreated on every risize call
    function debounceAction() {
        activateSearch();

        //Personal preference. The "early return" looks better since
        // it avoids any additional indention
        if (!slider.length) return;

        slider.delay(700).animate({opacity: 1}, 500);

    }

    // Since you use jQuery, use it to abstract the resize function instead.
    $(window).on('resize', function () {
        // And all the handler's got to do is call debounce
        debounce(debounceAction, 250);
    });
});

As for your activateSlider, you should cache the fetched DOM elements into variables and reuse them when necessary. Each time you do something like $('.slider'), it looks for elements with class slider. Caching them avoids this searching. I have already done it with $('#slider') by fetching it once, and passing it into activateSlider.