Search for all matching users and security groups using System.DirectoryServices.AccountManagement

I don't know better ways to query for principals, so below is some general comments.

        if (!(usr is UserPrincipal user) || recipients.Any(m => m.Name == (user.DisplayName ?? user.Name) && m.Type == RecipientType.Group)) continue;

I think m.Type == RecipientType.Group should be m.Type == RecipientType.User

When I run your function I get an InvalidOpeartionException for this filter:

  new GroupPrincipal(ctx) {DisplayName = search}

You could consider to extend the function with an argument, that allows the client to specify the context type:

public static IEnumerable<Recipient> Search(string search, ContextType contextType)

The returned Principals from new PrincipalSearcher(principal).FindAll() is of the same type as the argument Principal so you can omit this check:

  if (!(grp is GroupPrincipal group)...

Both PrincipalSearcher and Principal implements IDisposable so all those objects should call Dispose() or be wrapped in a using() statement.

You do essentially the same in the two loops so you should only have one that can handle different types of data. Below I've tried to do that, where all disposable objects are disposed.

public static IEnumerable<Recipient> Search(string search, ContextType contextType)
{
  search = $"{search}*";

  using (PrincipalContext context = new PrincipalContext(contextType))
  {
    var recipients = new List<Recipient>();

    var filterTypes = new[]
    {
      new {
        Filters = new Func<Principal>[]
        {
          () => new UserPrincipal(context) {DisplayName = search},
          () => new UserPrincipal(context) {Name = search},
          () => new UserPrincipal(context) {SamAccountName = search}
        },
        RepicientType = RecipientType.User },
      new {
        Filters = new Func<Principal>[]
        {
          //() => new GroupPrincipal(context) {DisplayName = search},
          () => new GroupPrincipal(context) {Name = search},
          () => new GroupPrincipal(context) {SamAccountName = search}
        },
        RepicientType = RecipientType.Group },
    };

    foreach (var principalFilter in filterTypes)
    {
      foreach (var filterFunc in principalFilter.Filters)
      {
        using (var filter = filterFunc())
        using (var searcher = new PrincipalSearcher(filter))
        {
          foreach (var foundPrincipal in searcher.FindAll())
          {
            using (foundPrincipal)
            {
              if (recipients.Any(m => m.Name == (foundPrincipal.DisplayName ?? foundPrincipal.Name) && m.Type == principalFilter.RepicientType))
                continue;

              recipients.Add(new Recipient()
              {
                Name = foundPrincipal.SamAccountName,
                DisplayName = foundPrincipal.DisplayName ?? foundPrincipal.Name,
                Type = principalFilter.RepicientType
              });
            }
          }
        }
      }
    }

    return recipients;
  }
}

Here I use new Func<Principal>[] instead of just new Principal[] in order to signal, that the "client" (the loop) is responsible for cleaning up the created object.

I'm not sure I like this:

      foreach (Principal foundPrincipal in searcher.FindAll())
      {
        using (foundPrincipal)
        {
           ...

but it's doable.

Just for the exercise: a version that goes all in on LINQ with the same considerations as above:

  public static class ActiveDirectory
  {
    private static IEnumerable<TPrincipal> Search<TPrincipal>(
      this IEnumerable<Func<TPrincipal>> filters,
      IEqualityComparer<TPrincipal> equalityComparer,
      ContextType contextType) where TPrincipal : Principal
    {
      return filters
        .SelectMany(creator =>
        {
          using (TPrincipal principal = creator())
          using (var searcher = new PrincipalSearcher(principal))
          {
            return searcher.FindAll();
          }
        })
        .Cast<TPrincipal>()
        .Distinct(equalityComparer)
        .ToArray();
    }

    private static IEnumerable<Recipient> Convert<TPrincipal>(this IEnumerable<TPrincipal> principals, RecipientType recipientType, bool disposePrincipals = true) where TPrincipal : Principal
    {
      foreach (TPrincipal principal in principals)
      {
        Recipient recipient = new Recipient
        {
          Name = principal.SamAccountName,
          DisplayName = principal.DisplayName ?? principal.Name,
          Type = recipientType
        };

        if (disposePrincipals)
          principal.Dispose();

        yield return recipient;
      }
    }

    public static IEnumerable<Recipient> Search(string search, ContextType contextType)
    {
      search = $"{search}*";

      using (var context = new PrincipalContext(contextType))
      {
        var userFilters = new Func<UserPrincipal>[]
        {
          () => new UserPrincipal(context) {DisplayName = search},
          () => new UserPrincipal(context) {Name = search},
          () => new UserPrincipal(context) {SamAccountName = search}
        };

        var groupFilters = new Func<GroupPrincipal>[]
        {
          //() => new GroupPrincipal(context) {DisplayName = search},
          () => new GroupPrincipal(context) {Name = search},
          () => new GroupPrincipal(context) {SamAccountName = search}
        };

        var users = userFilters.Search(new PrincipalEqualityComparer<UserPrincipal>(), contextType);
        var groups = groupFilters.Search(new PrincipalEqualityComparer<GroupPrincipal>(), contextType);

        return users.Convert(RecipientType.User).Concat(groups.Convert(RecipientType.Group)).ToArray();
      }
    }
  }

  class PrincipalEqualityComparer<TPrincipal> : IEqualityComparer<TPrincipal> where TPrincipal : Principal
  {
    public bool Equals(TPrincipal x, TPrincipal y)
    {
      if (x != null && y == null || x == null && y != null) return false;
      return ReferenceEquals(x, y) || string.Equals(x.Name, y.Name) || string.Equals(x.DisplayName, y.DisplayName);
    }

    public int GetHashCode(TPrincipal obj)
    {
      return 0; // obj.GetHashCode();
    }
  }


Extract changesets between last two tags in Mercurial

You didn't specify that you wanted to leave a tags.txt file as an intentional side-effect of your script.  I'm going to assume that it's an unwanted temporary file.  In that case, you can read the output of hg directly through a pipe.  Furthermore, the file object can be used as an iterator to fetch just two lines, with no for-loop.

from subprocess import Popen, PIPE

# Read the first two lines of `hg tags`
with Popen(['hg', 'tags'], stdout=PIPE).stdout as hg_log:
    latestTagLine = hg_log.next()
    previousTagLine = hg_log.next()

The code to interpret each line is repeated, and therefore deserves to be put into a reusable function.  Instead of splitting, use a capturing regular expression.

import re

def parse_tag_line(line):
    match = re.match(r'^(.*) *(\d+):(.*)', line)
    return dict([
        ('tag', match.group(1)),
        ('rev', match.group(2)),
        ('hash', match.group(3)),
    ])

Finish up by generating the output:

log_range = '%s:%s' % (latestTag['hash'], previousTag['hash'])
with open('diff.txt', 'w') as diff:
    Popen(['hg', 'log', '-r', log_range], stdout=diff)

  Personally, I would prefer to just dump the output to sys.stdout, and use the shell to redirect the script's output to a file (script > diff.txt) instead of hard-coding diff.txt in the script itself.  Then, the epilogue would become

log_range = '%s:%s' % (latestTag['hash'], previousTag['hash'])
Popen(['hg', 'log', '-r', log_range])

Putting it all together:

import re
from subprocess import Popen, PIPE

def parse_tag_line(line):
    match = re.match(r'^(.*) *(\d+):(.*)', line)
    return dict([
        ('tag', match.group(1)),
        ('rev', match.group(2)),
        ('hash', match.group(3)),
    ])

# Read the first two lines of `hg tags`
with Popen(['hg', 'tags'], stdout=PIPE).stdout as hg_log:
    latestTag = parse_tag_line(hg_log.next())
    previousTag = parse_tag_line(hg_log.next())

log_range = '%s:%s' % (latestTag['hash'], previousTag['hash'])

# Write `hg log -r ...:...` to diff.txt
with open('diff.txt', 'w') as diff:
    Popen(['hg', 'log', '-r', log_range], stdout=diff)


Prompting for two integers and dividing, using exceptions to handle divide-by-zero errors

Exceptions are for exceptional cases

  I'm trying to learn exception handling in C++.

This is a very bad example to learn exceptions. They are meant for situations where you cannot know that there is something wrong. For example if you want to use std::vector<int> but you're out of memory:

std::vector<int> vec(4000000000LL); // will likely throw std::bad_alloc

I'll add an exercise for you at the end of this review. But let's have a look at your code.

A review of your code

You're not using using namespace std, which is a great plus.

However, you include <stdexcept>, which isn't necessary here. You don't use any of the standard exception, instead, you throw 0. However, system is in <cstdlib>. You should include that one instead.

Next, naming.

int i1, i2;

Those names don't have any meaning. What is i1? What is i2? Naming is hard, but it's important. You're going to use them as numerator and denominator, or as dividend and divisor, so call them appropriately:

int numerator, denominator;

Getting rid of goto

Now to your try block. Don't. Use. goto. You want to repeat the block until you didn't get 0. We can do that with a simple while:

int main (){
    int numerator, denominator;

    cout << "Give two integers" << endl;
    cin >> numerator;

    // continue forever                               (1)
    while(true) {
        try {
            cin >> denominator;
            if (denominator == 0)
                throw 0; // this will "go to" catch   (2)

            cout << numerator / denominator << endl;
            break; // we didn't throw, we can stop    (3)
        }
        catch (...) {
            cout << "Second integer cannot be zero , please enter a valid integer" << endl;
        }
    }

    system("pause");
    return 0;
}

A "clean" version without exceptions

However, that's not how I would write the program, since exceptions are meant for exceptional cases. I would write

#include <iostream>
#include <cstdlib>

int main() {
    int numerator, denominator;

    std::cout << "Please enter two integers." << std::endl;
    std::cin >> numerator >> denominator;

    while(denominator == 0) {
        std::cout << "Second integer cannot be zero. Try again." << std::endl;
        std::cin >> denominator;
    }

    std::cout << (numerator / denominator) << std::endl;

    system("pause");
    return 0;
}

As you can see, exceptions aren't really necessary to keep the user from entering a zero. Furthermore, the control flow is a lot easier to read.

Note that system("pause"); won't work on Linux, since there is no application called pause. If possible, try to use your IDEs features to keep your console window alive even after your program finished, or have the output logged somewhere, or use it in the CMD/PowerShell.

Exception exercise

We need a better exercise for your exceptions. How about this?

int divide(int numerator, int denominator) {
    if(denominator == 0)
        throw "divide: division by zero";
    return numerator / denominator;
}

This is a valid place for an exception. A function has only a single return value, so it can only tell you that something is wrong with an exception*.

Exercise: Try to use that function in your code and handle the exception. Also show the exception to the user, they're probably interested in what went wrong.

You should use the code similar to

std::cout << divide(numerator, denominator) << std::endl;

that is you don't check the denominator. Note that this is still a contrived example.

* Technically, that's not true. You can use references, pointers, or wrap the return value in some struct/variant, but let's keep things simple


Rotate a N by N matrix by 90 degrees clockwise

Copying 2D array

JSON is not for copying data.

const newMatrix = JSON.parse(JSON.stringify(matrix))

Should be

const newMatrix = matrix.map(row => [...row]);

Naming

The naming you use is too verbose and gets in the way of readability.

For 2D data it is common to use row, col or x,y to refer to the coordinates of an item.

As x and y are traditionally ordered with x (column) first and y (row) second 2D arrays don't lend them selves to that naming. It is acceptable to abbreviate to r, c or indexing 2D arrays (within the iterators, not outside)
transpose as a function name is too general. It would be acceptable if transpose included a argument to define how to transpose the array but in this case rotateCW would be more fitting.
For 2D data the distance from one row to the same position on the next is called the stride
As the input array is square there is no need to get the stride from the inner array.  const stride = matrix[0].length; should be   const stride = matrix.length;

Rewriting your solutions

Both these solutions are \$O(n)\$ time and space.

function rotateCW(arr) {
    const stride = arr.length;
    const res = arr.map(row => [...row]);
    for (let r = 0; r < stride; r++) {
        const row = arr[r];
        for (let c = 0; c < stride; c++) {
            res[c][stride - 1 - r] = row[c];
        }
    }
    return res;
};  // << redundant semicolon. Lines end with ; or } not both

Be careful when describing a function as declarative. Though the definition is somewhat loose you should make the effort to declare all high level processing as named functions and the imperative code at the lowest level.

const rotateCW = arr => {
    const rotItem = (r, c, item) => res[r][arr.length - 1 - c] = item;
    const processRow = (row, r) => row.forEach((item, c) => rotItem(c, r, item));
    const res = arr.map(row => [...row]);
    arr.forEach(processRow);
    return res;
}

Functional

Don't get caught up on declarative, in your past questions you had the focus on functional. You should keep that focus.

In this case the core of the solution is converting a row column reference (or coordinate) into the inverse of the rotation. We rotate CW by replacing the current item by the one 90deg CCW of it. arr[y][x] = arr[stride-1-x][y]

The next example is functional and also the smallest code.

const rotateCW = arr => {
    const rotItem = (r, c) => arr[arr.length - 1 - r][c];
    const processRow = (row, r) => row.map((item, c) => rotItem(c, r));
    return arr.map(processRow);
}

or as a one liner

const rotCW = arr => arr.map((row, y) => row.map((v, x) => arr[arr.length - 1 - x][y]));

The \$O(1)\$ space solution.

The "no extra space" simply means that it should be \$O(1)\$ space complexity. This can be done via the traditional swap,

 var a = 1, b = 2;
 const temp = a;
 a = b;
 b = temp;

Or in ES6+

 var a = 1, b = 2;
 [a,b] = [b,a];

The swap does not have to be just two items but can be over as many as you want (shifting), the only requirement is that only one spare slot is needed to shift all items.

var a = 1, b = 2, c = 3, d = 4;
const temp = a;
a = b;
b = c;
c = d;
d = temp;

Or in ES6+

var a = 1, b = 2, c = 3, d = 4;
[a, b, c, d] = [b, c, d, a];

Note The ES6 method for swapping, as a source code complexity reduction, is great...

but the JS engine does not know you are just swapping (or shifting), it creates an array to hold all the items on the right so that it does not overwrite them when assigning the new values. That means that the ES6+ swap is \$O(n)\$ space complexity.

Example

I come from a very heavy visual related background and x,y are the most logical way to index 2D+ arrays so will use it in this example.

function rotate2DArray(arr) {
    const stride = arr.length, end = stride - 1, half = stride / 2 | 0;
    var y = 0;
    while (y < half) {
        let x = y;
        while (x < end - y) {
            const temp = arr[y][x];
            arr[y][x] = arr[end - x][y];
            arr[end - x][y] = arr[end - y][end - x];
            arr[end - y][end - x] = arr[x][end - y];
            arr[x][end - y] = temp;
            x ++;
        }
        y++;
    }
    return arr;
}

The above is very unreadable and it pays to put a little order and alignment to the source

function rotate2DArray(arr) {
    const stride = arr.length, end = stride - 1, half = stride / 2 | 0;
    var y = 0;
    while (y < half) {
        let x = y;
        const ey = end - y;
        while (x < ey) {
            const temp = arr[y][x], ex = end - x;
            arr[y ][x ] = arr[ex][y ];
            arr[ex][y ] = arr[ey][ex];
            arr[ey][ex] = arr[x ][ey];
            arr[x ][ey] = temp;
            x ++;
        }
        y++;
    }
    return arr;
}

Thus the array is rotated in place for \$O(1)\$ space.


Caesar Cipher implementation - Odin Project

The code can be simplified, but you're on the right track.

A function is sufficient for a simple string filter like this; a class would be overkill.  I would rename the first parameter to plaintext and the result to ciphertext because that is the standard terminology.

The function should return the ciphertext rather than printing it.  The caller should have the flexibility to print it, show it in a GUI, store it in a database, or whatever.

Instead of split("").each, you can iterate over the plaintext using plaintext#each_codepoint.  You can also build the result by appending to a string rather than joining a list.

The if…elseif would be slightly better as a case expression.  You don't need the special case for " "

def caesar_cipher(plaintext, shift)
  ciphertext = ''
  plaintext.each_codepoint do |asc|
    ciphertext << case asc
      when 'a'.ord..'z'.ord
        'a'.ord + (asc - 'a'.ord + shift) % 26
      when 'A'.ord..'Z'.ord
        'A'.ord + (asc - 'A'.ord + shift) % 26
      else
        asc
    end
  end
  ciphertext
end


SqlConnection, SqlCommand and SqlDataAdapter are implementing the IDisposable interface. Enclosing the usage of these objects inside a using statement ensures that the objects will always be proper disposed because the using statement just equals a try...finally where the objects would be disposed in the finally part.

The main problem regarding your performance issue is, that by calling the AutoResizeColumns() method the event will be triggered for each row and each column.
This results for each row and each column that you iterate over every row in the DataGridView.

So if we assume you have 12,000 rows with at least 5 columns .... you can do the math yourself.

The DataGridViewCellFormattingEventArgs has a property RowIndex which allows to access a single row so you should use this.

Summing this up in some code could look like so

private bool shouldFormattingBeDone = false;
private void PopulateIT()
{
    datagridview1.Visible = true;
    lblNoData.Visible = false;

    string connString = @"Connection String";
    string query = @"SELECT * from tempdata";

    using (SqlConnection conn = new SqlConnection(connString))
    using (SqlCommand cmd = new SqlCommand(query, conn))
    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
    {
        conn.Open();
        da.Fill(formattedDT);
    }
    datagridview1.DataSource = formattedDT;

    shouldFormattingBeDone = false;
    datagridview1.AutoResizeColumns();
    shouldFormattingBeDone = true;
}

private void datagridview1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (shouldFormattingBeDone == false) { return; }

    DataGridViewRow row = datagridview1.Rows[e.RowIndex];

    if (row.Cells["Jake"].Value == System.DBNull.Value && row.Cells["Jones"].Value == System.DBNull.Value && row.Cells["Lati"].Value == System.DBNull.Value && row.Cells["Venitia"].Value == System.DBNull.Value)
    {
        row.DefaultCellStyle.BackColor = Color.Red;
    }

}

This could be beautified by having an extension method which takes a DataGridViewCell as a parameter like so

public static class DataGridViewExtension
{
    public static bool IsDbNull(this DataGridViewCell cell)
    {
        return cell.Value == DBNull.Value;
    }
}

resulting in  the if condition looking like so

if (row.Cells["Jake"].IsDbNull() && row.Cells["Jones"].IsDbNull() && row.Cells["Lati"].IsDbNull() && row.Cells["Venitia"].IsDbNull())

PS: I can't remember if the connection needs to be open when the constructor of the SqlDataAdapter is called.


PEP 8

The Style Guide for Python Code’s naming conventions recommends again mixedCase identifiers.  CapWords are for classes and types, snake_case is for functions, methods and variables.  Thus, getMaxCharCount, maxCount and finalWord should be renamed to get_max_char_count, max_count and final_word.

string

string is an importable module in Python.  Its use as an identifier should be discouraged.

Intervals

interval is a perfectly fine variable, but interval[0] and interval[1] are confusing.  Are those the zeroth and first intervals in a list of intervals?  It would be better to unpack the interval immediately into the starting and ending values of the interval.  This can even be done directly by the for statement:

    for start, end in queries:
        if start == end:
            ...

Special Casing

You have special-cased the length 1 interval.  Why?  Does the general purpose version of the code not work for the length one interval?  Is it too slow?  Is the special-case a common occurrence, or does checking for it actually slow down the general purpose case be introducing an unnecessary if statement?

List Comprehension

If we remove the special-case, your code reads approximately:

    max_count = []
    for start, end in queries:
        max_count.append(...)

This pattern is usually re-written using list-comprehension, since it is much faster than repeated calls to .append():

    max_count = [ ... for start, end in queries ]

The only issue is what should be used in place of ....  Prior to Python 3.7, there was no easy way to refer to the result of a computation multiple times in one expression.  Python 3.8 introduces the “walrus operator” (:=) which allows variables to be assigned inside of other expressions.  We can use this to avoid referencing and slicing final_word twice:

    max_count = [ (span := final_word[start:end+1]).count(max(span)) for start, end in queries ]

Reworked Code (Python 3.8)

def get_max_char_count(s, queries):
    final_word = s.lower()
    return [(span := final_word[start:end+1]).count(max(span)) for start, end in queries]

This code may be slightly faster than your original code, with the speed up mostly from replacing .append with list comprehension.  To really see significant speed gains, you need to improve the algorithm.

Algorithmic Improvement

Since this is a coding challenge, I won’t give you code for the better algorithm, but I will get you started in the right direction.

How many times are you looking at any given character of final_word?

Consider the following test case:

2000
AAAAAAAAAAA...[2000 A’s] ... AAAAAAAAAAAA
2000
0 1999
0 1999
0 1999
  :      :
[2000 duplicate lines]
  :      :
0 1999
0 1999

The result should be a list of 2000 copies of the number 2000.  We did this in our head.  Your algorithm will test each character 4000 times; 2000 times during max and another 2000 times during count.  Clearly, we’ve got room for improvement.  The ideal would be if each character was only tested twice, once during max, and once during count.  But how can we achieve this?

Consider another test case:

       20
     AAAABBBBCCCCBBBBCCCC
     3
     0 11
     4 15
     8 19

Can you see any way of computing intermediate results and reusing them?

   Can you divide this into 5 subproblems?  Can you combine the first 3 subproblems together to get the first answer?  4 A’s, 4 B’s and 4 C’s makes 4 C’s.  Subproblems 2 to 4 to get the second answer?  4 B’s, 4 C’s and 4 B’s makes 4 C’s.  Subproblems 3 to 5 to get the 3rd answer?  4 C’s, 4 B’s and 4 C’s makes 8 C’s.  How would you store the subproblems results?  Where did we get the boundaries of the subproblems?


Prefer double to float for calculations

Unless you're extremely constrained for space, or you have a platform with software floating-point (or very poor FP hardware), there's no reason to use float.

Reduce the scope of index variable

Modern C allows us to declare i local to the loops:

for (int i = 0;  i < input_len;  i++)

Hoist the log(sum) calculation

Your compiler's optimizer will probably spot that log(sum) does not change, but why not help it?

const double log_sum = log(sum);
for (int i = 0;  i < input_len;  i++) {
    input[i] = expf(input[i] - m - log_sum);
}

In fact, since m is also constant, we should hoist that, too:

const double scale = m + log(sum);
for (int i = 0;  i < input_len;  i++) {
    input[i] = expf(input[i] - scale);
}


More DRY way of conditionally filling variables?

Since you have a reasonable number of variables that all relate to one particular thing (chart settings), rather than having lots of standalone variables, you might consider using a single object instead. Regardless of any other issues with the code, I'd consider a single object to be slightly more appropriate than multiple similar standalone variables regardless.
Using a single object can also let you exploit a shortcut: if data doesn't exist, just use an empty object. Otherwise, type out the object literal using your formulas:
const getChartSettings = (gridInterval, data) => {
  if (isEmptyObject(data)) {
    return {};
  }
  const yTopTickValue = Math.ceil(data.yMax / gridInterval) * gridInterval;
  const yBottomTickValue = Math.floor(data.yMin / gridInterval) * gridInterval;
  const xTopTickValue = Math.ceil(data.yMax / gridInterval) * gridInterval;
  const xBottomTickValue = Math.floor(data.yMin / gridInterval) * gridInterval;
  return {
    yTopTickValue,
    yBottomTickValue,
    yTickCount : (chartSettings.yTopTickValue - chartSettings.yBottomTickValue) / gridInterval + 1,
    xTopTickValue,
    xBottomTickValue,
    xTickCount : (chartSettings.xTopTickValue - chartSettings.xBottomTickValue) / gridInterval + 1,
  };
};

Then you can call the function, reference chartSettings.yBottomTickValue, and either get a number or undefined.
YMMV on whether that's worth using or not.
It's unfortunate that the TickCounts depend on the prior calculated values - if they didn't, it could be made to look a lot simpler by just returning the single object literal instead of defining variables beforehand.
You could still return an object alone without prior defined variables by making the TickCounts getters instead, but that'd be weird-looking, I wouldn't use it:
return {
  yTopTickValue: Math.ceil(data.yMax / gridInterval) * gridInterval,
  yBottomTickValue: Math.floor(data.yMin / gridInterval) * gridInterval,
  get yTickCount() {
    return (this.yTopTickValue - this.yBottomTickValue) / gridInterval + 1;
  },
  // ...

Operator position You also might consider putting the + 1 at the beginning, rather than at the end, eg:
xTickCount : 1 + (chartSettings.xTopTickValue - chartSettings.xBottomTickValue) / gridInterval,

I think that's a bit clearer than putting it right next to the / gridInterval. You could also consider using no-mixed-operators.


Compare directory entries (sort by access date)

One declaration per line, please.

char File[SavesLen+Len[FirstLen > SecondLen]+2]; is extremely hard to read. In fact, I suspect that there is a bug. Correct me if I am wrong, an intention is to allocate enough memory to accomodate the longest pathname. Now, if FirstLen is indeed greater than SecondLen, the condition evaluates to true, which is in this context is 1. Now the VLA size becomes SaveLen + Len[1] + 2, that is SaveLen + SecondLen + 2, which is not enough for the longer first name.

The loop running just two iterations is better be two calls to a function. Consider
  static time_t get_atime(const char * filename) {
      char path[SavesLen + 1 + strlen(filename) + 1];
      sprintf(path, "%s/%s", S, filename);

      struct stat stat;
      stat(path, &stat);
      return stat.st_atimespec.tv_sec;
  }

  static int Q(const struct dirent **const First, const struct dirent **const Second) {
      time_t time0 = get_atime((*First)->d_name);
      time_t time1 = get_atime((*Second)->d_name);
      return time1 - time0;
  }

Of course, Q is not a name for a function. compare_atime perhaps?


Looping text in Python with directional control

When I try it, it doesn't really work unless I add stdout.flush() after each stdout.write().

The padding isn't controllable, as neither set_text() nor update_loop() accepts a padding parameter.

In my opinion, it should print the original text before performing the first shift.

Global variables are bad.  In this case, I'd eliminate them altogether by simplifying the code.  Take advantage of itertools.cycle() and Python's support for negative indexes.  I wouldn't bother with converting the string to a list and back to a string again.

DIRECTION_LEFT_TO_RIGHT is a bit verbose.  I suggest SCROLL_RIGHT instead.  "Frequency" sounds like it should go faster as the number increases: 10 Hz is faster than 1 Hz.  I suggest period as the name for the delay.

from itertools import cycle
from sys import stdout
from time import sleep

SCROLL_RIGHT = -1
SCROLL_LEFT = +1

def animate_text(text, scroll=SCROLL_RIGHT, period=0.5, padding=5):
    text += ' ' * padding
    for offset in cycle(xrange(0, scroll * len(text), scroll)):
        stdout.write('\r' + text[offset:] + text[:offset])
        stdout.flush()
        sleep(period)

animate_text('Beautiful Lie')


Simple Python Console Game With Inefficient Code Flow

Try to forget everything that you know about the code, and assume that you aren't the author. Imagine yourself to be a third person reading the code, he/she knows nothing about it and just reading it for the first time.
ui = userinput()
choosef(ui[0],ui[1])

Alright, userinput() must take some input and put it into ui. Makes sense, but what is choosef()?.
Naming convention
Use meaningful names for functions and variables. take this example
x = 3.14
y = 24

what is x and y to the reader? Is that the price of something?
pi_value = 3.14
number_of_hours = 24

Ahhh okay, now I know exactly what 3.14 means. So If I use it somewhere the reader will also know what I exactly mean. This is an important part of writing clean code.
Another aspect is the style. There are a few ways I can write user input*
user_input()
USERINPUT()
UserInput()
userinput()

Which one should I follow?
To have a consistent naming convention, python code follows the PEP-8 naming convention. When I say follows, I mean that it is recommended that you should follow it too as other python libraries also use this. It makes the code look cleaner.
Things like functions follow : lower_snake_case
Classes follow: CamelCase
You can read the link for more information.
Taking input in Python
print('Enter your name:')
n = input()

Clearly, you want to display a message to the user before he enters something. This is why the input() function has something called input prompt.
name = input("Enter your name: ")
You can display the message between the (). This removes the additional line. Also note that I changed n to name for the reasons I mentioned above.
Formatting strings
From your code, I can see that you concatenated strings with + to form meaningful sentences. That works but there is a huge problem when you want to use variables of different types.
name = "Eric"
age = 14
job = "Comedian"
print("Hello " + name  + "You are " + age + " years old and you are a " + comedian)

TypeError: can only concatenate str (not "int") to str

Simply use Python 3's f-strings. Place the letter 'f' before "
print(f"Hello {name}, you are {age} years old ")

Cleaner.
return value from userinput()
What you are currently doing is returning a tuple of choice and name. It's better that you keep them as they are because later on, you slice from it just to get them again.
This means you directly do
return name, choice

# Calling the function

name, choice = userinput()

Code structure
Couple of points

Do not ask "Do you want to play again? " in the play_again() function. The reason you called that function should be because the user wants to play again. Move that to a playgame() function which will call user_input() every time the user wants to play the game, and break from the loop only if the user enters 'n' or "no"

spaces = spaces + 1 can be simplified into spaces += 1

Move the part where you count the number of characters into a separate function which will return an integer. So your play_game() function doesn't do anything other than play the game. When you need the characters , number_of_char = character_len( name ).

Use enum for clarity.

An improved version of the code
from enum import Enum

class PrintChoices(Enum):
    number_of_char = 'c'
    reversed_name = 'r'
    exit_choice = 'e'

def find_num_of_char(name):
    return len(name) - name.count(' ')

def reverse_name(name):
    return name[::-1]

def user_input():
    name = input("Enter your name: " )
    choice = input("Would you like to (r)everse your name\n or would you like to print the number of (c)haracters or (e)xit?: ")
    return name, choice

def clear_screen():
    print(chr(27) + "[2J")

def play_game():
    while True:
        clear_screen()
        name, choice = user_input()
        if choice == PrintChoices.reversed_name.value:
            print(reverse_name(name))
            input("Press any key to continue...")
        elif choice == PrintChoices.number_of_char.value:
            print(find_num_of_char(name))
            input("Press any key to continue...")
        elif choice == PrintChoices.exit_choice.value:
            break
        else:
            input("Invalid input, Press any key to continue...")

play_game()

Note: I have also added print(chr(27) + "[2J") to clear the screen.


Program to compress a string of characters

For better performance you should be able to eliminate the Hashmap and use a StringBuilder to count and build the compressed string in one operation:

public static String Compress(String input)
{
    StringBuilder sb = new StringBuilder();
    int i = 0;
    int limit = input.length() - 1;
    char next = '\0';
    while (i < limit)
    {
        int count = 1;
        next = input.charAt(i++);
        while (i <= limit && next == input.charAt(i))
        {
            count++;
            i++;
        }
        sb.append(next);
        sb.append(count);
    }
    if(i == limit)
    {
        sb.append(input.charAt(i));
        sb.append(1);
    }
    return sb.toString();
}

Caveat:  This code won't work with the full unicode set


No, it's not correct.

View-model shouldn't contain anything related to view. It means LoginViewModel shouldn't contain references on progress bar and label. ProgressBar and Label properties inside a view-model violate MVVM.
Any changes in UI elements should be done via bindings specified in XAML. Those bindings have to be linked to properties of a view-model. Changing these properties, UI get updated.
To make bindings work you should notify them about changes in view-model. For that purpose you need to implement INotifyPropertyChanged interface on the view-model and raise PropertyChanged event every time a property changed.

Let's see example of how you can remove ProgressBar from the LoginViewModel.

First of all, view -model should implement INotifyPropertyChanged interface which contains PropertyChanged event:

public class LoginViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
}

Then remove ProgressBar property and add LoginInProgress:

private bool _loginInProgress;

public bool LoginInProgress
{
    get => _loginInProgress;
    set
    {
        if (value == _loginInProgress)
            return;

        _loginInProgress = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(LoginInProgress)));
    }
}

