Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded

Houston, you have some bugs

The algorithm counts incorrectly in some cases involving zeros.
For example, there's only one way to make "10" or "20", not 2.

A different problem is the overly strict condition <26,
which excludes "26" even it can be decoded to z.

Beware of string slicing

String.substring creates a new string.
This could become expensive when repeated often.
If you change the logic to work with a char[] instead of a String,
then you can check if the first digit is '1',
or the first digit is '2' and the second digit is <= '6'.

Unnecessary code

This condition will never be true:

if((int)message.charAt(n-k)==0)

The characters in the input are in the range of '0'..'9',
therefore their int values are in the range of 48..57.

Unnecessary Integer[]

You could safely replace Integer[] with int[],
and use a condition on zero value instead of null value.


1: Yes, your Card class should expose its rank and suit through a public interface. (See the previous thread and @user225770's answer for value.) It should at least give read-only access, but write access may not be necessary. (It is probably better to create a copy than to alter a card.)

The simplest indication of this is your output stream operator overload. The fact that it needs access to these members is a good indication that other client code (i.e. code using this class) will need access as well.

2: It depends, but in either case it should be modified a bit. Exceptions are used for exceptional circumstances, scenarios that you don't expect to run into a lot. If it's rare that your deck runs out of cards, then throwing an exception is fine. However, you shouldn't throw an exception for your own function. Let the exception propagate to the calling code, and let them decide how to handle the exception.

However, if it's a common occurrence that your deck runs out of cards, you should use another approach. What immediately comes to mind is to simply reduce the chance of this happening by checking empty() before calling deal(). You can verify this behavior by adding an assert at the beginning of the function.

(What you are technically doing is defining a precondition for your function. In short, this means that your function requires and assumes that the deck is not empty when deal() is called.)

3: No, I don't think this solution is over-engineered. However, a more interesting question is "How can I tell if I have over-engineered my solution?". Why, thank you for asking! This leads me to my next, and perhaps most important point:

Start doing unit tests. You are writing good code. The best way for you to improve now is by doing test-driven development. By writing unit tests, several of your questions will answer itself. For example: Should my class expose this member through its interface? Unit tests will answer this question for you by letting you know what you need access to to test and use your code in unit tests.

Test-driven development will let you know if your code is over-engineered. You write a test that works as a requirement to your code. Do you need to do X to make the test pass? Then implement it. Don't you? Then You Ain't Gonna Need It (yet).


Instead of parsing x, y, z one by one, you can use a list comprehension,
and pass the whole thing directly to the the constructor of Point using * like this:

def load_file(file_path):
    objects = []
    with open(file_path) as input_file:
        for line in input_file:
            obj = Point(*[float(x) for x in line.split()])
            objects.append(obj)
    return objects

I dropped the "r" in open(..., "r"), as that's the default anyway.
Even more importantly,
; are not required to end statements in Python,
and they are just noise in the posted code.

It would be even cuter to use a generator pattern instead:

def load_file(file_path):
    with open(file_path) as input_file:
        for line in input_file:
            yield Point(*[float(x) for x in line.split()])

You could iterate over this to do something with the objects, for example:

for obj in load_file(file_path):
    # do something ...

Or you could load all into a list using a list comprehension:

objects = [x for x in load_file(file_path)]


A simple log that tracks hours worked and and a python script that calculates wages

I think regex is a bit much for this scale of project. I decided to try rewriting your function without using regex, and I think the result is much cleaner and more Pythonic.

In addition, I replaced your hours_full  list of lists with a single number that tracks the total. This greatly simplifies the code.

However, the general structure is essentially the same.

def wage_calculator(log_txt_file, month, year, wage):
    date_pattern = "**Date**: "  # pattern identifying the date in the file
    hours_pattern = "**Hours**: " # pattern identifying the hours in the file
    hours_total = 0.0

    with log_txt_file as f:
        for line in log_txt_file:
            if line.startswith(date_pattern):
                if month in line and str(year) in line:
                    f.next() # skip a line
                    # skip the start of the line to just get a list of hours
                    hours_line = f.next()[len(hours_pattern):]
                    hours = sum(map(float, hours_line.split(', ')))

                    hours_total += hours

                    print line.rstrip()
                    print "Hours logged: " + hours_line
                    print "Total hours for the day " + str(hours) + "\n"

    print "Total hours worked in {0} {1} is {2}".format(month, year,
                                                        hours_total)
    print "At ${0}/hr, your total wage for {1} {2} is ${3}".format(wage, month
                                                                   , year, hours_total * wage)

Beyond this, I would look into more error handling and data cleanup. For example, verify that the **Hours** line matches the **Time** line.

Also a .txt doesn't seem suitable for this data, maybe use a .csv?


Returning the lowest and highest number based on input

If you are only worried about showing Min and Max, and nothing else is the desired result then why not use an immediate calculation approach like this? It surely does not store unnecessary inputs -

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int max = Int32.MinValue, min = Int32.MaxValue;
            int value = 0;

            while (int.TryParse(Console.ReadLine(), out value))
            {
                max = Math.Max(max, value);
                min = Math.Min(min, value);

                Console.WriteLine(" lowest is {0} ", min);
                Console.WriteLine(" highest is {0} ", max);
            }
        }
    }
}

This program will print min and max, until a non-digit character is given.


This type of question actually requires a little thinking outside the box.

The idea here, since we need to store the max with each element, is to use the built-in Stack more creatively.

public class ChallengeValue {
    public int max;
    public int value;
}

I think that should tell you where we're going:

import java.util.*;

public class Stackers {
    public static Stack<ChallengeValue> stack;
    public static String output = "";

    public static void main(String[] args) {
        stack = new Stack<>();
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        for(int i = 0 ; i < n + 1; i++){
            String op = sc.nextLine();
            performOperation(op);
        }

        sc.close();
        if(!output.isEmpty()){
            System.out.println(output);
        }
    }

    public static void performOperation(String op) {
        if (op.startsWith("1")) {
            String remains = op.split(" ")[1];
            int rem = Integer.valueOf(remains);

            ChallengeValue newVal = new ChallengeValue();
            newVal.value = rem;

            ChallengeValue last = stack.peek();
            newVal.max = last.max > newVal.value ? last.max : newVal.max;
            stack.push(newVal);
        } else if(op.equalsIgnoreCase("2")) {
            stack.pop();
        } else if(op.equals("3")) {
            int max = stack.peek().max;
            output += (max + "\n");
        }
    }
}

Now we are storing the max with the stack values, so when we pop one we get the new max immediately. This turns the max (3) command into an \$O(1)\$ operation. (Your version is likely \$O(n)\$.)


Below code is more readable and no need of using our logic around single quotes.

String[] w = fqField.split("\"");
for (int i = 1; i < w.length; i+=2) {
    prefixes.add(w[i]);
}


A couple of things:

Indentation

Indentation seems a little off in your question. Is this because of formatting issues when copy and pasting from your IDE, or is it your code? Most IDEs have a format function that formats the code for you. In eclipse, that is found in Source -> Format or the keyboard shortcut Ctrl+Shift+F.

Spacing

You have what I call overspacing:

static int [] [] grid;

and underspacing:

for  (int i=1; i<n+1; i++){

Again, formatting in an IDE will usually fix that.

After formatting, your code will look like:

import java.util.ArrayList;
import java.util.Arrays;

public class MagicSquareSolver2 {

    static ArrayList<Integer> numbers;

    static int n;

    static int[][] grid;

    static int count;

    public static void main(String[] args) {

        n = 4;

        grid = new int[n][n];

        bruteSolve(0, 0, n);
    }

    public static void bruteSolve(int a, int b, int n) {

        for (int i = 1; i < n + 1; i++) {
            grid[a][b] = i;
            if (b == n - 1 && a == n - 1) {
                if (isValid(grid)) {
                    count++;
                    System.out.println(Arrays.deepToString(grid));
                    System.out.println(count);
                }
            } else if (b == n - 1) {
                bruteSolve(a + 1, 0, n);
            } else {
                bruteSolve(a, b + 1, n);
            }
        }

    }

    public static boolean isValid(int[][] grid) {

        int factorial = 1;
        int fibonacci = 0;
        int totalX1 = 1;
        int totalY1 = 1;
        int totalX2 = 0;
        int totalY2 = 0;

        for (int i = n; i > 0; i--) {
            factorial = factorial * i;
        }

        for (int i = n; i > 0; i--) {
            fibonacci = fibonacci + i;
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                totalY1 = totalY1 * grid[i][j]; // checks all columns
                totalX1 = totalX1 * grid[j][i]; // checks all rows
                totalX2 = totalX2 + grid[j][i];
                totalY2 = totalY2 + grid[i][j];
            }
            if (totalX1 != factorial || totalY1 != factorial
                    || totalX2 != fibonacci || totalY2 != fibonacci) {
                return false;
            }
            totalX1 = 1;
            totalY1 = 1;
            totalX2 = 0;
            totalY2 = 0;
        }

        return true;

    }

}

After some edits in spacing that are not fixed by the IDE:

import java.util.ArrayList;
import java.util.Arrays;

public class MagicSquareSolver2 {

    static ArrayList<Integer> numbers;
    static int n;
    static int[][] grid;
    static int count;

    public static void main(String[] args) {
        n = 4;
        grid = new int[n][n];
        bruteSolve(0, 0, n);
    }

    public static void bruteSolve(int a, int b, int n) {
        for (int i = 1; i < n + 1; i++) {
            grid[a][b] = i;
            if (b == n - 1 && a == n - 1) {
                if (isValid(grid)) {
                    count++;
                    System.out.println(Arrays.deepToString(grid));
                    System.out.println(count);
                }
            } else if (b == n - 1) {
                bruteSolve(a + 1, 0, n);
            } else {
                bruteSolve(a, b + 1, n);
            }
        }
    }

    public static boolean isValid(int[][] grid) {
        int factorial = 1;
        int fibonacci = 0;
        int totalX1 = 1;
        int totalY1 = 1;
        int totalX2 = 0;
        int totalY2 = 0;

        for (int i = n; i > 0; i--) {
            factorial = factorial * i;
        }
        for (int i = n; i > 0; i--) {
            fibonacci = fibonacci + i;
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                totalY1 = totalY1 * grid[i][j]; // checks all columns
                totalX1 = totalX1 * grid[j][i]; // checks all rows
                totalX2 = totalX2 + grid[j][i];
                totalY2 = totalY2 + grid[i][j];
            }
            if (totalX1 != factorial || totalY1 != factorial
                    || totalX2 != fibonacci || totalY2 != fibonacci) {
                return false;
            }
            totalX1 = 1;
            totalY1 = 1;
            totalX2 = 0;
            totalY2 = 0;
        }
        return true;
    }

}

