General comments

you have 'good' mid-finding code: int mid = lo + (hi - lo) / 2; This is fancy code, and, if you have not learned why it is done this way, then you should read up on the midpoint bug in Java.
your algorithm generally looks sound. It works

The basic premise of your sort is good. The code is neat, and, if you know the merge-sort, it is readable, and does the right sort of things at the right times.

With just your code in front of me, I would say 'good job'. To make it better, I would recommend that:

you make your code conform to the standard usage in Java, where you would have two methods:

MergeSort.sort(int[] data);
MergeSort.sort(int[] data, offset, length);

Java typically uses a 'length' argument, instead of a 'high' argument. In the case of the MergeSort, the 'high' variation is more useful, so I would recommend making your current method private, and then adding a new recursion-wrapping frontend to the code that makes it conform to typical Java method calls.

About the aux

This is the second reason to consider wrapping your current sort-entry method in to a calling method.... something like:

public static void sort(int[] data) {
    sort(data, 0, data.length);
}

public static void sort(int[] data, int offset, int length) {
    int[] aux = new int[data.length]; // smarter implementation can be used for if length != data.length
    recursiveSort(data, aux, offset, offset + length);
}

Where the method recursiveSort is the method you currently have as sort.

The reason for doing the aux in the calling method is for memory efficiency. At some point you will need to do the final merge, which will require the entire data array to fit in to a memory 'copy', the aux. You will also do many more smaller merge sorts requiring a smaller size of memory. If you are going to need the large space anyway, you may as well create it in the beginning, and reuse it many times, which is better than creating many small aux which never get reused.


Generic database select method for within my application

First things first: your current code has a huge optimization to be made.

foreach (var p in parameters)
{
    args.Add(argNames[parameters.IndexOf(p)], p);
}

This is wrong, because argNames has an indexer and parameters is a List<string>. The IndexOf(T) method you call on parameters to get the index increases the amount of effort, work and time that your program has to perform in order to give you a result when all you really need to do is index the list.

for (int i = 0; i < parameters.Count; i++)
{
    args.Add(argNames[i], parameters[i]);
}

Much simpler. Of course, if the parameters list is larger than argNames, it will throw an exception. You can either keep it that way, or throw and explicit exception (which you should do to inform the user why their code failed).

public List<T> Get<T>(List<string> parameters)
{
    argNames = DatabaseConstants.SelectParameters<T>();
    if (argNames.Length != parameters.Count) // Is argNames a List? If so replace `Length` with `Count`
    {
        throw new ArgumentException($"The argument provided for '{nameof(parameters)}' was not the same length as the required number of parameters for this query.");
    }

    query = DatabaseConstants.Select<T>();
    args = new DynamicParameters();
    foreach (var p in parameters)
    {
        args.Add(argNames[parameters.IndexOf(p)], p);
    }

    return NewSelect<T>(query, args);
}

Next, let's rethink your process.

public static string SelectQuery<T>()
{
    if (typeof(T) == typeof(Pallet))
    {
        return "SELECT * FROM subGRVReceived WHERE GRVNo=@grv";
    }
    else if (typeof(T) == typeof(Sample))
    {
        return "SELECT * FROM subReceivingQC WHERE GRV=@grv AND PalletSeq=@pallet";
    }
    else if (typeof(T) == typeof(QCItem))
    {
        return "SELECT * FROM subQCItems WHERE GRV=@grv AND PalletSeq=@pallet AND SampleNo=@sampleno";
    }
    else
    {
        return string.Empty;
    }
}

This screams for a proper ORM, or at least a fake implementation of one. You also mention in the comments:

  I added some examples, but while doing so I realised that I'm actually going to need to query the same table but with an extra parameter at some point, so this probably wont work .. However as it stands it could be fairly useful (although not as reusable or generic as I might like!)

What if I told you that not only could we make this generic (and generate the query dynamically), but we could solve that problem at the same time?

I'm going to solve them one-at-a-time, but it won't be too difficult.

First, we need two pieces of data. We need the table name and property name, assuming that they're not defined by the property name itself. (As it appears.)

If you have access to the System.ComponentModel.DataAnnotations library, and the System.ComponentModel.DataAnnotations and System.ComponentModel.DataAnnotations.Schema namespaces, then this is significantly easer, otherwise you need to define the three attributes we're going to use. I'm going to use built-in's.

First, we're going to define our keys on the object with the System.ComponentModel.DataAnnotations.Key attribute, then we'll define the System.ComponentModel.DataAnnotations.Schema.Table attribute, and the System.ComponentModel.DataAnnotations.Schema.Column attribute.

[Table("TestTable")]
public class Foo
{
    [Key]
    [Column("fooId")]
    public int Id { get; set; }

    public string Name { get; set; }
}

[Table("TableBar")]
public class Bar
{
    [Key]
    [Column("barId")]
    public int BarId { get; set; }

    [Column("barName")]
    public string Name { get; set; }
}

public class Baz
{
    [Key]
    public int Id { get; set; }

    public int Order { get; set; }
}

The result is going to be something like:

SELECT * FROM TestTable WHERE fooId = @fooId
SELECT * FROM TableBar WHERE barId = @barId AND Name = @Name
SELECT * FROM Baz WHERE Id = @Id

So, how do we get there? A lot of reflection.

public static List<string> GetParameters<T>(IEnumerable<string> additionalConstraints = null)
{
    var type = typeof(T);

    var result = new List<string>();
    var keys = type.GetProperties().Where(x => x.IsDefined(typeof(KeyAttribute), true));
    if (keys.Any())
    {
        foreach (var key in keys)
        {
            if (key.IsDefined(typeof(ColumnAttribute), true))
            {
                var nameAttr = (ColumnAttribute)key.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault();
                result.Add($"@{nameAttr.Name}");
            }
            else
            {
                result.Add($"@{key.Name}");
            }
        }
    }

    if (additionalConstraints?.Any() == true)
    {
        foreach (var constraint in additionalConstraints)
        {
            var prop = typeof(TableAttribute).GetProperties().Where(x => x.Name == constraint).First();
            if (prop.IsDefined(typeof(ColumnAttribute), true))
            {
                var nameAttr = (ColumnAttribute)prop.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault();
                result.Add($"@{nameAttr.Name}");
            }
            else
            {
                result.Add($"@{prop.Name}");
            }
        }
    }

    return result;
}

public static string BuildSelect<T>(IEnumerable<string> additionalConstraints = null)
{
    var type = typeof(T);

    var sb = new StringBuilder();
    sb.Append("SELECT * FROM ");

    var tableAttribute = type.GetCustomAttributes(typeof(TableAttribute), true).FirstOrDefault();
    if (tableAttribute != null)
    {
        sb.Append(((TableAttribute)tableAttribute).Name);
    }
    else
    {
        sb.Append(type.Name);
    }

    var appendedClause = false;
    var parameters = GetParameters<T>(additionalConstraints);
    if (parameters.Count > 0)
    {
        sb.Append(" WHERE ");
        foreach (var p in parameters)
        {
            if (appendedClause)
            {
                sb.Append(" AND ");
            }

            sb.Append($"{p.Substring(1)} = {p}");
            appendedClause = true;
        }
    }

    return sb.ToString();
}

Advantages? Your code doesn't need modified, at all, to add support for a new type. Simply add the type, define [Table(name)], [Key] and [Column(name)] if necessary.

Downsides? Calling it frequently can become expensive, it would not be difficult to build a cache to hold all the queries and select the relevant one from, so that if you call BuildSelect<Foo>() it would return the result from the cache.

Now the point we're at is great if you only need select queries, if you need more than that we hit a slight issue in that we have a lot of code to reproduce to build a new query. Now there is a fix for that.

public class QueryProperty
{
    public PropertyInfo Property { get; set; }
    public string Name { get; set; }
}

public class QueryData
{
    public string TableName { get; set; }
    public List<QueryProperty> KeyProperties { get; set; } = new List<QueryProperty>();
    public List<QueryProperty> NonKeyProperties { get; set; } = new List<QueryProperty>();
    public List<QueryProperty> AllProperties { get; set; } = new List<QueryProperty>();

    public string AsSelect(bool explicitColumns = true, bool includeKey = true)
    {
        var sb = new StringBuilder();
        sb.Append("SELECT ");

        if (explicitColumns)
        {
            sb.Append(string.Join(", ", AllProperties.Select(x => x.Name)));
        }
        else
        {
            sb.Append('*');
        }

        sb.Append(" FROM ").Append(TableName);

        if (includeKey)
        {
            sb.Append(" WHERE ");
            sb.Append(string.Join(" AND ", KeyProperties.Select(x => $"{x.Name} = @{x.Name}")));
        }

        return sb.ToString();
    }

    public string AsInsert(bool explicitColumns = true)
    {
        var sb = new StringBuilder();
        sb.Append("INSERT INTO ").Append(TableName).Append(' ');

        if (explicitColumns)
        {
            sb.Append('(');
            sb.Append(string.Join(", ", AllProperties.Select(x => x.Name)));
            sb.Append(')');
        }

        sb.Append(" VALUES (");
        sb.Append(string.Join(", ", AllProperties.Select(x => $"@{x.Name}")));
        sb.Append(')');

        return sb.ToString();
    }

    public string AsUpdate(bool explicitColumns = true, bool includeKey = true)
    {
        var sb = new StringBuilder();
        sb.Append("UPDATE ").Append(TableName).Append(' ');

        sb.Append("SET ");
        sb.Append(string.Join(", ", NonKeyProperties.Select(x => $"{x.Name} = @{x.Name}")));

        if (includeKey)
        {
            sb.Append(" WHERE ");
            sb.Append(string.Join(" AND ", KeyProperties.Select(x => $"{x.Name} = @{x.Name}")));
        }

        return sb.ToString();
    }

    public static QueryData Build<T>(IEnumerable<string> additionalConstraints = null)
    {
        var result = new QueryData();

        var type = typeof(T);
        if (type.IsDefined(typeof(TableAttribute)))
        {
            var attr = (TableAttribute)type.GetCustomAttribute(typeof(TableAttribute), true);
            result.TableName = attr.Name;
        }
        else
        {
            result.TableName = type.Name;
        }

        foreach (var prop in type.GetProperties())
        {
            if (prop.IsDefined(typeof(ColumnAttribute), true))
            {
                var nameAttr = (ColumnAttribute)prop.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault();
                result.AllProperties.Add(new QueryProperty { Property = prop, Name = nameAttr.Name });
            }
            else
            {
                result.AllProperties.Add(new QueryProperty { Property = prop, Name = prop.Name });
            }
        }

        var keys = result.AllProperties.Where(x => x.Property.IsDefined(typeof(KeyAttribute), true));
        if (keys.Any())
        {
            foreach (var key in keys)
            {
                result.KeyProperties.Add(key);
            }
        }

        var nonKeys = result.AllProperties.Where(x => !x.Property.IsDefined(typeof(KeyAttribute), true));
        if (nonKeys.Any())
        {
            foreach (var nonKey in nonKeys)
            {
                result.NonKeyProperties.Add(nonKey);
            }
        }

        if (additionalConstraints?.Any() == true)
        {
            foreach (var keyName in additionalConstraints)
            {
                var key = result.AllProperties.Where(x => x.Property.Name == keyName).FirstOrDefault();
                if (key == null)
                {
                    throw new ArgumentException($"The value '{key}' provided for '{nameof(key)}' was not a property of the type '{type.FullName}'.");
                }

                result.KeyProperties.Add(key);
            }
        }

        return result;
    }
}