Now in the LoginCommand body instead of

ProgressBar.IsVisible = true;

write

LoginInProgress = true;

And instead of

ProgressBar.IsVisible = false;

write

LoginInProgress = false;

Then in XAML bind Visibility of the progressBar to this property:

<ProgressBar x:Name="progressBar"
             Visibility="{Binding Path=LoginInProgress, Mode=OneWay, Converter="{StaticResource BooleanToVisibilityConverter}"}"
             .../>

Somewhere in resources you should define BooleanToVisibilityConverter:

<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>

And that's all. You need to eliminate all the view related stuff from the view model in such way. It is how MVVM have to be implemented.


Dynamic programming based range minimum query

1. Review

There are no docstrings. What do these functions do? What do they return? How do I use them?
The function build_rmq constructs a persistent data structure which can then be queried by calling the function rmq_query. When you have a persistent data structure and functions that operate on it, this is good candidate for making into a class.
The comment on this line is not quite right:

rmq_map = defaultdict(int) # key: tuple of (start, end) index, value: min value

the second element of the key is a step, not an end index.
There is no need to use a defaultdict here, since the code always fills in the entry before looking it up. An ordinary dictionary would do fine.
This code:

j = 0
while 2 ** j - 1 < len(numbers):
    j += 1

computes the smallest power of 2 that is greater than len(numbers). It would be simpler to use int.bit_length:

j = len(numbers).bit_length()

(In ChatterOne's answer it is suggested that you use int(log(len(numbers), 2)). I think this is a dangerous suggestion, because log makes approximations that can lead to errors. For example,

int(log(2**48 - 1, 2))

evaluates to 48, but the correct result is 47. In order to check that these errors can't actually cause your code to fail, you need to do numerical analysis. This seems complicated and error-prone to me, compared to sticking with integer arithmetic where you know the results are exact.)
Similarly, this loop:

j = 0
while start + 2 ** j - 1 <= end:
    j += 1

becomes:

j = (end - start + 1).bit_length()

This code subtracts 1 from j and then adds it back again, which is not necessary:

j -= 1
for step in range(0,j+1):

range(0, x) can be abbreviated to range(x).
rmq_map[(i,step)] does not need the parentheses: rmq_map[i, step] is the same.
The two loops over step and i can be combined into a single loop using itertools.product
I would avoid the special case if step == 0 by having a separate loop to handle that case:

rmq_map = {(i, 0): m for i, m in enumerate(numbers)}

and then looping over step starting from 1.
In Python it is usual to represent a range in half-open fashion (exclusive at the upper end). It would be convenient if rmq_query took its arguments in the same way.
The top-level code runs a single range query but does not check that the result is correct. It would be easy to check the result of rmq_query(start, end) against min(numbers[start:end+1]). It would then be easy to turn this into a unit test using the features in the unittest module.

2. Revised code

from itertools import product

class RangeMinimum(object):
    "Data structure providing efficient range-minimum queries."

    def __init__(self, numbers):
        "Build a RangeMinimum object for the given sequence of numbers."
        # Mapping from (start, step) to min(numbers[start:start + 2**step])
        self._rmq = rmq = {(i, 0): m for i, m in enumerate(numbers)}
        n = len(numbers)
        for step, i in product(range(1, n.bit_length()), range(n)):
            j = i + 2 ** (step-1)
            if j < n:
                rmq[i, step] = min(rmq[i, step-1], rmq[j, step-1])
            else:
                rmq[i, step] = rmq[i, step-1]

    def query(self, start, stop):
        "Return min(numbers[start:stop])."
        j = (stop - start).bit_length() - 1
        x = self._rmq[start, j]
        y = self._rmq[stop - 2 ** j, j]
        return min(x, y)

import unittest
import random

class TestRangeMinimum(unittest.TestCase):
    def test_range_minimum(self):
        n = 1000
        numbers = [random.randrange(n) for _ in range(n)]
        rmq = RangeMinimum(numbers)
        for _ in range(n):
            start, stop = sorted(random.sample(range(n + 1), 2))
            self.assertEqual(rmq.query(start, stop), min(numbers[start:stop]))

3. Generalization

There's nothing special about the minimum here — exactly the same algorithm can be used for range-maximum queries, or for querying other kinds of statistic on a range (such as the longest common prefix, or the union of sets).

So that suggests this kind of generalization:

from itertools import product

class RangeQuery(object):
    "Data structure providing efficient range queries."

    def __init__(self, items, fn):
        """Build a RangeQuery object for a sequence of items.

        fn -- function taking two items and returning their query
        result, for example "min" to query the range-minimum. It must be
        associative, commutative, and idempotent.

        """
        # Mapping from (start, step) to reduce(fn, items[start:start + 2**step])
        self._rq = rq = {(i, 0): item for i, item in enumerate(items)}
        self._fn = fn
        n = len(items)
        for step, i in product(range(1, n.bit_length()), range(n)):
            j = i + 2 ** (step-1)
            if j < n:
                rq[i, step] = fn(rq[i, step-1], rq[j, step-1])
            else:
                rq[i, step] = rq[i, step-1]

    def query(self, start, stop):
        "Return reduce(fn, items[start:stop])."
        j = (stop - start).bit_length() - 1
        x = self._rq[start, j]
        y = self._rq[stop - 2 ** j, j]
        return self._fn(x, y)

import random
import unittest

class TestRangeQuery(unittest.TestCase):
    def test_range_minmax(self):
        n = 1000
        items = [random.randrange(n) for _ in range(n)]
        rqmin = RangeQuery(items, min)
        rqmax = RangeQuery(items, max)
        for _ in range(n):
            start, stop = sorted(random.sample(range(n + 1), 2))
            self.assertEqual(rqmin.query(start, stop), min(items[start:stop]))
            self.assertEqual(rqmax.query(start, stop), max(items[start:stop]))


This question is better suited for Programmers Stack Exchange than Code Review...

To answer your question - if you do evaluations like that it means that most likely you have a design issue at the first place. In most cases you should not branch your logic based on specific type you're working with, since it breaks Open/Closed principle and Liskov substitution principle.
Either your class should be a generic class accepting type of the animal to work with, or there must be a virtual method on Animal that should be overridden in Cat and Dog, or something else, depending on specifics of your case.

In most cases the is/as checks are used to check whether a certain object supports an interface or well-known behaviour like:

object message = ....;
if (message is IEnumerable) //now we know that we can iterate on it

or

int Count(this IEnumerable source) //"simplified" version of LINQ's extension method
{
    ICollection collection = source as ICollection;
    if (collection != null)
        return collection.Count;

    int count = 0;
    foreach (var element in source)
        count++;

    return count;
}


Getting all (forward) permutations of a list of strings

Here's an alternative approach using itertools.combinations to generate the (start, end) pairs:

from itertools import combinations
w = "Vehicula Sem Risus Tortor".split()
results = [' '.join(w[i:j]) for i, j in combinations(range(len(w) + 1), 2)]


Will this code adjust its alignments automatically with respect to the user's screen?

Yes

the code will auto align to the user's browser window, as long as the browser window is greater than 1200px

Second Question

if you keep the files on your computer they will not be online, you have to host the pages on a web server and obtain a Domain name and all sorts of other stuff pertaining to attaching that site to the Domain Name and DNS Servers and such.

most of the time they will give you a root directory and as long as you keep the file structure the same you shouldn't have to change the links, you should look into absolute pathing and because I could be wrong, I usually have to check to make sure that I set my links right,  but I am pretty sure that your graphics should show up if they are in the root folder of the site with out having to change the links.

personally I would recommend that you create a folder called images or pictures or graphics  something to that effect, and change the links to images/logo.gif same with your StyleSheets those should as well be in their own folder, I usally name my CSS folder CSS


Ok, so I'm happy with the foreach loops now.

To get the Table names where I wanted them I simply had to encapsulate the PHP in HTML tags:

<?php print_r($phpCore->getDbTables()); ?>

<form>

<?php
foreach($phpCore->getDbTables() as $tablename) {
    echo '
'.$tablename.'
';
    echo '
';
    foreach($phpCore->getColumnNames($tablename) as $fieldnames) {
        echo ''.$fieldnames.'	';
    }
    echo '
';

    echo '
';
    foreach($phpCore->populateTable($tablename) as $tabledata) {
        echo '<input type="text" value="'.$tabledata.'"></input>	';
    }
    echo '
';

}
?>

</form>


Specify Requirements Up Front

The whole point of binary search is that it's O(lg N). If you're going to check that the array is sorted first, you may as well do a linear search. Not to mention that you're doing even worse here since you're checking that the array is sorted on every recursive call, so now we have an O(N lg N) search. Binary search should assume a sorted list. If the user doesn't provide one, it's garbage in garbage out.

Use appropriate defaults

Usage-wise, it makes more sense to just write:

idx = binSearch(ary, 5)

So let's do:

def binSearch(ary, elem):
    def recurse(first, last):
        ...

    return recurse(0, len(ary)-1)

What if it's not found?

You should have an error case, if first > last, you should return None. Otherwise, you have infinite recursion.

Full solution:

def binSearch(ary, elem):
    def recurse(first, last):
        mid = (first + last) / 2
        if first > last:
            return None
        elif (ary[mid] < elem):
            return recurse(mid + 1, last)
        elif (ary[mid] > elem):
            return recurse(first, mid - 1)
        else:
            return mid

    return recurse(0, len(ary)-1)


Handling default value for int64_t representing an edge in an adjacency matrix

Use of macros
In this case, the macro you using is from a library header that was included with your compiler. This header (ultimately limits.h, although <climits> is usually used with C++ code) is also used by C code, so C++ specific language features cannot be used. These are OK to use.
The C++ way of referencing a minimum value for a type is to make use of std::numeric_limits (in the <limits>) header. In your case, you can replace _I64_MAX with std::numeric_limits<int64_t>::min().
Other notes
All of the references to this-> are unnecessary and can be removed from your code. You rarely need to specify this in C++ code (there a few specific cases where it is needed, like for variable name disambiguation or calling a function thru a member function pointer).
The for loop might be able to be rewritten using iterators or the range-for style if this is supported by the SinglyLinkedList type.


Loading GIF form on a Windows console app using threads

I don't know much about threading, so I can't really comment on that, but there is an opportunity to extract some logic that I am sure is used elsewhere in your project. You have this in ShowLoadingGif()

Point formCenterPt = new Point()
{
    X = this.Location.X + (this.Width/2),
    Y = this.Location.Y + (this.Height/2)
};

And this in ShowLoading()

Point offsetPt = new Point()
{
    X = parentCenter.X - (loading.Width /2),
    Y = parentCenter.Y - (loading.Height/2)
};

I would create two functions that take a form as an argument and return a point representing the StartingPosition and center point respectively.

I'm not a fan of this If statement.

try
{
    this.Enabled = true;
    if(loadingThread.IsAlive)
    loadingThread.Abort();
}

First off, at the very least, loadingThread.Abort needs to be indented properly.

if(loadingThread.IsAlive)
    loadingThread.Abort();

But I still don't like it. Let's say down the road Mr. Maintainer realizes that something else should happen if(loadingThread.IsAlive. Then they do something like this.

if(loadingThread.IsAlive)
    loadingThread.Abort();
    foo.bar();

The problem here is, foo.bar() will always be executed, but it looks like it will only be executed if(loadingThread.IsAlive).

So, there are really only two options in my mind.

Write it as a single line If statement.

if (loadingThread.IsAlive) loadingThread.Abort();

Or put the braces in.

if (loadingThread.IsAlive)
{
    loadingThread.Abort();
}

This also makes me uncomfortable.

catch (Exception ex)
{
    Log(String.Concat("Loading gif thread release failed: ",ex));
}

You're swallowing every possible exception with nothing more than a message in a log file. You should figure out which exceptions you can gracefully handle and catch only those.


I'd suggest to accompany the code with comments. Not just for the purpose of review, but also for your own. After a few weeks it's hard to remember all the details, and what seems to be clear now will be hard to read later. Especially in this case when all arguments are of String or [String], it'd be very helpful to document them (see Function arguments).

Some more thoughts: The code isn't that easy to read. One reason for that I see
is that your functions often entangle together several goals. Extracting common
functionality into smaller helper functions would help.

Specific comments:

parse :: String -> ([String], String)
parse ('/':'/':text)    = parseCustomDelimiters [] text
parse body              = (defaultDelimiters, body)

The name is basically meaningless - what does it parse? Why do you call the
string text in one place and body in another?

parseDelim :: String -> String -> (String, String)
parseDelim (']':xs) delim = (delim, xs)
parseDelim (x:xs) delim = parseDelim xs (delim++[x])

This basically is "read until a specific character and return both parts". And
the second argument is redundant, it's only an implementation detail, and
obscures how the function should be used.  I'd create a helper function like
readUntil :: Char -> String -> (String, String), and implement it using
break.
And then just parseDelim = readUntil ']'.

splitAtDelims :: ([String], String) -> [String]
splitAtDelims (delims, body) = foldr splitEachOnSubStr [body] delims
    where
        splitOnSubStr = split . dropBlanks . dropDelims . onSublist
        splitEachOnSubStr = concatMap . splitOnSubStr

The type is quite uncommon. I'd rather use

splitAtDelims :: [String] -> String -> [String]

and then use uncurry splitAtDelims when needed.

parseCustomDelimiters :: [String] -> String -> ([String], String)
parseCustomDelimiters [] (delim:'\n':body) = ([[delim]], body)
parseCustomDelimiters delims ('\n':rest)   = (delims, rest)
parseCustomDelimiters delims ('[':rest)    = parseCustomDelimiters newDelims remainingText
    where
        parsed = parseDelim rest ""
        newDelims = delims ++ [fst parsed]
        remainingText = snd parsed

Again, the first argument is just an implementation detail and makes the
function both harder to read and harder to use. Rather you should define it for
example as:

parseCustomDelimiters :: String -> ([String], String)
parseCustomDelimiters = loop []
  where
    loop =  -- your original definition

Also you use both names body and rest for the same purpose, which is very
confusing. You could also use readUntil from before to simplify this, as
apparently new-line terminates processing the input. So you could just split the
body on '\n' and parse the delimiters from the first part.

Notice that when parsing delimiters, you match on the starting marker "//" in
a different function than the ending marker "\n". It's much easier to read
when such related parts are together, in one function. So you could write
another helper function, like

readBetween :: String -> String -> (String, String)

where the first and the second argument are the starting and ending makers. Then
you could write readBetween "//" "\n" text and parse the returned content.

I'd strongly encourage you to explore ReadP, which is available in base, or some other parser (like Parsec AttoParsec). The code will be then much more readable!

You can also go without such a full-featured parser, and instead implement your own, tiny one. Already you can see in your types that the core structure of a parsing function (that doesn't handle errors or multiple possibilities) is

String -> (a, String)

That is, we parse some expected value of type a and return the rest of the string. A parser is then just an encapsulation of such an idea, like newtype Parser a = Parser (String -> (a, String)) and common operations on them.

As mentioned in the comments, you didn't specify any tests, even though this was a TDD exercise. Including them would be definitely helpful. And a great way to learn about property-based testing! Testing is also extremely valuable for refactorings, to make sure you don't introduce a regression.

I hope this helps!


Convert tree to circular doubly linked list

Your code certainly seems to do the job (assuming that the tree is only a root node with two branches; otherwise you will need to implement some recursion).  It doesn't "feel" very Java-esque, but you've said in your previous questions/comments that you don't really want critique of method and variable names, so I'll try to avoid that.

if (left == null) return right;
if (right == null) return left;

This code will return null if I pass in null for both left and right.  Is that intentional?  It's unclear from the way you've written your code that that would be the desired result.  When I think about it, it makes sense that the method would return null in this scenario, but I'm not sure if you understood that consequence when you coded it, just based on the style.

if (node == null) {
    return null;
}

You should try to use consistent style in your code.  If you're going to put these checks and return statements at the beginning, either put them on the same line as the if() statement or don't.  It doesn't matter which you do, as long as you do the same thing throughout.  Makes your code much more readable and easier to maintain.

// get last element of left linkedlist
TreeNode leftLast = left.left;
TreeNode rightLast = right.left;

leftLast.right = right;
right.left = leftLast;

// now we form the list into circular again.
rightLast.right = left;
left.left = rightLast;

return left;

This entire block is very difficult to scan.  What it does isn't readily apparent by the way you've named all your variables.  For example rightLast sounds like the rightmost node in the tree, but in fact it's the left node of the right node in the tree.  Then with all the subsequent processing, it's very confusing without stepping through line-by-line to get a better understanding.  Consider renaming your variables to be more meaningful.  In my opinion, the most beautiful and elegant code is self-documenting.

Also, if you were looking for ways to further improve the code's functionality (besides adding recursion), you might look into generic types so that your nodes can hold any data, rather than just an int.


Conversion of datetime strings in PHP pages to user's timezone

I would think it would be easier and more reliable to use timezone offsets rather than exact server time vs. client time. You can get the client-side offset using new Date().getTimezoneOffset() which returns the offset in minutes from UTC. When the timezone is +2 then the offset is -120.

PHP

<meta name="timezoneoffset" content="<?php echo date('P') ?>" />

HTML

<meta name="timezoneoffset" content="+0200" />

JavaScript

var serverTimeZone= $("meta[name='timezoneoffset']").attr("content").substring(0,3);
// getTimezoneOffset returns (client timezone * -60).
// With timezones the the formula would be (clientTz - serverTz) * 60 * 60000
var timezoneOffset = (new Date().getTimezoneOffset() + (serverTimeZone * 60)) * 60000;
$("span.datetime-convert").each(function(){
    var date = parseDatetime($(this).text());
    if(date) { // If date is not wellformed the script would crash without this guard
      var offsetDate = new Date(date.getTime() + timezoneOffset);
      $(this).text(offsetDate .toLocaleString());
    }
});
function parseDatetime(value) {
    var a = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/.exec(value);
    if (a) {
        return new Date(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);
    }
    return null;
}

Also there's no need to calculate the offset for each individual date. It can be actually a bit misleading when the offset is slighlty different for each date.

http://jsfiddle.net/xXVPC/1/

More functional:

var serverTimeZone= $("meta[name='timezoneoffset']").attr("content").substring(0,3);
// getTimezoneOffset returns (client timezone * -60).
// With timezones the the formula would be (clientTz - serverTz) * 60 * 60000
var timezoneOffset = (new Date().getTimezoneOffset() + (serverTimeZone * 60)) * 60000;
$("span.datetime-convert").each(function(){
    var e = $(this);
    parseDatetime(e.text(), new function(date) {
      var offsetDate = new Date(date.getTime() + timezoneOffset);
      e.text(offsetDate.toLocaleString());
    });
});
function parseDatetime(value, callback) {
    var a = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/.exec(value);
    if (a) {
        callback(new Date(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
    }
}


You can save a bit in your input parser. You can run the list comprehension to replace the old list instead of making a new one. It's also easier to just return the list truncated with slicing rather than delete the start and end of it. Also x if True else y will always return x, so I don't know what the point of that is?

Also I'd pass in the data as a parameter, as well as give these variables and the function better names

def parse_data(raw_data):
    data = raw_data.split("\n")
    data = [line.split(" ") for line in data]
    return data[1:-1]

You're also performing inaccurate time testing. You take the start time at the beginning of the whole script. That means that it's measuring how long it takes to initialise constants and create the functions as well as running both functions. For a simple time testing approach, take a look at timeit.


Using Guava to reduce code complexity (and possibiliy to improve readability) of null check and assign default value

This is a 'specialized' task, converting an input string to a double value. Whenever I have micro-tasks like this I try to refactor them in to a method which does things properly.

As far as I am concerned, neither of the above two systems are valid. You should be validating the input value to make sure that, even if it is populated with a value, that the value is meaningful, and the parse succeeds.

So, I would have a function:

private static final double inputToDouble(String input, double defaultval) {
    if (input == null || input.isEmpty()) {
        // clear out the obviusly invalid values
        return defaultval;
    }
    try {
        return Double.parseDouble(input.trim());
    } catch (NumberFormatException nfe) {
        // silently ignore invalid data, and return the default value
        return defaultval;
    }
}

Sure, the above may be a bit more complicated, but, using it is a charm....

a = inputToDouble(input, defaultValue);

Sometimes applications do this sort of thing a lot, and in those cases I centralize these micro-tasks to static classes like:

public final class InputUtils {
    private InputUtils() {
        // nothing
    }

    public static final double inputToDouble(......) {....};

    .....

}

And then you can reference these micro-tasks from many places, perhaps even doing a static import on the class.


Based on the code provided, here are a few suggestions for where decreasing the time it takes to run it:

Too many ranges, iterators

The first thing that pops out as an area for improvement is the number of basic iterators being used, like for x in range()... and when you are using the Pandas library, it's likely there's a speed improvement there.

The problem with using for x in range() is that the script has to go through every single item in the range, one at a time. Pandas has a number of more efficient approaches to handling this, namely df.groupby(), df[colname].apply(), and in the worst case scenario for index, row in df.iterrows() that will very likely cut down your time.

Here's one example:

yi = []
for i in range(len(filtered_data)):
    if filtered_data[i].name != x_parameter:
        yi.append(filtered_data[i])

It appears you are simply trying to make a subset of filtered_data where the column name doesn't match the x_parameter. Assuming that filtered_data is a Pandas dataframe object, you can replace the code block above with this and it should be faster:

yi = filtered_data.loc[filtered_data.name != x_parameter]

Parallelize the chart generation

Instead of having the code blocked from processing data while it waits for matplotlib to create and save the next chart, making this into a separate function and process that can be run concurrently may save you some time. Breaking up the different steps in your pipeline allows you to run the slow loops separately, and also makes testing easier. For a specific example of how to use multiprocessing to run your charting code concurrently, check out this answer on Stackoverflow.

Use ipython magic functions

It is very helpful to use ipython and the magic functions it contains to debug time issues in code. For instance, if you have broken up your one big script into smaller functions, you can use %timeit and to find out what is taking too long.

Lose your self

This isn't really a speed optimization, but definitely helps with readability.

self is the first argument to this function, however it doesn't seem this variable is used elsewhere. My guess is that the function being asked about is actually a method within a class. One quick and easy optimization would be to remove self from the argument list, since it doesn't appear that you need it, and then add @staticmethod to the just before your function. So this will look like:

@staticmethod
def scatter_x_yi(filtered_data, x_parameter):
    [... rest of the method...]

More Possibilities

There may be some additional ways to optimize this code hidden in the Parameter_Estimation_Tools(). What is that process doing? Take a look if that is taking too much time.
It appears this isn't a standalone function but a method contained in a class. What if this function were broken out to run in isolation?


Parsing displayed month/year for calendar

I wouldn't worry about this being inefficient - you're not doing anything crazy here, and a calendar header probably won't need to be refreshed millions of times per second anyway.

Still, I can think of some changes that will improve readability and maintainability:

I would use a guard clause to reduce nesting, and to make it more obvious what happens when grid is null: if (_grid == null) return null;. This also gets rid of edge-cases early on, while in the current code you have to scan down to the end to see if maybe there's still an else statement following.
Adding an empty line between the end of the else block and the next if statement will make it more obvious that they're not related.
However, the last if statement only applies when displaying two months, so why not put it inside the above else block? That also allows you to remove the months.Count != 3 check.
Putting first = _grid[21]... on the same line as that if statement, and without braces, makes the control flow more difficult to see at a glance. Omitting braces can also result in subtle bugs, so some people make a point of always using braces. Either way, consistency matters: if an else statement uses braces I'd expect the related if statement to also use them.
Why assign the result to _viewMonthYearStr instead of returning it directly? That field does not seem to serve any purpose.
0, 21 and 41 are 'magic values': the meaning of those values isn't directly clear, and they easily break the code when the size of _grid needs to be changed. Replacing _grid[0] with _grid.First(), _grid[41] with _grid.Last() and _grid[21] with _grid[_grid.Length / 2] will make the code more robust and easier to understand. You could also assign their results to local variables, such as: var middleDate = _grid[_grid.Length / 2];. That simplifies the code somewhat, and it allows you to use _grid[0] and _grid[_grid.Length - 1] instead of First and Last without sacrificing readability, if you really need that little bit of performance gain.
Instead of using the local variables first, middle and last, you can return results immediately. That will make the possible output formats easier to see.
Instead of using a hash set, you can also check if the Month of the middle date is different from that of both the first and the last date. That will put a tiny bit less pressure on the GC.
Instead of calling date.ToString(format), and then using the result in an interpolated string, you can also specify the format in the interpolated string directly: $"{date:format}".
I'd rename ViewedMonthYearStr to Header or Title - that's what it's used for, after all.

With all that, this is what I would end up with:

public string Header
{
    get
    {
        if (_grid == null)
            return null;

        var firstDate = _grid.First();
        var middleDate = _grid[_grid.Length / 2];
        var lastDate = _grid.Last();

        // If more than 2 months are displayed, focus only on the middle month:
        if (middleDate.Month != firstDate.Month && middleDate.Month != lastDate.Month)
            return $"{middleDate:MMMM yyyy}";

        if (firstDate.Year != lastDate.Year)
            return $"{firstDate:MMMM yyyy} - {lastDate:MMMM yyyy}";

        return $"{firstDate:MMMM} - {lastDate:MMMM yyyy}";
    }
}


Program Arcade Games: Ch 16 Worksheet 2D-Array Algorithm

Welcome to Code Review, few suggestions:

Instead of calling .format() you can use f-Strings: print(f"#{i} is the one.")
Is better to return the result, instead of printing in the method and break
You can use all() to test the celebrity and make the code more compact.

Applying the suggestions:
def check_celebrity(grid):
    for i in range(len(grid)):
        # Check if i is a candidate celebrity
        if grid[i][i] == 1 and grid[i].count(1) == 1:
            # Ensure that i is a celebrity
            if all(grid[j][i] == 1 for j in range(len(grid))):
                return i

Test:
grid = [ [1, 0, 0, 0],
         [1, 0, 0, 0],
         [1, 0, 1, 0],
         [1, 0, 1, 0] ]

print(f"#{check_celebrity(grid)} is the one.")
# Outputs: #0 is a celebrity


Packing and unpacking two 32-bit integers into an unsigned 64-bit integer

Union provides no guarantee of memory arrangement for this.  The C++ standard merely says that it's no bigger than the storage required for the largest element, and that it's designed to only have one active data member.

If you are only targeting one compiler and one architecture it may be okay to use it to translate between types, but it is definitely skiing off-piste.

I'd be tempted to wrap the whole thing up in a class and provide getter methods.  This insulates the user from changes in the implementation of the API in the most flexible way. And, use the bitwise operations (>>, <<, | and &) inside the class.  These operations will happen on a register, rather than in memory, and therefore do not suffer for endian issues.


Categorization algorithm for discrete variables

The code can be largely simplified using apply. But first, you need a better way to test your values and assign them an id:

def convert_count_to_id(count, limits=(2, 5, 10, 20, 32)):
    for id, limit in enumerate(limits, 1):
        if count < limit:
            return id
    return id + 1

This is equivalent to your elifs chain but harder to get wrong.

Now your function can become:

def ramses_id_category(data):
    serie_name = 'Ramses Trade Id'
    value_ramses = data[serie_name].value_counts()
    id_ramses = values_ramses.apply(convert_count_to_id)
    data[serie_name] = data[serie_name].apply(id_ramses.get)

Note that I removed the return data at the end. Since you are mutating the parameter in place, there is no need to return it back since the caller will already be able to see the changes on the reference they hold when calling this function.


Let us review!

Why are you strip_slashing and strip_tagging the username and passwords before they enter the database? Why do you care? (You don't, I'll get to that in the end).
Calling __construct() inside of another method of the same object is not recommended. (What does __construct() do? As opposed to what do setUser() and setPassword() do)
Hashing your password:

With your salt constant, it loses its meaning. An attacker with access to your server can see your code, and with access to the database, he can easily run a rainbow table against your password database.
Hashing just with SHA1 once isn't very helpful. SHA1 is too fast and is susceptible to brute force attacks.
The solution to both is to use password_hash() and password_verify() look them up. (Both of those functions require PHP 5.5 or higher. If you don't have PHP 5.5 or higher, you should use the password_compat library by ircmaxell, who is the same person who wrote the above functions for PHP's core.

Indentation - Please, for the love of God.

What's wrong with your sanitizing

Sanitizing is an important job of the server. It makes sure nothing nasty comes in and affects what your users are seeing/experiencing.

Sanitizing is done as late as possible, for a simple reason. When the username is entered to the database, you shouldn't make assumptions on who is going to use that username. It could be your application later on, it could be an API you may or may not choose to provide one day, it could be a desktop application or a mobile application which does not care for HTML formatting.

When you extract that value from the database and are about to put it in HTML, that's the point where you should escape for HTML using htmlspecialchars(). Maybe at a different point you may want to output it to a JSON response for an API, in which case, json_encode is good, but htmlspecialchars() not as much.


The best functions have functional cohesion,
meaning they do one thing, and do it well.
I don't see a reason to merge these functions, and I don't see how that would be an improvement.

The first function takes Object, Array, String arguments,
the second one takes Array, String, String.
If you need something that works with both Object and Array,
then you can make it check the underlying type of its parameter,
and delegate to the appropriate method.
So it will be a 3rd function, using the other two under the hood.

  I need to be easy to test.

There's nothing special here to make testing hard.
You can either test the two main worker methods directly,
or test everything through the 3rd method.


I'll express my thoughts step by step reading your code (just a note: you should post a complete compilable code, at least of your main class Watchdog, if you take out what you think is not relevant then it is much harder to understand what you're doing).

  internal class Watchdog : IDisposable

internal modifier (unless Watchdog is a nested class) is superfluous. Moreover if you're not supposed to derive any class from Watchdog I'd declare it as sealed (note that it's an internal class then you can simply remove it when you will need to derive, there is not any public interface to respect).

sealed class Watchdog : IDisposable

IDisposable interface usually comes together with a common pattern implementation, I see no reason to avoid that (even in simple cases):

~Watchdog() {
    Dispose(false);
}

public void Dispose() {
    Dispose(true);
    GC.SuppressFinalize(this);
}

private void Dispose(bool disposing) {
    try {
        if (disposing)
            _timer.Elapsed -= _timer_Elapsed;
    }
    finally {
        _timer.Dispose();
    }
}

  private Timer _timer = new Timer(1000);

_timer is initialized only here (or, better, in constructor) then it should be market as readonly:

private const int TimerTickInMilliseconds = 1000;
private readonly Timer _timer;

public Watchdog() {
    _timer = new Timer(TimerTickInMilliseconds);
    _timer.Elapsed += _timer_Elapsed;
}

  public bool Status { ... }

In your setter you do not check if value changed, if you repeatedly assign true to Status then you'll fire StatusChanged each time.

public bool Status {
    get {
        return _status;
    }
    set {
        if (_status != value) {
            _status = value;
            OnStatusChanged(EventArgs.Empty);
        }
    }
}

That said Status name is pretty misleading. What does it mean? Does it indicate whether timer is enabled? It actually means watchdog is running and after a fixed amount of time watched operation didn't complete. Make it clear, change its name to, for example, Hanged.

public bool Hanged { ... }

  public void SetStatus() { ... }

Your methods have too vague name, as for Status property it should be clear what they do. I'd suggest to rename them:

public void Stop() { ... }
public void Start() { ... }

SetManually() is pretty weird (IMO) but I didn't read caller code (so far) so I'd temporary...drop it. Externally they may simply set Hanged to true.

  void _timer_Elapsed(object sender, ElapsedEventArgs e) { ... }

You're performing this check:

if (a > b)
    doThis();
if (a < b)
    doThat();

It may be simplified to (note that we're also handling a == b case).

if (a > b)
    doThis();
else
    doThat();

You're also setting Status (now Hanged) to false but you don't actually need it, its value must be set in Start() method. I'd also rename this method to something slightly more meaningful and move out 22 seconds magic number:

public void Start() {
    _timer.Enabled = true;
    Hanged = false;
}

private void OnTimerTick(object sender, ElapsedEventArgs e) {
    if (DateTime.Now - _watchedActivityStartTime > Timeout)
        Hanged = true;
}

Few notes:

Timeout may be private readonly TimeSpan Timeout = TimeSpan.FromSeconds(22) or a public accessible property.
You do not need to set Hanged to false (see previous paragraph).
I renamed _latestAction to _watchedActivityStartTime trying to make clear what it contains.
You may consider (it depends which kind of watchdog you want to implement) to also stop the timer when you detected that task hanged (just add a call to Stop()).
If you need to also detect if operation recover (after signaling it was hanged) then you should add this logic in this method (checking Hanged status and adding another DateTime _lastHangOccurence and eventually adding a Reset() method to update _watchedActivityStartTime).

Note that you do not need to perform this check each second, timer can directly be initialized to = new Timer((int)Timeout.TotalMilliseconds) and stopped after hang has been detected (no need to check if (DateTime.Now - _watchedActivityStartTime > Timeout)):

public Watchdog() {
    _timer = new Timer((int)Timeout.TotalMilliseconds);
    _timer.Elapsed += TimerOnElapsed;
}

private void OnTimerTick(object sender, ElapsedEventArgs e) {
    Hanged = true;
    Stop();
}

One final minor note: you should consider to group your methods (somehow), you're now mixing public/protected/private methods/variables in apparently random order.

I skip review of calling code because there isn't (really!) enough context to suggest anything but basic design notes.

All these said I'd consider to change your overall design. As it is now you have an utility class (Watchdog) that is nothing more than a timer. All the logic is spanned between this and callers. A better (IMO) design should centralize all this logic. Just a proof of concept (I omit not relevant code) of one way to do it:

sealed class Watchdog : IDisposable {
    public Watchdog(Action action) {
    }

    public void Start() {
    }

    public event EventHandler Hanged;
}

Used like this:

var watchdog = new Watchdog(TryConnect);
watchdog.Hanged += OnConnectionHanged;
watchdog.Start();

I said one way because (according to your usage pattern) you may have completely different interfaces (you may, for example, have a Start() method that accepts two delegates). The main point is: remove all watchdog logic from callers, what they have to provide are just two actions to call:

One action to execute, this is the watched task.
One action to call when watched task hanged.

Everything else must stay inside your Watchdog class.


Is this a good implementation of a simple "Size" value type

I'm not sure what the point is for making a distinction between a size and the default size.  But you shouldn't expose the default value as a field, use a property.  That will give you much more flexibility should you decide to do other things when getting the value.  No need for a backing field, it's a value type and it isn't all that complex.

public static Size Default
{
    get { return new Size(true); }
}

Consider renaming _default to something that would indicate it is a bool.  I'd usually go with something like _isDefault.  You already did that for the constructor parameter and property, I don't know why you didn't do the same for the field.

Your Equals() method should not ever throw exceptions.  What would happen if you passed in something that was not a Size?

public override bool Equals(object other)
{
    if (other is Size)
        return Equals((Size)other);
    return false;
}

Your Equals(Size) method is a little unusual.  You can merge the second and third conditions into a single this._isDefault != other._isDefault.  It might make more sense to combine that test with the tests for width and heights.  And personally, I wouldn't mix accessing fields and properties within a single method, I'd choose one or the other unless the properties had other logic that I needed to be fired.

public bool Equals(Size other)
{
    if (this._isDefault && other._isDefault)
        return true;

    return this._isDefault == other._isDefault &&
           this._width == other._width &&
           this._height == other._height;
}

Any time you override the equals method, you must override the GetHashCode() method too.  Use an implementation something like this:

public override int GetHashCode()
{
    unchecked
    {
        var hashCode = 79;
        hashCode = hashCode * 97 + _isDefault.GetHashCode();
        hashCode = hashCode * 97 + _width.GetHashCode();
        hashCode = hashCode * 97 + _height.GetHashCode();
        return hashCode;
    }
}

While we're on the subject of overriding methods, you should consider overriding the ToString() method as well to return something reasonable.

Your Parse() method should do more validation than that IMHO.  You make the assumption that the input will be a comma separated pair of values.  You check if you have a pair which is good, but you should explicit perform checks to make sure the values are integer numbers (i.e., digits).  It's not as useful receiving a generic format exception coming from the int.Parse() method than if it came from your Parse() method.  On a minor note, use width and height for the local variables and not x and y... that's not what they're representing.


First off when you're optimizing code you need to know what to optimize. At first I thought the problem code was not the groupby, but instead the creation of num_writes. And so I changed your code to be able to find the performance of it.

import cProfile
import random

from itertools import groupby

def group_blocks(num_writes, threshold):
    i = 0
    for key, group in groupby(num_writes, lambda x : x >= threshold):
        # This is faster compared to len(list(g))
        length = sum(1 for _ in group)
        if key:
            yield [i, i + length - 1]
        i += length

def build_writes(block_count, writes):
    num_writes = [0] * block_count
    for lower, upper in writes:
        for i in range(lower, upper + 1):
            num_writes[i] += 1
    return num_writes

def blockStorageRewrites(blockCount, writes, threshold):
    num_writes = build_writes(blockCount, writes)
    return list(group_blocks(num_writes, threshold))

block_count = 10**5
writes = []
for _ in range(10**4):
    a = random.randrange(0, block_count)
    b = random.randrange(a, block_count)
    writes.append([a, b])

cProfile.run('blockStorageRewrites(block_count, writes, 10**4)')

Resulting in the following profile:

         200008 function calls in 25.377 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.002    0.002   25.377   25.377 <string>:1(<module>)
   100001    0.019    0.000    0.025    0.000 lus.py:10(<genexpr>)
        1   25.342   25.342   25.342   25.342 lus.py:16(build_writes)
        1    0.000    0.000   25.375   25.375 lus.py:24(blockStorageRewrites)
        1    0.000    0.000    0.033    0.033 lus.py:6(group_blocks)
   100000    0.007    0.000    0.007    0.000 lus.py:8(<lambda>)
        1    0.000    0.000   25.377   25.377 {built-in method builtins.exec}
        1    0.007    0.007    0.033    0.033 {built-in method builtins.sum}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Changing the code as per Georgy's comment to:

def build_writes(block_count, writes):
    num_writes = dict(enumerate([0] * block_count))
    for lower, upper in writes:
        num_writes[lower] += 1
        num_writes[upper] -= 1
    return list(accumulate(num_writes))

Gets the following profile, which is orders of magnitude faster:

         200011 function calls in 0.066 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.002    0.002    0.066    0.066 <string>:1(<module>)
   100002    0.021    0.000    0.028    0.000 lus.py:10(<genexpr>)
        1    0.025    0.025    0.025    0.025 lus.py:16(build_writes)
        1    0.003    0.003    0.064    0.064 lus.py:24(blockStorageRewrites)
        2    0.000    0.000    0.036    0.018 lus.py:6(group_blocks)
   100000    0.008    0.000    0.008    0.000 lus.py:8(<lambda>)
        1    0.000    0.000    0.066    0.066 {built-in method builtins.exec}
        2    0.008    0.004    0.036    0.018 {built-in method builtins.sum}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


Extracting and cleaning up duplicate emails

You'll be able to simplify this a lot if you use a better in memory datastructure than a List<T>. You only want distinct items, HashSet<T> will generally be better here as it has O(1) lookups.

public void Mail(string file)
{
    var strRegex = @"[A-Za-z0-9_\-\+]+@[A-Za-z0-9\-]+\.([A-Za-z]{2,3})(?:\.[a-z]{2})?";
    var myRegex = new Regex(strRegex, RegexOptions.None);
    var matches = new HashSet<string>();
    foreach (Match matchedValue in myRegex.Matches(file))
    {
        // Changed per Mjolka's comment
        if (matches.Add(matchedValue.Value))
        {
            Log.Mail(matchedValue.Value);
        }
    }
    CleanDuplicates();
}

Note that I've removed the uneccessary check for Success on the Match object.

Your naming could do with a bit of work myRegex doesn't really mean anything.

You could also store the Regex as a field on the class to declutter this method.

You can leverage a HashSet<string> in your CleanDuplicates method too:

private void CleanDuplicates()
{
    var fileLocation = System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory) + @"\EmailList.txt";

    var lines = new HashSet<string>(File.ReadAllLines(fileLocation));

    File.WriteAllLines(fileLocation, lines.ToArray());
}

Definitely add a using System.IO it removes a lot of clutter.

Prefer built in methods e.g. File.WriteAllLines overwrites the file or creates a new one - no need to whip out a StreamWriter.

Also note that if your file becomes really large this will start getting pretty slow.

Final(?) Edit

Can't use var in the foreach loop as MatchCollection implements IEnumerable only - not the generic version. Sorry about that.

In order to use a Linq method (such as Select) we have to supply the type by calling Cast<T>:

foreach (var matchedValue in myRegex.Matches(file).Cast<Match>().Select(m => m.Value))
{
    if (matches.Add(matchedValue))
    {
        Log.Mail(matchedValue);
    }
}


Sequential and parallel addition of 2 vectors

#define NUM_OF_THREADS 8
#define VECTOR_SIZE    512

Don't use #define for constants or "functions" (⧺ES.31)

using time_point = std::chrono::high_resolution_clock::time_point;

Good!  bring down just the stuff you need, and give it a friendly name.  I think

using std::chrono::high_resolution_clock::time_point;

would be the same thing, and is the usual way of importing symbols from a library’s namespace.

assert(first.size() == second.size());

That will not do anything in a release build, you know.

If you really want checking, make a precondition that always works.  The GSL support library has Expects that can be programmed at compile time to assert, throw, or die.

In general operator+ looks good!  You are using a value return, and you ensure NVRO takes place.  You reserve the vector size.  You use STL algorithms.

for (int i = 1; i <= VECTOR_SIZE; i++)
{
    first_vec.push_back(i);
    second_vec.push_back(i);
}

There is a standard algorithm for that.

time_point t1_seq = std::chrono::high_resolution_clock::now();
⋮

Use auto (almost everywhere).

since there is no code-movement barrier, your benchmark might not be accurate.

for (auto &thread : threads)

Good!  You use the range-for where you can.


Naïve optimization by stepping until the error falls below a threshold

The guys at #haskell pointed me to until. This makes it satisfactory to me.

f :: Num a => a -> a
f x = abs(42-x)^2

improve :: Fractional b => (b -> c) -> (b, a) -> (b, c)
improve f (x, _) = (newX, f newX) where newX = x+0.1

optimize:: (Ord a, Fractional b) => (b -> a) -> a -> b -> (b, a)
optimize f goal x = until isDone (improve f) (0, f x)
    where isDone (_, err) = err < goal

main :: IO ()
main = print $ optimize f 0.5 0

http://ideone.com/ZlC7x8


Optimization code for checking if a list contains any element ID of another list

Put the values into a HashSet<T> (see here) as the lookup for that is constant O(1).

var sessionsWithErrorSet = new HashSet<int>(
    SessionsFilteredByDate.Where(i => i.TrackerId > 0 && i.StatusId == 0).Select(i => i.SessionId));

var sessionsWithErrorFixedSet = new HashSet<int>(
    BusinessClient.Instance.Tracker.GetAllTrackerAttempts().Select(i => i.SessionId));

var sessionsWithErrorIntersection = sessionsWithError.IntersectWith(sessionsWithErrorFixed);
var sessionsWithErrorsNotFixed = sessionsWithError.ExceptWith(sessionsWithErrorIntersection);


Golang unbuffered channel - Correct Usage

I've majorly written the review comments inline with the code. I could've made the code simple as @thwd suggested; but as you're learning and this is not an actual use case, I'm not changing the logic.
Also, to know about buffered channels better, do read this.
package main

import (
    "fmt"
    "sync"
)

// As goroutine could schedule in any order, it's better if the
// operation is stored as well, with the result.
type result struct {
    op string
    v  int
}

// It's better to use unidirectional channels if bi-directional
// is not needed. It can also distinguish how a channel should be used
// in different function/ methods (eg. producer, consumer)
type fn func(int, int, chan<- result, *sync.WaitGroup)

func add(x, y int, r chan<- result, wg *sync.WaitGroup) {
    fmt.Println("op: add")
    r <- result{"add", x + y}
    wg.Done()
}

func sub(x, y int, r chan<- result, wg *sync.WaitGroup) {
    fmt.Println("op: sub")
    r <- result{"sub", x - y}
    wg.Done()
}

func prod(x, y int, r chan<- result, wg *sync.WaitGroup) {
    fmt.Println("op: prod")
    r <- result{"prod", x * y}
    wg.Done()
}

func main() {
    // In case of multiple declaration, you can group
    // But it's totally dependent on the developer writing it.
    // But the ultimate goal is write clean code.
    var (
        fops = []fn{add, sub, prod}
        ch   = make(chan result, len(fops))
        wg   sync.WaitGroup
        x, y = 10, 20
    )

    wg.Add(len(fops))
    for _, f := range fops {
        go f(x, y, ch, &wg)
    }

    wg.Wait()
    close(ch)

    // Either use range, or you run a loop from [0, len(fops));
    // that would work as well!
    for v := range ch {
        fmt.Println(v)
    }
}


Factory design pattern with music classes

You have implemented is a factory pattern.
What you describe in the first paragraph is an Abstract factory pattern. Slightly different.
An abstract factory allows you to plug in one of multiple different factory's in at run-time to get different situations.
As a big note. Stop using pointers like that. That is a complete no no in C++

Do you need to create the factory dynamically.
A local object will probably do.

Even though the factory probably needs to create the objects dynamically you don't want to return pointers (but rather a smart pointer or a reference depending on how you want to handle ownership semantics (there are several good articles on SO about this so go have a read)).

Example:
class MusicFactory
{
    public:
        virtual std::unique_ptr<Music> getMusic(genre_e genre) = 0;
};

class AsianMusicFactory: public MusicFactory
{
    public:
        virtual std::unique_ptr<Music> getMusic(genre_e genre);
};
class AfricanMusicFactory: public MusicFactory
{
    public:
        virtual std::unique_ptr<Music> getMusic(genre_e genre);
};
class EuropeanMusicFactory: public MusicFactory
{
    public:
        virtual std::unique_ptr<Music> getMusic(genre_e genre);
};
class SouthAmericannMusicFactory: public MusicFactory
{
    public:
        virtual std::unique_ptr<Music> getMusic(genre_e genre);
};
class NorthAmericannMusicFactory: public MusicFactory
{
    public:
        virtual std::unique_ptr<Music> getMusic(genre_e genre);
};
// Special factory used when running unit tests.
class UnitTestMusicFactory: public MusicFactory
{
    public:
        virtual std::unique_ptr<Music> getMusic(genre_e genre);
};

So you have a bunch of different factories that all implement the same interface. But how do you know which one you should use. A common way is for a single creation point. Just ask the system it will create one for the lifetime of the application.
MusicFactory& getMusicFactory()
{
     // Note the static here.
     // It will only be created and initialized once (on first call).
     static std::unique_ptr<MusicFactory>  factory = createMusicFactory();
     return *factory;
}
// Never call this method directly.
// This function should only be called by getMusicFactory().
std::unique_ptr<MusicFactory> createMusicFactory()
{
     // Get info from user configuration.
     // Command line arguments. IP information etc whatever helps you
     // Make the decision on the actual factory that should be instantiated.
     // So we can decide what factory should be used by the application.
     std::unique_ptr<MusicFactory>  result(new XXXXX);
     return result;
}

int main()
{
    // Get the factory.
    MusicFactory&          fac   = getMusicFactory();

    // Use the factory to create the music.
    // At compile time we don't know what continents the music is from
    // as this is decided at run-time by he system and what factory is
    // created.
    std::unique_ptr<Music> music = fac.getMusic(ROCK);

    cout<<"Song: ";
    music->song();   // Should test for NULL
}


There are a few things bothering me in one version or an other:

the error=error or None is unnecessary as error is either assigned 'Invalid Email or Password' or  None, stick to the simpler error=error;
the ): on its own line in the third version is more than disturbing, it feels like a syntax error and force the reader to go through the code again to understand what is going on. Instead, put it at the end of the previous line and include more indentation to distinguish the condition from the rest.;
each version seem to consider the success case as an error of the error case, that is the flow of reading the code does not feel as if it's a signin function (this seems to be the bad outcome) but rather a deny_access function;
the third version seems to accept invalid password and deny entry on successful passwords.

Instead, I would test each failing condition and bail out with a specific error message at that point rather than making the error case the "natural" exit point of the function:

@app.route('/signin', methods=['POST'])
@public
def do_signin():
    user = get_user_by_email([request.form.get('email')])
    if user is None:
        return render_template('signin.html', error='Invalid Email')

    if not bcrypt.checkpw(
            request.form.get('password').encode('utf-8'),
            user['password'].encode('utf-8')):
        return render_template('signin.html', error='Invalid Password')

    session[SESSION_TOKEN] = add_token(user['id'])
    return redirect(url_for('index'))


Powershell script to save user credentials in a xml file

Instead of letting the user (1) choose a folder and (2) choose a file name, you can just present the user with a Save File Dialog. It also warns the user if he tries to overwrite an existing file.
If the user cancels one of your dialogs, you should cancel the script rather than continue with invalid data.

$dialog = New-Object System.Windows.Forms.SaveFileDialog
$dialog.FileName = "Credentials.xml"
$dialog.Filter = "XML files (*.xml)|*.xml|All files|*.*"

if ($dialog.ShowDialog() -ne "OK")
{
    exit
}

...

Get-Credential | Export-Clixml $dialog.FileName


Bash code to install bootstrap in a Ruby on Rails repository

It's worth starting with a shebang; I'd also advise setting shell flags -e (exit on error) and -u (error when using unset variables):
#!/bin/bash

set -eu

Please use more whitespace and comments to make it easier to follow.
Perl is overkill for the simple substitution here - if we stick to sed, then that's one fewer dependency:
sed -e '/^extract_css:/:.*/ true/' \
    -i config/webpacker.yml

I omitted creating the backup because I don't think there's any value in keeping the original.  If your later processes depend on having it around, then use -i.bak instead of -i, as in Perl (in fact, that's where Perl got that option).
The two transform-and-move pairs can also use sed -i, making the script more consistent, and thus easier to follow.  We can use the (standard sed) r command to read a file, instead of the non-standard e command:
sed -e '/module.exports = environment/rexpose-loader.txt' \
    -i config/webpack/environment.js
sed -e '/javascript_pack_tag .application/rstylesheet_pack_tag.txt' \
    -i app/views/layouts/application.html.erb

$s1 is only used once, and doesn't add any value (such as a meaningful name), so just inline it.
If we can eliminate the one use of C-escape quoting, then we can use plain POSIX shell instead of Bash.

Modified code
#!/bin/sh

set -eu

yarn add bootstrap jquery popper.js expose-loader
yarn install --check-files

sed -e '/^extract_css:/:.*/ true/' \
    -i config/webpacker.yml

printf '\n\n%s' 'import "bootstrap/dist/js/bootstrap";' \
       >> app/javascript/packs/application.js
echo '@import "~bootstrap/scss/bootstrap";' \
     > app/javascript/packs/styles.scss

sed -e '/module.exports = environment/rexpose-loader.txt' \
    -i config/webpack/environment.js
sed -e '/javascript_pack_tag .application/rstylesheet_pack_tag.txt' \
    -i app/views/layouts/application.html.erb


Knowing that you had a ton of scrappers questions, this doesn't look nice at all. It looks like you were in a hurry and didn't much care about how the code looks.

Styling

Use 4 spaces per indentation level
Constants should be LOWERCASED
You should have a space after ,
Your lines are way too long. Stick to 72 characters or 120 (at most)

Code
First, you don't have to hardcode your search items. Instead, you might as well define a function which returns the data you need (the entire URL):
def build_url(item, location, page):
    params = urllib.parse.urlencode({
        'search_terms': item,
        'geo_location_terms': location,
        'page': page
    })

    return '{}/search?{}'.format(URL, params)

With that in mind, your code might be restructured nicer, like this:
import requests
import urllib

from lxml import html

URL = "https://www.yellowpages.com"
LOWER_LIMIT = 1
UPPER_LIMIT = 10

def build_url(item, location, page):
    params = urllib.parse.urlencode({
        'search_terms': item,
        'geo_location_terms': location,
        'page': page
    })

    return '{}/search?{}'.format(URL, params)

def scrape():
    for page in range(LOWER_LIMIT, UPPER_LIMIT):
        url = build_url('pizza', 'Los Angeles CA', page)
        html_ = requests.get(url).text
        for item in html.fromstring(html_).cssselect('div.info h2.n a:not([itemprop="name"]).business-name'):
            for data in html.fromstring(requests.get(URL + item.attrib['href']).text).cssselect('a.email-business'):
                print(data.attrib['href'].replace("mailto:", ""))

if __name__ == '__main__':
    scrape()

Other changes that I did above:

Move the logic into separate functions
Make the range arguments constants so that they can be easily modified
Add the guard check if __name__ == '__main__'

As is, your scrapper is pretty slow because it has to search in each page the entire html for that specific a info. You might consider using Scrapy.