static variables

No, no, no. Rarely should you use static variables, such as a public static final class constant, or something that needs to be static when there is no other option available. You can easily redesign your code to not need static variables:

import java.util.Arrays;

public class MagicSquareSolver2 {

    public static void main(String[] args) {
        int n = 4;
        int[][] grid = new int[n][n];
        bruteSolve(0, 0, n, grid);
    }

    public static void bruteSolve(int a, int b, int n, int[][] grid) {
        for (int i = 1, count = 0; i < n + 1; i++) {
            grid[a][b] = i;
            if (b == n - 1 && a == n - 1) {
                if (isValid(grid, n)) {
                    count++;
                    System.out.println(Arrays.deepToString(grid));
                    System.out.println(count);
                }
            } else if (b == n - 1) {
                bruteSolve(a + 1, 0, n, grid);
            } else {
                bruteSolve(a, b + 1, n, grid);
            }
        }
    }

    public static boolean isValid(int[][] grid, int n) {
        int factorial = 1;
        int fibonacci = 0;
        int totalX1 = 1;
        int totalY1 = 1;
        int totalX2 = 0;
        int totalY2 = 0;

        for (int i = n; i > 0; i--) {
            factorial = factorial * i;
        }
        for (int i = n; i > 0; i--) {
            fibonacci = fibonacci + i;
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                totalY1 = totalY1 * grid[i][j]; // checks all columns
                totalX1 = totalX1 * grid[j][i]; // checks all rows
                totalX2 = totalX2 + grid[j][i];
                totalY2 = totalY2 + grid[i][j];
            }
            if (totalX1 != factorial || totalY1 != factorial
                    || totalX2 != fibonacci || totalY2 != fibonacci) {
                return false;
            }
            totalX1 = 1;
            totalY1 = 1;
            totalX2 = 0;
            totalY2 = 0;
        }
        return true;
    }

}

What I did with your variables:

static ArrayList<Integer> numbers;

You didn't even use this...
static int n;

Just simply put this in the main method, and added a int n argument to your isValid() method.
static int[][] grid;

Just simply put this in the main method, and added a int[][] grid argument into your bruteSolve() method.
static int count;

You only really need this in your bruteSolve() method; actually just the for loop, so I just put it there.

Naming

What's a? How about b? What is n? Why are they one-letter names?

One-letter variable names are not good, as they are confusing to understand. The only place you should use them is, for example, a for loop counter.

Change:

a into num1
b into num2
n into size (or, optional: remove the n variable completely, and directly use either grid.size or the number itself, or change it into a constant, as I will do)

Final Code

import java.util.Arrays;

public class MagicSquareSolver2 {

    public static final int SIZE = 4;

    public static void main(String[] args) {
        int[][] grid = new int[SIZE][SIZE];
        bruteSolve(0, 0, grid);
    }

    public static void bruteSolve(int num1, int num2, int[][] grid) {
        for (int i = 1, count = 0; i < SIZE + 1; i++) {
            grid[num1][num2] = i;
            if (num2 == SIZE - 1 && num1 == SIZE - 1) {
                if (isValid(grid)) {
                    count++;
                    System.out.println(Arrays.deepToString(grid));
                    System.out.println(count);
                }
            } else if (num2 == SIZE - 1) {
                bruteSolve(num1 + 1, 0, grid);
            } else {
                bruteSolve(num1, num2 + 1, grid);
            }
        }
    }

    public static boolean isValid(int[][] grid) {
        int factorial = 1;
        int fibonacci = 0;
        int totalX1 = 1;
        int totalY1 = 1;
        int totalX2 = 0;
        int totalY2 = 0;

        for (int i = SIZE; i > 0; i--) {
            factorial = factorial * i;
        }
        for (int i = SIZE; i > 0; i--) {
            fibonacci = fibonacci + i;
        }

        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                totalY1 = totalY1 * grid[i][j]; // checks all columns
                totalX1 = totalX1 * grid[j][i]; // checks all rows
                totalX2 = totalX2 + grid[j][i];
                totalY2 = totalY2 + grid[i][j];
            }
            if (totalX1 != factorial || totalY1 != factorial
                    || totalX2 != fibonacci || totalY2 != fibonacci) {
                return false;
            }
            totalX1 = 1;
            totalY1 = 1;
            totalX2 = 0;
            totalY2 = 0;
        }
        return true;
    }

}

Looks good now!


Speeding up the process of obtaining data

It looks fast enough to me, nothing screams "major slowdown" in your code, so I would recommend putting a profiler on your code to spot any remaining hotpoints. After that, it's a case of damage control to try to reduce the impact of the data transfer time. As such, consider starting the download as early as possible.

On other matters:

Use var when the right hand side of your declaration makes the type obvious:

string dateAndTime = string.Format("{0}-{1}-{2}+23:00", day, month, year);

should be:

var dateAndTime = string.Format("{0}-{1}-{2}+23:00", day, month, year);

The reason for doing this is that should you change the type of the variable, you only have to change it in one place.

I'm also seeing a few magic strings and numbers that it might be wise to extract as constants or readonly instance variables.

I also don't like your short variable names for your float datapoints. Firstly, if there's nothing that distinguishes them other than the order in which you read them, store them as an array, although I suspect this is not the case, because f0 is given special treatment in the following code.

Secondly, to a maintenance programmer f1 means nothing, unless you're referring to a high-speed motor race. Call them dataPoints if you must, but f1 is extremely unhelpful.

I also note a couple of worrisome points about your implementation:

You don't seem to handle any potential errors at all. What if you can't make a connection, what if the connection drops half way through? Looking at your code literally nothing would happen.

You also only clear your graphReadyData variable when the download completes. If the download fails, this variable will contain the previous correctly-downloaded data. This has the potential to cause errors if not for yourself then for a maintenance programmer, so I would recommend clearing it when you begin the download.


Creating procfs entry on linux in Kernel Module

memset

for (int i = 0; i < sizeof(data) - 1; i++){
    data[i] = 'a';
}

shouldn't be needed. Just use memset from string.h, which is indeed available in the kernel.

sizeof

You have this:

int i = 0; i < sizeof(data) - 1; i++

but also this:

pos + len < sizeof data ? len : sizeof data - pos

Today I learned that the parens are needed on types and optional on expressions:

  The operator has a single operand, which is either an expression or a data type cast. A cast is a data type enclosed in parenthesis.

The only syntax I've ever seen is with parens. You should at least stay internally consistent.

Buffer sizes

5000 is a little unusual, especially inside the kernel. Unless there are hidden motivations, consider just making it 1024*4 == 4096.


Batch program to xcopy from host PC to remote destination with multi-processing

Technical issues:

You are reading whole files into memory at once. Consider what happens if the directory contains huge files.
You use multiprocessing, apparently in an attempt to parallelize things, and use locks to synchronize.
First, why do you need a lock anyway? Which data do you want to protect? The only shared data are in the filesystems, which could be changed by other processes at any time anyway.
Next, each call to multi_distribute_file gets its own lock instance, that is only used once by this call. So there is no synchronization happening at all.
On the other hand, if you would use a single lock for all calls to multi_distribute_file, the processes will execute one after another, as each acquires the lock for its entire runtime. Your parallelizing efforts would be in vain.
You are spawning a new process for each file being copied. This can create a huge number of processes very quickly. Consider what this will do to your system performance.
If something goes wrong in multi_distribute_file and raises an exception, the lock will never be released. And things will go wrong occassionaly as you are communicating over a network. Use a with statement instead.
Don't use string manipulation (format and re) to manipulate paths. Use os.path instead. This is saver and more reliable.

Style issues:

There are no docstrings and no comments (apart from the header)
Avoid single-letter and other abbreviated names like d, l, m, and lo.
mydictionary is a meaningless and misleading name. Meaningless, as it doesn't tell us anything about the purpose of the variable, and misleading as it is actually a list, not a dictionary. A better name might be server_list (like you do elsewhere).


var query = (from x in Directory.GetFiles(_path, "*.csv").AsParallel()
                     where x.Contains(dateTime)
                     select x).First();

If Directory.GetFiles(_path, "*.csv") doesn't return any files where x.Contains(dateTime), this line will blow up with an InvalidOperationException that might be a bit off-putting / surprising.

I find the query would be clearer with a 100% method syntax - this would be equivalent:

var query = Directory.GetFiles(_path, "*.csv")
                     .AsParallel()
                     .Where(name => name.Contains(dateTime))
                     .First();

The name query is wrong/misleading. It would be a query if it were an IQueryable<string> (i.e. up to right after the .Where() call)... but it's not, var actually stands for string and what you call query is actually a fileName: .First() materializes the query, and returns the first element... or throws an exception.

It would be better to call .FirstOrDefault(), which would make your result null if no files matched your search criteria.

I don't understand why you're using var here, given that you're using explicit types everywhere else.. especially since var is just a string. Don't get me wrong though: I prefer seeing var here... and everywhere else.

#region Read CSV File

Using #region inside a method clearly says your method is doing more than one thing. Whenever you do that, you're missing a refactoring opportunity. Consider extracting a method here:

private string GetFileName(string formattedDateTime)
{
    return Directory.GetFiles(_path, "*.csv")
                    .AsParallel()
                    .Where(name => name.Contains(formattedDateTime))
                    .FirstOrDefault();
}

(lacking context to recommend passing in an actual DateTime)

That leaves you with a method that (hopefully) now only has this #region block, which is now completely redundant and can be discarded (if there's still more to it, extract methods as needed)

That said...