Now the call becomes:

var queryData = QueryData.Build<Foo>(new string[] { nameof(Foo.Name) });
var selectQuery = queryData.AsSelect();

I leave building a DELETE query up to you, once you have it I recommend posting a new Code Review question. :)


First of all, The Http server send all the headers Line by Line. In your sample i see you created a dummy sample with the next buffer:

char * msg= "GET / HTTP/1.1\r\n"
            "Host: 192.241.213.46:6880\r\n"
            "Upgrade-Insecure-Requests: 1\r\n"
            "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
            "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8\r\n"
            "Accept-Language: en-us\r\n"
            "Accept-Encoding: gzip, deflate\r\n"
            "Connection: keep-alive\r\n\r\n";

I suppose that you first recive all the header before analyzing it with your method void parse_header( void *msg )... and that is the reason that the task to get each Key-Value is so hard because you are using parsers like this:

http_request[ std::string( ( char * ) msg ).substr( tail - ( char *)msg , ( mid ) - tail  ) ] = std::string( ( char * ) msg ).substr( mid + 2 - ( char *) msg , ( head - 3 ) - mid );

What will I do to improve your code:

I will keep the map<string,string> to store all headers.
Read the header one line by time and, before to continue with the other line, analyze it.
I don't see any issue with the code to parse the first but I will modify it to analyze is a single line and simplify the parsers.

If you read and analyze one line by line, the code to map all the keys with values could be like this:

void parseFirstLine(string line)
{

    string key = "";
    string value = "";
    int  position, lpost;

    // Find request type
    position = line.find(' ');
    http_request[ "Type" ] = line.substr(0, position);
    position++; //Skip character ' '

    // Find path
    position = line.find(' ', lpost);
    http_request[ "Path" ] = line.substr(lpost, (position-lpost));
    position++; //Skip character ' '

    // Find HTTP version
    http_request[ "Version" ] = line.substr(position);
}

void parseHeader(string line)
{

    string key = "";
    string value = "";

    if(data.size() == 0) return;

    int posFirst = line.find(":",0); //Look for separator ':'

    key = line.substr(0, posFirst);
    value = line.substr(posFirst + 1);

    http_request[key] = value;
}

(*) This code could have some bugs because I'm writing this code without any developer environment to review this.

Is your decision where you get each line to analyze, at the moment you get it from socket reading or after finishing of read all the header.


Instead of looping one more time through your isPrime array, consider expanding the iterations on your first for loop and then exiting from there once you reach the desired result:

    ...
    int counter = 0;
    for (int i = 2; i <= max; i++) {
        if (isPrimeArray[i]) {
            if (++counter == n) {
                return i;
            }
            for (int j = i; i * j <= max; j++) {
                isPrimeArray[i * j] = false;
            }
        }
    }
    throw new IllegalArgumentException("n is not valid");


One thing that can speed up insertion sort is to pull the partition value to the side and slide elements up into the vacancy until the correct location is found, then drop the partition value into that location.  This eliminates one of the three assignments in the while loop:

for p in range(1, len(seq)):
    if seq[p] >= seq[p-1]:
        continue
    p_value = seq[p]
    while p != 0 and p_value < seq[p-1]:
        seq[p] = seq[p-1]
        p -= 1
    seq[p] = p_value
return seq

The unit test shows a substantial speed improvement from doing this.


TDD workflow best-practices for .NET using NUnit

It is important to get one's mindset in a TDD mode beforehand. What I mean by this is

1) Identify the responsibility of a class - this helps in identifying the test cases.
2) Identify the interactions of the class with external dependencies - Unit testing shouldn't be testing the behaviour of the external dependency.

In this case - you have written a wrapper class around SendMail whose responsibility is to "Collect and Despatch".

I'd say SmtpClient is a dependency - you should be able to Mock it's behaviour in your test.

Mailer.cs

using System.Net.Mail;
using System;

namespace Dotnet.Samples.NUnit
{
    public class Mailer
    {
        readonly string from;
        public string From { get { return from; } }

        readonly string to;
        public string To { get { return to; } }

        readonly string subject;
        public string Subject { get { return subject; } }

        readonly string cc;
        public string Cc { get { return cc; } }

        readonly string bcc;
        public string BCc { get { return bcc; } }

        readonly string body;
        public string Body { get { return body; } }

        readonly string smtpHost;
        public string SmtpHost { get { return smtpHost; } }

        readonly string attachment;
        public string Attachment { get { return Attachment; } }

        private SmtpClient smtpClient;

        public Mailer(string from = null, string to = null, string body = null, string subject = null, string cc = null, string bcc = null, string smtpHost = "localhost", string attachment = null, SmtpClient smtpClient= new SmtpClient())
        {
            this.from = from;
            this.to = to;
            this.subject = subject;
            this.body = body;
            this.cc = cc;
            this.bcc = bcc;
            this.smtpHost = smtpHost;
            this.attachment = attachment;
        }

        public void SendMail()
        {
            if (string.IsNullOrEmpty(From))
                throw new ArgumentNullException("Sender e-mail address cannot be null or empty.", from);

            MailMessage mail = new MailMessage();
            smtpClient.Send(mail);
        }
    }
}

Testing SendMail

[Test]
public voud ShouldCallSendOfSmtpClientWhenSendMailIsCalled
{
    //Stub & Setup
    var mockSmtpClient = MockRepository.GenerateMock<SmtpClient>();
    var mailer = new Mailer(smtpClient: mockSmtpClient);

    //Act
    var message = new MailMessage();
    mailer.SendMail(message);

    //Assert
    mockSmtpClient.AssertWasCalled(m=>m.Send(Arg<MailMessage>.Is.Anything));
}


Scrape a reddit post submission for comments and save comments to JSON file

First of all, naming: do not abbreviate names unless they are used in a one-liner like [x.something for x in somelist]. Do not try to spare characters - use IDE to suggest continuations if you want to type fast. Really pays off.

Second, try not to mix abstractions of different types in the same function, eg, write_comments_to_file deals now with preparing content as well as low-level detail of writing to file, extract to a function with meaningful name - will make code more readable. Try to avoid names with data, info, etc in it - they are useless. Everything is data.

The same function seems to make changes to submission - if it is the case, make it explicit and in a separate function: submission_replaced = replace_more(submission) (good names here as well - I just tried to guess one).

All that is needed for the code to show the intention behind it.
except Exception as e is too broad. What exceptions you really want to catch? Maybe, only IOError is enough?

Magic numbers: -6 <- why six? Extract that to a new function with a meaningful name like strip_html_postfix (or whatever is the intention of that) - then, there is no need to leave a comment, function name will serve as a comment. Using appropriate names can lessen the need to document the code, even to the point that no separate docstrings will be necessary.

You have not told whether this is one-time script or part of bigger system, so I will not touch possible use of classes. For example, propagation of fp (is it filepath?) and if for missing fp may be a signal, that the code may benefit from using a Loader class (omitting manager here, because it is usually as useless as data in class names unless correspond to manager in real world). For example, I see classes: Loader, Scraper, and Outputter which will nicely decouple the load manager configuration, process of scraping and saving the results to whatever destination - but of course it's overkill for a script, and is useful only if you foresee more Loaders, Scrapers or Outputters.

No matter of the programming language, functions are always more readable when they have explicit arguments and return results they produce. For instance, scrape at the moment uses module-level data - it's harder to write tests, configure, and guess what it does.

Hopefully, my findings above will help you write code, which will be self-explanatory and will not require the How it works you provided. This would be ultimately Pythonic.

PS. for ... data[i][1]["responses"] = cmt_data - this is dangerous in Python if you intend to use the result beyond converting to JSON. For example, if the data structure will be mutated, then it will be mutated for all responses (cmt_data is a pointer, not value, so to say!), which is hardly what is desired. And in this case data is from outside, so you may already have a problem elsewhere in the code and spend time to debug, because it will not be immediately clear the function in question make your responses entangled. Use copy or deepcopy, and overall it's not good idea to mutate data structure in a function without explicitly returning it back, and even then assignment of cmt_data can be frowned upon.


In Java, the most efficient implementation of this will likely be

public int searchInsert(int[] numbers, int target) {
    int index = Arrays.binarySearch(numbers, target);

    if (index < 0) {
        index = -index - 1;
    }

    return index;
}

With that said, the place where I'd look first are your special cases.  Under what circumstances would midIndex be less than 0 or more than numbers.length - 1?  Never (if it was, numbers[midIndex] would throw an out of bounds exception).  And when will it be equal?  When we've found the edge, when endIndex will be less than startIndex.

So simplify

    while (startIndex < endIndex) {
        midIndex = (endIndex - startIndex) / 2 + startIndex;
        if (numbers[midIndex] == target) {
            return midIndex;
        }

        if (numbers[midIndex] < target) {
            startIndex = midIndex + 1;
        }
        else {
            endIndex = midIndex - 1;
        }
    }

    return startIndex;

This will do one extra assignment and outer loop comparison but save two comparisons on every iteration.  Since the assignment only involves registers and math, it should be quick (possibly quicker than the comparisons, which have to load the registers from cache if not memory).

Without the extra checks, the code will update either startIndex or endIndex and make the same return.  Because startIndex will equal either midIndex or midIndex + 1, the same as was returned in the original code.


Two things:

Your class only provides a if-else statement, really. If it would also provide all the features in the existing java.util.Optional, it would have been slightly more useful.
private Optional<T> optional; should definitely be marked with final

Okay then, three things:

Your factory method takes an existing Optional<T>, but you don't provide a getter or anything for the Optional<T>, which means that you could also provide an ordinary OptionalConsumer<T> ofNullable(T value)


Add type signatures to top-level functions

You should always add a type signature to top-level functions:

get_budget_values :: [Float] -> Int -> Int -> IO [Float]
get_budget_values _values _index _length = do
    ...

Make functions easy to use and hard to misuse

However, this function's type is weird. We want to get _length values, so why do we have to supply them first? That's error prone. Our funtion should have the type Int -> IO [Float] instead:

get_budget_values :: Int -> IO [Float]
get_budget_values n = go [] 0 n
  where
    go values index len = do
      tmp_value <- getLine

      let new_value = read tmp_value
      let new_values = new_value : values
      let new_index = index + 1

      if new_index < len
          then go new_values new_index len
          else return new_values

Note that due to get_budget_values' type signature we don't have to use :: Float at read temp_value anymore.

Follow naming conventions and use existing library functions

Still, our function is sub-par, since we don't follow the common naming convention (camelCase) on the one hand don't  use library functions for our advantage.

So let's say we have doNTimes :: Int -> IO a -> IO [a] so that doNTimes n action repeats the action n times and collects the results in a list. Then we can write

getBudgetValues :: Int -> IO [Float]
getBudgetValues n = doNTimes n getSingleFloat
  where
    getSingleFloat = do
       tmpValue <- getLine
       return (read tmpValue)

The getLine followed by read approach is so common that there is a function for that, namely readLn:

    getSingleFloat = readLn

We end up with

getBudgetValues :: Int -> IO [Float]
getBudgetValues n = doNTimes n readLn

What's missing is doNTimes. Now, we know that there is replicate :: Int -> a -> [a], which is almost correct, but we would end up with [IO Float] instead of IO [Float]. But there's also sequence :: [IO a] -> IO [a].*

Therefore, we can write

doNTimes :: Int -> IO a -> IO [a]
doNTimes n action = sequence (replicate n action)

The final result

This function is also often used and available as replicateM in Control.Monad. We end up with

import Control.Monad (replicateM)

getBudgetValues :: Int -> IO [Float]
getBudgetValues n = replicateM n readLn

Exercises

Write replicate and sequence yourself without looking at their respective source code. replicate :: Int -> a -> [a] should fulfil the following properties for positive n:

let result = replicate n x
in length result == n && all (== x) result

For any non-positive n, the list should be empty.

sequence :: [IO a] -> IO [a] should execute the actions and collect their results, e.g.

sequence [putStrLn "Hello", putStrLn "World"]

should print Hello and World on two lines and return [(),()].

* the actual types are more general


List enrolled users & show checkmark if all activities are complete

Before looking at the code, there's a simple and immediate option for speeding things up: When a user completes an activity (or a part of one), check the user's other activities, and set an overall completed flag on the user's enrollment accordingly. That way, you only need to check completion for one user at a time and only in connection with an activity update (whereas right now, you check completion for everyone, all the time). Whenever you need to display the list, you'll already have completed boolean values to use.

So that's one way to go.

Now, looking at the code, the first thing I see is a lot of duplication.

Second thing I see is that you unnecessarily abbreviate stuff. Ironic that "spelling" is spelt "spel"... Really, just write what you mean, and mean what you write. There's no reason whatsoever to abbreviate.

Anyway, duplication: The only thing that differs from method to method is the activity name.

So you could get rid of all the completed_* method, and just do this:

def users_with_completed_activity(name)
  lesson = Lesson.find(params[:id])
  enrolled_users.map do |user|
    current_enrollment = lesson.enrollment_for(user)
    user if current_enrollment.send(name).all?(&:completed?)
  end
end

Note that this:

all? { |x| x.completed == true }

is just checking "is true true?", so it's the same as:

all? { |x| x.completed }

which, with Ruby's shortcuts, is the same as:

all?(&:completed)

However there's another weird thing going on. You load the Lesson record. Then you call enrolled_users (which also loads the Lesson, by the way), which finds users from their enrollments, and then, for each user, you go back and get their Enrollment.

So:

Fetching the Lesson should probably be extracted into a before_action (Rails' scaffolded controllers include examples of exactly this)
You're getting the enrollments to get the users to get their enrollments... Notice the runaround there?

Sidestepping that, you get something like (assuming Lesson's been set in a before_action):

def users_with_completed_activity?(name)
  @lesson.enrollments.map do |enrollment|
    enrollment.user if enrollment.send(name).all?(&:completed?)
  end
end

Of course, I'm not exactly sure why you want an array with a mix of User records and nils. All it means is that you make it vastly more complicated in the view because you have to use include?. And that's slow, since it has to look through the array every time. So you have a system that'll get exponentially slower the more users you add.

It'd make more sense to send back an array of user/completed pairs:

def users_with_completed_activity?(name)
  @lesson.enrollments.map do |enrollment|
    [enrollment.user, enrollment.send(name).all?(&:completed?)]
  end
end

which you can then step through like:

users_with_completed_activity(:spelling).each do |user, completed|
  # do something
end

Getting a combined completed-all-activities boolean I'll leave to the reader (since this is all just stop-gap improvements anyway - read on).

I'd also ask why the Enrollment is also responsible for tracking activity completion. It's not necessarily wrong, but it doesn't seem the best fit either. Whether or not a user completes an activity doesn't really affect their enrollment. Whether or not you do well, you're presumably still enrolled. But with this structure, that's what happens. So that's a little odd.

Lastly, you have a call to uniq because - for some reason - it seems it's possible for users to be enrolled multiple times? I can't see any other reason. But why would someone be enrolled multiple times? It doesn't make sense in the real world, nor as a software model. How do you know which enrollment to update when an activity is completed? Which enrollment to check?

Now, none of this is likely to make things go much faster. The trouble is still that you're simply doing too much each request. As mentioned in the beginning, the simplest solution would probably be to update a flag on the enrollment, when a user completes an activity. Then that's all you need to check. It's not something that changes very often, so why go through all the motions of figuring it out every time? It's like a bank account balance: If every time you wanted to check your balance, the bank had to sum up all deposits and withdrawals, things would grind to a halt. So it stores the current balance and keeps it up to date.

There are many other ways to go about this (doing more processing in the database layer, doing different data modelling, in-memory caching, etc. etc.) but the simplest one is simply to store the things you need to access often.


Shell script to detect router slider status

First of all, there are so many pitfalls associated with /bin/sh programming that I prefer to write all except the most trivial scripts in a language like perl, python or even awk. I realize that availability is a concern, but all of those languages are pretty standard now.

If you write the script in a better scripting language you can get rid of the duplicate call to grep which is one thing that I presume bothers you about the code.

If you must write in /bin/sh, then run your code through one of the following static analyzers to help you find potential coding problems:

http://www.shellcheck.net
checkbashisms on Debian / Ubuntu systems

For instance, ShellCheck found these issues:

if [ $status != $test ] ; then
                ^---- should use "$test"

elif [ $status == $test ] ; then
               ^---- == not supported in POSIX sh

In perl your script would look like this:

#!/usr/bin/env perl

use strict;
use warnings;
use File::Slurp;

my $test = read_file( '/root/logs/sliderstatus' );
chomp $test;

my ($found1, $found2);
open(my $fh, "</sys/kernel/debug/gpio");
while (<$fh>) {
  if (m/\(sw1\s*\)\s+in\s+hi/) { $found1 = 1 }
  if (m/\(sw2\s*\)\s+in\s+hi/) { $found2 = 1 }
}
close($fh);

my ($status, $script);
if ($found1 && $found2) {
  $status = "AP";
  $script = "/root/scripts/shell/AP_MODE.sh";
} elsif ($found1) {
  $status = "CLIENT";
  $script = "/root/scripts/shell/CLIENT_MODE.sh";
} else {
  $status = "CUSTOM";
  # don't set $script
}

if ($status ne $test) {
  print "Status is $status, executing now.\n";
  if ($script) {
    system("$script &");
  }
} else {
  print "Status $status and slider $test are the same.\n";
}

It's still basically the same code, but has these advantages:

It only reads /sys/kernel/debug/gpio once
It's a lot safer
It's easier to express more complex logic
You have more versatile data structures available to you - e.g. real arrays and hash maps.

Finally, I have a question about your patterns for sw1 and sw2. What does the output of /sys/kernel/debug/gpio look like? Presumably the inputs are number something like sw1, sw2, sw3, etc. Could there be a sw10? There should be a delimiter in the output you can use to make sure you are matching the full switch number.


The last rule is completely superfluous, but harmless: it just maps the desired URL to itself.

The four cases can be combined into one rule:

RewriteRule ^(_user/)?login(\.php)?$ _user/login.php

In a regular expression, (something)? makes the something optional.  That is, whether the URL starts with _user/ or not, and whether the URL ends with .php or not, it will get mapped to the desired login page.


Generate all partitions of a set of items

I see the performance tag added to this post. Did you intent to have answers address performance in terms of time, space or other aspects?
If you are looking to optimize performance in terms of time then I must restrain myself from suggesting changing the outer for loop to a for of loop. However I do see there is a forEach loop inside the nested for loop. If you really want to optimize for performance, then consider using a for loop instead of that .forEach method. Also consider whether the same result can be achieved by iterating backwards through the loops - this would allow for fewer operations1.
Given that an arrow function is used in the .forEach() callback, other ecmascript-6 features can be used - e.g. const and let instead of var, spread syntax instead of calling .concat(), etc.


Four algorithms to find the Nth Fibonacci number

For tailHelper(), the term == 1 case is superfluous and should be eliminated.

In fibonacciBinet(), the quantity \$\frac{1 + \sqrt{5}}{2}\$ appears twice.  Since that quantity is known as the Golden Ratio, I would define an intermediate value

var phi = (1 + math.Sqrt(5)) / 2;

However, none of these four solutions is particularly idiomatic for Go.  The most expressive way to write a Fibonacci sequence in Go is as an iterator, such as this one.


customSignupForm code to allow signup for only the invited user

A good motivation to overwrite the Form's clean() method is when you need to modify/check multiple fields (reference):

  The form subclass’s clean() method can perform validation that
  requires access to multiple form fields. This is where you might put
  in checks such as “if field A is supplied, field B must contain a
  valid email address”.

And, the overwritten clean() method usually returns the modified cleaned_data.

In your case, you only work with a single field, use the clean_<fieldname>() method - clean_email() to be specific.

I would also handle the "email is falsy" case beforehand (though, I am not completely sure if you actually need to worry about it here and having required=True on your email form field is not enough).

Also, I'm not sure you actually need to call clean_email() on the adapter - if you are using the default account adapter, I think it is doing nothing and is simply a "stub" for custom adapters (source).

I think using get_or_create() first and then checking the request_approved value could be a bit cleaner.

Here is a variation of the code with applied assumptions and suggestions (described above):

def clean_email(self):
    email = self.cleaned_data.get['email']

    if settings.INVITE_MODE:
        invitation, _ = Invitation.objects.get_or_create(email=email)
        if not invitation.request_approved:
            self.add_error('email', 'Sorry at this time you are not invited. But we have added you to our invite list')

    return email

One concern with that though - I am not sure if creating an invitation record from a form field's clean form method is a good thing and is not a sign of a bad design..

Another note is that if a new user would submit the form multiple times with the same email address, the user would get the same "Sorry at this time you are not invited. But we have added you to our invite list" message. Instead, may be, if email does not exist, you can say that the user was added to the invite list, but if email exists but the invitation is not approved, you can say something more specific, like "Your invitation is waiting for approval".


The problem with your intLog' function is definitely that it goes through all n numbers in the list. As a result of this it takes ages for large n (for n = 2^130 it ran until I killed it, while your other solutions all returned the result instantly).

The reason that it has to go through all the numbers is of course that using a condition in a list comprehension is like using filter and does not make use of the fact that once the condition is false for the first time, it will always be false thereafter. What you should use instead is takeWhile which takes elements from the list while the condition is true and then stops the first time the condition is false. This way the code would look like this:

intlog n b = maximum $ takeWhile (\i -> b^i <= n) [0..]

Since it will no longer go through the list to its end, we also no longer need to pick an upper bound and can just leave it off. This function will instantly return a result like the other solutions.

Of course, except for learning purposes, the best solution is still to just use the built-in functionality with conversion as there is no point reinventing the wheel. Regarding that you should note that you can use the prelude function logBase instead of dividing the logs of n and b.


The code you have posted is straightforward and basic. Because of this, I'm going to assume you are not super-experienced with Python. I'll make some direct suggestions to go from your current code to a faster version of your code, but I don't expect you'll be able to make the time limit with this structure. See @vnp's answer for how to do that.

You wrote:

n,q = map(int,input().split())
c = [0]*n
for i in range(q):
    j,k,l = list(map(int,input().split()))
    co = 0
    if j == 1:
        #do Something
        for m in range(k,l+1):
            if c[m] == 1:
                co += 1
        print(co)
    if j == 0:
        #do something
        for m in range(k,l+1):
            if c[m] == 1:
                c[m] = 0
            else:
                c[m] = 1

When I read the assignment, this is what I saw:

  There are N coins kept on the table, numbered from 0 to N - 1.
  Initially, each coin is kept tails up. You have to perform two types
  of operations:

  1) Flip all coins numbered between A and B inclusive. This is
  represented by the command "0 A B" ...

Yet, when I look at your code, I see this:

for i in range(q):
    j,k,l = list(map(int,input().split()))

You aren't mapping the problem space into your code. This makes it harder for you- and me, and everyone else that sees it- to reason about your code.

Let me suggest right up front that you adopt names that reflect the problem statement whereever possible. Note that in cases where you get clever and use a different algorithm, the names are entirely up to you. In that case, they should not conflict with the problem statement:

N, num_opns = list(map(int, input().split()))

for i in range(num_opns):
    operation, A, B = list(map(int, input().split()))

See the difference? N is N. There are operations that can be 0 or 1. Guess which is the operation? And there are parameters A and B, clearly marked. I haven't changed how it functions, but someone reading the code can now refer to the instructions and see what's what.

Adding Faster

Next, let's look at your two operations. Here's your first one, counting the 1 values:

for m in range(k,l+1):
    if c[m] == 1:
        co += 1

Your code looks at every value, and if it's 1, adds 1 to the count, and if it's not 1, adds nothing to the count.

Now, think like a programmer! Ask, "how can I get rid of any of that code?" In this case, what happens when c[m] is not equal to 1? Why, then, it's equal to 0. And what happens when you add 0 to any number? Nothing - the number doesn't change. So you could change that code to:

for m in range(k,l+1):
    co += c[m]

And get the same result!

Going further, it turns out that Python has a built-in sum that adds up a sequence of values! You can switch from adding these numbers in Python to having Python's interpreter add the numbers in C. That should speed things up nicely:

co = sum(c[k:l+1])

There's two things going on in there. The first, c[k:l+1] is called a slicing expression. It creates a "sub-list" of the c list, with just the values in question. The second is the use of the sum() built-in.

Switching Faster

Your second operation just changes values:

for m in range(k,l+1):
    if c[m] == 1:
        c[m] = 0
    else:
        c[m] = 1

There are a couple of ways to speed this up, and they all involve doing some kind of single operation instead of an if statement. For example, you could perform a bitwise exclusive-or of the value with 1. Bitwise xor is also bitwise (no borrow) subtraction modulo 2, so when you xor things 0 becomes 1, and 1 becomes 0.

for m in range(k,l+1):
    c[m] ^= 1

Alternatively, you could store the values in a tuple and map the old value to the new value:

new_values = (1, 0)
for m in range(k,l+1):
    c[m] = new_values[c[m]]

Finally, I'll point you at the timeit module, which is the standard Python way of measuring speed. If you are trying to beat a time limit in any challenge, make sure you use timeit so you can keep track of what effect every change you make has on performance.


Convert light-years to other representations

Constants should be Constant

You shouldn't be able to change constants; they should be fixed, non-modifiable values.  In Java, this means declaring them final.

If you create two instances of your class, you'll end up with two instances of lightYear, hoursInDay and so on.  But since these values are fixed compile-time constants, it doesn't make sense to have multiple copies of them.  You just need one copy of these constants, which means declaring them as static.

Things like hours in a day, and days in a year are also fairly general values.  They could be of use in other classes, so it makes sense to make these values sharable, which means public.

Finally, convention is to name constants with an UPPERCASE_NAME.

So ...

public final static long MILES_PER_LIGHT_YEAR = 5878625541248L;

public final static int  HOURS_PER_DAY = 24;
public final static int  DAYS_PER_YEAR = 365;
public final static int  YEARS_PER_CENTURY = 100;
public final static int  YEARS_PER_MILLENNIUM = 1000; // Note: 2 N's

Time Conversion

As noted by @Sixsmith, the Hours to Days, Years, Centuries, and Millennium calculation is being repeated.  Unfortunately, they went a little far and added System.out.println("Driving the fastest car in space to their hoursConversion() function, so it is not general enough to use for the plane (or eventually, space probe).

Reducing the conversion code slightly produces a reusable function:

public static void output_hour_equivalents(long hours) {

    long days = hours / HOURS_PER_DAY;
    if (days > 0)
        System.out.println(hours + " hours is equivalent to " + days + " days.");

    long years = days / DAYS_PER_YEAR;
    if (years > 0)
        System.out.println(days + " days is equivalent to " + years + " years.");

    long centuries = years / YEARS_PER_CENTURY;
    if (centuries > 0)
        System.out.println(years + " years is equivalent to " + centuries + " years.");

    long millennia = years / YEARS_PER_MILLENNIUM;
    if (millennia > 0)
        System.out.println(years + " years is equivalent to " + millennia + " millennia.");
}

You could, of course, add "weeks" and "months" to this without loss of generality.  I added tests at each conversion to avoid printing out a zero duration if given a small number of hours, like output_hour_equivalents(10000).

Duration for distance at speed

The conversion from speed and lightyears, for the fastest class of an object, to duration can be moved into a general purpose function.  But we don't want to hard-code too much text.  We want to fly a plane, not drive one, so we should take in the object class, and the action we perform with it, as well as it's maximum speed and the distance to be traversed:

public static void describe_fastest(String object, String action, double max_speed, long light_years) {
    long miles = light_years * MILES_PER_LIGHT_YEAR;
    long hours = (long)(miles / max_speed);

    // Capitalize the first letter of our action, for output.
    action = action.substring(0, 1).toUpperCase() + action.substring(1);

    System.out.println(action + " the fastest " + object + " in space, would take you " + hours + " hours to travel " + light_years + " light years.");
    output_hour_equivalents(hours);
}

You can now use this in your method.  For example, from main, borrowing @Sixsmith's variable names:

public static void main(String[] args) {

    long light_years = ...

    describe_fastest("car", "driving", carMph, light_years);
    describe_fastest("plane", "flying", planeMph, light_years);
    describe_fastest("space probe", "traveling in", spaceProbeMph, light_years);
}

1 Light Year

If you provide the value 1 for light_years you'll get something like:

  Driving the fastest car in space ... to travel 1 light years.

I hate that "1 light years."  It should be "1 light year."  Singular.  MessageFormat can help us here:

private final static String MSG_FORMAT =
    "{0} the fastest {1} in space, would take you {2} hours to travel " +
    "{3} {3,choice,0#light years|1#light year|1<light years}.";

public static void describe_fastest(String object, String action, double max_speed, long light_years) {
    long miles = light_years * MILES_PER_LIGHT_YEAR;
    long hours = (long)(miles / max_speed);

    // Capitalize the first letter of our action, for output.
    action = action.substring(0, 1).toUpperCase() + action.substring(1);

    System.out.println(MessageFormat.format(MSG_FORMAT, action, object, hours, light_years));
    output_hour_equivalents(hours);
}

The format string constant is private, since it is unlikely that anyone else would re-use that string anywhere.

You can also add commas between groups of 3 digits, and other things to make the output a little more pleasing.  See MessageFormat for details.

You can also make it output "hour" or "hours", "day" or "days", "year" or "years", "century" or "centuries", and "millennium" or "millennia" in the other messages.

Exercise left to student.


Is there a "code less" way to construct this JS loop?

I would do it like this. Note how the zero-padding is encapsulated in a function and how the double loops are turned into a single loop by using modulo and integer division. Also, the vars are pre-declared as is considered good style in JavaScript.

function zeroPad(number) {
    if (number <= 9) {
        return "0" + number;
    } else {
        return number;
    }
}

var i, hour, minute,
    arrHours = [];
for (i = 0; i < 60 * 24; i += 15) {
    hour = Math.floor(i / 60);
    minute = i % 60;
    arrHours.push(zeroPad(hour) + ":" + zeroPad(minute));
}


Function that tests whether all items in a list are the same

First, a note about testing: inside singleton-list? you check if the argument is a pair, while it is called by all-same? always with a non-empty list, so the test will be always true.

So you can simplify the program by eliminating the auxiliary function and replacing, inside the definition of all-same?, the second branch of the conditional with the only significant test:

((null? (cdr ls)) #t)

Then, note that your function returns a boolean value, and each branch of the cond and the inner if returns a boolean value. This is a good reason to perform a little simplification of the function, by using and and or as control structures (this is typical of the lisp languages). So the function could be redefined as:

(define all-same?
  (lambda (ls)
    (and (not (null? ls))
         (or (null? (cdr ls))
             (and (equal? (car ls) (cadr ls))
                  (all-same? (cdr ls)))))))

Finally, it may be questionable to decide that the function should return false when the list is empty, since in mathematics the universal quantifier is true even for an empty set. So, in case the function could be defined to return true even if the list is empty (“there are no elements, so there are no two element different”), we could further simplify the function in the following way:

(define all-same?
  (lambda (ls)
    (or (null? ls)
        (null? (cdr ls))
        (and (equal? (car ls) (cadr ls))
             (all-same? (cdr ls))))))


I see one instance of undefined behavior in your code.

LoadAsync( size_t queue_size, function<Container()> f )
        : find_next( f ), size( queue_size ),
          worker_thread( &LoadAsync<Container>::worker_thread_function, this )
...

void worker_thread_function()
{
    while ( true ) {
        unique_lock<mutex> lk( m );

...

thread worker_thread;
mutex m;

The LoadAsync constructor constructs each member variable in the order in which they were declared — i.e., it constructs this->worker_thread before constructing this->m. And the way you construct worker_thread causes it to start running immediately, and the first thing it does is attempt to lock m — whose constructor may not have finished yet!

The simplest solution is to reorder your member variables so that worker_thread will be constructed last.

Style notes:

using namespace std; is a bad idea, and you shouldn't do it (especially in a header file like this). Explicitly qualify std::mutex, std::domain_error, and so on. It's a good habit to get into.
&LoadAsync<Container>::worker_thread_function is a verbose way of saying &LoadAsync::worker_thread_function: the <Container> part is implied in this context, just as it is in your copy-constructor declaration.
You don't need to explicitly = delete your copy-constructor: since one of your non-static member variables is a non-movable std::mutex, your class itself becomes non-movable by default.
cv and cv_init are bad names. Consider cv_consume and cv_produce, or cv_queue_empty and cv_queue_full. (Also, it's strange that your pop_front will block waiting for the producer to finish running find_next() even when the queue isn't empty. Doesn't that basically defeat the purpose of having two threads?)
qued is a weird name; perhaps you meant q or queue?
Container is a bad name for the object type being contained by your queue. I suggest renaming it T.

You don't provide any way to clean up after your worker_thread. By default, std::thread's destructor simply blocks until the thread finishes, which (since your worker thread is just an infinite loop) means that destroying a LoadAsync object will hang forever.

Calling worker_thread.detach() is one solution, but will still "leak resources" in a sense. It would be better to change the worker_thread's condition from while (true) to something like while (!this->finished), change your predicate from

[this] { return this->qued.size() < this->size; }

to

[this] { return finished || (qued.size() < size); }

and then change the body of the destructor to

{
    unique_lock<mutex> lk(m);
    this->finished = true;
}
this->cv.notify_one();
this->worker_thread.join();

It's bad practice to call the user-provided function find_next() while holding the lock on m. Consider what would happen if find_next tried to take the same lock:

bool first = true;
LoadAsync<int> la(3, [&]() {
    return first ? (first = false, 42) : la.pop_front() + 1;
});

The easiest solution is to drop the lock, call find_next(), and then reacquire the lock to move the result into the queue. Of course, the move-constructor of Container might take the lock...

Also, notice that if find_next throws anything other than std::domain_error, your program will die in std::terminate. That's not so good.

Lastly, notice that you're relying on the notion of a "producer thread" and a "consumer thread" being able to run concurrently with each other. If your program is running in a context so resource-constrained that it can only get hold of a single thread, then your code will deadlock. IMHO that's extremely unlikely, and even if it did happen I would hope that thread's constructor would throw an exception instead of blithely continuing on its way. But I don't know.


You should avoid setting your event handlers like that (by assigning a function to the onclick property) because you can only have a single function assigned to that property so anything else you assign to it will overwrite the previous event. Instead you should use addEventListener.

function addHandler(id, fn, eventName) {
  document.getElementById(id).addEventListener(eventName || 'click', function() {
    if (obj = canvas.getActiveObject()) {
      fn.call(this, obj);
      canvas.renderAll();
    }
  });
}

There is a line of code (i.e. var isUnderline = (getStyle(obj, 'textDecoration') || '').indexOf('underline') > -1;) which is repeated a lot. It is probably enough to justify giving it it's own function...

function hasStyle(obj, prop, value){
    return !!~(getStyle(obj, prop) || '').indexOf(value);
}

This saves you from having to put isUnderline into memory and then garbage collect it later..

addHandler('bold', function(obj) {
  setStyle(obj, 'fontWeight', hasStyle(obj, 'fontWeight', 'bold') ? '' : 'bold');
});

Finally, you could remove redundancy (for the D.R.Y. principle) by using an object..

var styles = {textDecoration: 'underline', fontWeight: 'bold', fontStyle: 'italic'};
for(let prop in styles){
    if(!styles.hasOwnProperty(prop)) continue;
    addHandler(styles[prop], function(obj) {
        setStyle(obj, styles[prop], hasStyle(obj, prop, styles[prop]) ? '' : styles[prop]);
    });
}


Conditional callback for asynchronous file copy

You can write

function(callback) {
  callback();
}

as just

callback


First Rust program - squares which are sum of squares

How can it be improved? Well, it all depends on your goals with the code. I'll assume the goal is to make it prettier and more in line with typical Rust style.
First of all, while loops are rare in Rust code and you should replace them with for. This is because while works on your hand-rolled logic, whereas for .. in .. works with external iteration that is composable and idiomatic Rust.
I see you have one for loop already. Let's turn all others into for.
You always start with 1, so the first iterator will be (1..). We keep taking elements of the range as long as a condition is satisfied, so the next element of the iteration pipeline will be .take_while(|&b| ...). This Rust standard library method best fits the situation.
fn main()
{
  for a in 1..101
  {
    for b in (1..).take_while(|&b| a*a-b*b >= 0)
    {
      for c in (1..b).take_while(|&c| a*a-b*b-c*c>=0)
      {
        for d in (1..c).take_while(|&d| a*a-b*b-c*c-d*d>=0)
        {
          if a*a-b*b-c*c-d*d==0
          {
            println!("{}²={}²+{}²+{}²",a,b,c,d);
          }
        }
      }
    }
  }
}

This code is much more idiomatic already. Next up, I noticed that the intent of the two inner loops is to iterate until we hit the number above, so let's make two simple changes:

for c in (1..b).take_while(|&c| a*a-b*b-c*c>=0)
for d in (1..c).take_while(|&d| a*a-b*b-c*c-d*d>=0)

For readability, we can Don't-Repeat-Yourself by making a tiny function.
fn square_diff(a: i32, b: i32, c: i32, d: i32) -> i32 { a*a-b*b-c*c-d*d }

For all instances of a*a-b*b or a*a-b*b-c*c or ..., we replace them with square_diff(a, b, 0, 0) etc.
One more observation: (1..).take_while(|b| square_diff(a, b, 0, 0) >= 0) is equivalent to 1..=a.
Next up, we don't do C-style indentation in Rust. We put a single space after every comma in arguments. The result so far is:
fn main() {
  for a in 1..101 {
    for b in 1..=a {
      for c in (1..b).take_while(|&c| square_diff(a, b, c, 0) >= 0) {
        for d in (1..c).take_while(|&d| square_diff(a, b, c, d) >= 0) {
          if square_diff(a, b, c, d) == 0 {
            println!("{}²={}²+{}²+{}²", a, b, c, d);
          }
        }
      }
    }
  }
}

fn square_diff(a: i32, b: i32, c: i32, d: i32) -> i32 { a*a - b*b - c*c - d*d }

I tried to test whether these abstractions really reduce to zero-cost, but
alas, Rust@godbolt failed me. Benchmarking is left as a small exercise.
Good luck on your Rust journeys.


Some remarks:

def is_valid_location(self, location):
    return location >= 0 and location < self.board_length

In contrast to many other programming languages, this can be expressed
in Python more succinctly as a chained comparison:

def is_valid_location(self, location):
    return 0 <= location < self.board_length

However, that function seems unnecessary to me, since nowhere in your
program an invalid location is created.

The winning combinations are not dependent on the particular
instance of a board, it is more logical to define them as a
class variable:

class Board():
    winning_combinations = [
            [0,1,2], [3,4,5], [6,7,8],
            [0,3,6], [1,4,7], [2,5,8],
            [0,4,8], [2,4,6]]

    def __init__(self):
        self.board_length = 9;
        self.squares = [NONE for idx in range(self.board_length)]

    // ...

The efficiency of the get_winner function can be improved.
It is not necessary to check both players against each winning combination:

def get_winner(self):
    for combo in self.winning_combinations:
        player = self.squares[combo[0]]
        if player is not None and self.squares[combo[1]] == player and self.squares[combo[2]] == player:
            return player
    return NONE

The only purpose of  _ = 1 in

    if board.get_winner() == X:
        #print(board)
        _ = 1
    else:
        find_winners(board, depth + 1, O if player == X else X)

seems to be to avoid an empty if-block. Python has a pass statement
for that purpose:

    if board.get_winner() == X:
        #print(board)
        pass
    else:
        find_winners(board, depth + 1, O if player == X else X)

You define three variables

X, O, NONE = ("X", "O", ".")

for the possible states of a cell. A better way to express mutually
exclusive values is an enumeration:

from enum import Enum

class Cell(Enum):
    X = "X"
    O = "O"
    empty = "."


Couple of pointers.

In general it's good practice to avoid putting anything other than a call to another function (such as main()) in the if __name__ == "__main__" function, just to aid in ease of unit testing.

Document strings for functions are also nice to have:

def foo():
    '''This function does foo-all, always returns None'''
    pass

A nice (ish) one liner for the decode function might be something like this:

def encode(message):
    message = message.replace(" ", "")
    length = math.ceil(math.sqrt(len(message)))
    ''.join(message[i::length] i in range(length))

Although I admit it needs a bit of refactoring as its a tad long for one line (EDIT adapted a very nice improvement from 200_success 's answer, which they explain well). It does demonstrate that you can skip building the grid though.


You didn't implement the game of Blackjack

number = Random.rand(1..10)

This does not bear a strong resemblance to drawing from a shuffled deck of playing cards. A value of 10 should occur four times more often than 9, even if Aces are only valued as a 1. I understand the desire to simplify, but this goes a bit far.

To model a dealer with a large (or "infinite") number of decks shuffled into the shoe, draw with replacement by using Random.rand(1..13) and then map all values above 9 to 10, to account for J Q K.

To model a single shuffled deck, or a small number of them, that we draw from without replacement, allocate an array of size at least 52, and use Fisher-Yates-Knuth.

  aces are valued as either 1 or 11 according to the player's choice.

This rule is pretty central to the decision of whether to hit or pass.
You really can't use simple + (addition) when summarizing a player's hand.
Minimally you need to model the number of Ace cards he holds and (separately) the sum of non-Ace card values, to properly determine if he is "bust" yet. Also, please don't make $array_sum global. And a better name for pull_push_random() would be deal().

There are several other house rules, such as betting options, that would add more complexity if implemented. I agree with your design decision to avoid such complexities. One can still capture the essence of Blackjack in a fairly short program, if a handful of important rules are implemented.


Euclid's Algorithm (Greatest Common Divisor)

Firstly, your implementation is (arguably) not quite correct:

 else if((m < 0) || (n < 0))
     return -1;

The GCD of two negative numbers is perfectly well defined. However, if you really don't want the user to pass in negative numbers, make it explicit in the function signature:

unsigned greatestCommonDivisor(unsigned m, unsigned n)

Euclid's algorithm is one of the most basic examples of where recursion shines:

unsigned greatestCommonDivisor(unsigned m, unsigned n)
{
    if(n == 0) return m;
    return greatestCommonDivisor(n, m % n);
}

We first check the base case, which is 2: If r is 0, n is the answer; if r is not 0, continue to step 3. The recursive call actually combines steps 1 and 3 here: m % n sets n to be the remainder r, and we call the function again with n = m.

As a final note, a lot of people avoid recursive functions in C/C++ because most compilers don't optimise tail-calls to use constant stack space. However, Euclid's algorithm will perform only O(log N) steps, hence it's easy to see on any computer with (reasonable) stack size, this won't cause a stack overflow for numbers whose size is constrained by int or unsigned.


I'm just going to comment on these three lines:

SendMail = "echo '" + MsgBody % (uid,ExpireIn,d2) + "' \
          mail -s " + '"' + Subject + '"' + ' ' + \
          uid + '@' + EmailDomain
#os.system(SendMail)
print SendMail

This doesn't work! You've commented out the line that sends the e-mail. Now, I understand that you did this so that you can test the script without spamming your users with these messages, and that you intend to uncomment the line when you deploy the script. But this isn't the best approach.

The first problem is that the need to test the script will come up again after you deploy it — you'll need to revise the text of the messages or change some other aspect the way it works, and then you'll want to test it again. So it would be worth your while to build in a permanent testing mechanism that's better than commenting out a line.

The second problem is that just printing the mail command doesn't actually constitute a test. You have to read the output in order to check that it's correct, and you could easily miss a problem.

What I suggest is that you have a setting that can be turned on and off to indicate whether the script is in testing or deployment:

deployed = False           # Is script deployed?
test_uid = 'rahul.patil'   # Send e-mail to this user if not deployed.

and that you send the e-mail to the test user when testing:

if not deployed:
    uid = test_uid
SendMail = "echo '" + MsgBody % (uid,ExpireIn,d2) + "' \
          mail -s " + '"' + Subject + '"' + ' ' + \
          uid + '@' + EmailDomain
os.system(SendMail)

Ideally you would provide a way to set the deployed flag (and the test_uid) through the script's command-line interface — see the argparse module for one approach to doing this.
When you run a command using os.system, the command gets interpreted by the shell. This is risky, because the shell has complicated quoting and evaluation rules that you may not understand. For example, suppose that you edited MsgBody like this:

MsgBody = """
Dear %s,
     Your password will expire in %s day(s). We're sorry for the
inconvenience, but we need you to change your password by %s.
"""

Looks good, right? But if you actually try this, you'll find that the call to os.system fails with an error like this:

sh: line 3: inconvenience,: command not found
sh: -c: line 4: unexpected EOF while looking for matching `''
sh: -c: line 5: syntax error: unexpected end of file

That's because the single quote in We're was interpreted by the shell as terminating the argument to echo.

In order to avoid problems like this (where data gets wrongly interpreted as code by the shell), you should avoid passing the arguments to the shell. Instead of os.system, you should use the functions in the subprocess module. For example, like this:

import subprocess

p = subprocess.Popen(['mail', '-s', Subject, uid + '@' + EmailDomain],
                     stdin=subprocess.PIPE)
p.communicate(MsgBody % (uid, ExpireIn, d2))


Some suggestions:

Semi-colons are optional so, avoid them if possible.
Use type inference when possible. For example:

val aInteger = 1 // Int is inferred by the compiler as the type of `aInteger`

val aListOfInt = listOf(1, 2) // List<Int> is inferred by the compiler as the type of `aListOfInt`

Constructors, in particular primary constructor, are very powerful. For example: class Guesser(val range: IntRange = 1..100) is equivalent to:

class Guesser(range: IntRange) {
  val range = range

  constructor(): this(1..100)
}

val is for read-only properties. If you need to re-assign a property, use var instead.
The use of raw strings with the trimMargin() member function is preferable over multiple println invocations.
The when expression is similar to the more traditional switch. You can learn more about it here.

This is the whole thing:

class Guesser(val range: IntRange = 1..100) {
  private var upperLimit = range.last
  private var lowerLimit = range.first
  private var turnCount = 0
  private var lastGuess = 0
  private var lastResponse = Response.UNKNOWN

  init {
    printIntro()

    while (lastResponse != Response.CORRECT) {
      lastResponse = presentNextGuess()
      turnCount++

      when (lastResponse) {
        Response.CORRECT -> println("I guessed your number in $turnCount turns.")
        Response.UNKNOWN -> println("I'm sorry, I didn't understand that.")
      }
    }
  }

  fun calcNextGuess(): Int {
    var roundingFactor = 0

    when (lastResponse) {
      Response.HIGHER -> {
        lowerLimit = lastGuess
        roundingFactor = 1 //compensates for rounding down
      }
      Response.LOWER -> {
        upperLimit = lastGuess
      }
      else -> assert(false) // Assume error if this is reached
    }

    return (lowerLimit + ((upperLimit - lowerLimit) / 2)) + roundingFactor
  }

  fun presentNextGuess(): Response {
    val nextGuess = calcNextGuess()

    println("Is your number $nextGuess?")

    val response = readLine()

    lastGuess = nextGuess

    return parseResponse(response)
  }

  fun parseResponse(response: String?) = when (response?.toLowerCase()) {
    null -> Response.UNKNOWN
    "higher", "h" -> Response.HIGHER
    "lower", "l" -> Response.LOWER
    "yes", "y" -> Response.CORRECT
    else -> Response.UNKNOWN
  }

  fun printIntro() {
    println(
      """
        Think of a number between 1 and 100. I am going to try and guess it.
        If i guess correctly respond with 'yes' (or 'y')
        Otherwise respond to with either 'higher' (or 'h') or 'lower' (or 'l')
        Okay, here we go...
      """.trimIndent()
    )
  }

  enum class Response {
    HIGHER, LOWER, CORRECT, UNKNOWN
  }
}

fun main(args:Array<String>) {
  Guesser()
}

Note: I'm also learning the language and I could be wrong with some things so, the above code can be improved and is not free of mistakes and non-idiomatic constructs.


Just a few pointers, some of which are my personal preference!

Since you use modern concepts like arrow functions, const, and shorthand objects, you might as well replace jQuery $(".square") with document.querySelectorAll(".square")
Passing a div as an argument is not a good idea. I would keep all visualisation of the game in one separate function, for example: function drawBoard(). This function does all the DOM manipulation, and the DOM elements or jQuery functions should not be mentioned anywhere else in your code.
I would use one game state array, and the event handlers should alter that game state array directly. If square 1 is clicked by player one, the state array would become [1,0,0,0,0,0,0,0,0], and after the game state has updated, you call drawBoard() which draws the X and O visuals in the DOM.
You can use this state array in your checkWin function too, instead of using so many temporary arrays! If you use numbers you can even see who won just by adding the numbers.
You use a lot of temporary variables. I've added a suggestion to switch players without using those.
Don't nest so many functions in each other, don't call them implicitly by sometimes adding () at the end, and other times not. It's hard to reason about.
Arrow functions don't have their own scope, but sometimes you DO need a scope, for example in your gameboard class.

Below are just a few sketches to rewrite the code, I realise this is far from complete but it might give you some ideas:

function Player(name, mark, id){
  this.name = name
  this.mark = mark
  this.id = id
}

function GameBoard(){
  let state = [0,0,0,0,0,0,0,0,0]
  let player1 = new Player("Mark","X", 1)
  let player2 = new Player("Joe", "O", 2)
  let currentPlayer = player1

  this.initHandlers = function(){
    let fields = document.querySelectorAll(".field")
    for(let f of fields){
     f.addEventListener("click", (e)=> this.updateState(e))
    }
  }

  this.updateState = function(e){
    console.log("id of the clicked tile is " + e.target.id)
    let id = parseInt(e.target.id)
    state[id] = currentPlayer.id
    this.drawBoard()
    this.checkWin()
    currentPlayer = this.switchPlayers()
  }

  this.switchPlayer = function(){
      return (currentPlayer == player1) ? player2 : player1
  }

  this.drawBoard = function(){
    // all DOM manipulation here
  }

  this.checkWin = function(){
    if(state[0] + state[3] + state[6] == 3) console.log("player one wins!")
  }
}

let board = new GameBoard()
board.initHandlers()


I'll focus first on

static func sortDateByMonth(dateArray:[Date]) -> [[Date]]

because that contains the main logic, then mention some other points, and finally
present an alternative solution.

Your code seems to work correctly (as far as I can tell), with one exception: Apparently
it is assumed that the given array is not empty, and it will crash at

resultArray[0].append(inputArray[0])

otherwise. Adding

if dateArray.isEmpty {
    return []
}

right at the top of the function would solve that problem.
In

var inputArray:[Date] = dateArray
inputArray.sort()

the type annotation is not needed because the type can be inferred automatically:

var inputArray = dateArray
inputArray.sort()

But this can be shortened to

let inputArray = dateArray.sorted()

Similarly as above,

var resultArray:[[Date]] = [[]]
resultArray[0].append(inputArray[0])

can be combined to

var resultArray = [[inputArray[0]]]

In

for i in 1 ..< (inputArray.count) { ... }

the parentheses on the right are not needed. But I prefer

for i in inputArray.indices.dropFirst() { ... }

because that works for other collection types as well, where the index is not
necessarily zero-based (such as ArraySlice).
Inside the loop, the statement

        resultArray[k].append(inputArray[i])

appears twice, this can be improved to

for i in inputArray.indices.dropFirst() {
    if inputArray[i].yearInt != inputArray[i-1].yearInt
        || inputArray[i].monthInt != inputArray[i-1].monthInt {
        resultArray.append([])
        k += 1
    }
    resultArray[k].append(inputArray[i])
}

Accessing the count of an array is a O(1) operation, therefore one can get even
get rid of the variable k:

for i in inputArray.indices.dropFirst() {
    if inputArray[i].yearInt != inputArray[i-1].yearInt
        || inputArray[i].monthInt != inputArray[i-1].monthInt {
        resultArray.append([]) // Start new row
    }
    resultArray[resultArray.count - 1].append(inputArray[i])
}

Now let's try to make the date comparison simpler and more efficient. Your code
requires 4 calls to a format parsing method in each iteration. Generally, if you
are interested in the numerical values of the date components (such as year and
month number) then using

let yearAndMonth = calendar.dateComponents([.year, .month], from: inputArray[i])

is more efficient, it computes both numbers in a single call and gives you
integers instead of strings.

But here we can do even better: There is a dedicated Calendar method to check
if two dates are equal down to some specified component:

calendar.isDate(date1, equalTo: date2, toGranularity: .month)

so that the loop becomes

    let calendar = Calendar(identifier: .gregorian)
    for i in inputArray.indices.dropFirst() {
        if !calendar.isDate(inputArray[i-1], equalTo: inputArray[i], toGranularity: .month) {
            resultArray.append([]) // Start new row
        }
        resultArray[resultArray.count - 1].append(inputArray[i])
    }

This makes your extension Formatter and some of the extension Date
properties obsolete, at least for this application.

Note also that I used the Swift Calendar type instead of the Foundation NSCalendar
type.

One can even get rid of the index i in the above loop by iterating over
the inputArray and a shifted version of that array, and then the
complete function looks like this:

static func sortDateByMonth(dateArray:[Date]) -> [[Date]] {

    if dateArray.isEmpty {
        return []
    }

    let inputArray = dateArray.sorted()
    var resultArray = [[inputArray[0]]]

    let calendar = Calendar(identifier: .gregorian)
    for (prevDate, nextDate) in zip(inputArray, inputArray.dropFirst()) {
        if !calendar.isDate(prevDate, equalTo: nextDate, toGranularity: .month) {
            resultArray.append([]) // Start new row
        }
        resultArray[resultArray.count - 1].append(nextDate)
    }
    return resultArray
}

Now some additional remarks:

Setting the timezone to NSTimeZone.default is not needed because that is the default. On the other hand, it is
a good idea to set the locale to some well-defined value, such as "en_US_POSIX",
because otherwise the formatter behavior can depend on the user's regional settings
(see Technical Q&A QA1480 – NSDateFormatter and Internet Dates):

extension Date {

    static func parse(_ string: String, format: String = "yyyy-MM-dd") -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = format
        return dateFormatter.date(from: string)!
    }
}

Of course this will crash if the string does not match the provided date format.
An alternative is to define a (failable) initializer method:

extension Date {

    init?(_ string: String, format: String = "yyyy-MM-dd") {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = format
        guard let date = dateFormatter.date(from: string) else { return nil }
        self = date
    }
}

which can be used as

let date = Date("2014-05-20")

and the caller decides whether to force-unwrap the result, or to safely unwrap it
with optional binding.
Your

class DateArrayConversionHelper

is apparently used to provide a namespace for the static helper function.
If that is the only purpose and no instances of that type are ever created, then
a struct with a private init method:

struct DateArrayConversionHelper {
    private init() {}

    static func sortDateByMonth(dateArray:[Date]) -> [[Date]] { ... }
    // ... other helper methods ...
}

or a caseless enum

enum DateArrayConversionHelper {

    static func sortDateByMonth(dateArray:[Date]) -> [[Date]] { ... }
    // ... other helper methods ...
}

are good alternatives, compare for example
Swift constants: Struct or Enum
on Stack Overflow.

Finally an alternative approach, which might be simpler for the usage as
a table view data source.

The Dictionary(grouping:by:)
initializer (introduces in Swift 4)

  creates a new dictionary whose keys are the groupings returned by the given closure
  and whose values are arrays of the elements that returned each key.

and can in your case be used as

let calendar = Calendar(identifier: .gregorian)
let groupedDates = Dictionary(grouping: dateArray.sorted()) { (date) in
    return calendar.dateInterval(of: .month, for: date)?.start ?? Date.distantPast
}

This returns a dictionary of type [Date : [Date]] where each key is a date
representing a start of the month, and the corresponding values are the dates in
that month.

Then

let availableMonths = groupedDates.keys.sorted()

is an array of dates, each date representing the start of one month, this can be used to compute the number
of sections and the section titles.

For each month,

let datesInMonth = groupedDates[month]

is an array of dates in that month, this can be used to compute the number of rows in a section and for the
tableView(_:cellForRowAt:) method.


Extracting files and directories from a provided list into separate lists

Most is said about this code in the other answer, but there is a simplification which can be used to beautify this code a lot.

The Directory class has two methods which returns IEnumerable<string> namely EnumerateFiles() and EnumerateDirectories().

The results of the calls to this methods can be used to call AddRange() on the ShortFileList and FullList.

Like so

List<string> fullList = new List<string>(LoadFiles("patch.txt"));
List<string> shortCatalogList = new List<string>();
List<string> shortFileList = new List<string>();

for (int i = 0; i < fullList.Count; i++)
{

    if (System.IO.Path.HasExtension(fullList[i]))
    {
        shortFileList.Add(fullList[i]);
        continue;
    }

    shortCatalogList.Add(fullList[i]);

    var files = Directory.EnumerateFiles(fullList[i]);
    shortFileList.AddRange(files);

    var directories = Directory.EnumerateDirectories(fullList[i]);
    fullList.AddRange(directories);

}


Find the highest product between elements in a set

Test case that could be failing: {0,-1}.
In your case it returns 1 while it should have been 0.

About the algorithm:

Since you are already sorting it, just multiply everything except zero and first negative number. If its still negative multiply the first negative number.


Retrieve high views per day questions with few answers

Overall
I think your query is pretty nicely written and returns useful information.

Use some variables to refer to repeated values, for example, the GETDATE() reference could just be declared as a variable at the top and reused throughout.
DECLARE @now DATETIME2 = GETDATE();

You could also use variables to eliminate some magic numbers, such as the Posts.PostTypeId for questions and answers.

You might want to add a field to indicate when the question was actually posted. A day count is all fair and well, but knowing the actual post date might be good information as well.
SELECT
  /* ...*/
  Question.CreationDate AS DatePosted

You might want to rename the Days column to something a bit more descriptive, like DaysSinceFirstPosted or just DaysOld.

Use day instead of dd, they work the same but day makes the code easier to read.
You also don't need to convert datetime fields to date fields for calculations to work correctly, it's all factored in for you already, e.g.:
DATEDIFF(DAY, Question.CreationDate, @now) AS DaysSinceFirstPosted

ViewsPerDay would be better named as AverageViewsPerDay based on your calculations.

SELECT
    /* ... */
      (SELECT MAX (Answers.Score)
       FROM POSTS "Answers"
       WHERE Answers.ParentId = Question.Id
       AND   Answers.PostTypeId = 2
      ) "Highest Answer Score",

This would make more sense as a normal table join rather than an inline subquery:
SELECT
    /* ... */
    MAX(Answers.Score) AS [HighestAnswerScore],
    /* ... */
FROM
    Posts AS [Question]
    LEFT JOIN Posts AS [Answers]
        ON Answers.ParentId = Question.Id
        AND Answers.PostTypeId = @answer
WHERE
    /* ... */

If you plan on using quoted identifiers as you did, you would want to declare SET QUOTED_IDENTIFIER ON; at the top of your query. SE Data Explorer must have that set by default, yet it's not the case for some other databases. I personally find it more practical to use default square brackets for identifiers.

With all of the above applied, here is the new query:
DECLARE @now DATETIME2 = GETDATE();
DECLARE @question INT = 1;
DECLARE @answer INT = 2;
SELECT TOP 500
    Question.CreationDate AS QuestionPosted,
    Question.ViewCount AS QuestionViews,
    DATEDIFF(DAY, Question.CreationDate, @now) AS DaysSinceFirstPosted,
    Question.Id AS [Post Link],
    Question.ViewCount / DATEDIFF(DAY, Question.CreationDate, @now) AS AverageViewsPerDay,
    Question.AnswerCount,
    MAX(Answers.Score) AS HighestAnswerScore,
    Question.Tags
FROM
    Posts AS [Question]
    LEFT JOIN Posts AS [Answers]
        ON Answers.ParentId = Question.Id
        AND Answers.PostTypeId = @answer
WHERE
    Question.PostTypeId = @question
    AND Question.AcceptedAnswerId is null
    AND DATEDIFF(DAY, Question.CreationDate, @now) > 10
    AND (Question.ViewCount / DATEDIFF(DAY, Question.CreationDate, @now)) > 5
GROUP BY
    Question.CreationDate,
    Question.ViewCount,
    DATEDIFF(DAY, Question.CreationDate, @now),
    Question.Id,
    Question.ViewCount / DATEDIFF(DAY, Question.CreationDate, @now),
    Question.AnswerCount,
    Answers.Score,
    Question.Tags
ORDER BY
    AnswerCount ASC,
    HighestAnswerScore ASC,
    AverageViewsPerDay DESC;


Not being familiar with the algorithm in question, it was very non-obvious to me what the code did, and in general I think it's good to write code in such a way that it's comprehensible with minimal reasonable effort even if the reader isn't a domain expert (i.e. they should be able to look up documentation, look at your code, and see how the two relate).  The main hindrances I faced were:

It wasn't immediately obvious that x, y, u, v represented two distinct series (where u was always a prior value of x, etc).  In general there are a lot of variables in this code to keep track of, and not a lot of explanation of what they're all for.
Dependencies between the different values likewise were not obvious.  Having all the assignments smushed onto one line made it hard to discern this visually; it's nice to use compact tuple assignments when the relationships are obvious, but it doesn't necessarily always improve readability.
There're no doc/comments explaining what's going on.
The name ext_ggT doesn't follow Python's snake_case naming convention and is a bit cryptic.

After reading the wiki link (thx Peilon) I was able to sort of reverse-engineer it and then I made some changes so that the code matches up more with my understanding based on the wiki article (and is commented so that anyone looking at this code side by side with the wiki article will immediately see what goes with what).

from collections import deque
from typing import Tuple

def extended_euclidean(a: int, b: int) -> Tuple[int, int, int]:
    """
    Returns (gcd, x, y) such that:
       gcd  = greatest common divisor of (a, b)
       x, y = coefficients such that ax + by = gcd
    """
    # We only need to keep the last two elements of each series.
    r = deque([b, a], 2)
    s = deque([0, 1], 2)
    t = deque([1, 0], 2)

    # The next element of each series is a function of the previous two.
    # We stop building these series once r (the remainder) is zero;
    # the final result comes from the iteration prior to that one.
    while r[-1] != 0:
        q = r[-2] // r[-1]
        r.append(r[-2] % r[-1])
        s.append(s[-2] - s[-1] * q)
        t.append(t[-2] - t[-1] * q)

    return r[-2], s[-2], t[-2]

assert extended_euclidean(240, 46) == (2, -9, 47)

The biggest change is that I've represented the various series described in the wiki article as iterables, rather than representing each as two scalars; this doesn't make much difference to the way the code actually runs, but the fact that these six values (previously a, b, x, y, u, and v) represent three distinct series is now very obvious to the reader.  The three series are initialized and extended in such a way as to "make alike look alike" -- you can see at a glance how each successive element is computed from the prior two, and easily discern where there are and aren't dependencies between these values.

You could initialize these series as simply:

r = [b, a]
s = [0, 1]
t = [1, 0]

and the code would return the correct result, but to preserve the behavior of only keeping the last two elements (which I agree is a good space optimization) I've converted them to deques with maxlen=2.  The deque abstracts away the business of automatically popping the unneeded values off of the left side, which helps declutter the "interesting" part of the implementation while still preserving the property of having it use constant space.


You can use more built-in characteristics of the strings.  This code grabs each pair of digits and builds a list, which it then joins with no separator.  Then it adds the remainder from each string.  The shorter string's remainder is the empty string.

def int_merge(a, b):
    str_a = str(a)
    str_b = str(b)
    min_len = min(len(str_a), len(str_b))

    # Grab pairs of numbers while the lengths of both strings allow.
    # After that, add the remainder -- the shorter string will have none.
    result = ''.join([str_a[i]+str_b[i] for i in range(min_len)]) + \
             str_a[min_len:] + str_b[min_len:]
    return result

test = [
    (1548, 369),
    (1356, 24),
    (13, 2456)
]
for case in test:
    print int_merge(case[0], case[1])


Displaying all the numbers between 200 and 600


Handling users connection to the application

If your class takes care of the authentication of your application don't call it User but Auth or Authentication.

You shouldn't "putting everything in a class". Wrapping your code in a class is not OOP. See SOLID and start with the Single responsibility. Every class should have one single responsibility. Your class takes care to recover users data and handles authentication on your application. Too much responsibility for one class. Separate the user handling from the database query.

$_SESSION is an hard dependency. $_SESSION is global, and global is evil.  If at some point you choose to store session data in a different storage you will need to change the implementation of the class. If you write orthogonal code you will enables to changes isolated areas of the code without influence other areas.
You can use abstractions such as those provided by packages like Symfony2, HttpFoundation.

Although there are few who worry about it.


Some small things that jump out to me:

It looks like a lot of duplication in each if check
There are a lot of magic numbers
Those later if checks should probably be elif, unless it's possible to satisfy several of them in one pass
Day/week/month end are identical
You should probably have a single return at the bottom - the things that fill it are the same each time, so just use the checks to determine what gets returned.  Then you only need to change the formatting in one place if you decide to later.

I think I'd prefer to write this with a dictionary mapping adjustments to each type of frequency.  After doing this, calculating the return values for each category can be done by the same code:

adjustment = {
    end: {#dict for adjustments for each frequency},
    start: {#dict for adjustments for each frequency},
    prev_end: {#dict for adjustments for each frequency},
    prev_start: {#dict for adjustments for each frequency}
}

def get_international_dates(timezone, frequency):
    tz = pytz.timezone(timezone)
    today = datetime.now(tz).date()
    midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=True)
    last_full_day_midnight = int(midnight.astimezone(pytz.utc).strftime("%s"))

    end = last_full_day_midnight - adjustment[end][frequency]
    start = end - adjustment[start][frequency]
    prev_end = end - adjustment[prev_end][frequency]
    prev_start = start - adjustment[prev_start][frequency]

    return end, start, prev_end, prev_start


Compress and decompress a string from a file

As you said, not much to do, I only defined the file read as a function, used the with context manager to read and write files instead of opening and closing, some PEP8 enhancements and string.format() instead of concatenation.

import re
import os
from ast import literal_eval

def get_filename():
    while True:
        filename = input('Please input text file name in current directory: \n')
        filename = filename if filename.endswith('.txt') else '{}.txt'.format(filename)
        if os.path.isfile(filename):
            return filename
        else:
            print('No Such text file in current directory: {}'.format(filename))

def comp():
    with open(get_filename(), 'rb') as file_in:
        p = re.compile(r'[\w]+|[\W]')
        split = p.findall(file_in.read())

    word_list, b = []
    for word in split:
        try:
            r = word_list.index(word) + 1
        except ValueError:
            word_list.append(word)
            r = len(word_list)
        b.append(r)

        with open('compressed.txt', 'r+') as file_out:
            file_out.write('{}\n{}'.format(str(word_list), str(b)))

def decomp():
    with open(get_filename(), 'rb') as file_in:
        words = literal_eval(file_in.readline().rstrip('\n'))
        pos = literal_eval(file_in.readline())

    temp = []

    for index in pos:
        temp.append(words[index-1])
    print(''.join(temp))

I might help some more, but need some more context on what you are trying to accomplish. Maybe working on multiple files, taking filenames as arguments or some more improvements.

EDIT:

After reviewing the assignment the previous solution won't take care of punctuation, this will:

import string
import os

def get_filename():
    """Function to get the file name from user input"""
    # Infinite loop to ask the user for a file name that must be valid in order to break the loop.
    while True:
        # Ask the user for a file name.
        filename = input('Please input text file name in current directory: \n')
        # Append .txt extension if not provided.
        filename = filename if filename.endswith('.txt') else '{}.txt'.format(filename)
        # Test if the file exist and return it, print an error and continue loop if not.
        if os.path.isfile(filename):
            return filename
        else:
            print('No Such text file in current directory: {}'.format(filename))

def comp():
    filename = get_filename()
    with open(filename, 'r') as file_in:
        full_text = file_in.read()

    # Making a translation table to get rid of punctuation and keep only letters.
    table = str.maketrans(string.punctuation, ' ' * len(string.punctuation))
    only_words = full_text.translate(table)
    # Create a sorted list of unique elements.
    word_list = sorted(set(only_words.split()))
    # Replace every word of the original text by it's index in the word list.
    for index, word in enumerate(word_list):
        full_text = full_text.replace(word, '{{{}}}'.format(index))  # Double brackets are ignored by .format()

    # Create a separate file with the same name but _COMP_, to dump the compressed text.
    with open('_COMP_{}'.format(filename), 'w') as file_out:
        file_out.write('{}\n***{}***'.format(full_text, '|'.join(word_list)))  # The word list reference is appended.

def decomp():
    with open(get_filename(), 'r') as file_in:
        # Read each line to a list element.
        full_text = file_in.readlines()
        # Remove the last line of the text and convert it to a sorted list of the reference words.
        reference = sorted(full_text.pop(-1).strip('*').split('|'))
    # Print the full text replacing the indexes by the corresponding word in the list.
    print(''.join(full_text).format(*reference))


Maybe you should check validity of the input and ask again if input is wrong?
while baseData["collecting"]:
  baseData["x"].append(float(input("X:")))

This is always True, so just discard this part:
if len(baseData["x"]) == len(baseData["y"]):

Maybe you should give an option to exit?
while True:
  data = input("X/Data:")
  print(int(data)-median)

And in general, calling this a "machiene-learning thing" is quite a stretch of imagination, no? Maybe you should have a look at how to fit data. I.e. a basic linear model fit.


Repetitive unit tests for a programming language

You can make your code less verbose and more expressive at the same time. Now let me explain what I mean.

Make creating test cases easier without all those new lists and types like this

AssertProgram(new TestData
{
    Sources = { "a", "x" },
    TestCases =
    {
        { "abc", "xbc" },
        { "Hello, World!", "Hello, World!" },
    }
});

It's at the same time less verbose because there is only one new for TestData and it's easier to understand what all the strings are.

In order for this to work you'll need three helpers with lists that are already instantiated so that you can just use the collection initializer.

class TestData
{
    public List<string> Sources { get; set; } = new List<string>();
    public TestCaseList TestCases { get; set; } = new TestCaseList();
}

class TestCase
{
    public string Input { get; set; }
    public string Output { get; set; }
}

class TestCaseList : List<TestCase>
{
    public void Add(string input, string output) => Add(new TestCase { Input = input, Output = output });
}

The last class is necessary so that you can add a new Add overload to the list and create your test case easily.

protected void AssertProgram(TestData testData)
{
    var interpreter = new Interpreter(testData.Sources);

    foreach (var testCase in testData.TestCases)
    {
        var actualOutput = new StringWriter();
        interpreter.Execute(testCase.Input, actualOutput);

        Assert.AreEqual(expectedOutput, actualOutput.ToString());
    }
}

If we now rewrite the AssertProgram method to work with the TestData class, it'll be much easier to use the properties than simple strings or repeat the tuple names everywhere.

BTW: you are not using the Output anywhere... yet?


I don't see why you need to calculate permutations. Simply calculate the quotient and remainder of the division starting from the highest coins. In imperative style:

def get_num_coins(coins, value)
  ncoins = 0
  coins.sort.reverse.each do |coin|
    ncoins +=  value / coin
    value = value % coin
  end
  ncoins
end

In functional style:

def get_num_coins(coins, value)
  coins.sort.reverse.reduce(value: value, ncoins: 0) do |state, coin|
    q, r = state[:value].divmod(coin)
    {value: r, ncoins: state[:ncoins] + q}
  end.fetch(:ncoins)
end


Parsing a string using a regex and doing a mathematical calculation if there is a match

There is a wonderful overload of the Regex.Replace method that takes a MatchEvaluator delegate which does exactly what you need it to:
var pattern = "FL2 (77) Flashing,77,a=1.875,A=90.0,b=3.625,B=95.0,c=1.375,C=175.0,d=2.5,hem=0.5,16GA-AL,";
var regex = new Regex("(?<label>[a-zA-Z]+)=(?<value>[^,]+)", RegexOptions.ExplicitCapture);

var result = regex.Replace(pattern, m =>
{
    // Edited - as Paparazzi noted in the comments, I missed
    // the fact that the calculation was different for uppercase
    // and lowercase...

    var newValue = m.Groups["label"].Value.Any(char.IsUpper)
        ? Math.Round(Convert.ToDouble(m.Groups["value"].Value))
        : Math.Round(Convert.ToDouble(m.Groups["value"].Value) * 2) / 2;

    return $"{m.Groups["label"].Value}={newValue}";
});

I've used a few things that might be new to you:

ExplicitCapture specifies that the only valid captures are explicitly named or numbered groups of the form (?…) See documentation
String interpolation - see documentation
var which is implicit typing

I appreciate that the Regex might be more complicated than you're comfortable with but it simply says that I'm looking for 2 groups seperated by an = sign. The label group and the value group. You can then access these by name in the match evaluator. The [^,]+ means match one or more of any character which is not a comma.
Edit:
You don't actually need the ExplicitCapture option - sorry, I modified your Regex and the first iteration had an extra set of () around it. I'll leave it in the answer as it's something that's worth knowing about.