All in all there is not much to comment. I like the iterative mechanism with the stack. Trying other collections (linked list, dictionary, hashset etc.) doesn't seem to improve the performance.

One could argue that it would be nice to have the partition part in a dedicated function to improve readability, but again the algorithm isn't that hard to understand.

The really improvement of performance comes from the use of InsertionSort() when the range is smaller than 31 - and that magic number seems to be the right limit. And Insertion Sort seems to be the right choice over other simple algorithms like Selection Sort.

The performance gain from SampleMedian() is little or absent for smaller data sets, but is significant for larger (> 10000) - compared to let it return values[startIndex] or values[startIndex + (endIndex - startIndex) / 2].

All in all a well designed algorithm optimized in respect to performance.

A minor thing in SampleMedian():

I don't like:

if (0 > comparer.Compare(values[right], values[left]))

but rather:

if (comparer.Compare(values[right], values[left]) < 0)

but that's a matter of habit.

Of course you should check if the arguments are valid (values != null, startIndex < endIndex etc.)


Some ideas:

is_prime_number doesn't scale well when dealing with bigger primes - the range of odd numbers 3..sqrt(number) is going to get very big. You'd be better off implementing a more sophisticated algorithm such as Eratosthenes' Sieve, where the cost of checking primality of subsequent primes grows slower.
sum_prime_factors duplicates the implementation of primality checking from is_prime_number.
[print_output(item, 1) for item in map(int, sys.stdin) if item != 4] is awkward. I would use a main method and any of the common

if __name__ == '__main__':
    main()

patterns for making the code reusable and testable.


Rolling mean lag function for multiple variables

Answering my own question here, but certainly open to suggestions.

library(RcppRoll)

# Loop through n = 10
for (i in 1:10){

  # Create custom col labels
  lab1 <- paste0("x_", i)
  lab2 <- paste0("x2_", i)
  lab3 <- paste0("x3_", i)

  # Loop through each fips and calculate rollingmean
  dat <- dat %>%
      group_by(fips) %>%
      mutate(!!lab1 := roll_mean(x, i, align = "left", fill = "NA"),
             !!lab2 := roll_mean(x2, i, align = "left", fill = "NA"),
             !!lab3 := roll_mean(x3, i, align = "left", fill = "NA")) %>%
    ungroup()

  # Progress bar for loop
  print(i)
}

> names(dat)
 [1] "fips"  "x"     "x2"    "x3"    "x_1"   "x2_1"  "x3_1"  "x_2"   "x2_2"  "x3_2"  "x_3"   "x2_3"
[13] "x3_3"  "x_4"   "x2_4"  "x3_4"  "x_5"   "x2_5"  "x3_5"  "x_6"   "x2_6"  "x3_6"  "x_7"   "x2_7"
[25] "x3_7"  "x_8"   "x2_8"  "x3_8"  "x_9"   "x2_9"  "x3_9"  "x_10"  "x2_10" "x3_10"


a Python script to format plain text to markdown title

iterator

There is no need for the intermediate list, just iterate over the text file line per line, and write the parsed line to the output file

variable name

f_name those 3 characters will not make writing or executing the code any slower, but writing it in full can help you understand the code later one

re.compile

You can compile the regular expression

For extra points, you can also name the groups:

re_pattern_chapter = re.compile(r"^(?P<chapter>\d{1,2})(?P<text> +.*?)")
re_pattern_out = r"# chapter(?P=chapter):(?P=text)"

import re

file_name_in = "data_multi_lines.txt"
file_name_out = "your_file.md"

re_pattern_chapter = re.compile(r"^(?P<chapter>\d{1,2})(?P<text> +.*?)")
re_pattern_out = r"# chapter(?P=chapter):(?P=text)"

with open(file_name_in, "r") as file_in, open(file_name_out, "w") as file_out:
    for line in file_name_in:
        line_parsed = re_pattern_chapter.sub(re_pattern_out, line)
        file_out.write(line_parsed)


Generic Template implementation of merge sort in C++

Well, it's a bit curious to indent after template<...>, but at least you are consistent there.

In merge() I would mark the only variable const.

In mergesort() I would make both variables const auto. There's no reason to make them references.

And I would change the initialization of mid so mutable forward-iterators are good enough. In addition, you only really need to refer to size once, though I expect any half-way useable compiler to optimize it appropriately.

const auto mid = std::next(first, (size + 1) / 2);

Be aware that if you have random-access-iterators and first / mid are generally only moved a relatively small amount in merge each iteration, std::find_if (O(n)) would beat std::upper_boud (O(log(n))). Not that it matters, your in-place-merge will be quadratic in that case anyway.


Review

I see no reason not to seal this class. No need for virtual methods.
You prefer readability over argument checks: Comparer.Equals(Text, other.Text)
I would make != the opposite of == as blackbox:  !(left == right);
If you want to be a bit more resilient to unicode shenanigans, you should do text.Normalize(); (á is not always á, unless you normalize)


Copying a Dictionary and Replace its Values

Why an inherited class?

I don't see anything about this problem that requires an inherited class. strip could just as easily be a free function:

def strip(dct, value=None):
    ...

Also strip isn't a particularly good name - it doesn't really resemble the str.strip() function. I don't know what a better one would be though:

Callable

If you're going to allow passing an arbitrary function, then I think you may as well pass the full value instead of just the length. If the caller wants the length, the caller can use len at that end. This'll enhance all the things you can do.

Also, in Python, EAFP: it's easier to ask for forgiveness than permission. Just try to use the callable as a callable and catch the TypeError:

def strip(dct, value=None):
    try:
        tmp = dict.fromkeys(dct.keys())
        for k,v in dct.items():
            tmp[k] = value(v)
        return tmp
    except TypeError:
        return dict.fromkeys(dct.keys(), value)

Dictionary comprehension

For the except case - fromkeys() makes sense. But in the callable case, not really. You're creating a new dictionary and then re-modifying it. Better to just create the correct dictionary up front:

def strip(dct, value=None):
    try:
        return {k: value(v)
            for k,v in dct.items()
            }
    except TypeError:
        return dict.fromkeys(dct.keys(), value)


Writing utility classes is hard enough without reinventing everything from scratch each time. Whenever possible, class authors should take advantage of available tools. In this case, Scala has a trait for ordering objects in a collection: scala.math.Ordering and it should be used for the compareFunction which will undoubtedly require some adjustment of the code.

For the most part, the code is well laid out and easy to follow. Good job! Note that standard indentation for Scala code is two spaces. It's hard to tell if the four space indentation is what is used in the code, or if it was an artifact of transferring the code into this question.

While Scala pattern matching is a great tool, it is possible to over user it. I think that using it in the pop method is not just overkill, but also results in code that is harder to read. I would write it like this:

def pop: Option[T] =  match {
  if (heapRepresentation.isEmpty) None
  else {
    val firstValue = heapRepresentation(0)
    if (heapRepresentation.size == 1) {
       heapRepresentation.remove(0)
    }
    else {
      swap(0, lastIndex)
      heapRepresentation.remove(lastIndex)
      bubbleDown(0)
    }
    Some(firstValue)
  }
}


Dynamically mess images inside a container

I think your code is good and more importantly it works. The main thing I would change is that huge if else statement. You repeat yourself a lot there. Here's another way you could do it:

Also here's your edited fiddle.

Acho que o seu trabalho está bom e mais importante ele funciona. A parte que chama minha atenção é o if/else enorme. Você se repete muito ali. Outra forma que você pode fazer é assim:

if(type === 1){
    //You had these every time, so you can declare them once here.
    //Você declara isso em todos os casos, mas só precisa fazer uma vez aqui.
    topFt = { "from" : 1, "to" : ftBottom };
    transFt  = { "from" : 1,  "to" : 30 };

    //I Took out all the repetitions and left the cases where we actually change something.
    //Tirei todos os casos em que você estava se repetindo e deixei somente os que realmente estão mudando algo.
    switch(index){
        case 0:
            maxIndex = getNumImg;
            break;
        case 1:
            leftFt   = { "from" : 30, "to" : 40 }
            break;
        case 2: //If index === 2
        case 3: //OR if index === 3
            leftFt   = { "from" : -30,  "to" : -40 }
            break;
        case 5:
            leftFt   = { "from" : 40,  "to" : 50 }
            break;
        //Add more cases if you want/need to.
        //Adicione mais casos aqui se precisar.
        default:
            break;
    }
}


An algorithm that finds a sequence of numbers to fill a square grid

While not a complete solution for your first example, you can do two things to help speed it up.