FileStream stream = new FileStream(query, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (StreamReader reader = new StreamReader(stream, Encoding.Default, true, 1024))

Disposing the StreamReader will also cleanly close and dispose the FileStream, but that is far from obvious unless you know it, and if Jon Skeet says it's best practice to put it in its own using block, then I can only agree with him.

Your code can use a variable (declared outside the loop's body) for the value separator: you're creating a new character array for every single row you're reading!

char[] separator = new char[] { ',' };

Or more succinctly:

var separator = new[] { ',' };

This makes the temp assignment even clearer/cleaner:

string[] temp = currentLine.Split(separator, StringSplitOptions.None);

Looking at the currentLine, it's far from obvious what's going on here:

while ((currentLine = reader.ReadLine()) != null)

Using the result of an assignment rarely results in easily readable code. I like how it cleverly combines reading the next line into currentLine and verifying whether that's a null value though... so I'm not sure I'd recommend rewriting that part after all.

It's not clear what happens to your List<string[]> when you're done reading the file, so I'll assume you're just returning it. In that case, you could consider yielding the results instead:

private IEnumerable<string[]> ReadCsv(string fileName)
{
    char[] separator = new[] { ',' };
    string currentLine;

    using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (var reader = new StreamReader(stream, Encoding.Default, true, 1024))
    {
        while ((currentLine = reader.ReadLine()) != null)
        {
            yield return currentLine.Split(separator, StringSplitOptions.None);
        }
    }
}


Generalized Project Euler #4: Largest palindrome from product of two n-digit numbers in Python

Instead of build a list of palindromes, calculate max palindrome.
When z * z is lower than max_palindrome, You can break the first for loop (all other palindromes will be lower).
When palindrome is lower than max_palindrome, You can break the second for loop (all other palindromes will be lower). Thanks @Peter Taylor for fix location of if statement.
Convert int to str is expensive. Do it once, not twice.
Based of @Peter Taylor algorithm, set step to -2
Based on Joe Wallis algorithm, modify second loop to range(max_plier, int((z * z) ** 0.5), -2)

Code:

min_plier = 10 ** (digits - 1)  # Minimum n-digit number for eg. if digits = 3, min_plier = 100
max_plier = 10 ** digits - 1    # Maximum n-digit number for eg. if digits = 3, max_plier = 999

max_palindrome = 0

for z in range(max_plier, min_plier, -2):
    if z * z < max_palindrome:
        break

    for x in range(max_plier, int((z * z) ** 0.5), -2):
        product = z * x

        # Check if product is greater than previously obtained palindrome.
        if product < max_palindrome:
            break

        sproduct = str(product)

        # Check if product obtained is palindrome.
        if sproduct == sproduct[::-1]:
            max_palindrome = product

print("Largest palindrome is : %s" % max_palindrome)

Test you solution:

  No. of digits : 4, Largest palindrome : 99000099, Time required for
  execution : 32s

  No. of digits : 5, Largest palindrome : 9966006699, Time required for
  execution : 55min

Test my solution

  No. of digits : 4, Largest palindrome : 99000099, Time required for
  execution : 1ms

  No. of digits : 5, Largest palindrome : 9966006699, Time required for
  execution : 7ms

  No. of digits : 6, Largest palindrome : 999000000999, Time required for
  execution : 67ms

  No. of digits : 7, Largest palindrome : 99956644665999, Time required for
  execution : 373ms

Final soulution and explanation

Lets look at simple example:

mmax = 4
for i in range(mmax, 1 - 1, -1):
    for j in range(mmax, i - 1, -1):
        print(i, j)

  4 4
  3 4
  3 3
  2 4
  2 3
  2 2
  1 4
  1 3
  1 2
  1 1

It's combinations with replacement (not permutation). In this case first palindrome is max palindrome.

digits = int(input("Enter no. of digits in multipliers : "))

def largest_product_two(digits):
    min_plier = 10 ** (digits - 1)  # Minimum n-digit number for eg. if digits = 3, min_plier = 100
    max_plier = 10 ** digits - 1    # Maximum n-digit number for eg. if digits = 3, max_plier = 999

    for z in range(max_plier, min_plier, -2):
        for x in range(max_plier, z - 1, -2):
            product = z * x
            sproduct = str(product)

            # Check if product obtained is palindrome.
            if sproduct == sproduct[::-1]:
                return product

    return None

out = largest_product_two(digits)

print("Largest palindrome is : %s" % out)

Hint to check

For size=3 palindrome is when:

\$100000x + 10000y + 1000z + 100z + 10y + x\$

\$100001x + 10100y + 1100z\$

\$11(9091x + 910y + 100z)\$

For size=4 is similar.

Palindrome is divisible by 11

for z in range(max_plier, min_plier, -2):
    for x in range(max_plier, z - 1, -2):
        product = z * x
        if product % 11 != 0:
            continue

or more pythonic

products = (z * x
            for z in range(max_plier, min_plier - 1, -2)
            for x in range(max_plier, z - 1, -2)
            if z * x % 11 == 0)
for product in products:
    sproduct = str(product)

    # Check if product obtained is palindrome.
    if sproduct == sproduct[::-1]:
        max_palindrome = product
        break

  No. of digits : 6, Largest palindrome : 999000000999, Time required for
  execution : 30ms

  No. of digits : 7, Largest palindrome : 99956644665999, Time required for
  execution : 166ms

  No. of digits : 8, Largest palindrome : 9999000000009999, Time required for
  execution : 51s


IMHO looping twice over the input string is not acceptable for multiple reasons

the string is of unknown size
you invalidate your code for generators

While this might not be necessary for your project you should learn to think like that. So a single pass algorithm should collect all necessary data to answer the question (e. g. the letter in original case).

import sys
assert sys.version_info >= (3, 6)

def non_repeat(s):
    repeated = set()
    candidates = dict()
    for original_case in s:
        lower_case = original_case.lower()
        if lower_case not in repeated:
            if lower_case not in candidates:
                candidates[lower_case] = original_case
            else:
                repeated.add(lower_case)
                del candidates[lower_case]

    if candidates:
        return next(iter(candidates.values()))
    else:
        return ''

This code makes use of the insertion order of a dict which is already implemented in 3.6 and guaranteed in 3.7.

Edit: generator example

Say you want to check a big file that does not fit into memory (for brevity I assume a line fits into memory). Yor write a little character generator and run your algorithm on the generator.

def char_gen(f):
    for line in f:
        for c in line.strip():
            yield c

with open('bigfile.txt') as f:
    print(non_repeat(char_gen(f)))

also you might use the algorithm on a generator expression

print(non_repeat(c for c in "aabbcd" if c != 'c'))


Shortening and optimizing diamond-printing code

Error handling

When you detect an error condition, it's usually better to put the error handler immediately after the if-condition, then bail out.  The error handler is usually shorter than the main code, so it's less mental workload to get it out of the way instead of having to look for the matching else many lines further down.  The advantage of putting the error handler first becomes more apparent when multiple errors are involved:

if (SUCCESS != validate1()) {
    return handleError1();
}
if (SUCCESS != validate2()) {
    return handleError2();
}
if (SUCCESS != validate3()) {
    return handleError3();
}
// The main processing can proceed here

… is more readable than:

if (SUCCESS == validate1()) {
    if (SUCCESS == validate2()) {
        if (SUCCESS == validate3()) {
            // Do the main processing here
        } else {
            handleError3();
        }
    } else {
        handleError2();
    }
} else {
    handleError1();
}

Secondly, it is usually more appropriate to print error messages to System.err.  You don't want unexpected junk contaminating your output.

Consider changing the behaviour such that it throws an IllegalArgumentException rather than printing an error message.  Throwing an exception allows the function's caller to programatically handle the error, making it more flexible and reusable.

Flow of Control

Using boolean variables (like limitReached) to control the flow of your program is usually a sign that you could structure the code better.  In this case, you always take the else-branch when printing the top half of the diamond, then always take the if-branch for the bottom half.  You might as well write it as two for-loops.

On the other hand, there is a competing Don't-Repeat-Yourself principle regarding the body of the loop.  In my opinion, you would still be better off clarifying the flow-of-control by splitting it into two loops.  To avoid copy-and-pasting the loop body, you want to push the special cases into your printing function, so that the body is just one function call.  That would be a smart move anyway, as it makes your printing function more resilient and versatile.

Printing Function

It turns out that your printOtherLines() can be used to print the apex and the base just fine.  You don't need printStartEnd() at all.

I would rename the numLines parameter to size or width.  Calling it numLines in the context of printOtherLines() is a bit confusing, since you are only printing one line per function call.

Object-Oriented Thinking

I don't know whether your exercise specifies a particular interface, but I don't like drawDiamond(int numLines, char sign, char fill).  A more object-oriented approach would be:

Diamond d = new Diamond(/* size= */ 5);
d.draw(System.out, '*', ' ');

In other words, the diamond knows how to draw itself.

Suggested Solution

import java.io.PrintStream;

public class Diamond {
    private int size;

    /**
     * Constructor.
     * @param size The size of the diamond in lines (or columns)
     * @throw IllegalArgumentException if size is negative or even
     */
    public Diamond(int size) {
        if (size <= 0) {
            throw new IllegalArgumentException("Diamond size must be positive");
        }
        if (size % 2 == 0) {
            throw new IllegalArgumentException("Diamond size must be odd");
        }
        this.size = size;
    }

    public void draw(PrintStream out, char sign, char fill) {
        int posL = this.size / 2,
            posR = posL;
        while (posL > 0) {
            // Handle the top half
            this.printLine(out, sign, fill, posL--, posR++);
        }
        while (posL <= posR) {
            // Handle the bottom half, including the middle (widest) line
            this.printLine(out, sign, fill, posL++, posR--);
        }
    }

    private void printLine(PrintStream out, char sign, char fill, int posL, int posR) {
        // Loop condition could be (col <= posR) to omit trailing filler
        for (int col = 0; col < this.size; col++) {
            out.print((col == posL || col == posR) ? sign : fill);
        }
        out.println();
    }

    public static void main(String[] args) {
        try {
            Diamond d = new Diamond(Integer.parseInt(args[0]));
            d.draw(System.out, '*', ' ');
        } catch (IllegalArgumentException e) {
            System.err.println("Sorry, the number of lines must be an odd number...");
        }
    }
}


Script to hide Excel rows where certain columns contain 0

The first rule of optimizing Excel when formatting: "TURN OFF SCREEN UPDATING"

 Application.ScreenUpdating = False

These line continuations are just ugly.  They add nothing to the readability or functionality of the subroutine.

    Case "Form1", _
        "Form 2", _
        "Form 3"

I would remove the line continuations

   Case "Form1", "Form 2", "Form 3"

There are only a sew cases where it is advantageous to Select or Activate an Object.  This isn't one of them.  Watch: Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)

With ws.Activate

I guess your original code might have needed this line: With ws.Range("B" & i) but now it's just leftover parts.  Remove it.

I hate the old style where you first find the last row and then use it in a loop or Range.  IMO, there isn't a good reason to do this with a simple loop or Range selection.

LR = ws.Range("B" & Rows.Count).End(xlUp).Row
  For i = 1 To LR

What's next..hmm. For Each Cell in My 1 Cell Range????  Have you watched the formationed Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset) yet???

For Each c In Range("B" & i)

Range("B" & i) isn't qualified to the ws.  It is referencing the cells of the ActiveSheet. That's probably why you needed to activate the worksheet.

Often it is necessary to unhide all the cells on the worksheet before you reprocess the worksheet.  It probably doesn't apply to this scenario but I thought that I would mention it.

This statement seems somewhat redundant but I'll let someone else handle it.

If c.Value <> "All Forms" _
    And c.Value <> "Week One All Forms" _
    And c.Offset(0, 1).Value = 0 _
    And c.Offset(0, 1).Value <> vbNullString _
    And c.Offset(0, 2).Value = 0 _
    And c.Offset(0, 2).Value <> vbNullString _

Here is the real problem.  You are hiding each row individually.  The preferred method is to create one large Range (per worksheet) and hide all the cells at once.  The easiest way to do this is to use Application.Union.

Then Rows(c.Row).Hidden = True

The other method collects the range addresses and then creates a range from them.  Although faster, its not worth the extra work to processes a few thousand rows.

Rows(c.Row).Hidden = True works but again its ugly use c.EntireRow.Hidden = True

A better way:

Sub HideDoubleZeors()
    Dim ws As Worksheet
    For Each ws In Worksheets
        Select Case ws.Name
            Case "Form1", "Form 2", "Form 3"
                'Do nothing on these tabs
            Case Else                                 'If not one of the above tab names then do this
                ProcessWorksheet ws
        End Select
    Next
End Sub

Private Sub ProcessWorksheet(ws As Worksheet)
    Application.ScreenUpdating = False
    Dim cell As Variant, MyRows As Range
    With ws
        For Each cell In ws.Range("B1", .Range("B" & .Rows.Count).End(xlUp))
            If cell.Value <> "All Forms" And cell.Value <> "Week One All Forms" _
               And cell.Offset(0, 1).Value = 0 And cell.Offset(0, 1).Value <> vbNullString _
               And cell.Offset(0, 2).Value = 0 And cell.Offset(0, 2).Value <> vbNullString Then
                If MyRows Is Nothing Then
                    Set MyRows = cell
                Else
                    Set MyRows = Union(MyRows, cell)
                End If
            End If
        Next
    End With

    If Not MyRows Is Nothing Then MyRows.EntireRow.Hidden = True
    Application.ScreenUpdating = True
End Sub

Hopefully the OP gets more out of this than just some free code.

Good Luck and don't forget to watch that video!!


Optimal way to annihilate a list by removing items from the ends

Missing use of memoization
Your program is almost right, but you aren't using your memoization to the fullest potential.  When the array ends match, you don't check for the memoized value.  Therefore, a stress test of an array of 1000 elements with all the same values causes your program to run for a very long time.
Also, another optimization is that when the array ends match, you can always remove 2 instead of also trying to remove just 1 end (which can only be equal or worse than removing both ends).
Other things to note
Your use of 1010 as an array size is a bit odd.  First of all, you can use exactly 1000 as the problem stated.  Maybe you were afraid of a buffer overflow, but there isn't any.   Also you could use a #define instead of copy/pasting the value all over the place.  That way you could easily change the test size without accidentally missing one place or another.
You don't need to use long long for your array.  An int can hold values up to 10^9.
Corrected function
Here is your function with the memoization corrected:
int recur(unsigned int *arr,int i,int j){
    if(i > j){
        return 0;
    }
    if(memoization[i][j])
        return memoization[i][j];
    if(arr[i] == arr[j])
        return memoization[i][j] = 1 + recur(arr,i+1,j-1);
    return memoization[i][j] = 1 + minOf2(recur(arr,i+1,j),recur(arr,i,j-1));
}

I made an array of 1000 elements all the same value and ran the function 10 times.  With the original code, it took 9.6 seconds.  With the corrected code it took 0.04 seconds.


All primes end in either 1, 3, 7, or 9.  You could do a check up front to make sure the number satisfies that requirement.

Second, a number is prime if it has no prime factors besides itself and 1.  Therefore you should start you checking loop at 3, not at 1.  Since you only need to check against primes, you could start the loop at 3, increment it by 10, and check $x/$i, $x/($i+4), $x/($i+6), and $x/($i+8).  That would be 4 divide operations instead of the 10 you are presently doing.

Third, you only have to check possible factors up to the square root of the number you are checking, so figure out the sqrt($x) and make that the end of the loop.  You are also putting all the factors you find into an array, which is not necessary if you are simply trying to see if the number is prime.


SICP exercise 2.28 - counting leaves in a tree (recursive process)

How does it compare to the iterative version I linked to above?

I actually don't see any iterative versions, all of the examples call themselves twice in the main recursive logic. (as far as I can tell)

What is the order of growth of my function? Is it O(N)?

The best case as for time in any complete tree traversal is O(N log(N)) as is yours.  The big problem is that it's memory overhead is O(N)

How can it be faster?

Memory overhead can be kept to O(log(N))

If I used append rather than cons, would it slow my function a lot?

Looking through the examples, append is used mainly to keep the double-recursive call in the same order as input. Notice with yours (aux remaining '()))) that you flip the remaining to lst. when you hit the bottom of the tree. Using append on average will cause a O(N log(N)) delay.

How can I improve this code?

Using an ADT would help readibility. empty-tree? instead of null? - left instead of car, right instead of cdr.

Don't recur twice at the same time call e.g. (append (recur left) (recur right))

(define (leaf? tree)
   (not (pair? tree)))
(define (left tree)
   (car tree))
(define (right tree)
   (cadr tree))

(define (fringe tree)
  (define (fringe-helper tree acc)
    (if (leaf? tree)
        (cons tree acc)
        (let ((right-fringes
                  (fringe-helper (right tree) acc)))
           (fringe-helper (left tree) right-fringes))))
 (fringe-helper tree '()))

This evaluates right-fringes first, That way at most you have at most log(n) number of fringe-helpers on the stack waiting for a return. It's the same as the second try in your link, with some abstract procedures instead of directly using null? pair? etc.


Keep asking the user [after performing an action] until they wish to stop

Since you have a task you want to repeat at least once, the do-while is the most suitable. How about the following:

private void Main_Shown(object sender, EventArgs e)
{
    /* Let them select photos to be included in the portfolio
     * and move them to the permanent Photo Collection folder,
     * and display them on the form.
     */

    using (FolderBrowserDialog folderPicker = new FolderBrowserDialog())
    {
        folderPicker.Description = "Please browse to, and select the folder containing the files you'd like to add.";

        do
        {
            if (folderPicker.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                // Add files to list for processing later.
            }
            else
            {
                break;
            }

        } while (MessageBox.Show("Do you want to select more photos from another location?", "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
    }
}


Sorting array with respect to two properties

It looks like your implementation relies on Width.CompareTo(second.Width) to return either 1, 0, or -1.

This assumption is wrong. If first.Length is greater than second.Length, CompareTo is allowed to return 9999, or 1, or 500. These could very well screw up your additions.

Sure, the current .NET implementation returns either 1, 0, or -1, but that's an implementation detail. Furthermore, other C# implementations or even future version of .NET may return other values.

Also, tricks reduce readability.

A correct implementation would be:

things.Sort((first, second)
    => {
        var widthComparison = first.Width.CompareTo(second.Width);
        if(widthComparison == 0)
            return widthComparison;
        else return first.Length.CompareTo(second.Length);
    });

But instead of fixing your implementation, I would suggest using LINQ's OrderBy and ThenBy instead. It doesn't seem like you need to sort the list in-place, so there's no need to reinvent the wheel.

List<Thing> things = thingsDictionary.Select(thing => thing.Value)
                                     .OrderBy(x => x.Width)
                                     .ThenBy(x => x.Length)
                                     .ToList();


I don't think you can make this specifically better.

What you could do is make the function more generic, but that depends on what your data contains beyond the first two bytes. For example, you could simply skip any and all line feeds and carriage returns at the beginning:

private int skipLFandCR(byte[] bytes) {
    int pos = 0;
    while (pos < bytes.length && (bytes[pos] == '\r' || bytes[pos] == '\n')) {
        pos++;
    }
    return pos;
}

Also: Do you need a copy of the data? I'd just use a function that returns the start index such as mine and process the existing array starting at that index.


Refactor java methods that do not have a common hierarchy but have same API

Are you able to change your code to rely on a wrapper class then?  - myself

Going on a limb here, but do you want to consider using a wrapper class to encapsulate the fact that you have three similar generated classes, and provide a common way of accessing/modifying them? This assumes:

The methods on the generated classes have the same parameter and return types.
For the case of getDetail() method, that returns the same type as the input object, i.e. recursion.

If both conditions satisfy, then a sample wrapper implementation can be as such (using poorly named class names and variables, please excuse that):

public class WrapperClass {

    private final C1 o1;
    private final C2 o2;

    private WrapperClass(C1 o1, C2 o2) {
        this.o1 = o1;
        this.o2 = o2;
    }

    public String getCode() {
        return findAny(mapC1(C1::getCode), mapC2(C2::getCode));
    }

    // other getter methods

    private <T> T mapC1(Function<C1, T> mapper) {
        return Optional.ofNullable(o1).map(mapper).orElse(null);
    }

    private <T> T mapC2(Function<C2, T> mapper) {
        return Optional.ofNullable(o2).map(mapper).orElse(null);
    }

    private static <T> T findAny(Object... items) {
        return (T) Arrays.stream(items).filter(Objects::nonNull).findAny().orElse(null);
    }

    public static WrapperClass withC1(C1 o1) {
        return new WrapperClass(o1, null);
    }

    public static WrapperClass withC2(C2 o2) {
        return new WrapperClass(null, o2);
    }
}

You will need a map...(Function<?, T>) method for each oh your message class that performs the conversion, and the findAny(Object...) method to get the desired non-null value, if applicable. Each getter method, e.g. getCode() as shown, is relatively trivial to implement. In your case, since you are only dealing with three different classes (which is already a lot), you can also consider a simpler if-ladder instead of streaming through the values.

A slight benefit of the wrapper class is that it lets you perform additional conversions too, for example to an ErrorDetails object:

public final WrapperClass {

    // ...

    public ErrorDetails toErrorDetails() {
        ErrorDetails result = new ErrorDetails(getCode(), getDescription(),
                                                getSourceExceptionName());
        Optional.ofNullable(getSeverity())
                .map(Severity::value)
                .ifPresent(result::setSeverity);
        Optional.ofNullable(getType())
                .map(Type::value)
                .ifPresent(result::setType);
        return result;
    }

    // ...

}

Your current implementations of (convertToList()) will then just become:

public void convertToList(C1 o1, List<ErrorDetails> errors) {
    convertToList(WrapperClass.withC1(o1), errors);
}

public void convertToList(C2 o2, List<ErrorDetails> errors) {
    convertToList(WrapperClass.withC2(o2), errors);
}

private void convertToList(WrapperClass wrapper, List<ErrorDetails> errors) {
    errors.add(wrapper.toErrorDetails());
    convertToList(wrapper.getDetail(), errors);
}

Implementing the wrapper class's getDetail() will be quite similar, other than the slight difference that it should also return its own type:

public WrapperClass getDetail() {
    return new WrapperClass(mapC1(C1::getDetail), mapC2(C2::getDetail));
}


Assuming that entityMetadata.getAttributes() and attr.getAttributeType().getControls() returns some kind of Collection, the answer is an absolute YES.

entityMetadata.getAttributes().stream()
    .flatMap(attr -> attr.getAttributeType().getControls().stream())
    .anyMatch(control -> control.getIsMultiControl());

Other notes:

Comparing with == true is not necessary, that part could be removed entirely.
Prefixing interfaces with I is not something commonly done in Java, it is not recommended in any naming conventions. It is, however, done in C#. C# is not Java.
getIsMultiControl is a very weird name. Should preferably be named isMultiControl.


Handling exceptions with FileInputStream

Naming

Class name Solution does not describe the purpose of the class beyond it being a solution to some random assignment. For the sole purpose of archiving exercises I would name the package with the identifier of the assignment and use a more descriptive class name: your.domain.codegym.exercise42.LetterCounter and put the URL to the assignment in the JavaDoc (maybe package.html). BTW: If you haven't done already, I recommend setting up a GitLab repo for your exercises. One of my regrets is that I've lost so much code I wrote when I was young because broken hard disks and obsoleted hardware. We didn't have on-line repos then...

The parameter name args in the countLetters method does not tell what it is supposed to contain and it is misleading as the plural suffix 's' implies that the parameter would contain multiple values. The parameter should be named as fileName.

Unnecessary object initialization

The method countLetters does not rely on any member variable from the Solution class and the counter does not hold any state between invocations to countLetters. There is no need for the method to require a the Solution class to be instantiated. It could very well be a public static void countLetters(...). If the assignment required that an object is to be initialized, then the requirement is a bit artificial.

Inefficient algorithm

The array that contains the english alphabet letters never changes. It should be a static field in the Solution class. As it is now, your code allocates a new array for the alphabet every time your method is called. But an array like this is also a very inefficient way to look for a letter. As the US-ASCII charset fits in 7 bits and the upper and lower case letters form two consecutive blocks in the character table. You can simply compare the character to first and last letter:

if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
    count++;
}

Note that this approach does not work if the text in the file is in a character set that does not inherit US-ASCII. That would be very very rare these days.

Multiple responsibilities

The countLetters method is a utility method. It should have exactly one purpose so that it does not unnecessarily limit it's usability (also maintaining the single responsibility principle helps in maintainability and testability). You should not implement exception handling beyond closing the resources you have acquired in the method. So instead of printing out the error message, you should just let the exception escape and let caller decide how to handle the error.

So the countLetters has three responsibilities: it counts the letters in a file, handles error logging and also implements output handling. Instead of printing the letter count the method should just return the number of letters and let the caller handle the output. Use long instead int. Files can be large.

private long countLetters (String args) throws IOException {
    ...
    return count;
}

Error handling

For future reference, it is almost never correct to write errors to System.out. The correct stream for errors is System.err. And logging n exception simply with the exeption message causes trouble when you're trying to debug problems, because all the important information in the exception is in the stack trace. If you have to log an exception to the console, simply write ex.printStackTrace();. In the real world you would use a loging framework but still you would log the full stack trace, never just the message.

Add a check to see if the args array in the main method contains exactly one element. If you do not provide parameters to your program now you get an ArrayIndexOutOfBoundsExceltion.

Monolithic code

You've tried to not implement all your logic in the main method, but the attempt falls a bit short because the methods in the Solution class are all private. The only way to access the counter is is still via the main method only. Instead of implementing the main method to the Solution-class you should have two classes: one that implements the letter counting and one that has the main method, which invokes the letter counter class. I.e. separate the letter counting responsibility from the command line processing responsibility. This again follows the single responsiblity principle: the Solution-class is only responsible for counting. All other responsibilities are put into separate modules.


Shouldn't the count method be called isPalindrome?
count/isPalindrome only needs to iterate over half the string: i<a.length()/2. (Make sure to test it, it might be <=)
You should use boolean instead of int for isPalindrome.
There's no need to create a temporary a variable in countPalindromeSubstrings.
count would probably make more sense than countSubs.
The whitespace seems off.
Keep your indentation consistent (I'm using 4 spaces since that's what I prefer and it's hard to tell what you prefer [I actually prefer tabs, but spaces are strongly recommended on this site]).
Stay consistent with your brace style. I personally prefer K&R/Egyptian/whatever braces (the style you use around the class), but it seems you prefer ANSI/Allman/whatever braces (the style you use everywhere else in this code), so I'll use that.

Point 2 should provide about double the speed; the others probably won't change the speed much, put should still probably be made.

Result:

public class PalindromeSubstrings
{

    public static int countPalindromeSubstrings(String s)
    {
        int count = s.length();
        for(int i = 0; i < s.length(); i++)
        {
            for(int j = i+2; j <= s.length(); j++)
            {
                countSubs += isPalindrome(s.substring(i, j));
            }
        }
        return countSubs;
    }
    public static int isPalindrome(String a)
    {
        for(int i = 0; i < a.length() / 2; i++)
        {
            if(a.charAt(i) != a.charAt(a.length() - 1 - i))
                return 0;
        }
        return 1;
    }
}


Recursive function to get unique properties

The function is a bit repetitive, as both cases (iterating over sub array vs individual elements) check if the element is undefined and if the return array includes that value. That could potentially be abstracted to a separate function or simplified.

It appears that the following line:

var index = props[level];

Could be moved outside of the forEach function, since it doesn't depend on any of the variables defined inside the callback function.

If you know that the values to be compared will most likely be primitive values like strings or integers then Array.includes() could likely be used to replace the calls to retArray.some(). While it may not reduce the computational complexity, it would allow simplifying the code to check for existing values. Note that function isn't supported by IE and other older browsers, and is case-sensitive when comparing strings and characters1


find longest common substring in space O(n)

PEP 8

You are following most of the PEP 8 style guidelines.  One that you are breaking is method names should be snake_case; your function should be named longest_common_substring.

Tricky Code

Your dp matrix is properly allocated to the size m+1 by n+1.

When you index your matrix, you access [i-1][j-1] with \$0 \le i \lt m\$ and \$0 \le j \lt n\$.  This means you never access the last allocated row m or the last allocated column n, but instead rely on accessing the -1 row and the -1 column wrapping around to reach these "unused" spaces.  This is "surprising" code at best, and "crashing" code if translated to a different programming language.

It would be better to add one to the indices used to index the dp matrix.  The simplest way would be to start the i and j enumerations at one:

    for i, ic in enumerate(s1, 1):
        for j, jc in enumerate(s2, 1):

Useless else

Expand out this ... if ... else ... statement:

            max_len = dp[i][j] if len(max_len) < len(dp[i][j]) else max_len

Initially, this produces:

            if len(max_len) < len(dp[i][j]):
                max_len = dp[i][j]
            else:
                max_len = max_len

But we can immediately see the else: clause is a no-op, and can be removed:

            if len(max_len) < len(dp[i][j]):
                max_len = dp[i][j]

Which reads much more clearly than the original.

From \$O(n m)\$ to \$O(n)\$ space

During the first iteration of outer loop, you only access rows -1 and 0.  During the second iteration of outer loop, you only access rows 0 and 1.  During the third iteration of outer loop, you only access rows 1 and 2.  Etc.  You only need two rows of the dp matrix!

More over, you create the 0 row from the -1 row, you create the 1 from the 0 row, you create the 2 row from the 1 row, and so on.

Do you really need to keep the dp matrix?  Or could you use a previous_row and a current_row?  Only storing two length n rows reduces your space to \$O(2n)\$, which is simply \$O(n)\$.


Lack of modifiability

Your at(), row() and col() return copies. This means that once you construct your mat, it's permanently const. Also, for some Ts, this makes these functions unnecessarily expensive.

Prefer instead for at() to return a reference:

T& at(size_t row, size_t col);
T const& at(size_t row, size_t col) const;

Although, typically with the standard library, the at() member functions also do range checking. So consider some other non-throwing indexing mechanism (maybe operator()) and have at() defer to that one while doing bounds checking. Note that you don't need to pass the size_ts by reference-to-const, value is fine.

Now, for the other two, prefer instead:

std::vector<std::reference_wrapper<T>>       row(size_t );
std::vector<std::reference_wrapper<const T>> row(size_t ) const;
std::vector<std::reference_wrapper<T>>       col(size_t );
std::vector<std::reference_wrapper<const T>> col(size_t ) const;

reference_wrapper<T> since you can't have vector<T&>.

Constructing those rows/cols

Since you're storing everything in row order, returning a row can just use the iterator-pair constructor of std::vector:

std::vector<std::reference_wrapper<T>> row(size_t r)
{
    auto start = m_values.begin() + r * ncol();
    return {start, start + ncol()};
}

Returning a column is much more annoying, but you definitely want to use reserve() to avoid any extra allocations:

std::vector<std::reference_wrapper<T>> col(size_t c)
{
    std::vector<std::reference_wrapper<T>> result;
    result.reserve(nrows());
    for (size_t r = 0; r < nrows(); ++r) {
        result.push_back((*this)(r, c));
    }
    return result;
}

Where I'm assuming operator() is the non-throwing version of at.


I feel I am definitely overcomplicating things

I agree with you that the code is longer than necessary. Let's take a look.

YAGNI - you ain't gonna need it

Try to avoid writing code until a caller (such as a test method for a Story) forces you to write it. Then you know you really need it.

attr_accessor :info, :date, :year, :day, :month

The first two look good. I didn't notice any compelling reason to list y,m,d, as caller could get those from date. The day might be called mday for consistency with library.

def get_info
    @info
end

def get_date
    @date
end

Ummm, didn't attr_accessor already take care of those? We're writing in ruby, not java. Take advantage of its strengths!

I commented above that get_year & get_month seem redundant. Also, it seems odd to list them without get_mday (or perhaps get_day). Better to elide them entirely.

    appointments.each do |x|

This seems to be a global reference. I can't imagine that's a good thing. Consider moving that list into a class, such as the Appointment class.

        if x.get_month == month

I suggest it would be more natural to phrase that as x.date.mon.

Your recurring Day & Month classes appear to be unimplemented stubs, so far.
You have a design decision to make. Will adding a recurring appointment create several new entries until a date "very far" in the future? Or will it add a single entry and then you deal with that at query time? There is no right answer; each offers its own trade-offs.

puts "Would you like to check against OneTime, Day or Month appointment?"
checkagainst = gets.chomp

This seems a cumbersome UX. Rather than prompting, simply loop over all three, reporting the appointment and its type whenever you find a match.


Regarding the memoization, here are two different ways to do this (for single-valued functions):

import functools

def memoize(func):
    cache = func.cache = {}

    @functools.wraps(func)
    def wrapper(n):
        if n not in cache:
            cache[n] = func(n)
        return cache[n]
    return wrapper

def memodict(f):
    """ Memoization decorator for a function taking a single argument """
    class memodict(dict):
        def __missing__(self, key):
            ret = self[key] = f(key)
            return ret
    return memodict().__getitem__

@memodict
# @memoize
def factorial(n):
    """calculates n! with a simple recursive algorithm"""
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

The latter is faster because it saves one additional lookup, but only works for single-valued functions, whereas the first can be extended to also pass along multiple arguments.

The memoize is also nice, because it keeps the documentation of the function because of functools.wraps (try help(factorial) in both cases to see the difference).

Which implementation is faster depends on how often your try block misses and succeeds.

As for timings:
Using @memoize to calculate all factorials from 1 to 100000000 takes 2.66s on my machine, while doing the same with @memodict takes 2.51s, so not a big difference.

If you want to use a decorator to time the execution time of a function, this will not work very nicely here, since if you decorate factorial, every execution of the function will be timed (because of recursion this will be very often).

You can however use something like this:

def timeit(func, *args, **kwargs):
    starting_time = clock()
    result = func(*args, **kwargs)
    ending_time = clock()
    print 'Duration: {}'.format(ending_time - starting_time)
    return result

timeit(factorial, 100)

If you do want to use this as decorator, just insert a wrapper:

def timeit(func):
    def wrapper(*args, **kwargs):
        starting_time = clock()
        result = func(*args, **kwargs)
        ending_time = clock()
        print 'Duration: {}'.format(ending_time - starting_time)
        return result
    return wrapper

@timeit
def f():
    pass


Multiple input checks, repeat if conditions are not met

for {} (for loop without condition) loops forever until break.

Put the contents of the function in a for {}.
Remove the label and replace goto reception with continue. This will cause the current iteration of the loop to end and execution will continue with another iteration, starting from the top of the block.
Use break at the end to exit the for loop


Script to create a customized, efficient adblocking hosts file

Overall, this is pretty good, but all code can be better! A few suggestions:

There aren’t any docstrings telling me what a function does, or what it returns. With a small codebase like this, it’s fairly easy for me to just read the code, but it’s a good habit to get into.
I’m nitpicking, but module imports should really be alphabetically ordered. It’s not so much of a problem for short scripts like this, but it’s really useful in large codebases.
In the get_ad_dmns() function, you create the entries list by iterating over urllib.request.urlopen(src), then immediately iterate over the list. Could you skip creating the list? i.e.

for line in list(urllib.request.urlopen(src)):
    entry = line.decode('utf-8')
    # rest of the code here

I think that might be a little simpler and more memory efficient.
Rather than using dmns as an abbreviation for domains, just use the full name. Characters are cheap, and it makes your code easier to read.
In get_cur_dmns(), rather than using open(myfile) ... close(myfile), the more idiomatic construction is:

with open('hosts'() as hosts_file:
    for entry in hosts_file:
        # do stuff with the entry

Ditto for write_hosts_file().
In your main() function, the dmns_to_add list comprehension is just a little hard to read. I’d suggest adding an extra line break for the not in cur_dmns line to make it easier to read.


There are a few things in here that make sense. The first one is to use a function, and to return a List of words from that. The next thing is to use a do-while loop instead of a while loop... actually, truth is that I would personally use an assignment in the while condition. This is relatively uncommon, so let me explain:

private static List<String> readWords(Scanner source) {
    String word = null;
    List<String> words = new ArrayList<>();
    while (!(word = source.nextLine()).isEmpty()) {
        words.add(word);
    }
    return words;
}

That's a relatively complicated loop. It puts both the readline, and the loop-check in the same place. It reads the line in to word, then also makes sure that is not empty.

While the above is relatively uncommon to see, it makes the conditional really concise, and reduces duplicate checks.

Oh, and using a forEach on the resulting list makes the print really easy....

public static void main(String[] args) {
    List<String> words = readWords(new Scanner(System.in));
    words.forEach(System.out::println);
}


Evaluating an expression with integers, +, and *, as well as -, / - revision 3

From your second revision:

  I don't consider 2 * -3 a valid equation. It should look like this:

    -2*3

What if you need to multiply two negative integers? :p Hold that thought for awhile...

Validation logic

Even if we suppose you have made a case for your existing validation logic, it should belong to computeWithAllOperations(), possibly throwing an IllegalArgumentException exception containing a message to let the caller know what went wrong. You may want to go one step further to give a brief documentation about this on the method's Javadoc.

Handling -

Your code transforms the - sign based on a preceding digit, which is a slightly odd twist in logic. Instead, I think you should be checking whether a - sign is preceded by any other mathematical operators ignoring whitespaces, which will yield the following change:

final String parts[] = input.replaceAll("\\s+", "")
                            .replaceAll("--", "+")
                            .replaceAll("((?<![/*+])-)", "+$1");

Just like your original code, we strip out whitespaces, then transform a 'minus negative' operation into an addition, and finally replace only the - signs that do not follow other mathematical operators: /, * and +. These are the only cases when we need to treat it as a subtraction rather than to signify a negative value. More can be added here to support % and/or ^.

However, this change does introduce a slight quirk, which changes expressions starting with a negative integer to "+-1*5...". To mitigate that, we can do a simple short-circuiting in computeMultAndDivision():

private static final Pattern REGEX = Pattern.compile("(?=[/*%^])|(?<=[/*%^])");

public static double computeMultAndDivision(final String part) {
    final String[] parts = REGEX.split(part);
    if (parts[0].isEmpty()) {
        return 0;
    }
    ...
}

Unit testing

Last but not least, I'll suggest doing proper unit testing for your utility method to assert its correctness. :)


Currently you are calculating the mean each time in the loop, so that's slice + sum for each of the len(heightProfile) - smoothingInterval iterations. We can remove this by calculating the mean of first smoothingInterval items and then inside of the loop simply subtract current ith item from the sum of the previous mean and add (i + smoothingInterval)th item to the sum and calculate the mean for the current window. With this approach we can do this in almost linear time.

Also as you're using Python 2 don't forget to add this line at the top of the file, otherwise normal division will result in integer division.

from __future__ import division

You can replace:

for i in range(smoothingInterval):
        heightProfile.append(heightProfile[-1])

with:

heightProfile.extend([heightProfile[-1]]*smoothingInterval)

If smoothingInterval is very huge then consider passing a generator expression to list.extend, but in most cases [heightProfile[-1]]*smoothingInterval is as fast as you can get:

last_val = heightProfile[-1]
heightProfile.extend(last_val for _ in xrange(smoothingInterval))

Full Code:

from __future__ import division

def smoothen_fast(heightProfile, travelTime):

    smoothingInterval = 30 * travelTime

    heightProfile.extend([heightProfile[-1]]*smoothingInterval)
    # Get the mean of first `smoothingInterval` items
    first_mean = sum(heightProfile[:smoothingInterval]) / smoothingInterval
    newHeightProfile = [first_mean]

    for i in xrange(len(heightProfile)-smoothingInterval-1):
        prev = heightProfile[i]  # the item to be subtracted from the sum
        new = heightProfile[i+smoothingInterval] # item to be added
        # Calculate the sum of previous items by multiplying
        # last mean with smoothingInterval
        prev_sum = newHeightProfile[-1] * smoothingInterval
        new_sum = prev_sum - prev + new
        mean = new_sum / smoothingInterval
        newHeightProfile.append(mean)

    return newHeightProfile

Timing comparisons:

>>> from random import sample
>>> heightProfile = sample(xrange(1, 10**5), 10**4)
>>> travelTime = 1000
>>> %timeit smoothen(heightProfile[:], travelTime)
1 loops, best of 3: 11.3 s per loop
>>> %timeit smoothen_fast(heightProfile[:], travelTime)
100 loops, best of 3: 2.69 ms per loop

Note that in my function call I am passing a slice of the list because we are modifying the passed list object using its .extend method, which is usually a not a good idea unless the caller expects such modifications.


Your GoBack() method could be simplified in its current pattern to

public void GoBack()
{
    NavButtonUsed = true;

    Forward.Insert(0, Back[0]);
    Back.RemoveAt(0);

    CurrentItem = ItemList[ItemList.IndexOf(Back[0])];

    NavButtonUsed = false;
}

The whole switch..case is senseless, because the only thing it is doing is triggering the OnPropertyChanged() event twice.

Inside the switch..case you are assigning a MenuItem to the CurrentItem property (triggering an OnPropertyChanged() event) and you are breaking out of the switch.

Then you are assigning ItemList[ItemList.IndexOf(Back[0])] to the CurrentItem property (triggering an OnPropertyChanged() event), so you are just overwriting the property.

So, if this method works like intended, the switch..case can be removed.


How do I write my multithreading code correctly so that it is faster than a single thread?

How did you time your program?
I ran a modified version of your program (I didn't have "mex.h" so I rewrote the parts that needed it).  When I ran your program with 1, 2, and 4 threads, I got the following results:
1 thread  = 9.38 sec
2 threads = 4.93 sec
4 threads = 2.81 sec

So it seems to be working for me.  How did you time your program?  You may have been using a function such as clock() that measures cpu time across all cores, instead of measuring wall clock time.  See this Stackoverflow question for more information on that.


Minor issues

Don't use window. inconsistently. You use it in some places and then not in others. It's just noise so the best option is that if you find yourself typing window.blah you have added 7 needless characters.
Don't use compound declarations, they can be a source of hard to spot errors, especially as you are not using strict mode.
"use strict" Never release code that does not use strict mode, and it must have used strict mode from day one.
Avoid using parseInt unless you define the radix, eg parseInt("16",10). Better way to parse a string to a number is via Number(string). Or a safer form const number = isNaN(str) ? defaultNumber : Number(str);
Your slide function at first tests for both the left and right arrow. but if the only events that will generate the call are the two arrows the second statement should be else and not include the redundant if statement.
Don't do complex expressions inside conditional statements. Generally conditional statement should be limited to the test. You had if (trans <= amt * slides.length / 2 * -1) { would be better split as two lines; const pos =amt * slides.length / 2 * -1; then if(trans <= pos) {

Bad code.

There are some that will not agree, this is an opinion on good coding practice for JavaScript.

The code in question

try {
  let trans = parseInt(
    getStyleValue(slideContainer, "transform")
      .split(",")[4]
      .trim()
  );
} catch (e) {
  console.log("`trans` being set to 0");
  trans = 0;
}

There are very few situations in javascript when you need to use a try catch block.  I feel that if you are using them you are being lazy.

There are many problems that can be overlooked when using try catch. Here are just 3 for your case.

You catch all errors, not just the one you have planned for. Code running in the catch should always check the error and only handle the one you intend to handle, all other errors should be thrown to a higher level.

As you have it you will consume all errors, errors that could cause problems later in your code but will not know about till way after it first threw an error.
You are forcing the error via the trim function TypeError: Cannot read property 'trim' of undefined this is no guarantee of the problem being caught.

I was at first puzzled as to why the trim was there as parseInt will do it for you, till it dawned on me, to throw the (incorrect) error.

So not only badly using the try catch you are not using a standard method to throw a known error. You should have used throw and thrown a new Error("blah blah"); (I put "blah blah" because I do not consider it an error at all and have no words to describe it.)
Major scope problem You will never get the correct result as trans is declared as scoped to the try block and the catch if invoked assigns to a new global scope trans.

The only value trans will have after that code has run is as an undefined undeclared variable (Very dangerous) or as the global scoped trans = 0;

It does not take much effort to avoid the try catch, and in this case the  cluster of problems it has set up in your code.

Quick rewrite.

I did not look at variable naming, function design and layout, and other issues as It was the try catch the got my attention.

Thus all I did was rewrite the try catch block as a function returning transform property or zero. If you run it here as snippet, it will throw for a very different reason though.

function getTrans(element){
  var value = getStyleValue(element, "transform");
  value = value.split(",")[4];
  if(value !== undefined){
    return Number(value);
  }
  return 0;
}
var trans = getTrans(slideContainer);


As a starting point, address the issue you have: instead of returning an int (which is not sufficient for your needs), return an object that contains everything you WANT to get as a returnvalue.

In your case, that is:

an int (the return value of the alfabeta code)
a bestmove-object

So, define a return value class like this:

class MySpecialReturnvalueClass {
    int alfabetavalue;
    Best bestmove;
}

Of course you make the fields private, with getter-methods and 1 constructor with the 2 values, or setters, but that's a lower-level detail. The point is, if you NEED something to be returned, then just go and DO return it.

From that starting point, you change your code, then step back, look at the resulting code - and then you may see in which direction you could re-arrange. Maybe it turns out that class Best can contain the alfabeta value, thus the need for the new class vanishes, and you can return Best instead.


Seems to me that the right algorithm for this job is std::replace:

std::replace(input.begin(), input.end(), '\\', '/');

The easiest way to apply to a collection of strings is probably to use std::for_each with a lambda:

std::for_each(files.begin(), files.end(),
              [](std::string &s) { std::replace(s.begin(), s.end(), '\\', '/'); });

If you can't use a lambda, you can write a tiny function object instead:

class path_dos2unix {
    void operator()(std::string &s) {
        std::replace(s.begin(), s.end(), '\\', '/');
    }
};

...and then invoke that:

std::for_each(files.begin(), files.end(), path_dos2unix());


First of all, I'd strongly encourage you to change your vote-scheme to use a value attribute of either 1 or -1, rather than a vote_type that can be 0 or 1.
A) because +1/-1 is what the votes actually mean, and B) because it makes it a heck of a lot easier to calculate the total. You just have to do:

score = some_post.votes.sum(:value)

Obviously, it'd still be a good idea to cache the score somewhere when appropriate. The database is fast, but retrieving a cache is faster.

In the following I've assumed it's set up like that, because it makes a ton more sense.

I would also recommend that you just have 1 post model; not an Answer and a Question as separate models. I'd wager the two are practically identical anyway, and it'd mean you don't have to find one or the other. You can just call Post.find(id) and done. For this especially, there's no difference between a question and an answer.

Second, you can use .find_or_initialize_by for this:

vote = post.votes.find_or_initialize_by(user: user)
if vote.value == params[:value].to_id
  # already voted
else
  # never voted (new vote record) or changing the vote
  vote.value = params[:value].to_id
  vote.save!
end

If you can skip loading the post, that'll save you some time too (however minor), since you don't actually need the post itself for anything in particular. You just need its ID for reference. Of course, it's safer to load the post, just so you know it exists (otherwise, I could preemptively up- or downvote future posts by passing a large post ID to the action). But even so, you can add a .select(:id) to the query, so you don't waste time loading all the attributes you don't need here and now - e.g. a large piece of text content or similar. And if you have eager-loading associations, nerf them. Again, you only need to post's ID.

Alternatively, you can set up a uniqueness constraint on the post_id/user_id columns, and - if your database supports it! - use a bit of raw SQL:

INSERT INTO votes (post_id, user_id, value) VALUES (?, ?, ?)
  ON DUPLICATE KEY UPDATE value = ?;

You'd want to safely insert the right values in the sql, maybe add values for created_/updated_at, etc..

The above would just insert a new row if the user hasn't voted before, but if he/she has, the constraint is triggered, and it performs an update on the existing row instead.

The major drawback is of course that you don't get any immediate feedback from the database about what happened. You can be sure that the database is correct, but you won't be able to send the 409 Conflict. And again, not all databases support this.

You can also use a uniqueness constraint to trigger a RecordNotUnique exception: Attempt to insert a new record, and if the exception is raised, rescue it and update instead. Sort a manual, Rails-side version of ON DUPLICATE KEY UPDATE.

In any case, I wouldn't worry too much about performance for this. A database is fast, and voting is relatively rare (a post is likely viewed many more times than votes are cast on it). You're probably spending 10x as much time in Rails code, as the database is spending doing all the selects, inserts and updates you throw at it.


Instead of writing a long uncommented regex, compose it out of multiple parts. This makes it easier to understand what you're trying to do.

Let's go through the spec for a start tag:

  The first character of a start tag must be a "<" (U+003C) character.
  The next few characters of a start tag must be the element's tag name.
  If there are to be any attributes in the next step, there must first be one or more space characters.
  Then, the start tag may have a number of attributes, the syntax for which is described below. Attributes must be separated from each other by one or more space characters.
  After the attributes, or after the tag name if there are no attributes, there may be one or more space characters. (Some attributes are required to be followed by a space. See the attributes section below.)
  Then, if the element is one of the void elements, or if the element is a foreign element, then there may be a single "/" (U+002F) character. This character has no effect on void elements, but on foreign elements it marks the start tag as self-closing.
  Finally, start tags must be closed by a ">" (U+003E) character.

Expressed as a regex fragment, with insignificant whitespace:

$start_tag = "(?: [<] script (?: $ws+ (?:$attribute $ws+)* $attribute)? $ws* [>] )"

Attributes themselves are rather complex. They can either be empty, unquoted, single-quoted or double-quoted.

$attribute = "(?: $attr_name
              |   $attr_name $ws* [=] $ws* (?:[^${space_characters}\"'<>`&]+|$character_reference)+
              |   $attr_name $ws* [=] $ws* [\"] (?:[^\"&]|$character_reference)* [\"]
              |   $attr_name $ws* [=] $ws* ['] (?:[^'&]|$character_reference)* [']
              )"

Now once we fill in the appropriate values for character references and the space character recognized by HTML5 and possible attribute names, we have finally correctly matched the <script> start tag.

How does your solution hold up? I am led to believe that this part is supposed to match the start tag (I added whitespace for clarity):

<script (?: [^>"]* (?:"[^"]*")? )* >

Err, no. This fails to match single-quoted strings <script title='<You Fail>'>. This will also match some strings that do not contain valid HTML at all, like <script <<<<<<<>.

What is the point of this exercise? It's absolutely possible to correctly match HTML with the PCRE (it's not possible with a regular language, which has a specific computer science meaning. Too many people confuse the theoretical concept with a similarly named practical tool which happens to be more powerful). However, if you do want to do this, you have to follow the spec. Don't fudge it, read it. (Actually, I fudged it as well, but to a lesser degree. Do as I say, not as I do).

It is absolutely possible to write readable regexes. Compose them from multiple reusable parts. Use the /x option to include insignificant whitespace. But do not ram them onto a single line. That's just obfuscation, and you wouldn't do that in other languages.


Mocking config data in JavaScript unit tests

I agree with point number 2, just passing in the config is better (i.e. dependency injection).

You could do it like this:

// Definition of summarize:
export const summarize(config, optionName, optionValues){
    // stuff
}

// In some other file:
const summarizeWithConfig = require('./summarize');
const config = require('./config');

// Create a new function which has it's first argument bound to the config
let summarize = summarizeWithConfig.bind(null, config);

Now summarize can be used like before, and in your tests you can simply test the unbound function.

This kind of pattern should be used in all your code, and will make it a lot easier to test.
However, binding up functions like this becomes a little tedious (with the extra name "summarizeWithConfig", the ugly bind syntax, etc), so I would really recommend
using classes instead, and have the constructors of those classes as injection points.


cymysql.connect is a context manager and so you should use it in a with statement.
conn.cursor isn't a context manager. Which is very fishy, even more so that the original version of cymysql, pymysql, is.
Seperate SQL interactions from UI interactions. This is as multiple parts of the UI may need to use the same SQL interactions, however since they're mangled, it'll lead to code duplication or errors in your UI.
You don't need to do email = '', if you want to tell people it's a string then you can do email: str. A better thing to do however is use typing and make your code fully typed.
You may want to verify that the email is a valid email address. It doesn't look like your SQL does that, but I don't know enough about it.

import cymysql
from getpass import getpass

def get_user_info():
    while True:
        email = input("Input your Email address (max. 64 chars.): ")
        password = getpass("Input a password (max. 64 chars.): ")
        if len(email) < 64 and len(password) < 64:
            return email, password

def register(cur, email, password):
    cur.execute("INSERT INTO `users` (`Email`, `Password`) VALUES (%s, %s)", (email, password))

def login(cur, email, password):
    cur.execute("SELECT * FROM `users` WHERE `Email`=%s AND `Password`=%s LIMIT 1", (email, password))
    return bool(cur.fetchall())

def check_account(cur, email):
    cur.execute("SELECT * FROM `users` WHERE `Email`=%s LIMIT 1", (email,))
    return bool(cur.fetchone())

def main():
    conn = cymysql.connect(
        host='127.0.0.1',
        user='root',
        passwd='',
        db='david'
    )
    with conn:
        cur = conn.cursor()
        email, password = get_user_info()
        check = check_account(cur, email)
        if check:
            loggedin = login(cur, email, password)
            if loggedin:
                print("You've succesfully logged-in!")
            else:
                print("You failed logging-in!")
        else:
            register(cur, email, password)
            print("You've succesfully registered!")
        cur.close()

if __name__ == '__main__':
    main()


Is there a more efficient way to create a dictionary in win32 / c++.

Yes :-)

Let's look at the code:

Reading the file

// Read a file line by line.
while (std::getline(stream, temp)) {

    // Build one long........ string in memory.
    fileContent += temp;
    fileContent.push_back(L'\n');
}

// Then you split the long...... line you just built
// back into a vector of lines (using the '\n' you just inserted)
// to mark the line boundries.
std::vector<wstring> lines = split(fileContent, L'\n');

Issues

So you are basically doing the same work twice.
You are building a string in the most inefficient way possible.
Because you did not reserve space you are reallocating that string again and again and again. Each reallocation requires the whole string to be copied.

Why not read the lines directly into the vector?

 std::vector<wstring> lines;
 std::wstring line;

 while(std::getline(stream, line)) {
     lines.push_back(line);
 }

We can even do better than that with a tiny bit of work.

 // Define a class that represents a line.
 // Then define the input operator so it knows how to read itself.
 // Then define a conversion operator so it can be converted into a string.

 class Line
 {
     std::wstring   data;
     friend std::istream& operator>>(std::istream& str, Line& value)
     {
         return std::getline(str, value.data);
     }
     operator std::wstring&() const
     {
         return data;
     }
};
using LineStreamIter = std::istream_iterator<Line>;
// now you can declare your vector and load it in a single line.
std::vector<std::wstring>  lines(LineStreamIter(source), LineStreamIter());

Moving on to loading the map:

for (std::wstring line : lines) {
    std::vector<wstring> word = split(line, L'\t');
    dict.insert(dict.end(), make_pair(word[0], word[1]));
}

So basically you are saving your map as two strings separated by the first tab onto a single line. I assume there are no '\n' characters in the meaning, otherwise your encoding is going to break.

But again this is ineffecient as you build a vector in place then use that to build the dictionary. Why not just build the dictionary directly from the file.

std::map<std::wstring, std::wstring> dict;

std::wstring word;
std::wstring meaning;

while(std::getline(source, word, '\t') && std::getline(source, meaning))
{
    dict.emplace_back(std::piecewise_construct, word, meaning);
}

Note: std::getline() allows you specify a third argument that defines the line terminator (by default this is '\n'). By setting this to tab '\t' you can read up-to (but not including) the tab and extract the word first then extract the meaning separately.

I would take this a step further and define a dictionary class with a specific interface then use std::map internally. This has several advantages.

You can replace std::map with std::vector later as suggested by @ilmale
You can write the load/save functions in a self contained way.

Here is an outline:

class Dict
{
    class DictFileElement
    {
        std::pair<std::wstring, std::wstring>   value;
        frined std::istream& operator>>(std::istream& s, DictFileElement& value);
        frined std::ostream& operator<<(std::ostream& s, DictFileElement const& value);
    };

    std::map<std::wstring, std::wstring>  data;
    public:
        Dict(std::string fileName);
        std::wstring getMeaning(std::wstring const& word);
};
// I leave the implementation to you .
// Should be easy given all the code I wrote above.


3-way multiplexer built on 2-way multiplexers in Verilog

I don't see any problems with the code functionally, and the layout follows good practices for the most part.  That style guide seems mostly reasonable, and it is a good idea to use a set of guidelines.
In my many years of Verilog coding, I have most frequently seen parameters use all capital letters (this departs from the guide you posted):
Use WIDTH instead of Width.
The guide recommends 2-space indents in some places and 4 in others; I recommend 4-space indent everywhere because I think it is much easier to read.
I don't think  your for loop follows the guide.  I would lay it out like this:
for (int i = 0; i < 3; i++) begin
    control = i;
    #1
    $display("When Control = %d, Y = %c", control, y);
end

I would also add a space between reg and [:
  reg [1:0] control;
  reg [7:0] a;
  reg [7:0] b;
  reg [7:0] c;
  reg [7:0] y;

I usually find it helpful for debugging to also display the time (copied from my Answer to your previous Verilog Question):
$display($time, " When Control = %d, Y = %c", control, y);

The for loop exercises 3 of the 4 possible values of Control.  It is a good practice to simulate all possibilities (Control = 3).  Perhaps make it an extra-credit question to explain what happens and why.

I assume one of the goals of this assignment is to demonstrate module hierarchy using an extremely simple design.  Otherwise, your design modules normally would be replaced with a single assign statement.


How to design interface of deep-copy behaving pointer containers?

I think you are going about it the wrong way.

Containers already perform copy on copy construction/assignment because they are designed for value objects not pointers. What you really want is a wrapper object for pointers that performs a deep copy when that object is copied.

This has the added advantage of working with all containers.

If you define the move operators then it also works well with re-size operations as the move semantics will be applied to the wrapper when the the container is re-sized.

The other advantage here is you can make the wrapper behave like the underlying type. So you get easy access to all the algorithms.

template<typename T>
class Deep
{
   T*     value;
   public:
       Deep():                      value(NULL)         {}
       // Take ownership in this case.
       Deep(T const* value):        value(value)        {}
       Deep(T const& value):        value(new T(value)) {}
       ~Deep()                      {delete value;}
       Deep(Deep&& move)            {std::swap(value, move.value);}
       Deep(Deep const& copy)       {T* tmp = new T(*(copy.value));swap(tmp,value);delete tmp;}
       // Note this does do a deep copy via copy and swap
       Deep& operator=(Deep copy)   {std::swap(value, copy.value);return *this;}
       Deep& operator=(Deep&& move) {std::swap(value, move.value);return *this;}

       // Note: undefined behavior if used when value is NULL.
       //       You may want to add logic here depending on use case.
       operator T&()                {return *value;}
       operator T const&() const    {return *value;}

       T* release()                 {T* tmp = value;value = NULL;return tmp;}
};
int main()
{
    std::vector<Deep<int>>   deep(5,7);
}


AJAX-based PHP server-side form validation

What I would do:

Use an autoloading function (basic example, PHP manual) to get rid of require_once
$this->$username won't work as you expect, replace it with $this->Username
Avoid magic numbers like if (strlen($ProposedUsername) => 4), instead define constants (or class constants)

But basically, it seems that you have quite well understood the basic principles of OOP.

As a matter of preference, I would:

Use Allman coding style
Use // instead of /* */ for one line comments
throw a UsernameAlreadyTakenException (create it by simply extending Exception) and do nothing if username is available, instead of simply echoing the checking results.
EDIT: I like exceptions for such "checking" functions, because IMO it's a good way to refactor tons of "if" + error handling code. Calls look like:

// clean readable checkings, and if something goes wrong, you are informed :-)
// however and obviously, in production environments, all exceptions should be
// caught at high level ==> logged + a user-friendly message displayed.
$user->checkUsernameExists();
$user->checkEmailExists();

// or in a few cases
try {
  $user->checkUsernameExists();
} catch (UsernameAlreadyExistsException $e) {
  //...
}


A recursive algorithm to find the number of distinct quantities of money from a pile of coins

Instead of calculating each combination recursively, you can build up the list one coinage type at a time.  This would involve fewer iterations in the case that any combinations form the same total, and more importantly wouldn't require adding up each combination separately.  For example:

std::set<int> sums;
for(int c = 0; c < coins.size(); ++c)
{
    // Include zero on the initial list, but not subsequent ones
    if(sums.empty())
    {
        for(int q = 0; q <= quantity[c]; ++q)
        {
            sums.insert(q * coins[c]);
        }
    }
    else
    {
        std::vector<int> current(sums.begin(), sums.end());
        for(int q = 1; q <= quantity[c]; ++q)
        {
            for(int sum : current)
            {
                sums.insert(sum + q * coins[c]);
            }
        }
    }
}

Using a vector instead of a set to accumulate sums (removing duplicates at the end) might be faster, and would eliminate the need for a temporary copy (current).  However, it wouldn't eliminate the redundant loops based off the same total, so some measurements would be needed to see which is better.

std::vector<int> sums;
for(int c = 0; c < coins.size(); ++c)
{
    // Include zero on the initial list, but not subsequent ones
    if(sums.empty())
    {
        for(int q = 0; q <= quantity[c]; ++q)
        {
            sums.push_back(q * coins[c]);
        }
    }
    else
    {
        int oldSize = sums.size();
        for(int q = 1; q <= quantity[c]; ++q)
        {
            for(int i = 0; i < oldSize; ++i)
            {
                sums.push_back(sums[i] + q * coins[c]);
            }
        }
    }
}

std::sort(sums.begin(), sums.end());
sums.erase(std::unique(sums.begin(), sums.end()), sums.end());


Adding few improvements to @Steve's answer:

It is always good to check for spaces(blanks):     if(!string.IsNullOrWhiteSpace(filterCod))
Wouldn't be nicer to have queries.Any() instead of queries.Count >= 1 ?