If you don't have to use an array of values, don't just use a min and max (though the code doesn't change much if you do use a range).

You also don't need the third for-loop. Your third number will always be target - x - y. If target isn't in the range, you can throw it away.

You can further limit your for loop because you don't need to go all the way through every number in both loops. Since you know that you can't have 2 numbers which are both greater than half of your target, you can go through just the first part in the first loop, and the second loop through the second part. This lets you trim off a good bit from your for loops.

I also ended up using it as a string for this part, since it makes the check for uniqueness a bit easier, though it's not strictly necessary. My reduce also ensures no double digits.

const min = 1;
const max = 8;
const target = 12;

const allCombinations = (target, min, max) => {
  const combos = [];
  for (let i = min; i <= target / 2 && i <= max; i++) {
    for (let j = max; j >= target / 2 && i >= min && target - i - j >= min; j--) {
      combos.push([i, j, target - i - j].sort().join(''));
    }
  }

  return combos
    .reduce((result, a) => result.concat(!result.includes(a) && a[0] !== a[1] && a[1] !== a[2] && a[2] !== a[0] ? a : []), []);
};

console.log(allCombinations(target, min, max));


Optimize/ refactor program that highlights differences between two text collections

Since you're using WPF, you should really consider implementing MVVM.

Wouldn't Environment.Newline be better than "\r\n"?

Also, why do you add the new line at those times? That way you're intorducing several points where you could forget to do so. Wouldn't it be better to apply this only in AssignTextToTextBox(), e.g. Text = text + Environment.Newline?

Comments should explain why something was implemented in that way, not what the code is doing. For example: //If lines aren't the same, apply brush doesn't tell me anything the code isn't showing me already. If you need comments to explain what your code does, it's a sign you need to re-write the code.

I don't particularly see the point of text1Length and text2Length, just use text1.Count and text2.Count directly. But more importantly, why are you using StringCollection when List<string> is available?

If you apply these changes, I think your logic can be reduced to this:

var maximum = (list1.Count > list2.Count) ? list1.Count : list2.Count;

for (var i = 0; i < maximum; i++)
{
    var text1Line = (i >= list1.Count) ? string.Empty : list1[i];
    var text2Line = (i >= list2.Count) ? string.Empty : list2[i];

    var applicableBbrushColour = (text1Line == text2Line) ? null : brushColour;

    AssignTextToTextBox(richTextBox1, text1Line, applicableBbrushColour);
    AssignTextToTextBox(richTextBox2, text2Line, applicableBbrushColour);
}

You could even move (i >= list1.Count) ? string.Empty : list1[i]; to a separate method, considering this logic is repeated; perhaps even to an extension method?


Find the first missing positive integer in an array of integers

Instead of

if (res.isPresent()) {
    return res.getAsInt()+1;
}

return inputArray.length+1;

you could make use of the orElse method of OptionalInt:

return res.orElse(inputArray.length) + 1;


Without getting into why you designed your business logic this way (I would've made Pars a separate class or struct, to accommodate the complexity), I guess this is somewhat a decent approach.

By using an IComparer<T>, you can implement whatever logic you need, thus separating the concern of sorting Pars into its own place.

I've used a predefined list of characters (in C#, the simplest list of char is string, but you can use any type that has an IndexOf method) in order to have a single, distinct source of truth for the order of the chars that can be easily modified without breaking anything. I've named it PairOrder for lack of a better name, feel free to name it whatever you like.

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
  public static void Main()
  {
    var data = new[] {
      new Result { Score = 110, Pars = "3C" },
      new Result { Score = -200, Pars = "4Hx" },
      new Result { Score = -100, Pars = "3Hx" },
      new Result { Score = -100, Pars = "3Sx" },
      new Result { Score = 400, Pars = "3N" }
    };

    var sortedByScore = data.OrderBy(item => item.Score)
      .ThenBy(item => item.Pars, new ParsComparer());

    Console.WriteLine("Sorting by Score first");
    foreach (var item in sortedByScore)
    {
      Console.WriteLine(item);
    }

    var sortedByPars = data.OrderBy(item => item.Pars, new ParsComparer())
      .ThenBy(item => item.Score);

    Console.WriteLine("\nSorting by Pars first");
    foreach (var item in sortedByPars)
    {
      Console.WriteLine(item);
    }
  }
}

public class Result
{
  public int Score { get; set; }
  public string Pars { get; set; }

  public override string ToString()
  {
    return string.Format("Score: {0}; Pars: {1}", Score, Pars);
  }
}

public class ParsComparer : IComparer<string>
{
  private string ParsOrder = "CDHSN";

  public int Compare(string a, string b)
  {
    var delta = a[0].CompareTo(b[0]);

    if (delta == 0)
    {
      var indexA = ParsOrder.IndexOf(a[1]);
      var indexB = ParsOrder.IndexOf(b[1]);

      delta = indexA.CompareTo(indexB);
    }

    return delta;
  }
}

The output is what you expected:

Sorting by Score first
Score: -200; Pars: 4Hx
Score: -100; Pars: 3Hx
Score: -100; Pars: 3Sx
Score: 110; Pars: 3C
Score: 400; Pars: 3N

Sorting by Pars first
Score: 110; Pars: 3C
Score: -100; Pars: 3Hx
Score: -100; Pars: 3Sx
Score: 400; Pars: 3N
Score: -200; Pars: 4Hx

Disclaimer: it's been a while since I've written any significant C# code. There are probably better ways to write and organize this code.

I also don't make any promises regarding performance. I don't think you'll have any issues, but the IndexOf lookup might introduce a bottleneck, specially if the list of chars gets too big.


Loose coupling, accessing class properties

As DataRow does not implement IDataRecord, you would have to pass an adapter that wraps the row and implements the interface. Also, passing an IListSource would only help if it always returned a ITypedList (which is not guaranteed) which you could then query for available properties by name. But what would be the advantage of all that?

In my opinion, the parameter types are alright. We are still talking about a private helper method, not one that needs to be accessible using all kinds of interfaces. There are, however, some things that I might change:

Either: Rename the method to represent that it actually does not care about the legal first name. You could currently rename it to ContainsLegalLastName without any change in behaviour.
Or: Remove the legalFirstNameColumn and get that value from somewhere else (some configuration, const, …).

Unless you decide to remove the column name parameter and get the column name from an instance variable, make the method static. It currently does not use any state at all.


Most importantly, use slices to your advantage. You do not need high and low arguments, as a slice can represent a part of a slice. For example, instead of quickSort(a, low, p - 1) you could write quickSort(a[low:p]).

Swapping can be written much more elegantly with multiple assignment: a, b = b, a

Use fmt.Printfln instead of fmt.Print("Array: ", slice, "\n"). Once you have learned printf, it is almost always clearer than concatenating strings. In this simple case fmt.Println would be appropriate as well, though.

Other than that the code is clean. It seems you have used gofmt and using int instead of uint for indices is the correct choice. (Uint should only be used where absolutely needed, because it is inconvenient and error-prone to calculate with.)


This is pretty good, but there are a few things that needed to be improved. Here are a few of those things, specifically regarding your, odd, design.

Using % for string formatting is deprecated. To format strings, you should use str.format. For example, you'd do this: print 'Best out of {0}'.format(turn).
Your naming is, strange. For example, I'd rename args to possible_moves. Good variable names should reflect the purpose of the variable.
The way you've designed this is odd. I'd reccomend an object-oriented-design. with a Game class with certain methods and attributes to manage a game. A few things that I'd reccomend implementing would be:

A total_turns attribute which would allow there to be a custom amount of turns.
A Game.pick_move to choose a random choice.

That's about all I can think of for improvement. If there's anything that you want me to comment on, just tell me about it. I hope this helps!


Obviously, every third Fibonacci number is even, and the rest of them are odd. Less obviously (but trivially follows from, say, Binet's formula), they satisfy another linear recurrence:

\$F_{3(n+1)} = 4 F_{3n} + F_{3(n-1)}\$

Using this fact, you may cut the execution time threefold.


Here are some improvements that can be done

Move the


def return_gmail_user(email):

Return isn't a very descriptive word to use as the beginning  of a function name. Call it parse_gmail_user or something along those lines instead.

    username = email.split('@')[0]
    domain = email.split('@')[1]

Read up about sequence unpacking. There's no need to use indices directly, just assign the result of the split operation directly to both variables.

    valid_email_char = '[\w\d\.]+'
    # check if email is of gmail
    if domain != 'gmail.com':

The comment is redundant, it adds nothing to the code — remove it.

        return False

It would be more Pythonic to raise an exception instead of returning False.

    # get username
    m = re.match(valid_email_char, username)

Give m a descriptive name, such as valid_user, making the code more fluent.

    if m:

You could combine the two if statements to fail early if an incorrect value is given for email.

        username = m.group(0)

group retrieves the first group by default, no need to supply 0.

        #print username

This comment is probably a remnant from testing; commented-out code should be removed immediately as it adds clutter and serves only to confuse.

        return "".join(username.split('.'))

replace('.', '') would be a more descriptive option of achieving the above.

    return False

Following my suggestions, you could arrive the below solution.
Note that the semantics are insignificantly different (the match is performed regardless of the validity of the domain), but readability and simplicity is substantially better.

def return_gmail_user(email):
    user, domain = email.split('@')
    valid_user = re.match('[\w\d\.]+', user)
    if domain != 'gmail.com' or not valid_user:
        raise ValueError('invalid gmail address: ' + email)
    return valid_user.group().replace('.', '')


Selenium Framework using a lot of statics

if(failMessageContainer.isDisplayed()){
            return true;
        }
        else return false;

Why not simply return failMessageContainer.isDisplayed()?

@Test(priority = 0)
public void loginfail() {
    LoginPage.goTo("http://127.0.0.1:8080/login");
    LoginPage.loginAs("wrong username", "wrongpassword");
    boolean didLoginFail = LoginPage.loginErrorDisplayed();
    Assert.assertTrue(didLoginFail == true, "Bad login was successful");
    if (didLoginFail){
        LoginPage.getLoginErrorMessage();
    }
}

What about Assert.assertTrue((((didLoginFail == true) == true) == true, ...). I mean, if writing a==true was better than a, then doing it more often must be even better.

The following if is superfluous, the getLoginErrorMessage doesn't get used.

  I've noticed that I am writing a lot of statics so that the tester doesn't have to instantiate the page objects and methods every time.

I'd start by dropping all the static modifiers and making it fluent. With a proper API the tester will happily do the instantiation as it leads them to what they want to do.

I don't find something like

public void loginfail() {
    LoginPage loginPage = new LoginPage()
        .goTo("http://127.0.0.1:8080/login")
        .loginAs("wrong username", "wrongpassword");
    Assert.assertTrue(loginPage.loginErrorDisplayed());
    Assert.assertTrue(loginPage.getLoginErrorMessage().contains("WTF?"));
}

harder to use than the static version. You could provide even more, but this is most probably not worth the effort (you'd sort of do the tester's job by providing fluent versions of all asserts they may need; this goes too far, but might be useful for the most commonly used assertions):

public void loginfail() {
    LoginPage loginPage = new LoginPage()
        .goTo("http://127.0.0.1:8080/login")
        .loginAs("wrong username", "wrongpassword")
        .assertThatLoginErrorDisplayed()
        .assertThatLoginErrorMessageContains("WTF?");
}


Count the number of riders in each category

Set membership
valid_clubs = []
with open("validclubs.txt") as f:
    for line in f:
        valid_clubs.append(line)

should be
with open("validclubs.txt") as f:
    valid_clubs = {line.strip() for line in f}

Lines coming back from a file handle in Python include their line ending, which you have to strip yourself; and you should be using a set, not a list. Set membership lookups will be much faster than list lookups.
Consider DictReader
The csv module has a reader that gives you back a dictionary based on the headings, so that you do not have to write row[0], but rather row['Category'].
Use Counter
Your list of category ifs can be condensed to a one-liner; read about Counter. This will be easier to use and perform better.
Empty rows
Based on # ignore errors where row is empty, this should be done up-front. Rather than hitting your face on an IndexError and having to ignore it, simply check for an empty row:
if row:


void op(parser::info &lhs,parser::info &rhs,parser::info &r,const std::string &op){

I think I'd prefer a more descriptive name than r here. I'm guessing it's intended to stand for "result", in which case I think I'd prefer to just name it result.

  peg::grammar math("Math");

  math << "Math" << "Set | Expression" << parserTools::show("%v0\n");

It's not immediately clear why you specify Math both when you create the grammar object and when you specify rules. I think the second is naming the top-level rule Math, but it's not clear what the parameter to the constructor accomplishes.

  math << "Set" << "Variable '=' Sum" << set << parserTools::pass(1);

At least without some documentation on your parserTools, the meaning of the pass(1) isn't immediately obvious. Presumably this is (at least roughly equivalent to) a semantic rule that's executed when the associated pattern is matched. I can think of a couple of different things pass(1) might be intended to mean, but lac, context to even guess at which is likely to be accurate. Sufficient study of your documentation would undoubtedly make the meaning clear, but it wasn't immediately obvious.

This is kind of a difficult situation: you're basically defining an EDSL, which means understanding the code pretty much requires learning the language you've defined. In other words, no matter how carefully or well written the code is, it's likely to be at least somewhat difficult to understand in isolation.

Summary: looking at the code in isolation, the grammar rules are highly readable, but the (presumed) associated actions much less so.

math << "Exponent" << "Atomic   ('^'  Atomic  )*" << parserTools::leftbinary(op);

At first glance, I'd have assumed that leftbinary was intended to signify a left-associative binary operator--but exponentiation is normally right-associative. I'm left uncertain whether:

it's a bug,
you intentionally changed it from right- to left-associative, or
I've completely misinterpreted what leftbinary really means.

  while (1) {
    std::string str;
    IO << "> " >> str << str << " -> ";

I have mixed feelings about this mixture of input and output in the same expression. It does lead to relatively terse code, but requires unusual care in reading to keep track of which parts are input vs. output.

Ultimately, I think it would probably be better to review the parser generator and the IO library separately. Here I'm really concentrating on the parser generator, but the design if the I/O library might well be worth examination and review in its own right.


Rewriting this function to use `promises` instead of `async: false`

I don't know Parse() myself, but this should show you the general idea for using promises with jQuery Ajax:

function accountCreation(){
    var user = Parse.User.current(); // get the currently logged in user object

    // loop through each image element
    var promises = $('.images').map(function(index, element) {
        var src = $(element).attr('src');
        return $.ajax({
            type: "POST",
            url: "encodeImgToBase64.php", // you may need to adjust this path depending on where you store the file in relation to this file
            data: 'url='+src,
        });
    });
    $.when.apply($, promises).then(function() {
        // arguments[0][0] is first result
        // arguments[1][0] is second result and so on
        for (var i = 0; i < arguments.length; i++) {
            var file = new Parse.File("photo.jpg", { base64: arguments[i][0] }); // this part actually saves the image file to parse
            user.set("image" + i, file); // set this image to the corosponding column on our object
        }
        // save the user object
        user.save(null,{
          success: function(user) {
              // do success stuff...
          },
          error: function(user, error) {
              // do fail stuff...
          }
        });
    });
 }

Here's a description of how the code works:

$('.images').map() cycles through all the images, calling a custom function for each item.  The return value from the custom callback is added to an array and the final result of the .map() call is an array of all the returned values.

return $.ajax() returns from the .map() callback, the promise that $.ajax() returns.  So, when the .map() is done, it will have an array of ajax promises.

$.when.apply($, promises) passes the array of promises to $.when() which then waits until all the promises are resolved (e.g. all the ajax calls have completed) before calling the .then() handler.

In the .then() handler, the results of all the ajax calls are passed as arguments.  Each argument is an array of length three.  [0] in each array is the returned data from the ajax call.  [1] is the status from the ajax call, [2] is the jqXHR object from the ajax call.  In this case, you just need [0] because we already know the status.

So, then .then() handler cycles through all the arguments object passed to the .then() handler with one array passed as an argument for each ajax call that was executed and the [0] in each of those arrays is the ajax result.

Then, after processing all the ajax results, user.save() is called.

FYI, when looking at the Parse documentation, user.save() looks like it also returns a promise and new Parse.File() looks like it has a .save() method (not sure if that needs to be called).


Clarification (OK)
After update of your question, it has gotten clear that:

you work on a DAG, which includes a Tree
both your strategies DFS and BFS are in Pre-Order

=> original answer requesting clarification from the OP
Review Definitions
Before being able to review your code, I would like to review your definitions. Perhaps you should clarify your algorithm with examples.

I believe this code prints both the DFS and BFS of a directed graph.

How do you decide the breadth level of a node when it has multiple parents? Or would you only work with Tree instead of DAG?

As a reminder of the difference:
DFS (Depth first search) starts with a given node and explores the
first unexplored node it comes across before returning to itself again
and exploring its remaining nodes (e.g: if the parent node 1 has 2
children 2, 3 the DFS method will explore 2 and its children nodes
before exploring 3

Because you say to explore remaining nodes before returning to self, you are not very clear whether the order is A or B.

(A) 1 -> 2 -> 3
(B) 2 -> 3 -> 1

BFS (Breadth first search) works down a tree in a top-to-bottom manner
(e.g: a graph with parent 1 and children 2, 3 will print level 1 first
(1) then level 2 (2, 3) and then level 3 (the children of nodes 2 and
3)

The order is independant of search strategy (DFS/BFS). BFS can be both top-to-bottom or bottom-to-top.

Terminology

DFS: process each child completely before processing the next child
BFS: process each level across childs before processing the next level
Pre-Order: process self before rest of tree
Post-Order: process rest of tree before self

In your example of parent 1 having child 2 and child 3:

DFS Pre-Order: 1 -> 2 -> 3
DFS Post-Order: 2 -> 3 -> 1
BFS Pre-Order: 1 -> 2 -> 3
BFS Post-Order: 2 -> 3 -> 1

Suppose 2 would have its own child 4:

DFS Pre-Order: 1 -> 2 -> 4 -> 3
DFS Post-Order: 4 -> 2 -> 3 -> 1
BFS Pre-Order: 1 -> 2 -> 3 -> 4
BFS Post-Order: 4 -> 2 -> 3 -> 1

You could even add a third dimension direction in which case we distinguish left-to-right and right-to-left.


When i started the game, i found it pretty confusing as to what what coordinates should we input. I added an instructions method:

    @classmethod
    def __instructions(cls):
        print(
            'Welcome to TicTacToe\n'
            'Here is the board:\n'
            )
        cls.__display()
        print(
            'The coordinates start at top left\n'
            '(1, 1) (2, 1) (3, 1)\n'
            '(1, 2) (2, 2) (3, 2)\n'
            '(1, 3) (2, 3)  (3, 3)\n'
            )

I found having 0, 1, 2 on the board is pretty confusing. I replaced empty cells with a symbol, in this case -

    @classmethod
    def __display(cls):
        """Displays current game state."""
        for line in cls.__game_matrix:
            symbols = []
            for elem in line:
                if elem == 0:
                    symbols.append('-')
                else:
                    symbols.append(str(elem))
            print(' '.join(symbols))

I rearraged private methods before

I added a win annoncement to know who won:

print("Game finished: Player {} won!".format(player))

If you used a normal class you would not have needed

@classmethod
def __game_finished(cls):

but would have used the normal
def __game_finished(self):

less writing

Here is my code:
class TicTacToe:
    """Plays a 2-player TicTacToe Game."""

    __curr_player = False  # simple bool player switch
    __game_matrix = [  # representation of game state
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
    ]

    @classmethod
    def __game_finished(cls):
        """Returns True if one player has won or all fields are filled."""
        # all filled?
        if all([value for line in cls.__game_matrix for value in line]):
            return True
        # horizontal win?
        if any(all([x == line[0] and x for x in line]) for line in cls.__game_matrix):
            return True
        # vertical win?
        if any(all([line[column] == cls.__game_matrix[0][column] and line[column] for line in cls.__game_matrix]) for column in range(3)):
            return True
        # diagonal win?
        if (cls.__game_matrix[0][0] == cls.__game_matrix[1][1] == cls.__game_matrix[2][2] != 0) or \
           (cls.__game_matrix[0][2] == cls.__game_matrix[1][1] == cls.__game_matrix[2][0] != 0):
            return True
        return False

    @classmethod
    def __is_valid_field(cls, x, y):
        """Checks if field is already filled or out of range."""
        if x > 3 or x < 1 or y > 3 or y < 1:
            return False
        return not cls.__game_matrix[y - 1][x - 1]

    @classmethod
    def __update(cls, x, y, player):
        """Update game state."""
        cls.__game_matrix[y - 1][x - 1] = player

    @classmethod
    def __display(cls):
        """Displays current game state."""
        for line in cls.__game_matrix:
            symbols = []
            for elem in line:
                if elem == 0:
                    symbols.append('-')
                else:
                    symbols.append(str(elem))
            print(' '.join(symbols))

    @classmethod
    def __reset(cls):
        """Reset game state."""
        cls.__curr_player = False
        cls.__game_matrix = [
            ['-', '-', '-'],
            ['-', '-', '-'],
            ['-', '-', '-'],
        ]

    @classmethod
    def __instructions(cls):
        print(
            'Welcome to TicTacToe\n'
            'Here is the board:\n'
            )
        cls.__display()
        print(
            'The coordinates start at top left\n'
            '(1, 1) (2, 1) (3, 1)\n'
            '(1, 2) (2, 2) (3, 2)\n'
            '(1, 3) (2, 3)  (3, 3)\n'
            )

    @classmethod
    def play(cls):
        cls.__instructions()
        """Play a single round."""
        while not cls.__game_finished():

            # set current player
            player = 2 if cls.__curr_player else 1

            # get player move
            while 1:
                try:
                    print(f"Player {player}'s turn.")
                    x = int(input("X: "))
                    y = int(input("Y: "))
                    if cls.__is_valid_field(x, y):
                        break
                    else:
                        print("Invalid field.")
                except ValueError:
                    print("Invalid Input.")

            cls.__update(x, y, player)
            print("Current game state: ")
            cls.__display()

            # change player
            cls.__curr_player = not cls.__curr_player

        print("Game finished: Player {} won!".format(player))
        cls.__display()

        # reset state
        cls.__reset()

def main():
    TicTacToe.play()

if __name__ == "__main__":
    main()

The code was well commented, broken down, easy to follow and clean!


First of all, there are many things in this code which you did right. Setting the proper error reporting mode is brilliant! And always setting the port explicitly is also a very good thing, saving you from many confusions, on Mac especially. Setting the charset is also often forgotten while being very important.
However, too many things are wrong as well - on the conceptual, technological and the implementation levels. To highlight the main problems:

if an error occurs, a web page should never return an OK signal. It should return an error signal instead. There is a thing called HTTP response code and your page should return different codes in different situations. In case of error it's 500, no 200 which your code currently returns.
with this code you just left yourself without the explanation, why the error occurred. The error message is invaluable source of information that could help you to fix the issue, but you are simply ditching it!
writing a dedicated code to handle every distinct error in your script is a waste. Or, to put the other way - why so much attention to the failed database connection? An include could fail as well. Just like there is no special error reporting code for the every include, there shouldn't be dedicated error reporting code for the DB connection as well. If every module would report its errors in its own manner the code would become a complete mess!
redirecting a user to the login page in case of error just makes no sense. What would they do there? An error page should stay where it is.
testing for the connection right after include is simply redundant. Can't your connection code already handle the failure? It can.
database credentials are hardcoded which makes the code less portable

To solve these problems you must separate the error handling from the rest of your code and make it uniform, providing equal treatment for all errors in your application, no matter in which module or in which situation they occur.
Reporting database errors
Do not report them
I do understand where it's coming from. Every [insert your favorite obscene emphasis word here] example on the Net tells you to test for the connection success. So people just habitually reproduce this behavior. Which - if you think of it - is a nonsense. A database error is no different from any other error. If your script says "Oh my, headers already sent!" you don't wrap a header() function call in a try catch. But for some reason a database connection is followed by this honor guard everywhere. Well, just drop this bad habit. Make your database errors equal to all other errors.
Reporting errors in general
I do also understand why the error reporting is so much confused: every PHP apprentice profusely confuses themselves with a site user. No wonder why: during the development, they are the only site user for the long time, and just cannot imagine other people working with the site. But if you just think of it, the difference become apparent - you just need to distinguish a programmer from a site user, as they both require the completely different treatment. A site user doesn't care whether your database connection failed or a hard disk went nuts. All they need to know is that something went wrong but you are already working on it. Then tell them exactly this.
On the other hand, when your site goes live, you don't sit behind every PC browsing your site. This means any specific error information you are displaying will go for naught. On a live site an error must be logged.
Setting the proper charset.
The older default for MySQL, utf8 charset implements only a limited subset of the original UTF-8 standard. Hence, for the full Unicode support, and to avoid "Incorrect string value" errors caused by a mere emoji, always use utf8mb4 charset.
Storing database credentials
Let's digress for a while from the main subject of error reporting and look at the database credentials. The present code is again the direct product of the "I am working alone on my home PC and it's going to be so forever" mindset. When the time comes, your site will go live. And a live site wold definitely have different credentials so you will need to rewrite them. And when you will need to work a bit more on the code, you will have to rewrite them back... and so on. Which is far from being convenient.
There are many advanced techniques for providing the settings but the simplest one would be just storing them in a separate file. This way you'll be able to keep different credentials files on different servers. So instead of hardcoding  the credentials, just use variables defined in a separate file:
<?php
$host = '127.0.0.1';
$port = 3306;
$db   = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

and then just include this file in your DB connection script
Implementing all the above.
In theory, given the connection shouldn't report errors by itself, only the following lines should be enough:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
require __DIR__.'/db_credentials.php';
$mysqli = new mysqli($host, $user, $pass, $db, $port);
$mysqli->set_charset($charset);
unset($host, $db, $user, $pass, $charset); // we don't need them anymore

It will raise an error that would be handled elsewhere.
But given we are employing exceptions here, and every exception contains a stack trace, and a stack trace contains every function parameter used, there is a slight chance that database credentials could be leaked. To prevent even such a small chance, it's better to catch the exception and then throw a brand new one, which will have no stack trace and hence no database credentials to leak:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
    require __DIR__.'/db_credentials.php';
    $mysqli = new mysqli($host, $user, $pass, $db, $port);
    $mysqli->set_charset($charset);
} catch (\mysqli_sql_exception $e) {
     throw new \mysqli_sql_exception($e->getMessage(), $e->getCode());
} finally {
    unset($host, $db, $user, $pass, $charset);
}

Now if an en error occurs, the exception will contain only the error message but not a stack trace. Note that stack traces are extremely helpful for debugging and here we are ditching it only as a tradeoff between the security and usability. But as a rule you should preserve as much debugging information as possible.
So this is it for the connection. What about error reporting in general?
Everything said above is a gist of my article on PHP error reporting, where I have a complete basic universal error handling solution. This code does everything what was said above: in case of error it sets the appropriate HTTP response code, and then changes its behavior depends on the user's type: for a site user it logs the error while showing only a generic text, but for a programmer it will show the error message on-screen.
I wouldn't copy the exact code here because it constantly gets improved over time and better to get the latest version.
How to actually use it?
Just have three files somewhere in your codebase, error_handler.php, mysqli.php, db_credentials.php. Then require the first two in your application.


Project Euler 19 (count Sundays in the 20th Century) with a while loop

Your logic is checking about Number of Days in Month, Leap year and related date logic.

Following snippet will work. This logic will loop thru the each month(1 to 12) with in 20th century and  and checks first day of month is Sunday or not.

      var result = 0;
        for(int year =  1901; year <= 2000; year++)
        {
            for(int month = 1;month<=12;month++)
            {
                if (new DateTime(year, month, 1).DayOfWeek == DayOfWeek.Sunday)
                    result++;
            }
        }
        Console.WriteLine(result);


Fetching specific foreign exchange rates from fixer using curl and jsconcpp in C++

These are C headers

#include <string.h>
#include <stdio.h>

You should probably use the C++ version (I hope you are not using C-String anywhere).

#include <strings>
#include <cstdio>

Header include paths

#include <jsoncpp/json/json.h>

This should probably be json/json.h and you should specify the location where jsoncpp is installed with compiler flags.

Curl is a C library.

Therefore any callbacks should be C functions (not C++ functions). There is no guarantee in the standard thay they use the same ABI.

static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)

Should be:

extern "C" size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)

Never use C-Casts

C casts are hard to spot (in general). But also using C++ casts you can mark dangerious casts by uisng the appropriate cast.

    ((std::string*)userp)->append((char*)contents, size * nmemb);

I would use reinterpret_cast<> here. So that it is easy to spot and you intuitively know that this is a dangerous operation.

reinterpret_cast<std::string*>(userp)->append(static_cast<char*>(contents), size * nmemb);

Always check error codes.

All the following return an error code. You should validate these functions worked by checking this error code.

 curl_global_init( CURL_GLOBAL_ALL );
 curl_easy_setopt(myHandle, CURLOPT_URL, "http://api.fixer.io/latest?symbols=USD,GBP");
 curl_easy_setopt(myHandle, CURLOPT_WRITEFUNCTION, WriteCallback);
 curl_easy_setopt(myHandle, CURLOPT_WRITEDATA, &readBuffer);

Prefer "\n" over std::endl

 std::cout<<"\nSucess parsing json\n"<<std::endl;
 std::cout << root<< std::endl;
 std::cout <<"Base = "<< root["base"].asString() << std::endl;
 std::cout <<"Date = "<< root["date"].asString() << std::endl;
 std::cout <<"Rate GBP ="<< root["rates"]["GBP"].asFloat() << std::endl;
 std::cout <<"Rate USD ="<< root["rates"]["USD"].asFloat() << std::endl;

The difference is that std::endl also calls std::flush on the stream. There is no need to flush the stream manually. The stream is designed to flush when it needs too. When you do it manually you will make your code much more eneficent.

RAII

 myHandle = curl_easy_init ( ) ;
 // STUFF
 curl_easy_cleanup( myHandle );

When you see this pattern. You should be thinking of using RAII. This will make sure your resources are cleaned up correctly in all situations (including when exceptions are thrown) are the function returns early (aka return 1;).


User Access Authorization for Web Resources

If you're going to use const for some variables, then use that (or let) for all variables. Avoid var unless you have a good reason - e.g. you really need a global variable and/or hoisting.

The variable authResult can be eliminated from function isAdmin since it only gets a default value assigned, which then gets overwritten before it is returned. The function could merely return the value from the call to rolesBoundToAlias.some(). The arrow function passed to .some() could be declared on the previous line if you want, in an effort to decrease line length. Actually you might be able to just use Array.includes() bound to the array of roles instead of an extra arrow function.

The name adminRolePolicy might be better named as DEFAULT_ROLES. I use all caps since it is more like a real constant that wouldn't change much - and could be declared outside the function if deemed appropriate. And while there is likely some overlap, Dev and BaseUser seem separate from the concept of admin.

Instead of calling the second parameter policyOverride, you could call it roles with the default of DEFAULT_ROLES - then there would be no need to assign the parameter to a different variable.


Bit Array in Ruby using integer as a storage

My 2nd question on this site concerned bitmasks, actually. As @tokland correctly pointed out back then, bitmasks are really a pretty low-level technique that doesn't quite belong in a high-level language. Yes, it has its uses, but a hash or an array of symbols would solve the same kinds of problems in a more high-level, more expressive, and more readable manner.

In fact, trying to do this in a high-level language like Ruby presents some oddities, since you're using strings and integers to work with bits. And strings and integers are objects in Ruby, so you've got all these really high-level concepts and constructs involved in trying to do something with the lowest-level aspect of computing. It works, but it's like packing something tiny in a giant padded box.

Still, code's code, so:

Your #test_iterate doesn't quite test what you think. You're just printing to stdout. What the assertion is actually testing is the value of @field.to_s(2)[1..-1].split("") - it doesn't really test that anything is being iterated. This implementation would also pass your test, even though it never iterates anything:

def each(&block)
  # block argument ignored, no iteration; passes tests anyway
  @field.to_s(2)[1..-1].split("")
end

With your current code, I'd write the test like:

expected = [1, 1, 0]
BitArray.new(3).set([1,2]).each do |bit|
  assert_equal expected.shift, bit
end
assert expected.empty? # check that we looped the expected number of times

You test for #get is also kinda strange. In all cases you check for 0 - how about a test where you expect to get 1 back? There really are only two possible return values, so you should probably check both.
Why on Earth is your class using a 1-based indexing scheme? It's an array of a sort, so why not use a zero-based index like, well, like an array would do? I know this confused me greatly.
Your #get method could perhaps just return a boolean. That's the closest you'll get to returning a raw bit.

Update: I wasn't aware of this, but Fixnum actually has subscripting access to bits already. So #get can be written as simply:

def get position
  @field[position]
end

Your #set and #clear methods should probably just use splats - it'd let you skip the array-boxing if just a single integer's passed in:

def set *positions # use a splat
  positions.each { |position| @field |= 1 << (@size - position) }
  self
end

unset might be a better name than clear - I'd expect clear to reset the entire array.
You're going out of your way to always calculating @size - (some position) to make sure that you fill your array "from the left". I.e. position 1 is the left-most bit, rather than the (more natural) right-most bit. However, there's really no need. Inside your class, you can do whatever you want. Your current tests mostly check the string representation, so you can just flip that, rather than flip everything else.
Filling from the right would also let you skip the size argument entirely; as you say, Ruby will catch overflows anyway, but you never actually check (or test) trying to get or set a bit outside the size.
It's also just simpler to find and flip bits if you go from the right, and use a zero-based index, since any bit is given as simply 2**position. For instance:

def set *positions
  positions.each { |position| @field |= 2**position }
  self
end

You're including Enumerable, so use it. Your #count method could be written as just

def count
  inject(0, :+)
end

since it'll use each, and each will yield either 1 or 0.

Again, this is all academic, as you're no doubt better off just using regular arrays or hashes. Still, here's a refactored version, because why not? Slightly different output for #to_s since I'm not using a size argument. And I'm using 0-based indices. But otherwise it's the same.

class BitArray
  include Enumerable

  def initialize
    @bits = 0
  end

  def set *positions
    positions.each { |position| @bits |= 2**position }
    self
  end

  def unset *positions
    positions.each { |position| @bits ^= 2**position }
    self
  end

  def get position
    @bits[position]
  end

  def each(&block)
    bits = @bits
    until bits == 0
      yield bits & 1
      bits = bits >> 1
    end
  end

  def to_s
    @bits.to_s(2).reverse
  end

  def count
    inject(0, :+)
  end
end

require 'minitest/autorun'

class BitArrayTest < MiniTest::Test
  def test_equal
    assert_equal "0", BitArray.new.to_s
  end

  def test_set
    assert_equal "0001", BitArray.new.set(3).to_s
    assert_equal "1011", BitArray.new.set(0, 2, 3).to_s
    assert_equal "0100000000101", BitArray.new.set(1, 10, 12).to_s
  end

  def test_unset
    assert_equal "101", BitArray.new.set(0, 1, 2).unset(1).to_s
  end

  def test_get
    assert_equal 1, BitArray.new.set(1, 2).get(2)
    assert_equal 0, BitArray.new.set(12).get(11)
    assert_equal 1, BitArray.new.set(12).get(12)
  end

  def test_count
    assert_equal 3, BitArray.new.set(1, 2, 5).count
  end

  def test_iterate
    expected = [1, 1, 0, 1]
    BitArray.new.set(0, 1, 3).each do |bit|
      assert_equal expected.shift, bit
    end
    assert expected.empty?
  end
end

Note that this version and its tests still don't deal with the issue of passing, say, negative indices or non-numeric indices.


In general it looks fine to me. BufferedStream would not help anything here, your data is already in memory by the time any streams get created.

I would prefer to see the MemoryStream in a using block, although in this case it is being disposed when the StreamWriter is disposed.

It may be a good idea to check the response and handle any error status. If you do ever add any code that uses the FtpWebResponse, I would change to a using block, instead of the call to close.

Not really related to the code, but avoid using FTP if you can.


1) Possibly better structure

Since information from DesignInformation, CommonTransformerProperties, ..., TransformerLimits objects seem to be semantically linked, it should be grouped into a single object type (maybe a Transformer). The EF model should be similar to the class below (greatly simplified).

class Transformer
{
   int TransformerId { get; set; }

   DesignInformation designInformation;
   CommonTransformerProperties commonTransformerProperties,
   SecondaryWindings secondaryWindings,
   CapacitorVoltageDivider capacitorVoltageDivider,
   IntermediateVoltageTransformer intermediateVoltageTransformer,
   SpecialDesignInformation specialDesignInformation,
   TransformerLimits transformerLimits
}

The real gain here is that you can have a single ID to be generated, but you have to change child types to link them to the parent. I.e. DesignInformation, CommonTransformerProperties, ..., TransformerLimits should also have a TransformerId specified. Persistence code should be simpler:

    using (var newcontext = new DesignContext())
    {
        design = GetDesingByNameFromDatabase(newcontext, designInformation.DesignID, designInformation.Technology);

        UpdateSecondaryWindings(design, newcontext, designInformation, secondaryWindings);

        UpdateSpecialWires(design, newcontext, designInformation, specialDesignInformation);

        newcontext.SaveChanges();
    }

    int dbId = design.DesignInformation.DataBaseID;

    design.DesignInformation = designInformation;
    design.DesignInformation.DataBaseID = dbId;

    design.CommonTransformerProperties = commonTransformerProperties;
    design.CommonTransformerProperties.DataBaseID = dbId;

    design.SecondaryWindings = secondaryWindings;
    design.SecondaryWindings.DataBaseID = dbId;

    design.CapacitorVoltageDivider = capacitorVoltageDivider;
    design.CapacitorVoltageDivider.DataBaseID = dbId;

    design.IntermediateVoltageTransformer = intermediateVoltageTransformer;
    design.IntermediateVoltageTransformer.DataBaseID = dbId;

    design.SpecialDesignInformation = specialDesignInformation;
    design.SpecialDesignInformation.DataBaseID = dbId;

should be:

    using (var newcontext = new DesignContext())
    {
        var newTransformer = new Transformer();
        newcontext.Transformer.Add(newTransformer);

        design = GetDesingByNameFromDatabase(newcontext, designInformation.DesignID, designInformation.Technology);
        UpdateSecondaryWindings(design, newcontext, designInformation, secondaryWindings);
        UpdateSpecialWires(design, newcontext, designInformation, specialDesignInformation);

        newTransformer.DesignInformation = designInformation;
        newTransformer.CommonTransformerProperties = commonTransformerProperties;
        // ...

        newcontext.SaveChanges();
    }

EF will automatically push generated identifier to all children entities.

2) Database context usage

Database context should not be disposed so often. Usually Unit of work pattern is used to simplify its usage and also group everything that must be saved together (i.e. in a transaction). More details can be found here and here.

This will spare you from passing the context for calls like:

        design = GetDesingByNameFromDatabase(newcontext, designInformation.DesignID, designInformation.Technology);
        UpdateSecondaryWindings(design, newcontext, designInformation, secondaryWindings);
        UpdateSpecialWires(design, newcontext, designInformation, specialDesignInformation);

Those functions can use the context by just calling DesignContext.Instance method where the method would look like this:

    public static Instance
    {
        get
        {
            // Dirty (non thread-safe) check
            if (UnitOfWorkStore.GetData(DATACONTEXT_KEY) == null)
            {
                lock (objSync)
                {
                    // Thread-safe check
                    if (UnitOfWorkStore.GetData(DATACONTEXT_KEY) == null)
                    {
                        var context = new DesignContext();
                        UnitOfWorkStore.SetData(DATACONTEXT_KEY, context);
                    }
                }
            }
            return (DesignContext)UnitOfWorkStore.GetData(DATACONTEXT_KEY);
        }
    }

An improvement is to using Dependency Injection and to have the context injected. The whole process is explained in great detail here. Of course, other DI frameworks - such as Ninject - can be used.


Creating a server for user Internet orders

One thing that you could change is the way that this if else statement is written

var hostname;
if(os.hostname() == "kipos"){
    hostname = os.hostname()+".dev";
}else{
    hostname = os.hostname();
}

Here you are deciding what a variables value should be using an if/else statement, this is a good spot to use a JavaScript ternary operator.

Example Ternary Statement:

var variableName = red == blue ? trueValueAssignment : falseValueAssignment;

so your code would look like this

var hostname = os.hostname() == "kipos" ? os.hostname() + ".dev" : os.hostname();


Counting the number of character occurrences

You could do the same thing with LINQ:

var counts = longText.GroupBy(c => c) // put each character into a "bucket"
                     // order the buckets alphabetically
                     .OrderBy(c => c.Key);
                     // then convert to dictionary where key = character, value = count
                     .ToDictionary(grp => grp.Key, grp => grp.Count())

For convenience/readability, you could turn this into an extension method on string:

static class Extensions
{
    public static Dictionary<char, int> CharacterCount(this string text)
    {
        return text.GroupBy(c => c)
                   .OrderBy(c => c.Key)
                   .ToDictionary(grp => grp.Key, grp => grp.Count());
    }
}

And invoke it like this:

var longText = @"The quick brown fox jumps over the lazy dog";

var counts = longText.CharacterCount();

However, note that the above doesn't produce a sorted dictionary in the sense that if you were to add another key/value to it afterwards, the order would no longer be maintained. You could re-sort at that point, or use this SortedDictionary constructor to create a sorted dictionary.


Your solution honestly sounds great and better than proposed solution in readability, length, probably performance as well (although it's never too easy to know the engine complexity based on how they optimizes requests). And from my understanding there is no semantic difference.
Some nitpicks: I indent request differently, and I use the column name rather than index in the GROUP BY
SELECT r.name AS region_name,
       COUNT(*) AS orders_n
  FROM orders AS o
    INNER JOIN accounts AS a
      ON o.account_id = a.id
    INNER JOIN sales_reps AS s
      ON a.sales_rep_id = s.id
    INNER JOIN region AS r
      ON s.region_id = r.id
  GROUP BY region_name
  ORDER BY SUM(o.total_amt_usd) DESC
  LIMIT 1;

The request optimization engine will equally optimize your request and decide itself the join order if you use a WHERE clause. So you can also write it like this
SELECT r.name AS region_name,
       COUNT(*) AS orders_n
  FROM orders AS o,
       accounts AS a,
       sales_reps AS s,
       region AS r
  WHERE o.account_id = a.id
    AND a.sales_rep_id = s.id
    AND s.region_id = r.id
  GROUP BY region_name
  ORDER BY SUM(o.total_amt_usd) DESC
  LIMIT 1;


since you don't want rounding, treat as string rather than number...

function strange(number){
    var n=0;
    if (number !== 0) {
        nParts = number.toString().split(/\.|,/);
        if (nParts[1]){
            n=nParts[1].length;
            n = n <=2 ? 2 : n==3 ? 3 : 4;
            nParts[1] = nParts[1] + '0'
        }else{
            n=2;
            nParts[1]='00';
        }
    }
    return nParts[0] + '.' + nParts[1].slice(0,n);
}

;strange(14);
;strange(14.1);
;strange(14.123);
;strange(14.12347);

/*
14 => 14.00
14.1 => 14.10
14.123 => 14.123
14.12347 => 14.1234
*/


Heaviest Stone algorithm time complexity

Issue(s)

You sort descending, but then take and assign the heaviest stone to x and the second heaviest stone to y whereas in your problem you state "...stones have weights x and y with x <= y".
Code isn't as DRY (Don't Repeat Yourself) as it could be.

Suggestions

Provide stones a default/initial empty array value.
Sort descending and assign const y = stones[0]; and const x = stones[1]; and push new value stones.push(y - x); to match problem. (Or normal sort ascending and take from array end, more on this later)
Use array destructuring to assign to x and y since array::splice returns an array of spliced out values.
Sort once at the beginning of each iteration.
Remove extraneous array length checks, let the while-loop condition handle it.

Code
const lastStoneWeight = (stones = []) => {
  if (!stones || !stones.length) return 0;

  while (stones.length > 1) {
    stones.sort((a, b) => a - b);
    const [x, y] = stones.splice(-2);
    if (x !== y) stones.push(y - x);
  }
  return stones[0] || 0;
};

If you can use Optional Chaining and Nullish Coalescing
const lastStoneWeight = (stones = []) => {
  if (!stones?.length) return 0;

  while (stones.length > 1) {
    stones.sort((a, b) => a - b);
    const [x, y] = stones.splice(-2);
    if (x !== y) stones.push(y - x);
  }
  return stones[0] ?? 0;
};

Here I use the default sort (ascending) and splice off the last two elements, removes need to shift entire forward 2 indices.
Using a Heap Data Structure
Since you ask about improved performance and the going suggestion is to use a heap/priority queue. This is a very similar implementation.
const lastStoneWeightHeap = (stones = []) => {
  if (!stones?.length) return 0;

  const heap = new PriorityQueue(); // <-- uses equivalent comparator as array::sort
  stones.forEach((stone) => heap.enq(stone)); // <-- populate heap

  while (heap.size() > 1) {
    const y = heap.deq();
    const x = heap.deq();
    if (x !== y) heap.enq(y - x);
  }
  return heap.size() ? heap.deq() : 0;
};

t1 is regular algorithm
t2 is version using heap/priority queue data structure
10 iterations x 10000 runs
    # Elements  t0 avg      t1 avg
1   8           0.00363     0.00106
2   16          0.01036     0.00157
3   32          0.01781     0.00224
4   64          0.09148     0.00432
5   128         0.22560     0.00944
6   256         0.56833     0.01618
7   512         2.37584     0.06091
8   1024        8.78741     0.12614
9   2048        34.29092    0.29697
10  4096        130.50169   0.63872

Notes:

Time is in milliseconds

https://www.npmjs.com/package/priorityqueuejs
Conclusion
Using a heap data structure is orders of magnitude an improvement. With the naive implementation it is clearly at least an \$O(n^2)\$ complexity as each time the dataset size doubles (2x) the runtime roughly quadruples (~4x) whereas the implementation using a heap roughly only doubles (~2x) the runtime with each doubling of the dataset.
Performance Benchmarking
performanceBenchmark.js
const measurePerf = (fn, data, runs = 1e3) =>
  [...Array(runs).keys()]
    .map(() => {
      const start = performance.now();
      fn([...data]);
      const end = performance.now();
      return end - start;
    })
    .reduce((total, current) => total + current) / runs;

const toFixed = (val, fixed) =>
  Number.isFinite(val) ? Number(val).toFixed(fixed) : val;

export const benchmark = async ({
  functions = [],
  createRunData,
  iterations = 5,
  runs = 1e3,
  logIntermediateResults
}) => {
  logIntermediateResults && console.log(`${iterations} x ${runs}`);

  const results = [];

  logIntermediateResults &&
    console.log(
      `\t# Elements\t${functions.map((_, i) => `t${i} avg`).join("\t")}`
    );

  for (let i = 0; i < iterations; i++) {
    const data = createRunData(i);

    const res = await Promise.all(
      functions.map((fn) => measurePerf(fn, data, runs))
    );

    results.push(res);

    logIntermediateResults &&
      console.log(
        `${i + 1}\t${data.length}\t${res
          .map((t) => `${toFixed(t, 5)}`)
          .join("\t")}`
      );
  }

  return results;
};

Setup & benchmark
const ITERATIONS = 10;
const RUNS = 1e4;
const SEED = 8;

const functions = [
  lastStoneWeight,
  lastStoneWeightHeap,
];

const createRunData = (i) => {
  const dataLength = SEED << i;
  const stones = [...Array(dataLength).keys()].map(() =>
    Math.floor(Math.random() * dataLength)
  );
  return stones;
};

benchmark({
  functions,
  createRunData,
  iterations: ITERATIONS,
  runs: RUNS,
  logIntermediateResults: true
});

Extended heap implementation benchmark
15 x 10000
    # Elements  t0 avg
1   8           0.00100
2   16          0.00171
3   32          0.00242
4   64          0.00434
5   128         0.00933
6   256         0.01825
7   512         0.05681
8   1024        0.13715
9   2048        0.27621
10  4096        0.59631
11  8192        1.24577
12  16384       4.75092
13  32768       6.09799
14  65536       13.07677
15  131072      28.88058


Remove duplicated functions inside different if within a function?

The only difference between the two parts is that the second part has an additional parameter 1? You can provide an array with the original param, if function.length is 2, push 1 into it. the just call func.apply(null, params).
Here is a solution base on the idea:
function __throwError (func) {
  const testcases = [
    new TestCase(func, 0, 'The parameter should be an array'),
    new TestCase(func, 'item', 'The parameter should be an array'),
    new TestCase(func, [], 'The array is empty'),
    new TestCase(func, undefined, 'The parameter is null or undefined'),
    new TestCase(func, null, 'The parameter is null or undefined')
  ];
  if (func.length === 2) {
    testcases.forEach(testcase => testcase.value.push(1));
  }
  for (const testcase of testcases) {
    expect(testcase.fn).toThrowError(testcase.errMsg);
  }
}

class TestCase {
  constructor (testFn, value, errMsg) {
    this.value = [value];
    this.errMsg = errMsg;
    this.testFn = testFn;
  }
  fn () {
    this.testFn.apply(null, this.value);
  }
}
```


HTML parsing algorithm for extracting  tags

First of all, as Loki mentioned in the comments, it is incredibly cumbersome to parse any text that made by human. We tend to abuse things, so I'd refrain from parsing it myself. There are good libraries that does parsing. If you want performance, I'd go with boost.spirit that is based on expression templates. I've also made a topic request about expression templates on so.docs, but it still has low upvote count, so don't rely on it to come in near future. I strongly encourage you to read about both, because it is the greatest power to have in parsing input files.
About the code:
Good try, but probably you will need a lot more. Some people would think that I need to put suggestion about regex over hand rolled search, but I will just put
link to an article on very famous blog.
Use <cstdio> instead of <stdio.h>. All C headers have C++ equivalents and are preferred over C ones.
Don't mix <cstdio> and <iostream>. The I/O may become unordered.
Overflow:
int can and will overflow. For example here:
iterator + second_iterator

The C standard guarantees only 16 bit for it as I remember. It is not mandated by the standard that return type of the std::string::size() is int. In fact it will probably never be int, because it is signed type, but size can not be negative. I recommend you to use std::string::size_type. It is guaranteed by the standard that this type will have enough capacity to store the maximum possible index that std::string can have.
Readability comments:
second_iterator - 2
second_iterator - 1

Those 2 expressions rise alerts in my head, because type of second_iterator is int, which is signed. I know that it will never be less than 2 by design, but I think that there is at least one better solution, one of which is mentioned above.
I'd wait bool(s) from any function that has check word in it's name. I think the function now performs what sequence of std::string::find()s does. This suggests using standard one. It will be much more clear.
Performance comments:
Usually standard containers are implemented in terms of 3 pointers, not a pointer and 2 indices. This suggests that iterator based algorithms will outperform index based ones. Further reading.
I found it impractical using push_back() without preceding reserve() call where performance matters. On top of that, every push will have control flow manipulators, which will greatly decrease the throughput on the function.
I'd use std::string::compare to compare check string and the substring. The implementations are allowed to deploy more intelligent comparison functions, so it might have zero development cost optimization.
Redesign:
I'd redesign the function to accept Input Iterators. It will make it more customizable with zero runtime overhead (well it depends on the iterator, but it is possible and easy to do). It will also keep strings from being copied.
Notes about example code:
You can use range for loop to traverse whole container/range.
Declaring urlmap right on assignment would trigger copy elision (the output will start constructing right in urlmap).
Don't use system(). It is the source of many security issues.


a unit test is not really one if it talks to the network...

I am not so sure what you meant by that. It seems like you are trying to follow exactly what someone may have said in a book or a talk. Unit testing is all about testing a 'Model'. And the assumptions are that the Model is isolated from any other models in the overall project.

In your case the Unit Test for the ClientSocket would be called ClientSocketTest.

Class ClientSocketTest extends PHPUnit_Testcase
{
    private $s = null;

    public function testSend()
    {
        $cs = new ClientSocket();
        $cs->send("My Message");
        $result = $cs->result;
        $this->assert("Everything's Good", $result);
    }
}

I noticed that your send method has the variable $result. For Unit Testing to be successful a method should return something. The purpose of Unit Testing is to see whether the given input gives you the expected output. Don't overcomplicate it!

Start with PHPUnit... and stick to it! :)


Your algorithm to calculate the final image dimensions could be improved by simplifying the logical process that you use to determine the final size.

Fundamentally, there are two dimensions you are interested in, the height, and width of the final image. There are two possible outcomes for the scaling, one where the scaling produces the target height, and the other where it produces the target width. The scaling that is used is the one which produces the smallest image. The size of the final image is determined by the scaling factor, and there are two factors:

float scaleHeight = (float)BOXHEIGHT / (float)original.Height;
float scaleWidth = (float)BOXWIDTH / (float)original.Width;

Now, we have two scaling ratios, which one produces the smaller image? The one that has the smallest scaling factor.

float scale = Math.Min(scaleHeight, scaleWidth);

Now you can simply do the adjustment:

resizedImage = new Bitmap(original,
         (int)(original.Width * scale), (int)(original.Height * scale));


Implementing class equality/comparison in F#

There's a suggestion for [<AllowNullLiteral>]: I think this is a bad idea.

You wrote a class that is a lat/long pair, as a result, it's a standard GeoCoordinate, which is a regular value-type, and should be marked as such. I get that the book calls it a class, but as an F# developer, how many times in your life have you actually had to think about the difference?

As a result, I'd add the structure definition in some manner, either via struct/end, or [<StructAttribute>].

I also recommend implementing the generic IComparable<T>. It's cheap, and can offer more performance to avoid boxing/unboxing should the caller need it. (Reed also covered this.) Some of the newer API's will try to rely on both, preferring the IComparable<T>. You may also want to read this answer to another question, as it talks about a lot of performance intricacies with regard to the standard BCL stuff. (You may want to create an IEqualityComparer<T>, for example.)

Some might argue that the guidelines say to keep the instance size "under 16 bytes", I personally think that's rubbish, as I'm pretty sure that should read "at or under 16 bytes". These are not always law.

The .NET BCL contradicts itself here several times (Size structure, Guid structure, too lazy to find the others), and the Struct Design guidelines don't mention it, only the class vs. struct guidelines.

As a result, I think you're safe in that regard here. The item you're talking about is small (16-bytes), represents a value (physical location that doesn't change), and should not be directly changed. Just as well, the copying performance can often use native SIMD instructions, so it should not be a big deal to copy 16-bytes. (I had a source on this, but I lost it, going to try to dig it up again.)


Overall, looks good design. good breakdown into methods.
Here are my comments:

Avoid magic numbers
Magic numbers are literals (String or Numeric values).  They should be replced with constant variables (public static final ... and UPPER_CASE named).  This has two benefits: 1) give meaning to the literal value (helps readability) and 2) one place to change value and also avoid (runtime!) errors due to incorrect value due to typo.
Example: public static final int MAX_ROLL_COUNT = 21;
Meaningful variable names
This is particularly useful in your case where you have multiple index variables. You have both i and index.  IIUC, i is index on frames (==turns in bowling jargon, and don't forget to replace literal used as loop limit with constant!) and index is index on rolls.
Meaningful method names
rollIndex() is not a good name. perhaps calculateScoreForFrame() or something similar
Use collection streams
Depending on your proficiency in the language, you may want to experiment with replace these for loops with Java 8 collection streams.  It (arguably) makes the code even more clearer.


It's pretty good code. Well done! There are no major mistakes or pain points that  would annoy other developers. All I can do is to nitpick a little bit.

First of all take a look at some JavaScript style guide. jQuery has a good one and Google has a great one, too. You may find many others and although they all diverge a little bit there are a lot of common practices that they all agree on. One of those is braces' positioning. Instead of

render:
    function()
    {

you'd better use

render: function () { // note the spaces, too :)

Another point is the use of === instead of ==. I've noticed that you've never used a triple-equals operator in your code and I'm a little bit nervous. Maybe you know about the one vs. the other and you know what are you doing in this particular code (and btw your code works totally fine with double-equals). But what if you don't know? And what if some other developer who doesn't know JavaScript well take a look at your code and try to do something similar? Suppose he doesn't know the rules and you code is the largest and most complicated piece of JavaScript he's ever seen. Which way of thinking do you think is more bullet-proof for a JS-newbie:

  JavaScript is somewhat weird: I have to use === to compare things.

or

  JavaScript is so easy! I'll use == to compare stuff everywhere in my code!

I guess the former is better.
I noticed you use .bind() method for event binding. Consider switching to new .on() method introduced in jQuery 1.7. One of the current goals for jQuery team is to make their library smaller and more lightweight so they work hard to cut off all the fat that's accumulated over the years. At some point in future they may remove the old API so it's better start using new API today to make your code future-proof. It''l be a lot less hassle to switch to new version of jQuery in future.

Other than that your code is fine. I really like the fact that you use Underscore JS. That saves you and other developers a lot of time and headaches.


My solution consists of a single change:

Changed the is_prime function into a prime sieve (from this answer) + lookup

My final code (Also handled odd numbers just for fun, definitely not because I misread the question):

def main():
    import itertools
    import math
    izip = itertools.zip_longest
    chain = itertools.chain.from_iterable
    compress = itertools.compress
    def rwh_primes2_python3(n):
        """ Input n>=6, Returns a list of primes, 2 <= p < n """
        zero = bytearray([False])
        size = n//3 + (n % 6 == 2)
        sieve = bytearray([True]) * size
        sieve[0] = False
        for i in range(int(n**0.5)//3+1):
          if sieve[i]:
            k=3*i+1|1
            start = (k*k+4*k-2*k*(i&1))//3
            sieve[(k*k)//3::2*k]=zero*((size - (k*k)//3 - 1) // (2 * k) + 1)
            sieve[  start ::2*k]=zero*((size -   start  - 1) // (2 * k) + 1)
        ans = [2,3]
        poss = chain(izip(*[range(i, n, 6) for i in (1,5)]))
        ans.extend(compress(poss, sieve))
        return ans

    string2 = "Impossible"
    n = int(input())
    sieve = [t for t in rwh_primes2_python3(n) if t <= math.floor((n // 2) / 2) * 2 + 1][::-1]
    another = [t for t in rwh_primes2_python3(n) if t >= math.floor((n // 2) / 2) * 2 + 1]

    if n > 5 and n % 2 == 0:
        for smaller in sieve:
            if n - smaller in another:
                print (smaller, n - smaller)
                break
    elif n % 2 == 1 and n != 5:
        if n - 2 in another or n-2 in sieve: print (2, n-2)
        else: print ('Impossible')
    elif n == 4:
        print ('2 2')
    else:
        print ('2 3')

main()


As you seem to have already noticed yourself, the fact that the input to the function is a pair of strings is somewhat awkward. It violates the Zero-One-Infinity Rule.
You might be worried about YAGNI or the Rule Of Three, but I would argue that it is okay to fudge those guidelines here a little bit, since

the extension from two to many is obvious,
simplifies the code, and
is in service to another guideline.

One main question you need to ask yourself, which I feel is not really answered in the specification you gave in your question nor in the code snippet you are asking to have reviewed, relates to this statement from your question [bold emphasis mine]:

I want to create their combination with a delimiter between them if they both exist.

What, precisely do you mean by "if they both exist"? If we are looking at ways that an Option[String] in Scala can exist or maybe not exist, I can think of many different scenarios:

It can be null. (Unfortunately, since Scala is designed to tightly integrate with the underlying platform, and all of the "interesting" underlying platforms all have a concept of null, it is hard to get rid of this.)
It can be None.
It can be Some(""), i.e. the empty string.
It can be Some("  "), i.e. a string consisting purely of U+0020 Space characters.
It can be Some("  "), i.e. a string consisting purely of whitespace characters other than U+0020 Space. (There are at least 16 different whitespace characters that are not U+0020 which I have found in about 30s of research.)
It can be Some(""), i.e. a string consisting purely of zero-width characters. (Note, this is not an empty string! It contains a U+200B Zero-width space. For added fun, this particular character is not considered Whitespace by the Unicode standard!)

And these are just some of the things I can think of off the top of my head.
For example, both your original code in the question and your revised code in the answer will return Some(", ") when passed two empty strings, or Some(" ,  ") when passed two strings consisting of one space character.
If you are willing to accept a very broad definition, then a very simple implementation could be something like this:
def concat(s: Option[String]*) = s.flatten.mkString(", ")

However, this will always give you a String, it will not give you an Option[String]. For your None, None example, it will give you the empty string:
concat(None, None)
//=> ""

[Scastie link]
Any specification more complex than this very simple one, including the one from your question, will complicate the code, there is not much you can do about that. There is no getting around the fact that text processing looks deceptively simple (everybody knows what an "empty string" or a "character" is, right?) but is actually very complex.

<script src="https://scastie.scala-lang.org/JoergWMittag/1EScnd33SZ68MEXCCXjTQg.js"></script>


automating to push changes to github for multiple repos using python

Review

Stick to the PEP8 style guide

Functions and variables should be snake_case
Constants like gitUrl should be UPPER_SNAKE_CASE

There is a function for getting the current working directory

os.getcwd() Depending on your use case this might be useful
If you are using Python3.5+ you should change the older subprocces.call with the newer subprocess.run
Don't catch bare Exceptions

If you now what exceptions are going to be caught it is better to define them


Creating charts for my UPS metrics - Part 2

Quoting - you need double-quotes on the last line: it should be "${API_PARAMS[@]}" (remember that the [@] makes the shell expand it into multiple words, so it won't be seen by your http program as just one).

Instead of if [ "$field" -eq 2 ], it's clearer to compare the field name.  That will help if you change the properties list in future.  It may help to create a variable:

propname="${UPS_PROPS[$index]}"
value=$(/sbin/apcaccess -up "$propname")
if [ "$propname" = LOADPCT ]

We can supply standard input from a string without needing an echo process, by using <<< redirection:

    # bc required for floating point arithmetic
    value=$(<<<"$value * 6" bc)  # 600 Watt * load percent

We can make the array 1-based, and avoid the need to have $field different from $index:

UPS_PROPS=([1]="LINEV" "LOADPCT" "TIMELEFT")


I haven't used much boto, so I can just focus on some style comments:

Use four spaces per indentation level
Remove unused imports (boto.exception)
Try to order imports in alphabetical order
Move argument parsing and logging configuration code to separate functions
Be careful of the usage of next. What you were probably looking for is continue, but you can just remove that line to move on to the next region in the loop
--dedug and --verbose don't seem to make sense together. Have a look at ArgumentParser.add_mutually_exclusive_group.
Use a template or, at least, a multiline string to avoid writing so many print statements.


Converting from polar coordinates to rectangular coordinates

I would consider using a lookup table to find your sines. How precise an angle are you calculating for? This answer on stackoverflow has some interesting information on how to construct one and the benchmarks for using it to two decimal points. If you are using the full precision of a double, then your current method will be faster, but if you have a fixed precision, a lookup table will be benificial.

As long as the exception IS exceptional (and it looks to me like it is) it will add very little overhead to your run times. See: https://stackoverflow.com/q/52312/487663.


Parsing a string of key-value pairs as a dictionary

Note it is much easier to read if you chop up the comprehension into blocks, instead of having them all on one line

You could use unpacking to remove some usages of line.split

>>> {
...    int(k): v
...    for line in data.split()
...    for k, v in (line.split(':'),)
... }
{41: 'n', 43: 'n', 44: 'n', 46: 'n', 47: 'n', 49: 'n', 50: 'n', 51: 'n', 52: 'n', 53: 'n', 54: 'n', 55: 'cm', 56: 'n', 57: 'n', 58: 'n'}

Or if the first argument can be of str type you could use dict().

This will unpack the line.split and convert them into a key, value pair for you

>>> dict(
...    line.split(':')
...    for line in data.split()
... )
{'41': 'n', '43': 'n', '44': 'n', '46': 'n', '47': 'n', '49': 'n', '50': 'n', '51': 'n', '52': 'n', '53': 'n', '54': 'n', '55': 'cm', '56': 'n', '57': 'n', '58': 'n'}


Please follow the official PEP 8 style guide.  In particular, indentation matters a lot in Python!  One space per level of indentation is much too stingy for readability; four spaces is standard.  Also, using lowercase_with_underscores for function and variable names is the norm.

For this kind of function, I would strongly recommend writing a docstring with doctests.  You could easily test your code by running python -mdoctest reverse.py.

recursive is a poorly named function: it's not recursive, and the name tells you nothing about what it does.  I'd call it extract_and_reverse_substring.

You have too many variables, which makes the code confusing.  In particular, a is never used!  Furthermore, a lot of the complication arises from your decision to strip out all of the parentheses at the beginning, to form alteredstring.  If you keep the parentheses, and strip them out afterwards, then you wouldn't need alteredstring, numberofbrack, and recursivearray, because that information would still be preserved in the string itself.

Python strings are immutable.  When doing many repositioning operations on the characters in a string, consider using a list instead, for efficiency.  That would allow you to replace individual characters without allocating new strings.

Suggested solution

def reverse_parentheses(s):
    """
    Reverse the strings contained in each pair of matching parentheses,
    starting from the innermost pair. The results string should not contain
    any parentheses.

    >>> reverse_parentheses('a(bc)de')
    'acbde'

    >>> reverse_parentheses(
    ...     'The ((quick (brown) (fox) jumps over the lazy) dog)'
    ... )
    'The god quick nworb xof jumps over the lazy'
    """
    chars = list(s)
    open_bracket_indexes = []
    for i, c in enumerate(chars):
        if c == '(':
            open_bracket_indexes.append(i)
        elif c == ')':
            j = open_bracket_indexes.pop()
            chars[j:i] = chars[i:j:-1]
    if open_bracket_indexes:
        raise ArgumentError('Unclosed parenthesis')
    return ''.join(c for c in chars if c not in '()')


I'd use a dictionary (or a HashSet if you don't need the ID information) for coordination.

class UrlLog {
    private Dictionary<string, int> visited = new Dictionary<string, int>();
    public bool HasUrlBeenVisited(string Url) {
        lock(visited) return visited.ContainsKey(Url);
    }
    public void SetUrlVisited(string Url, int threadId) { /* id not strictly necessary */
        lock(visited) visited[Url] = threadId;
    }
}

Then pass one instance of this UrlLog to your threads, and they can use that.

Also, I'm not sure you even need the locks for the checks, but it's better to be safe than sorry. :)


Depends on what you want to do with it. It seems a bit odd to store each top 5 in its own variable.

For starters, you can slice a DataFrame by continent using .groupby:

for continent, continent_data in data.groupby("Continent"):
    # `continent` is now the name of the continent (you don't have to type the continent names manually)
    # `continent_data` is a dataframe, being a subset of the `data` dataframe

Edit based on first comment: if you want to plot the variables, it's definitely not a good idea to store them each in a separate variable. Do you already know how you want to visualize your data? That's something you will need to work toward. I can't really see a top 5 countries for each type of alcoholic beverage for each continent in one plot.

continents = []
top5s = {}
for continent, continent_data in data.groupby("Continent"):
    continents.append(continent)
    for beverage_column in ["Beer Servings", "Spirit Servings", "Wine Servings"]:
        topcountries = continent_data.nlargest(5, beverage_column)
        # do something with the data, such as:
        print(f"Top 5 countries in {continent} for {beverage}:")
        for row in topcountries.iterrows():
            print(f"- {row.Country}: {row['beverage_column']} servings")

To be very exact: groupby() doesn't return an iterable of tuples, but actually just a GroupBy object that implements iterability (i.e. the __iter__() method).


Search/match algorithm between 2 vectors

Some problems with this code I want to address before I even get into optimization of speed.

First of all, there's absolutely no indentation, which makes this very hard to read.

Second of all, your variable names are both lacking, and not in keeping with Objective-C standard conventions.  Variable names like val and val2 aren't really descriptive enough.  A variable name like like_user may be descriptive enough (I don't know, it's borderline), but Objective-C standards suggest that the variable should instead be named likeUser.  We prefer camel casing to underscoring.

Next, you're using a for loop where you should be using a forin (I'll get to that later), but we're using the loop iterator as an index into an array... which is fine-ish... but you're concerning yourself with the array's length in the for's condition.  You're risking an index out of bounds exception.

But we really don't want to use a for loop anyway.  Any time we need to do something with each object in an Objective-C collection, we should use a forin loop anytime we can.  forin loops run faster than regular for loops--they're processed in batches.

But as 200_success points out, in this specific instance, we don't need to iterate through the indexes.

You stated you just want to count the number of common liked pages.

So, just as 200_success suggested:

NSSet *userLikeSet = [NSSet setWithArray:userLike];
NSMutableSet *commonLikeSet = [NSMutableSet setWithArray:friendLike];
NSSet *commonLikes = [commonLikeSet intersectSet:userLikeSet];

NSInteger commonLikeCount = [commonLikes count];


Implementation of binary min-heap data structure

You've mentioned that you don't want to utilize the STL, so I'll honor that.  Just be aware that neglecting to use it may lessen the quality of your code, especially if you start to experience bugs.

I'll mainly address best-practices as I'm not so familiar with the algorithm myself.

Your lack of whitespace just makes this painful to read.  If a line appears to be too long, it either needs to be shortened (preferred) or wrapped onto separate lines.

Either way, you should especially have some whitespace between operators and operands so that it won't take others unneeded time to read and understand it.  This will also benefit you whenever you're maintaining the code (fixing bugs, adding things, and changing things around).

For instance, this line:

if(arr[x*2]>arr[x*2+1]&&(elm>arr[x*2]||elm>arr[x*2+1])){

should look like this:

if (arr[x*2] > arr[x*2+1] && (elm > arr[x*2] || elm > arr[x*2+1])) {

Isn't that easier to read?  There's no need to cram everything together; just let the code breathe.  You could still space out the operators within the [], but it's not quite as common.
Your variable names are very generic.  Many of them are only single letters, and your array data member is just named arr.  Without good naming, you'll just leave others guessing at what each variable does.  Plus, if you look at this code years from now, you may have no idea what it all means, and so you may be tempted to throw it away and start all over.
Although it's entirely optional, you can add the private keyword anyway, even though classes are private by default.  It may add a little more readability, especially if there is a lot of code.
The constructor:

min_heap(){
    P=1;
}

can be an initializer list:

min_heap() : P(1) {}

If it ever gets lengthy, you can list the members on separate lines:

min_heap()
    : P(1)
    , // additional ones
    , // separated by commas
{}

If pvt and arr need to be initialized, then it should be done here as well.  I'm not sure why you just initialize one data member.
You don't need std::endl here.  In most cases, a flush isn't necessary along with a newline, which is what's being done by that.

Instead, just output "\n" for a newline:

std::cout << "\n";

This is also mentioned here.

Overall, I'd highly recommend making this more readable first, so that it's easier to understand and improve for yourself and others.  Implementing all the algorithms yourself will especially require the code to be clean and self-documenting, otherwise you're really just writing C code instead.


Finding all factors and prime factors of a number

Correct me if I am wrong but I think your code in findprimes is checking every number to see if it is a factor and then checking every factor to see if it is prime.
Rather than doing this I suggest you want to find all the prime factors, and then making the list of all factors just comes from all the combinations of prime factors in two subsets.
When you look for the prime factors of a number you can save yourself some time buy only checking odd numbers (and 2) up to the square root of the number. Whenever you find a new prime factor reduce you target by that factor. There are more advanced algorithms that you may want to explore here
In terms of coding style you might want to change your inline comments to doc strings, remove double new lines between functions and add hyphens to your function names e.g findprimes >> find_primes
In terms of function names I would have expected isprime to return True or False if the number was or wasn't prime.
I've made a quick sketch of the method I am describing:
import math

def find_prime_factors(target, floor=2):
    prime_factors = []

    while floor == 2 and target % 2 == 0:
        target = target // 2
        prime_factors.append(2)

    candidate = floor + 1 if floor == 2 else floor

    while candidate <= target:
        while target % candidate == 0:
            target = target // candidate
            prime_factors.append(candidate)
        candidate += 2
    return prime_factors


Any simpler and more efficient way of writing this code?

This part is duplicated:

$orderBy = array_map(function() {
    return mt_rand();
}, range(1, count($id)));
array_multisort($orderBy, $id);

You apply the same logic to $id, $status, $online.

To eliminate duplication, you can move this common logic to a function with one parameter:

function reorder(&$arr) {
    $orderBy = array_map(function() {
        return mt_rand();
    }, range(1, count($arr)));
    array_multisort($orderBy, $arr);
}
reorder($id);
reorder($status);
reorder($online);

Note that we pass the array by reference (&$arr), because array_multisort does the same, and modifies the content of the array anyway.

UPDATE

As other answers and comments have pointed out, you could also eliminate the magic numbers and duplication when creating the $status array, for example like this:

$color1 = array("red", "no");
$color2 = array("green", "yes");
$num_color1 = 7;
$num_color2 = 3;
$status = array_fill(0, $num_color1, $color1)
          + array_fill($num_color1, $num_color2, $color2);


Regardless of your algorithm, you can simplify it much more with a simple if or switch.

int years = leapyear%4;
switch( years ) {
  case 0:
    println("Yeeees!");
    break;
  case 1:
    println("1 year later there is a leapyear.");
    break;
  default:
    println((4-years)+" years later there is a leapyear.");
    break;
}

But I doubt that this is a good practising exercise:

Do you have an unit test for it ? If you had to create one, how could you test the result since it is printed to the console.

How could you improve this code to make it testable and extendable. What could you do if I want to print another message ?


Caliburn Micro communication between list and edit viewmodels

Naming

You should use PascalCase to name methods and types. You do this most of the time, but slip up with modClienteViewModel

Your parameters should be in camelCase. Again, you do this most of the time, but slip up with TipoVista in your OpenTab method.

Avoid Hungarian notation, with a modern IDE it's not necessary, and it just makes types harder to read.

bool bFound = false;

should be

var found = false;

The same probably goes for miItem which can just be item without any loss of meaning.

Var

Prefer to use var in a declaration when the right-hand side makes the type obvious.

e.g.

AppViewModel myParent = (AppViewModel)this.Parent;

is obvious because of the cast, so we write

var myParent = (AppViewModel)this.Parent;

The reasoning behind this is that if you wanted to change a type, you would have to do so in two places in one line. With var, it is only one change.

You should also use var when defining the loop variable in a foreach loop.


IMHO The names are fine. You could maybe want to modify Modifiers in StatModifiersSummary as it's, after all, a summary "view" of the actual modifiers.

You should make its fields final or private, though.

In that case, your calculator would become StatModifiersSummaryCalculator.

W.r.t. extending / having one map inside, composition is in general preferable to inheritance, so stick with the current design: after all you happen to use a Map, but there is no reason why you couldn't use another representation and you don't want your "users" to be able to pass your calculator around where a map is needed.