What is the motivation behind hashing and reversing the string multiple times? If you have a secure hash function, then hashing a single time (combined with a sufficient amount of salt data) is perfectly sufficient. If you have an insecure hash function, then hashing multiple times is extraordinarily unlikely to be enough to make it secure.

The only slight security issue I can see in the code you've posted is the possibility that the random number generator will not be properly seeded, or is not a sufficiently secure random number generator. This is extremely unlikely to be a problem, however, since the purpose of salting is not typically undermined by having an insecure random number generator. Provided hashes get salt values that are reasonably well-distributed it won't help an attacker. If your attacker can interfere with the timing of password creation somehow, to ensure that the majority of users ended up with exactly the same salt, then this would render a dictionary attack easier at a later date, provided they could obtain the hashed passwords. In reality, any user who has this level of control over your system has probably got lots of other ways to obtain the passwords.

Which is of course the real point. Don't spend a lot of time trying to make your hash function cleverer or more secure, just make sure that it does its job. Spend the rest of your time looking over the rest of the system for any chinks in the armour. The system is only as strong as the weakest link in the chain, and that's unlikely to be the hash function. For example, maybe you store the unhashed function in the PHP session, and your server is misconfigured so that the session data is readable by other users on the same box. Maybe you forgot to configure HTTPS so the site is vulnerable to packet sniffers. Maybe your box got rooted and the attacker changed your PHP, so even though the code in your repository is flawless, all your users are compromised.


Area of the triangle generated by the hands of a clock

This is an addendum to Oscar's answer. Just doing some math.

Let t = 0 be 12 o'clock, when all hands are coinciding and the area is 0. We need to calculate the area as a function of t. Let s, m, h be the angles of second, minute and hour with respect to the trigonometric reference. Then
$$s=\frac{\pi}2-\frac{\pi}{30}t\\ m=\frac{\pi}2-\frac{\pi}{1800}t\\ h=\frac{\pi}2-\frac{\pi}{21600}t$$
and let S, M, H be the lengths of clock's hands. Then the area is
$$A=\frac12\left|SM\sin\alpha+MH\sin\beta+HS\sin\gamma\right|$$
where
$$\alpha=s-m,\;\beta=m-h,\;\gamma=h-s$$
Therefore we have
$$\alpha=-\frac{59}{60}\cdot\frac{\pi}{30}t\\ \beta=-\frac{11}{720}\cdot\frac{\pi}{30}t\\ \gamma=\frac{719}{720}\cdot\frac{\pi}{30}t$$
where t is a positive integer. As you see, doing some boring math can sometimes reduce the amount of codes needed for a job.

P.S. and here is a plot of A vs. t. It is periodic indeed.


Multiple file creation with sorted input

Formatting

Your if statement block should use braces { ... } to better identify the scope of each clause as a good practice. Also, you can consider renaming setgpa(double)/getgpa() to setGpa(double)/getGpa() respectively.

try-with-resources

Since Java 7, you should be using try-with-resouces for safe and efficient handling of your I/O resources:

private static final Path HONORS = Paths.get("Honors.txt");
private static final Path GOOD_STANDING = Paths.get("GoodStanding.txt");
private static final Path PROBATION = Paths.get("Probation.txt");
private static final String DELIMITER = ",";
private static final int QUIT = 999;

public static void main(String[] args) {
    try (PrintWriter honorsWriter = new PrintWriter(HONORS.toFile());
         PrintWriter goodStandingWriter = new PrintWriter(GOOD_STANDING.toFile());
         PrintWriter probationWriter = new PrintWriter(PROBATION.toFile());
         Scanner scanner = new Scanner(System.in)
    ) {
        // ...
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

I have taken the liberty to declare your file paths as private static final constants outside of the main() method, again as a good practice. Also, I have opted to use a PrintWriter, which is buffered, so that I can make use of its println(String) method.

Determining the student's details and ranking

You are creating only one Student instance, and then repopulating its details for each input. Ideally, you should be creating a new one each time, so that they can all go into a Collection in the future for further processing. Right now, you probably can settle for temporary variables in order to print them afterwards.

Assuming we are sticking with your approach, you can hide the Student creation within its own method, e.g. getStudent(Scanner). The idea is that given a Scanner instance, student details can be retrieved and a Student instance is returned:

Student student = getStudent(scanner);

Joining strings with delimiter

Since Java 8, you can use String.join(CharSequence, CharSequence) to easily join strings:

private static String toFileOutput(Student student) {
    return String.join(DELIMITER,
            Integer.toString(student.getID()),
            student.getFirstName(),
            student.getLastName(),
            student.getGpa());
}

Determining the file output

Instead of reassigning the writers to a writer, you should be using them directly:

Student student = getStudent(scanner);
while (student.getID() != QUIT) {
    String output = toFileOutput(student);
    if (student.isHonors()) {
        honorsWriter.println(output);
    } else if (student.isGoodStanding()) {
        goodStandingWriter.println(output);
    } else if (student.isProbation()) {
        probationWriter.println(output);
    }
    student = getStudent(scanner);
}

for vs while

Another way of looping through each Student input is to use a for loop, this approach is sometimes (often? always?) recommended to reduce the scope of the student instance:

for (Student student = getStudent(scanner);
     student.getID() != QUIT;
     student = getStudent(scanner)) {
    // ...
}

Shortening the process

Alternatively, you can consider Files.write(Path, Iterable, OpenOption) to expressively write (pun unintended) a line of output, the only thing to be aware of is that you will need to turn your single String into an Iterable, e.g. using Collections.singleton(T).

Putting it altogether:

public static void main() {
    try (Scanner scanner = new Scanner(System.in)) {
        for (Student student = getStudent(scanner);
             student.getID() != QUIT;
             student = getStudent(scanner)) {
            Set<String> output = Collections.singleton(toFileOutput(student));
            if (student.isHonors()) {
                Files.write(HONORS, output, APPEND);
            } else if (student.isGoodStanding()) {
                Files.write(GOOD_STANDING, output, APPEND);
            } else if (student.isProbation()) {
                Files.write(PROBATION, output, APPEND);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}


Since the RewriteBase directive applies to the entire .htaccess file, it should not be buried between two RewriteRules.

You don't need capturing parentheses for the RewriteCond.

Options +FollowSymLinks

RewriteEngine on
RewriteBase /

RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule .* http://www.example.com/$0 [R=301,L]

RewriteRule ^locations\.php$ compare-biomass.php [R=301]


Creating multiple threads to process items in a listview

We actually don't use the BackgroundWorker anymore. The same thing can be done much easier with the newer Task Parallel Library (TPL).

Briefly you need to (ok, you should) put the download logic into a new class that could have a Download method. It needs to be marked with async and return a Task to be awaitable. But you need a result so you can use it with a generic parameter Task<byte[]>. (Sidenote: remember to dispose the WebClient). For the new download to work you need to use the awaitable upload API.

If you want to be able to report progress or just be notified when a task is finished you can use the IProgress<T> interface as one of the parameters. You call it inside the method to report its progress. Here just an arbitrary task-id.

class Downloader
{
    public async Task<byte[]> Download(int taskId, NameValueCollection data, IProgress<int> progress)
    {
        using (var client = new WebClient())
        {
            var response = await client.UploadValuesTaskAsync("http://google.com", data);
            progress.Report(taskId);
            return response;
        }
    }
}

Your form code could then be reduced to a simple event handler that is also marked with async. It prepares a collection of download-tasks and then awaits them all or processes each one when it's finished (your choice).

When a task is finished, the form receives a progress report (that can be seen here as a notification) via the ProgressChanged event of an instance of the Progress<T> class.

class MyForm : Form
{
    private readonly Downloader _downloader = new Downloader();

    private async void button2_Click(object sender, EventArgs e)
    {
        // Initialize progress handling.
        var progress = new Progress<int>();
        progress.ProgressChanged += (downloader, taskId) =>
        {
            // update label...
        };

        var downloadCount = 2; //... get the count
        var downloadTasks =
            Enumerable
            .Range(0, downloadCount)
            // Create task specific arguments.
            .Select((x, i) => _downloader.Download(i, new NameValueCollection(), progress));

        var results = await Task.WhenAll(downloadTasks);
    }
}

You may also use a different pattern if you want to process each task result right away by doing it as soon as any task is finished with WhenAny and a loop:

for (int i = 0; i < downloadCount; i++)
{
    var firstTask = await Task.WhenAny(downloadTasks);
    var result = await firstTask;
    // process task result...
}


First a style nitpick: Python has an official style-guide, PEP8, which recommends using lower_case_with_underscores for variable and function names instead of camelCase.

Second, the comments you have above your functions should become docstrings.
These appear for example when calling help(your_function) in an interactive session. Just Have a string as the first line below the function header like so:

def f(a, b):
    """Returns the sum of `a` and `b`"""
    return a + b

It is recommended to always use triple double-quotes (i.e. """).

Now I am going to focus on the distance calculation.

First, you can greatly simplify your getNeighbors function using list comprehensions:

def getNeighbors(trainingSetX, trainingSetY, testInstance, k):
    distances = sorted((distance(testInstance, x), x, y)
                       for x, y in zip(trainingSetX, trainingSetY)
    return [(d[1], d[2]) for d in distances[:k]]

Here I used the fact that tuples already sort naturally, by first comparing the first index then (if they are equal) the second and so on. So I put the distance as the first index of the tuple and you don't need the key function any longer. sorted can take a generator expression and sort it directly. We can also iterate over multiple iterables at the same time using zip.

Since your variables are all numpy arrays, you could also do it more vectorized. For this I would first re-define the distance function to use numpy functions:

def distance(x, y):
    return np.sqrt(((x - y)**2).sum())

And then put the distances into a numpy array as well. Only returning the second and third column becomes then easier with array slicing.

def getNeighbors(trainingSetX, trainingSetY, testInstance, k):
    distances = np.array([(distance(testInstance, x), x, y)
                          for x, y in zip(trainingSetX, trainingSetY])
    distances.sort()
    return distances[:k, 1:]

This can probably be modified even further by trying to make the distance call vectorized as well.

Your function classVotes can be simplified using the collections.Counter class which implements exactly what you do her:

def getResponse(neighbors):
    classVotes = Counter(int(neighbor[-1]) for neighbor in neighbors)
    return max(classVotes.iteritems(), key=itemgetter(1))[0]

Your function getAccuracy can be slightly simplified using a generator expression and sum:

def getAccuracy(testSetY, predictions):
    correct = sum(y == p for y, p in zip(testSetY, predictions))
    return correct * 100.0 / len(predictions)

And lastly, in your start function, you can directly iterate over the elements of testSetX, make it a generator expression and use the fact that print can take multiple arguments:

def start():
    trainingSetX = X[:2000]
    trainingSetY = Y[:2000]
    testSetX = X[2000:]
    testSetY = Y[2000:]

    # generate predictions
    k = 4
    predictions = (getResponse(getNeighbors(trainingSetX, trainingSetY, x, k)]
                   for x in testSetX)
    accuracy = getAccuracy(testSetY, predictions)
    print('Accuracy:', accuracy)


IMHO separating computation and printing is the most important improvement to do.

A code which can't do the computation separately is just a throw-away junk; you can't ever use it for anything else.
A code which can't do the printing separately is useless for the same reason. You can't use it for anything else, not even for the decryption.

In s simple snippet it doesn't matter much, but learning it later with complicated algorithms is much harder.

Note an asymmetry: Your SecretMessage stores the plaintext, but not the ciphertext. Ask yourself, if it needs to store anything.

Think about naming. Is the SecretMessage really a message? Or is it maybe an Encryptor? The way you implemented it, your naming isn't bad, but when you change it, you should reconsider it.

Does encrypt really encrypt its argument? Or would you expect it to do something else? Maybe being more verbose with encryptWithKey(char key) makes more sense.

Efficiency is usually overrated. You must think about using efficient algorithms and data structures for the job, but you can ignore nearly everything else. Anyway, before you start optimizing, make sure you optimize the real bottleneck, i.e., profile you code.

Anyway, using System.out.print for single characters may slow you down as it's synchronized and it flushes the output.

First building the result (using StringBuilder) would be faster. Moreover, it's a step in the right direction (Separation of concerns).


Is there a more concise and/or readable way to write the following method?

There are at least two answers.
The short one:

public void add(int[] values, Func<int, int> transform = null)
{
    foreach (int v in values)
        add( (transform != null) ? transform(v) : v);
}

The efficient one:

public void add(int[] values, Func<int, int> transform = null)
{
    if( transform != null)
      foreach (int v in values)
        add( transform(v));
    else
      foreach (int v in values)
        add( v);
}

Not nice, but you wanted a short version.

Maybe someone has a LINQ at hand which does this even better.


AppEngine get/post on webapp2.RequestHandler

Yes, you can easily alias one method to another:

class Save(webapp2.RequestHandler):

    def post(self):
        #...

    get = post

But although I don't know anything about your application, you shouldn't alias GET to POST like this: the two methods have different semantics. GET is a safe method — it must only retrieve data and not update or store it — while POST is an unsafe method — it requests the server to store or update the data in the request. See "Safe methods" in Wikipedia.


The correct way to calculate MIPs of a function on a microcontroller

As you may know, MIPS means Mega Instructions Per Second.
So the formula would be

CHIP_MIPS = number_of_mega_instructions / number_of_seconds.

If your chip is running at 25 MHz, it means that it performs 25 mega instructions per seconds, so knowing the number of seconds and the CHIP_MIPS, the formula would be

number_of_seconds * CHIP_MIPS = number_of_mega_instructions

So fun needs 5 Mega Intructions


MergeSort implementation with java.util.List passed as argument, not returned

You could do

list.clear();
merge(right, left, list);

with

private static <E extends Comparable<E>> List<E> merge(List<E> source1, List<E> source2, List<E> destination) {
    // ...
    destination.add(element);
    // ...
}

The merge() function should be declared static to indicate that it doesn't use any instance variables.


Here are a few remarks. I'm not perfect or write perfect code but I hope these tips will help write better code:

Naming consistency:

It would be easier to understand if the names of your two methods had opposing names. For example: SerializeToFile and DeserializeFromFile. It's obvious that deserialization will return an object, omit that in the name.

Also, if you're using the same type/kind of parameter or variable in one method, give it the same name in the other method.

Truly generic:

You should make your serialize method generic too:

public static void SerializeToFile<T>(T obj, string fullPath)

In the point Type constraint a bit further you'll see why.

Scoping variables:

You should define variables as close to their usage as possible. In your case you can instantiate the XmlSerializer class inside the using statement since you don't need it outside the statement. Example:

using (var stream = new FileStream(fullPath, FileMode.Open))
{
    var xmlSerializer = new XmlSerializer(typeof(T));
}

Checking for the file:

In both methods an exception can be thrown in certain situations. In the serialize method, if the path doesn't exist you'll get a DirectoryNotFoundException and in the deserialize method you'll get a FileNotFoundException if the file doesn't exist. This can easily be solved:

//Check for directory in serialize:
var directoryPath = Path.GetDirectory(fileFullPath);
var directoryExists = Directory.Exists(directoryPath);

//Check for file in deserialize
var fileExists = File.Exists(fileFullPath);

You should decide whether you want positive or negative evaluation on this. For example, only perform the method if the checks are positive or throw an argument exception if the checks are negative. That is up to you.

Also, like Heslacher stated: what if the file already exists? As for now, the content of the file will be overwritten by the new content.

using statement:

Following:

using (var fs = new FileStream(fileFullPath, FileMode.Create))
{
    var writer = new XmlTextWriter(fs, Encoding.Unicode);
    xmlSerializer.Serialize(writer, myObject);
    writer.Close();
}

can be replaced by:

using (var stream = new FileStream(fullPath, FileMode.Create))
using (var writer = new XmlTextWriter(stream, Encoding.Unicode))
{
    var xmlSerializer = new XmlSerializer(obj.GetType());
    xmlSerializer.Serialize(writer, obj);
}

Type constraint:

Remember my point for making the serialize method generic too? For now, you don't validate the incoming and outgoing object. What if I pass an instance of a class that has no public parameterless constructor? During runtime I'll get an InvalidOperationException with a message like:

  ... cannot be serialized because it does not have a parameterless constructor.

The solution is to place type constraints on your methods. Definition from MSDN:

  When you define a generic class, you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class, these restrictions are called constraints.

You should use the class and new() type constraints. Here's their definition:

class: the type argument must be a reference type; this applies also to any class, interface, delegate, or array type.
new(): the type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.

Now you'll get a compile-time exception when trying to serialize an instance of a clas without a public parameterless constructor. You can read more on this here: Constraints on Type Parameters (C# Programming Guide).

public static void SerializeToFile<T>(T obj, string fullPath) where T : class, new()
{
    //method body
}

public static T DeserializeFromFile<T>(string fullPath) where T : class, new()
{
    //method body
}

Final code:

With all this applied, your code might look like following:

public class SerializationService
{
    public static void SerializeToFile<T>(T obj, string fullPath) where T : class, new()
    {
        if(Directory.Exists(Path.GetDirectoryName(fullPath)))
        {
            using (var stream = new FileStream(fullPath, FileMode.Create))
            using (var writer = new XmlTextWriter(stream, Encoding.Unicode))
            {
                var xmlSerializer = new XmlSerializer(obj.GetType());
                xmlSerializer.Serialize(writer, obj);
            }
        }
    }

    public static T DeserializeFromFile<T>(string fullPath) where T : class, new()
    {
        if(File.Exists(fullPath))
        {
            using (var stream = new FileStream(fullPath, FileMode.Open))
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                return (T) xmlSerializer.Deserialize(stream);
            }
        }
        return default(T);
    }
}


Do I have to replace the fixed sized array of object of class Dict with any other technique?

I suggest making the size a constant, like this:

public static int ALPHABET_SIZE = 26:

And then you may use:

obj = new Dict[ALPHABET_SIZE];

As you can see, the comment now becomes redundant and we can remove it, and it is always a good thing, as comments may become obsolete or wrong.

The same applies to:

int Linkno=((int)(str.charAt(it)))-97; //97 is the ascii value of 'a'.

Make a constant:

LOWER_A_ASCII_VAL = 97;

Get rid of repetition

Looking at:

    root.insertWord(root,"trasaction",0);
    root.insertWord(root,"transformation",0);
    root.insertWord(root,"transmission",0);
    root.insertWord(root,"trance",0);
    root.insertWord(root,"trap",0);

What if you want to add 10 more words? The code will become very long and repetitive, instead use a foreach loop:

for (String word : {"transaction", "transformation", ...} ) {
    root.insertWord(root, word, 0);
}

Miscellanous

Wrong indent hurts readibility, fix it in:

    if(it<str.length())
    {
    int Linkno=((int)(str.charAt(it)))-97; //97 is the ascii value of 'a'.
    if(Node.obj[Linkno]==null)
    {
        Node.obj[Linkno]=new Dict();
    }
    insertWord(Node.obj[Linkno],str,it+1);
    }

Always use braces to prevent bugs in :

        if(Node.obj[i].isWord==true) {
            System.out.println(str+((char)(i+97)));
        }

Avoid general names like obj and think about a more precise name.


Suggestions for a Profiler class in Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import functools
import math
import time

class Timer(object):
    def __init__(self):
        self.__values = []

You are using prefix __ to denote private attributess. This is perfectly valid and has special support within python. Having said that, I'm not a fan of it. Its designed for use when you are subclassing objects to prevent accidents. I think that if you are not designing your object to be subclassed, you should stick with single underscores.

    def start(self):
        self.__start = time.time()

        return self

Some frameworks do make use of this return self paradigm. However, its kinda unusual and will lead to code being confusing if you are not used to it. As it is you don't seem to be making use of this. I'd just get rid of return self. This doesn't seem to be the type of object which works well with the pattern anyways.

    def stop(self):
        self.__values.append(int(round((time.time() - self.__start) * 1000)))

The operations being performed here are just long enough to come across as awkward, I'd write it as

seconds_elapsed = time.time() - self.__start
milliseconds_elapsed = int(round(seconds_elapsed*1000))
self.__values.append(milliseconds_elapsed)

As another note, don't be afraid of floats. You'd probably be better off storing a list of floating point seconds rather then integer milliseconds. The code would be clearer and there is probably no noticeable difference in efficiency.

        self.__start = None

        return self

    @property
    def average(self):
        return sum(self.__values) / len(self.__values)

    @property
    def deviation(self):
        if self.average:
            return math.sqrt(sum((v - self.average) ** 2 for v in self.__values) / self.runs)

        return 0

I recommend using the numpy library which has functions to calculate average/stdev/pretty much everything. The math done in numpy will be much more efficient then your python versions.

    @property
    def elapsed(self):
        return sum(self.__values)

    @property
    def runs(self):
        return len(self.__values)

I don't like the name Timer for the class because it spends most of its effort keeping track of values not measuring time.

class Profiler(object):
    __timers = {}

    @staticmethod
    def info(timer_id):
        if not Profiler.__timers.has_key(timer_id):
            raise Exception('Timer not started')

        return Profiler.__timers[timer_id]

If you are going to store state on your class object, use classmethod like so:

    @classmethod
    def info(cls, timer_id):
        if not cls.__timers.has_key(timer_id):
            raise Exception('Timer not started')

        return cls.__timers[timer_id]

There also does not appear to be a good reason to be storing this state statically. I suggest that you really should implement this as a normal object. There are few cases where storing state on a static object is justified.

    def info(self, timer_id):
        if not self.__timers.has_key(timer_id):
            raise Exception('Timer not started')

        return self.__timers[timer_id]

Additionally, don't be afraid of exceptions. In python you shouldn't (in general) try to detect whether an exception will be thrown before attempting an operation. Just perform the operation and catch the exception. The above version ends up locating an element in a dictionary twice, which is just a waste. The above function should be implemented as:

    def info(self, timer_id):
        try:
            return self.__timers[timer_id]
        except KeyError:
            raise Exception('Timer not started')

Similar comments apply to your other functions.

    @staticmethod
    def profile(f):
        @functools.wraps(f)
        def wrap(self=None, *args, **kwargs):

You assume that your first parameter will be self (if it exists). Depending on how this is called, self may actually already be bundled into f as a method object. Also, if you are calling a function which is not a method something else will come in there. You shouldn't capture self this way, just let all parameters go into *args

            method = self.__class__.__name__ + '.' + f.func_name if self \
                     else f.func_name

As mentioned, you shouldn't capture self the way you do. The correct place to find the class is f.im_class. Be careful! That attribute won't be there on non-methods.

            Profiler.start(method)
            r = f(self, *args, **kwargs) if self else f(*args, **kwargs)

I recomment calling r, return_value for better clarity. Also by eliminating self, you'll make this bit of code cleaner
                Profiler.stop(method)

This is actually wrong in the case of recursion as another commenter has pointed out. Also, since Timer is really concerned with keeping track of times, perhaps calculating time spent would be better here.

            return r

        return wrap

Your API is counterintuitive on this point. I'd except a function called profile to profile a function, not return a new function which I then have to call in order to profile it. For what the function does it should be called profiled.

    @staticmethod
    def reset(timer_id):
        Profiler.__timers[timer_id] = Timer()

    @staticmethod
    def start(timer_id):
        if not Profiler.__timers.has_key(timer_id):
            Profiler.reset(timer_id)

        Profiler.__timers[timer_id].start()

    @staticmethod
    def stop(timer_id):
        if not Profiler.__timers.has_key(timer_id):
            raise Exception('Timer not started')

        Profiler.__timers[timer_id].stop()

if __name__ == '__main__':
    class Test(object):
        def isPrime(self, n):
            if n < 2 or (n % 2) == 0:
                return n == 2

            f = 3

            while (f * f) <= n:
                if (n % f) == 0:
                    return False

                f += 2

            return True

        @Profiler.profile
        def run(self):
            return filter(self.isPrime, range(1, 1000001))

    test = Test()

    for x in range(5):
        test.run()

    p = Profiler.info('Test.run')
    print 'runs = %d' % p.runs
    print 'elapsed = %d ms' % p.elapsed
    print 'average = %d ms' % p.average
    print 'deviation = %d ms' % p.deviation

I think a better API to implement would be one that works like this:

    class Test(object):
        def isPrime(self, n):
            if n < 2 or (n % 2) == 0:
                return n == 2

            f = 3

            while (f * f) <= n:
                if (n % f) == 0:
                    return False

                f += 2

            return True

        @profiled
        def run(self):
            return filter(self.isPrime, range(1, 1000001))

    test = Test()

    for x in range(5):
        test.run()

    stats = Test.run.stats
    print 'runs = %d' % stats.runs
    print 'elapsed = %d ms' % stats.elapsed
    print 'average = %d ms' % stats.average
    print 'deviation = %d ms' % stats.deviation

Essentially, store your Timer object on the function object itself. That will simplify your code considerably because you are using python's name resolution rather then your own.

As a final note, there are plenty of good profiling tools out there for python. You are probably best off using one one of those.


Select row based on another table row index

I'll start with your selectors:

First off, you should never have a selector with anything left of an id - searches for ids are about the fastest you can get on the DOM.

Second, if you don't want to wrap other tables in your tables (I assume you don't), get rid of the immediate child stuff (P > C). Searching by tag is also pretty fast, so we use the id-element as our base for that.

$('#baseTable tbody td').click(function() {
    var rowIndex = $(this).parent().index();
    $('#log').html(rowIndex);

    var myData= [];

    $($('#dataTable tbody tr')[rowIndex]).map(function() {
        return $(this.cells).get();
    }).each(function() {
        var headerVal = $(this).closest('table').find('thead th')
            .eq($(this).index()).html();
        myData.push([headerVal,parseFloat($(this).html())]);
    })

    alert(myData);
    console.dir(myData);
});

Next, you should cache elements you found, use more than once and which don't change. And usually, it's a bad choice to bind events to the elements directly. I'm assuming jQuery 1.7 is ok and you don't really want to use jQuery 1.4, so we can use on for event binding.

var logDiv = $('#log'),
    dataTableRows = $('#dataTable tbody tr');

$('#baseTable tbody').on('click', 'td', function() {
    var myData = [],
        element = $(this),
        rowIndex = element.parent().index();

    logDiv.html(rowIndex);

    $(dataTableRows[rowIndex]).map(function() {
        return $(this.cells).get();
    }).each(function() {
        var headerVal = $(this).closest('table').find('thead th')
            .eq($(this).index()).html();
        myData.push([headerVal,parseFloat($(this).html())]);
    })

    alert(myData);
    console.dir(myData);
});

Next, accessing the DOM is rather slow. If you need the data for jqplot, do you need the table headers and can the data change?

Anyway, I'd store all data in an array beforehand. Now it looks like this:

var logDiv = $('#log'),
    dataTable = $('#dataTable'),
    dataTableHeaders = [],
    dataTableData = [];

// cache data table headers
dataTable.find('thead th').each(function(col) {
    dataTableHeaders[col] = $(this).html();
});

// cache full row (including headers) for data table
dataTable.find('tbody tr').each(function(row) {
    var rowData = (dataTableData[row] = []);
    $(this).children().each(function(col) {
        rowData[2 * col] = dataTableHeaders[col];
        rowData[2 * col + 1] = parseFloat($(this).html());
    });
});

// the onClick - but on tr instead of td and with a fast lookup
$('#baseTable tbody').on('click', 'tr', function() {
    var rowIndex = $(this).index(),
        myData = dataTableData[rowIndex];
    logDiv.html(rowIndex);
    alert(myData);
    console.dir(myData);
});

I still don't like the need for index(). I like it even less than event binding on elements, so I'll compromise:

var logDiv = $('#log'),
    dataTable = $('#dataTable'),
    dataTableHeaders = [],
    dataTableData = [];

dataTable.find('thead th').each(function(col) {
    dataTableHeaders[col] = $(this).html();
});

dataTable.find('tbody tr').each(function(row) {
    var rowData = (dataTableData[row] = []);
    $(this).children().each(function(col) {
        rowData[2 * col] = dataTableHeaders[col];
        rowData[2 * col + 1] = parseFloat($(this).html());
    });
});

$('#baseTable tbody tr').each(function(row) {
    $(this).on('click', function() {
        var data = dataTableData[row];
        logDiv.html(row);
        alert(data);
        console.dir(data);
    });
});

Here's my last step (this is not really needed, but I like it): we isolate this code from the outside world and make accidental messups a lot harder. And we enable a recalculation and rebinding of the click event if anything changes (number of rows / cols or the content).

var tableData = (function(){
    var logDiv = $('#log'),
        cacheRows = function() {
            var dataTable = $('#dataTable'),
                dataTableHeaders = [],
                dataTableData = [];
            // fetch headers
            dataTable.find('thead th').each(function(col) {
                dataTableHeaders[col] = $(this).html();
            });
            // fetch column data, prepare row arrays
            dataTable.find('tbody tr').each(function(row) {
                var rowData = (dataTableData[row] = []);
                $(this).children().each(function(col) {
                    rowData[2 * col] = dataTableHeaders[col];
                    rowData[2 * col + 1] = parseFloat($(this).html());
                });
            });
            // return row arrays
            return dataTableData;
        },
        bindOnClick = function() {
            var dataTableData = cacheRows();
            $('#baseTable tbody tr').each(function(row) {
                $(this).on('click', function() {
                    var data = dataTableData[row];
                    logDiv.html(row);
                    alert(data);
                    console.dir(data);
                });
            });
        };
    bindOnClick();
    return {
        refresh: bindOnClick
    };
})();

Now, when the tables change, you can preserve the intended behavior by calling tableData.refresh(). This is still a little messy because we never call off, but as we only use jQuery to change the DOM, we rely on it to unbind event handlers if we change elements. It's probably better to change the returned object so it has two functions: one to refresh the cache and one to rebind. rebinding is needed when the whole table was rebuilt and no DOM node is reused. Otherwise, this leaks event handlers. If you update the table infrequently, you should be fine. For frequent updates, I'd change it back to using the index function again.

Edit: Here's an example for what I described in my comment below.

var prepareForPlotting = function(baseSelector, dataSelector, clickhandler) {
    var cacheRows = function() {
            var dataTable = $(dataSelector),
                dataTableHeaders = [],
                dataTableData = [];
            // fetch headers
            dataTable.find('thead th').each(function(col) {
                dataTableHeaders[col] = $(this).html();
            });
            // fetch column data, prepare row arrays
            dataTable.find('tbody tr').each(function(row) {
                var rowData = (dataTableData[row] = []);
                $(this).children().each(function(col) {
                    rowData[2 * col] = dataTableHeaders[col];
                    rowData[2 * col + 1] = parseFloat($(this).html());
                });
            });
            // return row arrays
            return dataTableData;
        },
        bindOnClick = function() {
            var dataTableData = cacheRows();
            $(baseSelector + ' tbody tr').each(function(row) {
                $(this).on('click', function() {
                    clickhandler(row, dataTableData[row]);
                });
            });
        };
    bindOnClick();
    return {
        recache: cacheRows,
        rebind: bindOnClick
    };
}

var logDiv = $('#log'),
    baseHandler = prepareForPlotting('#baseTable', '#dataTable',
        function(row, data) {
            logDiv.html(row);
            alert(data);
            console.dir(data);
        }
    );


Optimizing a divide-and-conquer algorithm for counting inversions

The problem with countSplitInv' is that merging two lists is has the characteristic of co-recursion (it consumes a finite amount of data from given lists to produce one output element), while computing the inversion count has the characteristic of recursion (accumulates value while traversing given lists).

One way how to remedy that would be to count the inversion count for each element separately. Then we'd be working with lists of [(a, Int)]. This also somewhat simplifies the code as it's not necessary to wrap/unwrap pairs at so many places. Also using as-patterns we can avoid recombining values unnecessarily.

import Criterion.Main

inversions :: (Ord a) => [a] -> Int
inversions xs = sum . map snd $ countInv' xs (length xs)

countInv' :: (Ord a) => [a] -> Int -> [(a, Int)]
countInv' []  _ = []
countInv' [x] _ = [(x, 0)]
countInv' xs  n =
    countSplitInv' (countInv' left leftLen) leftLen (countInv' right rightLen)
  where
    leftLen = n `div` 2
    rightLen = n - leftLen
    (left, right) = splitAt leftLen xs

-- we only need to keep track of the right part (nx)
countSplitInv' :: (Ord a) => [(a, Int)] -> Int -> [(a, Int)] -> [(a, Int)]
-- note that the case  [] _ [] is contained in xs _ []
countSplitInv' xs _ [] = xs
countSplitInv' [] _ ys = ys
countSplitInv' xs@((x, ix) : xs') nx ys@((y, iy) : ys')
    | x > y     = (y, iy + nx) : countSplitInv' xs nx ys'
    | otherwise = (x, ix)      : countSplitInv' xs' (nx - 1) ys

main = defaultMain [
    bgroup "inv" $ map bstep [1..10]
  ]
  where
    bstep n = bench (show n2) $ nf inversions [n2,n2-1..1]
      where n2 = 2^n

(I also added main for measuring performance using the criterion package.)

This way, countSplitInv' is just co-recursive. According to my benchmarks (compiling with -O2 and running main), for a decreasing list of length 1024 the original took 1.55ms, while this improved version takes 0.96ms.

However, we still do splitAt and computing the length of the list at the beginning. A way to solve that is dividing the list not from the top, but the bottom. The trick is to first convert [a] into a list of singletons [[a]] and then merge them pair-wise until we get to a single element. (See also the source of Haskell's standard sort.) It can be implemented in many ways. Since I like the abstraction of monoids, I used a monoid that keeps track of inversion counts of a list of elements, and the monoid operation is merging such two lists. And mconcat is implemented pair-wise so that the order of computations form a balanced binary tree:

import Data.Monoid
import Criterion.Main

countSplitInv' :: (Ord a) => [(a, Int)] -> Int -> [(a, Int)] -> [(a, Int)]
countSplitInv' xs _ [] = xs
countSplitInv' [] _ ys = ys
countSplitInv' xs@((x, ix) : xs') nx ys@((y, iy) : ys')
    | x > y     = (y, iy + nx) : countSplitInv' xs nx ys'
    | otherwise = (x, ix)      : countSplitInv' xs' (nx - 1) ys

-- Represents a computation of inversions.
data Inv a = Inv { invSize   :: !Int        -- ^ the length of the list
                 , invSorted :: [(a, Int)]  -- ^ sorted elements with their
                                            -- inversion counts
                 }

instance (Ord a) => Monoid (Inv a) where
    mempty = Inv 0 []
    mappend (Inv nx xs) (Inv ny ys) = Inv (nx + ny) (countSplitInv' xs nx ys)
    mconcat []  = mempty
    mconcat [x] = x
    mconcat xs  = mconcat (mergePairs xs)
      where
        mergePairs (x:y:zs) = (x `mappend` y) : mergePairs zs
        mergePairs zs       = zs

inject :: a -> Inv a
inject x = Inv 1 [(x, 0)]

inversions :: (Ord a) => [a] -> Int
inversions = sum . map snd . invSorted . mconcat . map inject

main = defaultMain [
    bgroup "inv" $ map bstep [1..10]
  ]
  where
    bstep n = bench (show n2) $ nf inversions [n2,n2-1..1]
      where n2 = 2^n

This variant is again faster, it takes 0.66ms for 1024 element list.

And if we use the same trick sort does (see the above link), and partition the input list into decreasing and increasing sequences (for which we can easily compute the inversion counts in linear time), we get somewhat more complex code, but very fast for lists that contain long ordered sequences:

import Data.Monoid
import Criterion.Main

countSplitInv' :: (Ord a) => [(a, Int)] -> Int -> [(a, Int)] -> [(a, Int)]
countSplitInv' xs _ [] = xs
countSplitInv' [] _ ys = ys
countSplitInv' xs@((x, ix) : xs') nx ys@((y, iy) : ys')
    | x > y     = (y, iy + nx) : countSplitInv' xs nx ys'
    | otherwise = (x, ix)      : countSplitInv' xs' (nx - 1) ys

-- Represents a computation of inversions.
data Inv a = Inv { invSize   :: !Int        -- ^ the length of the list
                 , invSorted :: [(a, Int)]  -- ^ sorted elements with their
                                            -- inversion counts
                 }

instance (Ord a) => Monoid (Inv a) where
    mempty = Inv 0 []
    mappend (Inv nx xs) (Inv ny ys) = Inv (nx + ny) (countSplitInv' xs nx ys)
    mconcat []  = mempty
    mconcat [x] = x
    mconcat xs  = mconcat (mergePairs xs)
      where
        mergePairs (x:y:zs) = (x `mappend` y) : mergePairs zs
        mergePairs zs       = zs

sequences :: (Ord a) => [a] -> [Inv a]
sequences (a:b:xs)
  | a > b      = descending b [a] 2 xs
  | otherwise  = ascending  b (a:) 2 xs
  where
sequences [x] = [Inv 1 [(x, 0)]]
sequences []  = []

descending :: (Ord a) => a -> [a] -> Int -> [a] -> [Inv a]
descending a as n (b:bs)
  | a > b             = descending b (a:as) (n + 1) bs
descending a as n bs  = Inv n (zip (a:as) [(n-1),(n-2)..]) : sequences bs

ascending :: (Ord a) => a -> ([a] -> [a]) -> Int -> [a] -> [Inv a]
ascending a as n (b:bs)
  | a < b             = ascending b (\ys -> as (a:ys)) (n + 1) bs
ascending a as n bs   = Inv n (zip (as [a]) [(n-1),(n-2)..]) : sequences bs

inversions :: (Ord a) => [a] -> Int
inversions = sum . map snd . invSorted . mconcat . sequences

main = defaultMain [
    bgroup "inv" $ map bstep [1..10]
  ]
  where
    bstep n = bench (show n2) $ nf inversions [n2,n2-1..1]
      where n2 = 2^n

(For the decreasing list of 1024 numbers, it took 0.11ms, as it computed the result in one single pass.)


Extract Pages from PDF based on search in python

You could try profiling but the code is simple enough that I think you're spending most of the time in PyPDF2 code. Two options:

You can preprocess your PDF files to store their text somewhere, which will make the search phase much faster, especially if you run multiples queries on the same PDF files
You can try another parser such as a Python 3 version of PDFMiner, or even a parser written in a faster language


You can use tuple unpacking/list unpacking to write :

if sites['twitter'][0] in url:
    link, brand = sites['twitter']
elif sites['facebook'][0] in url:
    link, brand = sites['facebook']
else:
    link, brand = sites['pininterest']
return link, brand

Now, the data structure you are using is a bit akward because you don't use the key at all. Instead of mapping string to list of strings, you could have a list of list of strings. Even better, you could use list of tuple of strings :

sites = [
    ('http://www.twitter.com/', 'twitter'),
    ('http://www.facebook.com/', 'facebook'),
    ('http://www.pininterest.com/', 'pininterest')
]

if sites[0][0] in url:
    link, brand = sites[0]
elif sites[1][0] in url:
    link, brand = sites[1]
else:
    link, brand = sites[2]
return link, brand

Now, this seems to be begging to be written with a loop

for (link, brand) in sites:
    if link in url:
        return link, brand
return None # or anything you like


Hello and thank your for your code. I dont' know what kind of improvements you want but from an Object Oriented perspective I see some improvements.

The first one is to get rid of all the static methods and fields. You can easily move all your methods to an AsciiTable class with a print(OutputStream out):void method.

You can also use arrays instead of list and split the single argument to one for the columns titles and another for the content. This will clarify the initiliazation of your table.

Table table = new Table(
    new String[]{"Name", "Sex", "Age"},
    new Object[][]{
            {"Klaus Ulbrecht", "male", 12},
            {"Dieter", "male", 14},
            {"Ursula", "female", 16}
        });

As you can see I changed the order so that the cognitive load is reduced, by
looking at the declaration we alrdeay have an idea of what are the titles and the content. We read for top to bottom, so it is more easier to have a declaration that already looks like that. This avoid your brain to switch the representation.

Another improvement that you can do is apply the separation of concerns principle by moving the "printing" away of the table. This is done easily with the builder where your Table is a director that drive a Format.

With this pattern you should be able to add another representation without changing the Table.

interface Format {
    void startHeader();
    void endHeader();

    void startBody();
    void endBody();

    void startRow();
    void endRow();

    void addColumn(Object value);
}

Format console = new Ascii(System.out, "   ");
table.writeTo(console);

Now that your model (Table) is separated from the view (Format) you may discover that the model is quite simple and exists mainly to drive the view as the director in the builder pattern. But you can add new methods to filter or sort your table.

Table table = new Table(
    new String[]{"Name", "Sex", "Age"},
    new Object[][]{
            {"Klaus Ulbrecht", "male", 12},
            {"Dieter", "male", 14},
            {"Ursula", "female", 16}
    });
table.filter(1, "male"::equalsIgnoreCase)
     .sort(2, Comparator.naturalOrder())
     .writeTo(console);

Name             Sex    Age
Klaus Ulbrecht   male   12
Dieter           male   14

If you don't want to migrate to the object oriented way you can still improve the robustness of your code by dealing with empty columns or rows.

[1] Single Responsibility Priniciple is part of the S.O.L.I.D. acronym. https://en.wikipedia.org/wiki/SOLID

[2] When I speak about the builder pattern I refer to the creational pattern. Not the "fluent way of writing". https://en.wikipedia.org/wiki/Builder_pattern


Show all records when current user is admin

About your code:

The argument name search is confusing (the same as the method), use instead the value it stands for: record_no.
"record_no LIKE ?". This is perfectly fine, but, if you used Arel instead, the query would work for all database.
if is_admin == false -> if !is_admin or unless is_admin. Shorter, more declarative, idiomatic.
DRY your code by reusing the repeated scope.
organization_id: Since you using anORM, you usually send objects as arguments, not their IDs. Does it make sense for you code?
where("organization_id = ?", organization_id). Use a hash instead.

I'd write:

def self.search(record_no, organization_id, is_admin)
  with_record_no = where(arel_table[:record_no].matches("%#{record_no}%"))
  if is_admin
    with_record_no
  else
    with_record_no.where(organization_id: organization_id)
  end
end


Weighting mysql full-text search results by date

A few "small" comments.

Don't use SELECT * for reasons outlined in this question's answers:

What is the reason to not use select *?
Linebreaks and indentation make your code much easier to read:

SELECT *, (MATCH(note) AGAINST (
    '$search' IN BOOLEAN MODE))/SQRT(GREATEST(1, DATEDIFF(NOW(), date)
    )) AS score
FROM notes
WHERE userid = '$userid'
HAVING score > 0
ORDER BY score DESC

Things I like:

You're not writing it ALL IN SHOUT-CASE ;)


1. Bug

You can't pop an item from the queue if it's the only item:

>>> q = PriorityQueueUpdateable()
>>> q[1] = 1
>>> q.pop()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr163560.py", line 41, in pop
    self._clear_heap()
  File "cr163560.py", line 25, in _clear_heap
    value, key = self._heap[0]
IndexError: list index out of range

The problem is in the pop method: it calls _clear_heap after popping the item (as well as before). But at this point there might be no items left in the queue. In your simple test, you add both keys to the queue multiple times, so that when you pop an item it's never the last item (because there are more items with the same key remaining in the queue).

2. Review

The Python library documentation has a section "Priority Queue Implementation Notes" which gives some advice on implementing a priority queue using a heap. This is well worth reading.
The docstring for the class doesn't give much of a clue as to how to use it. Docstrings should be written from the user's point of view, and shouldn't include implementation details (like "implemented with heapq module") — these are only needed by developers and so can be mentioned in comments.
There are no docstrings for the __init__, pop and peek methods.
It would be convenient if the __init__ method accepted an optional iterable of (key, priority) pairs. This would make it easier to create priority queues.
In __init__, there's no need to call heapq.heapify — this does nothing on an empty heap.
Using __setitem__ to add an item to the queue seems strange — normally one would expect a method adding something to a queue to be named something like push, append, or put. (Compare heapq.heappush, collections.deque.append, queue.Queue.put.)
The second argument to __setitem__ is named value, but this is misleading — actually it's the priority of the key.
Priorities work in reverse — if you want an item to have a higher priority then you have to give it a lower value (this happens because Python's heaps are min-heaps). It would probably suit more applications if priorities worked in the usual way. (You'd have to negate the priority values to make higher values mean higher priorities.)
You give a test case, which is great! It would be convenient to turn this into a unit test (perhaps using the unittest module) so that it can be automatically run.


For loop inside Render()

The loop gets called each time the component re-renders, it's a 1280 pushes to an array and that can be a performance issue, you can set it in componentDidMount or even outside the class since it's not dependent on its data,

Consider Array.from to create and fill the array without creating an intermediate one.

const range = Array.from({length: 1280}, (_, i) => i);

And since you're filling it with ints and the select value is an int you don't really need parseInt.

Using document.querySelector to read values

  Basically, you can't easily rely on the input field because the state needs to come from
  the React app's state, not from the browser's idea of what the value should be.

See more explanation in this blog post.

You should instead use the state to store the values of the inputs. ( see code snippet below )

Accessing the DOM using document.querySelector

  In React, we do not directly manipulate the actual DOM. Instead, we must manipulate the virtual representation and let React take care of changing the browser's DOM.

Check this article for in depth explanation and the different ways to access the DOM.

Using refs, instead of doing document.querySelector('video'), you can add a ref like : <video src={video} controls ref={video => this.video = video}/> then use this.video to do what you would do with a regular html element.

Using html5 canvas with react

import React, { Component } from 'react';
import './App.css';
import video from './video.mp4';
import watermark from './watermark.png';

const range = Array.from({ length: 1280 }, (_, i) => i);

class App extends Component {
  constructor() {
    super();
    this.state = {
      select: 0,
      live: false,
      positionX: 0,
      positionY: 0,
      checked: false
    };
  }

  componentDidMount() {
    const context = this.canvas1.getContext('2d');
    context.drawImage(this.video, 0, 0, 720, 1280);
    context.drawImage(this.watermark, this.state.select, this.state.select);

    if (this.state.live) {
      this.setState({ image: canvas.toDataURL() });
    }
  }

  render() {
    return (

        <video src={video} controls ref={video => this.video = video} />

            Watermark X
              <select
                className="positionX"
                onChange={value => this.setState({ select: value, positionX: value })}
                value={this.state.positionX}>
                {range.map(i => (
                  <option key={i} value={i}>{i}</option>
                ))}
              </select>

            Watermark Y
              <select
                className="positionY"
                onChange={value => this.setState({ select: value, positionY: value })}
                value={this.state.positionY}>
                >
                {range.map(i => (
                  <option key={i} value={i}>{i}</option>
                ))}
              </select>

            Live
            <input
              type="checkbox"
              name="live"
              checked={this.state.live}
              onChange={e => this.setState({ live: e.target.value })}
            />

          <button className="watermarkButton watermarkSubmit"
            onClick={() => {
              const context = this.canvas2.getContext('2d');
              context.drawImage(this.video, 0, 0, 1280, 720);
              context.drawImage(this.watermark, this.state.positionX, this.state.positionY);
              this.setState({ image: canvas.toDataURL() });
            }}> Watermark! </button>

          <canvas ref={canvas => this.canvas1 = canvas} width={1280} height={720} />
          <canvas ref={canvas => this.canvas2 = canvas} width={1280} height={720} />

           this.watermark = watermark}
          />

    );
  }

}

export default App;


Remove known Excel passwords with PowerShell

Once you've found the right password and moved the file, then there is no need to try the rest of the passwords on it. You can break out of the loop with a break command.

(You have to change the pipeline % into a foreach ( in ) because otherwise the break would break out of the outer pipeline too. Thanks to Lieven in the comments for that.)

foreach ($passwd in $arrPasswords)
{
    # ...

    # if password is correct save decrypted file to $decrypted_Path
    if ($Workbook.Worksheets.count -ne 0 )
    {
        # ...
        break;
    }

    # ...
}

That may or may not speed things up.

Otherwise, I haven't tried them but I understand that there are .NET Excel libraries that you can use to manipulate Excel files without having to use Excel itself. COM automation is pretty slow, so using one of these libraries might be faster.


#include <cstring>

seems unused.

using namespace std;

Not a good plan - just use the std:: qualifier, or import just the names you need, in the smallest reasonable scope.

inline std::vector<int> read_vector_from_disk(std::string file_path)
{
    std::ifstream instream(file_path, std::ios::in | std::ios::binary);
    std::vector<int> data((std::istreambuf_iterator<char>(instream)), std::istreambuf_iterator<char>());
    return data;
}

This is a very inefficient way to copy a file into memory - the vector will likely have to reallocate (copying its contents) several times, as the input iterators can't be used to predict the eventual size.

Two faster approaches would be

memory-map the file contents, probably using Boost::interprocess
work in a streaming fashion with character-by-character input (e.g. using std::transform())

Also, there's no check whether any of this reading succeeded at all.  That's bad.

std::vector<int> xored_file;

Again, we have a vector we'll append to without first reserving capacity.  That's reducing your efficiency.  I don't see why we need to store a copy of output, instead of immediately writing it to the output stream.

When we've finished writing, we should close the file and confirm that it was successfully written:

new_file.close();
if (!new_file) {
    std::cerr << "Failed to write output file\n";
    return EXIT_FAILURE;
}


Yes, varargs and default args obviously conflict, so choose either.  I think the API as it is, with two functions, is fine and it's a good way to distinguish the two cases.  And I wouldn't expect the default value to go first in any case.

You could also consider not using varargs, right?  So getOrThrow(base, steps, default), using an array for steps instead.


See below for comments on your overall approach, but taking the approach as a given, here are a few observations:

First, it seems unusual to pass initialcounts to histogramcount instead of making histogramcount self-contained.  Also, histogramcount is kind of a long name for such a simple function, and take 10 (repeat 0) is more succinctly written replicate 10 0.  Finally, the complex step of actually incrementing the count seems like it deserves its own function, so I might write:

-- |Return counts of integers from 0 to 9
count :: [Integer] -> [Int]
count = loop (replicate 10 0)
  where loop counts (x:xs) = loop (increment x counts) xs
        loop counts []     = counts

-- |Add one to a given count
increment :: Integer -> [Int] -> [Int]
increment x counts =
  let xint = fromIntegral x
      newcount = (counts !! xint) + 1
  in  take xint counts ++ [newcount] ++ drop (xint+1) counts

There's no particular reason to name linefunctions, and if you write:

map ($ calculatedcounts) (map drawline [maxheight,maxheight-1..1])

a pair of maps like this simplifies to a single map:

map (\height -> drawline height calculatedcounts) [maxheigh,maxheight-1..1]

which might be more clearly written as a list comprehension anyway:

[drawline h calculatedcounts | h <- [maxheight,maxheight-1..1]]

giving:

histogram :: [Integer] -> String
histogram numbers =
  unlines $ [drawline h counts | h <- [maxh,maxh-1..1]] ++ footer
  where counts = count numbers
        maxh = maximum counts
        footer = ["==========","0123456789"]

Note that Haskell code usually uses pretty short names for temporary variables.  It's also more common to use a where clause rather than a let clause when the variables being defined are just helpers, secondary to the main expression.  (Here, counts is arguable not secondary to the main expression, though that raises the question of whether or not we should separate out the function that graphs a set of 10 counts instead of combining it with the counting itself... hmm...)

The drawline function seems okay.  Again, maybe a list comprehension is clearer:

drawline :: Int -> [Int] -> String
drawline level counts = [if x >= level then '*' else ' ' | x <- counts]

or maybe you want to go the route of being excessively clever:

drawline :: Int -> [Int] -> String
drawline level = map (bool ' ' '*' . (>= level))

Before doing that, we should revisit increment.  It's pretty terrible.  The take/drop pair can be replaced with the more efficient splitAt standard function which can simultaneously fetch the current count and get everything prepared to update the count, like so:

-- |Add one to a given count
increment :: Integer -> [Int] -> [Int]
increment x counts =
  case splitAt (fromIntegral x) counts of
    (a,n:b) -> a ++ (n+1):b

That's better, and fairly idiomatic.  Note the use of a ++ (n+1):b in place of a ++ [n+1] ++ b, too.  That's pretty standard.

After you complete next week's lesson, you may discover that count is a fold and rewrite it as:

count :: [Integer] -> [Int]
count = foldr increment (replicate 10 0)

Further down the line, you may become concerned about whether a left fold would have been better for efficiency purposes, but there's not much point in worrying about that now.

Putting it all together, including breaking histogram up into the counting and the plotting and pulling the drawline helper function into the plot function, I might rewrite your program as:

-- |Plot histogram of counts
histogram :: [Integer] -> String
histogram = plot . count

-- |Return counts of integers from 0 to 9
count :: [Integer] -> [Int]
count = foldl (flip increment) (replicate 10 0)

-- |Add one to a given count
increment :: Integer -> [Int] -> [Int]
increment x counts =
  case splitAt (fromIntegral x) counts of
    (a,n:b) -> a ++ (n+1):b

-- |Plot a vertical bar chart of counts
plot :: [Int] -> String
plot counts =
  unlines $ [drawline h | h <- [maxh,maxh-1..1]] ++ footer
  where drawline level = [if x >= level then '*' else ' ' | x <- counts]
        maxh = maximum counts
        footer = ["==========","0123456789"]

main = do
  putStr $ histogram [1,1,1,5]
  putStr $ histogram [1,4,5,4,6,6,3,4,2,4,9]

Finally, I'd run hlint on it.  It gives "No hints", but if I'd run it earlier, it would have mentioned replicate 10 0 and recommended a foldl for the count version that used recursive loop calls.

Is this better than your original?  Well, I think so, of course, or I wouldn't be writing this.  I think the main improvements are:

removing long names for things that aren't very important, like linefunctions or initialcounts
giving top-level names to self-contained actions like count, increment, and plot that perform more well-defined operations than your original "histogramcount" and "drawline"

Now, let's get back to your overall approach.  The main criticism I have is that, like many new Haskell programmers, you're still trying to get over the tendency to use Haskell as an alternate syntax for writing Python (or any other imperative programming language of your choice).  You've started with an array of counts:

counts = [0] * 10    # Python syntax!

and you've looped over the input data, updating each count as you go:

for c in data:
    counts[c] += 1

Unfortunately, Haskell isn't Python, so you've had to represent your running counts as a list.  It has to be passed around as an extra argument, and it not only provides inefficient O(n) access to individual elements but also requires creating an updated immutable copy for every processed data point using the abominable expression:

take xint counts ++ [newcount] ++ drop (xint+1) counts

or its equally hideous cousin:

case splitAt (fromIntegral x) counts of (a,n:b) -> a ++ (n+1):b

Now, one "improvement" would be to switch from inefficient lists to an efficient Vector type to hold your counts.  Honestly, though, the resulting program would still be designed around your original imperative solution, and we aren't seriously concerned with efficiency here anyway.  If we need to process a few million data points, the fact that counting is slow isn't really the biggest issue as we try to generate hundreds of thousands of lines of vertical histogram output.

Instead, to really get a feeling for how Haskell programming is supposed to work, I'd suggest that you take a careful look at Data.List and try to imagine using the functions there as a pipeline of transformations on your data that gradual convert it from [Integer] to String.  See if you can do it without keeping track of any intermediate state, like counts or the current line "level" or anything like that.  As a hint, note that if you were to sort your data and then group it, you'd be close to having a set of required counts.

SPOILERS

Here's a super Haskelly solution to this problem.  Note how its just a pipeline of functional transformations composed together.  Read the pipeline from the bottom-up to understand how it works:

haskellHistogram :: [Integer] -> String
haskellHistogram =
    unlines      -- and print it as lines
  . reverse      -- flip it upside down
  . (['0'..'9']:) . (replicate 10 '-':)  -- add the header rows
  . takeWhile (any (=='*'))  -- take rows until we run out of stars
  . transpose    -- switch from horizontal rows of stars to vertical columns
  . map (  (++ repeat ' ')       -- extend with (infinite) spaces
         . flip replicate '*'    -- represent count as stars
         . (subtract 1)          -- drop the extra number we added
         . length                -- get the count
        )        -- for each group
  . group        -- group into 0s, 1s, 2s, etc.
  . sort         -- sort the input
  . ([0..9]++)   -- add one of each to ensure non-zero counts

I wrote that in one go, starting at the end of the pipeline and working my way backward, in about 5 minutes.  After it type checked and I tested it, I found I'd forgotten the unlines (because my type signature was wrong!) and the subtract 1, but it otherwise worked correctly.  That's what makes Haskell programming so much fun.


Here are some observations and suggestions that may help you improve your program.

Check your spelling

If you run a spell check on your comments, you'll find a number of things such as "peice" instead of "piece" and "accpets" instead of "accepts".  Since your code is nicely commented, it's worth the extra step to eliminate spelling errors.

Separate interface from implementation

The interface goes into a header file and the implementation (that is, everything that actually emits bytes including all functions and data) should be in a separate .cpp file.  The reason is that you might have multiple source files including the .h file but only one instance of the corresponding .cpp file.  In other words, split your existing Player.h file into a Player.h file and a Player.cpp file and do the same with Board.h.

Always return an appropriate value

Your Player::move() routine has control paths that cause it to end without returning any int value.  This is an error and should be fixed.

Don't use system("cls")

There are two reasons not to use system("cls") or system("pause").  The first is that it is not portable to other operating systems which you may or may not care about now.  The second is that it's a security hole, which you absolutely must care about.  Specifically, if some program is defined and named cls or pause, your program will execute that program instead of what you intend, and that other program could be anything.  First, isolate these into a seperate functions cls() and pause() and then modify your code to call those functions instead of system.  Then rewrite the contents of those functions to do what you want using C++.  For example, if your terminal supports ANSI Escape sequences, you could use this:

void cls()
{
    std::cout << "\x1b[2J";
}

Use appropriate #includes

The Player class uses a std::string as part of its interface, but there are no #includes in that file.  Each file should have only and exactly the required #includes.  In this case, it needs #include <string> within the header.

Eliminate "magic numbers"

In a number of cases, the code uses "magic numbers" such as 10 and 6 that have no obvious meaning.  These would be better as named constants if they're used more than once.

Avoid the use of global variables

In this code p1, p2 and board are all global variables. It's generally better to explicitly pass variables your function will need or declare them within the appropriately smallest possible scope rather than using the vague implicit linkage of a global variable.  For example, the main function could instead have three local variables like this:

Board board;
Player p1("X");
Player p2("O");

If the Player member functions need access to the board, then pass a reference to the board as needed.  For example:

p1.move(board)

Use include guards

There should be an include guard in each .h file.  That is, start the file with:

#ifndef BOARD_H
#define BOARD_H
// file contents go here
#endif // BOARD_H

Fix the bug

The way it's currently written, if player 1 wins by getting all the spaces in the middle column, it is not recognized by the program as a win.  I'll leave it to you to figure out what's wrong and fix it.

Simplify expressions

The Player code currently contains this line:

if (winner() == true) { return 1; } // Checks if this player has won

This has three problems.  First, as mentioned above, the function should also return something if the expression is false.  Second, if the return from the move function is interpreted as a binary value, the function should be declared as returning bool rather than int.  Third, this can be simplifed to this:

return winner(board);

Which takes care of all three problems and also assumes that the function has been modified to pass board instead of using a global.

Use const where practical

In the Board::display routine, the underlying Board is not altered.  Make this explicit by declaring that routine const as:

void displayBoard() const; // Displays the board[2D Array]

Rethink your class design

The Player classes freely access the internals of the Board class and the Board class member data is public, meaning that any code can modify it.  That's not good object design.  Better would be to think clearly about the separation between the Board and Player objects and to provide a clean separation and interface between the two.

Separate responsibilities

The Model-View-Controller design pattern is often useful for programs like this.  Because the view in this case is essentially just printing the board to std::cout, we can simplify a bit and just have a model, the Board class, and perhaps a pair of controllers, the Player class.

Use meaningful variable names

Your Board and Player class are descriptive and good enough, but the variable names are not so good.  In particular the x variable in main is not at all descriptive of the content.  A better name might be moveCount.

Declare the loop exit condition at the top

The for loop inside main currently says this:

for (int x = 0; x < 6; x++)

Reading that line, we would conclude that the play continues until x >= 6.  However, within the loop is are three breaks that occurs if one player has won or if it's a draw.  Rather than forcing the reader of the code to examine every line, it's better if you simply declare loop exit conditions completely and honestly at the top.

while (!board.full() && !p1.move(board) && !p2.move(board)) {
    // play until either draw or one player wins
}

Avoid using goto

Having a proliferation of goto statements is usually a sign of bad design.  Better would be to eliminate them entirely -- it makes the code easier to follow and less error-prone.  In this code, you could very easily use a loop instead:

do {
    // try to apply the move
} while (board.board[row][col] == "| X " || board.board[row][col] == "| O ");

Separate I/O from logic

The Player::move routine prints a prompt, gets input from the user and then applies that to the board.  It would be better to separate I/O from the game logic so that the game is cleanly separated from the I/O.  This would, for example, make it much easier to convert the game into a GUI version.

Use a better data structure

The Board class uses an array of printable strings as its data member.  There's nothing inherently wrong with this, but that only simplifies the printing of the board at the expense of every other use.  Instead, choose a more natural data structure, such as a 3x3 array, and you'll find that the calculations are much easier to write correctly.


OP's dropping of ungetc() is incorrect.  OP's thought of "it'll just unget this char and read it again in the next function call." assumes the next function call will be a repeated call to getint() - this is not warrented.  Since the calling code should inspect the return value and noting it is not 1, execute other code to consume the data in stdin.

if(!isdigit(c) && c != '+' && c != '-') {
  ungetch(c);  // not present in OP code, but present in K&R
  return 0;
}

The though being, if getint(int *pn) cannot read the int, leave stdin alone as much as practicable.  Other functionality could be to at least consume 1 character, but I find the first more in keeping with C I/O functions.

A quandary:

In other cases, OP's code below does "Fix it to push such a character back on the input" but IMO does not push back properly.  The sign character is not push-backed, only the digit.  Instead the sign is consumed by getint().

    c = getch()
...
sign = (c == '-') ? -1 : 1;
if(c == '+' || c == '-')
  c = getch();
if(!isdigit(c)) {
  ungetch(c);  // non-digit push-backed, but not sign.
  return 0;
}

But portably using ungetc() twice in a row is not guaranteed.

  One character of pushback is guaranteed. If the ungetc function is called too many times on the same stream without an intervening read or file positioning operation on that stream, the operation may fail.  C11dr §7.21.7.10 3

Since code really should "unget" 2 characters (+/- and the following non-digit), but it is not portable - what to do?  Since many systems do support pushing back more than 1 character with restrictions, consider attempting it.

Of course, all the consumed white-space characters are not push-backed either.  Yet pushing back the sign is prudent - many systems do this with scanf("%d", ...).

Checking the return value of ungetc() would discern success.  A slight variation follows:

int c;
int sign = EOF;

while(isspace(c = getch()))
  ;
if(c == EOF)
  return EOF;
sign = c;
if (sign == '+' || sign == '-')
  c = getch();

if (!isdigit(c)) {
  ungetch(c);  // Pedantic code would check this return value.
  if (sign == '+' || sign == '-') {
    // attempt to push-back sign
    if (ungetch(sign) == EOF) {
      ; // Operation failed
    }
  }
  return 0;
}

...

if (sign == '-') *pn = -(*pn);

Other code issues:

Code does not detect overflow.

Code unnecessarily overflows when scanning INT_MIN.  parse_int(char **s) offers a candidate solution.

Code does not differentiate between an EOF received from getch() due to end-of-file and input error.  Coding goal is "return EOF when end of file is reached".  OTOH, code has no specification concerning input error, so returning EOF for both conditions is reasonable.


Optimize Recursive Fetching of information?

All right, I've done a bit of work here (a good most of it stylistic, to be sure).  Do note I replaced object with a generic implementation to help avoid boxing of value types.  It does also employ LINQ in a couple instances to remove some complexity.  When I run it and generate 1,000,000 integer leaves, I find that the bulk of the time is taken in the class constructors and the methods themselves are close enough to 0 time to be considered 0.  Hope this helps:

internal sealed class Root<T>
{
    private readonly Leaf<T> rootLeaf = new Leaf<T>();

    // dictionary contains a reference to each item, and the leaf it is assigned to (its parent)
    private readonly IDictionary<T, Leaf<T>> allItems = new Dictionary<T, Leaf<T>>();

    /// <summary>
    /// Gets GetAllChildren.
    /// </summary>
    public IList<T> GetAllChildren
    {
        get
        {
            return this.rootLeaf.GetAllChildren;
        }
    }

    public void Add(T o)
    {
        var addedTo = this.rootLeaf.Add(o);

        this.allItems.Add(o, addedTo); // Add object reference to AllItems dictionary
    }

    public void Update()
    {
        foreach (var i in from i in this.allItems from b in this.GetNeighbors(i.Key) select i)
        {
            // Would do collision checks here
        }
    }

    private IEnumerable<T> GetNeighbors(T obj)
    {
        return this.allItems[obj].GetAllChildren.Where(o => ReferenceEquals(obj, o));
    }
}

internal class Leaf<T>
{
    private const int MaxChildCount = 1;

    private static readonly Random rand = new Random();

    private readonly IList<T> children = new List<T>();

    private List<Leaf<T>> childLeaves;

    private bool hasLeaves; // Should we use the leaves?

    private bool leavesGenerated; // Have the leaves been created? (Low Level, do not touch)

    /// <summary>
    /// Returns children of this leaf, and all of its subleaves
    /// </summary>
    public IList<T> GetAllChildren
    {
        get
        {
            var allChildren = this.children.ToList();

            if (this.hasLeaves)
            {
                this.childLeaves.ToList().ForEach(l => allChildren.AddRange(l.GetAllChildren));
            }

            return allChildren;
        }
    }

    /// <summary>
    /// Get count of all children in this leaf, and its subleaves
    /// </summary>
    public int GetChildCount
    {
        get
        {
            var allChildrenCount = this.children.Count;

            if (this.hasLeaves)
            {
                allChildrenCount += this.childLeaves.Sum(l => l.GetChildCount);
            }

            return allChildrenCount;
        }
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="o">The object to be added</param>
    /// <returns>The leaf the object was added to</returns>
    public Leaf<T> Add(T o)
    {
        if (this.children.Count < MaxChildCount)
        {
            this.children.Add(o);
            return this;
        }

        // Pick random subleaf, I know this isn't correct for a quadtree, but it will simplify this explanation code
        if (!this.hasLeaves)
        {
            this.CreateLeaves();
        }

        return this.childLeaves[rand.Next(0, 3)].Add(o);
    }

    protected void CreateLeaves()
    {
        if (!this.leavesGenerated)
        {
            // create each of the four leaves
            this.childLeaves = new List<Leaf<T>> { new Leaf<T>(), new Leaf<T>(), new Leaf<T>(), new Leaf<T>() };

            this.leavesGenerated = true;
        }

        this.hasLeaves = true;
    }

    protected void RemoveLeaves()
    {
        this.hasLeaves = false;
    }
}


ASP.NET MVC Html.XXFor OK to discard lambda argument and just use Model directly?

I'd fail this review if I saw it at my company.  Most are probably shown the first approach, doing this will only confuse people that come after you.  Now they have to determine if the way you've chosen is actually equivolent to the "standard" way.  I actually just went through that exercise myself.


PHP JPG image re-creation from original file

You may use this advice from stackexchange:

$im = imagecreatefrompng(input_filename)
imagejpeg($im, output_filename);

A call to imagecopyresample in your example is quite resource-consuming and can cause image quality loss. The call above is the same as 'open-save' in any graphical editor. I doubt that it leaves any malicious data intact, as imagejpeg re-compresses the raw image again.

Another option is to use exif_imagetype:

  exif_imagetype() reads the first bytes of an image and checks its signature.

This prevents upload of non-graphical files masked as graphical, but does not eliminate a file that contains a jpeg signature, but is not jpeg.


Project Euler #1 Sum of all the multiples of 3 or 5 below 1000

In general, your algorithm/solution is clever. It is an \$O(1)\$ solution which I like, when most other solutions would be an \$O(n)\$ and do a modulo on 3 and 5. The trick for subtracting the double-count is something that should have a clear comment, including the reason why.

The find_last_multiple is also a neat solution. No issues with that, and it is simple enough to not require a comment.

Unfortunately the sum_of_series has some problems.... it should be commented, for a start... the logic is far from obvious.... I have not figured it out... yet.

Also, at this point it becomes float based calculations, and that threw me for a second. I immediately started thinking int-based math because the code has int constants, and it does int values in the find_last_multiple but it then does implicit casts to float. Very confusing.

Finally, it makes the assumption that that the series starts from 3, 5, or 15, but the question description starts from somewhere else.... I suggest you discard the starts_from parameter, and simply use the difference instead.

So, using float-based logic, and returning a float based solution is unexpected.... and I would expect there to be some comment as to why the sum of integers in a series is a float.

Finally, your sum_of_series should represent the standard formula for the sum-of-a-series (see the alternate form in wikipedia):

$$
\frac{n}{2}(2a + (n - 1)d)
$$

where n is the number of terms in the series, a is the start value, and d is the difference.

That can be simplified by setting a to be 0 (eliminating the 2a term), and for int math by doing:

$$
\frac{n(n - 1)}{2}d
$$

Mathematically, any multiple of an even number is always going to be even. Now, either \$n\$ or \$n - 1\$ is even.... so, \$n(n-1)\$ will be even, and safe to divide by 2.

I would also start from 0. Using integer math, the problem is simpler:

int sum_of_series(int limit, int difference)
{
    // from: http://en.wikipedia.org/wiki/Arithmetic_progression
    // formula for calculating the sum of a progression from 0 to a 'limit'
    // in steps of 'difference'. e.g. limit 10, difference 2 adds 0, 2, 4, 6, 8, 10 = 30
    int n = 1 + limit / difference; // integer math gives number of terms including term 0
    return ((n * (n - 1)) / 2) * difference;
}

So, you can use the above safely as:

int sum = sum_of_series(999, 15);

which will give the result 15 * (67 * 66) / 2 or  33165

Note that the problem statement requires the sum of values less than 1000, and the sum_of_series formula calculates inclusive of the limit, so we use the limit of 999, not 1000

Additionally, using the int-based logic, there is no need for there to be the find-limit method at all. This reduces your main method to:

int main(void){

    int sum_of_series_3 = sum_of_series(999,3);
    int sum_of_series_5 = sum_of_series(999,5);
    int sum_of_series_15 = sum_of_series(999,15);

    int answer = sum_of_series_3 + sum_of_series_5 - sum_of_series_15;

    printf("sum of all the multiples of 3 or 5 below 1000\n");
    printf("answer = %d\n",answer);

    return 0;

}

I put the above together in a working Ideone


DFS/BFS implementation of Cormen's pseudo code

Preliminaries

It's conventional to include system headers with brackets instead of quotes and prefer std::vector over std::list unless proven wrong by a benchmark (note that the use of the word "list" in CLRS is not used in the same sense as std::list).

#include <vector>
#include <limits>

Data structures

Separate your algorithms and data structures and use a common naming convention where types have capitalized initial letters

enum {
    INFINITY = std::numeric_limits<int>::max()
};

enum Color {
    WHITE,
    GREY,
    BLACK
};

struct Vertex {
    int id;

    // BFS properties
    Color color;
    int discovery;
    Vertex* parent;

    // DFS properties
    int finish;
};

// adjacenty list representation (Figure 22.1 (b) of CLRS 3rd ed.)
struct Graph {
    std::vector<Vertex> vertices;
    std::vector< std::vector<Vertex*> > adjacent;
};

Several things can be said about my choice of data structures. For the purpose of illustrating BFS and DFS I wouldn't make them full-fledged classes with data hiding. You also need to set up some scaffolding code to initialize a Graph object, and make sure that the Vertex* inside adjacent are actually only pointing to Vertex objects inside vertices of the same Graph object (so that in fact adjacent only holds non-owning pointers). Real-world code would encapsulate the enforcement of such invariants inside the constructor and modifying member functions. For brevity this is not being show.

I also would remove the Edge class because it is implicitly represented as an Vertex* in the adjacency list graph representation. Finally, because the id in Vertex is an int, you get away with using a std::vector as a container. For std::string vertex labels, one would need to use a std::map<std::string, std::vector<Vertex*>> for the adjacent data inside Graph.

Note that the properties of BFS and DFS are put inside Vertex. This is to accomodate the style of notation of CLRS. They write on p592 that you can put that information in separate data structures as well (e.g. a std::map<Vertex*, SearchProperties>). Boost.Graph (the closest thing in C++ to a standardized graph implementation) uses such property maps to achieve the same effect more elegantly.

Breadth-first search

Document your algorithms pre- and post-conditions, as well as the runtime complexity as a function of the input size (look it up in CLRS!). I would give the function breadth_first_search the same signature as in CLRS, except that they are not very careful about whether they pass by value, reference or pointer.

#include <queue>

// pre-condition: graph of vertices with unitialized BFS properties
void breadth_first_search(Graph& g, Vertex* s)
{
    for (auto& v: g.vertices)
        if (v.id == s->id) continue;
        v.color = WHITE;
        v.discovery = INFINITY;
        v.parent = nullptr;
    }
    s->color = GRAY;
    s->discovery = 0;
    s->parent = nullptr;
    std::queue<Vertex*> q;
    q.push(s);
    while (!q.empty()) {
        auto u = q.front();
        q.pop();
        for (auto v: G.adjacent[u->id])) {
            if (v->color == WHITE) {
                v->color = GRAY;
                v->discovery = u->discovery + 1;
                v->parent = u;
                q.push(v);
            }
        }
        u->color = BLACK;
    }
}
// post-condition: graph with initialized vertex color and discovery times

Notice that I would strongly recommend to use the C++11 features auto type deduction and ranged for-loop. These enormously improve the readability of your code: the code above is in almost exactly the same notation as the listing of BFS(G,s) on p595 of CLRS (except that I use color, discovery and parent instead of the terser c, d and pi.

Except for debugging purposes, I would eliminate the std::cout calls from the BFS algorithm. Because the algorithm also keeps track of the parent information, you can completely retrace the algorithms steps after it finishes, should you want to, and print whatever information necessary.

Depth-first search

For the depth-first search, I again would follow the CLRS conventions as much as possible:

void depth_first_search(Graph& g)
{
    for (auto& u: g.vertices) {
        u.color = WHITE;
        u.parent = nullptr;
    }

    for (auto& u: g.vertices) {
        if (u.color == WHITE)
            depth_first_search_visit(g, &u, 1)
    }
}

void depth_first_search_visit(Graph& g, Vertex* u, int time)
{
    u->color = GRAY;
    u->discovery = time;
    for (auto v: g.adjacent[u->id]) {
        if (v->color == WHITE) {
            v->parent = u;
            depth_first_search_visit(G, u, time + 1)
        }
    }
    u->color = BLACK;
    u->finish = time + 1;
}

Note that I would pass the time variable by value along the recursive calls to depth_first_search_visit, which makes it slightly clearer to reason about the algorithm (and also avoids a few explicit increments here and there). Again note that the code above is in almost exactly the same notation as the listing of DFS(G) on p604 of CLRS.

Extra: note that BFS is written as a single function with an init phase + infinite loop over a std::queue, and DFS as an init function + a recursive fuction. It is a nice exercise to rewrite DFS as a single function with an init phase + infinite loop over a std::stack (instead of the implicit stack used by the recursion).

Further reading

If you want to know how the pros are doing it: familiarize yourself with Boost.Graph.


Finding pairs that add up to a given sum, using recursion

Recursion is about dividing and conquering. You are going to check the first element of an array (E0) against each element in the rest of the array. Once you have checked all the elements, you pick the next element (E1) in the array and check it against all the other elements. Since you've already checked E1 against E0 in the previous iteration, you only need to check E1 against the elements after it.

First of all, your naming is unclear. The "fixed" has no meaning here, so let's drop it. Single letter parameter and argiment names are only reserved for loop counters. So "k" must become "expectedSum". The entry-function to the iteration just takes the user input. It adds the initial entry parameters for the iterative function (indexes to first entry in the array and the first entry of the sub-array. Since the entry function initializes the recursive function with valid values, there is no need to check for magic -1 values in the iterative function anymore.

public static void findSumPairs(int[] array, int expectedSum) {
    recursiveSumPairs(array, expectedSum, 0, 1);
}

private static void recursiveSumPairs(
        int[] array,
        int expectedSum,
        int firstIndex,
        int nextIndex) {

    // End condition for recursion: first element to check is the last
    // element in the array. This also handles input arrays shorter than
    // two elements.
    if (firstIndex >= array.length - 1) {
        return;
    }

    // We have exhausted the sub-array. Advance the first element to the
    // next index and compare it to the rest of the elements left in the
    // array.
    if (nextIndex >= array.length) {
        recursiveSumPairs(array, expectedSum, firstIndex + 1, firstIndex + 2);
        return;
    }

    if (array[firstIndex] + array[nextIndex] == expectedSum) {
        System.out.println(array[firstIndex] + " + " + array[nextIndex]);
    }

    // Compare first element to the next element in the array.
    recursiveSumPairs(array, expectedSum, firstIndex, nextIndex + 1);
}

My presonal preference is to use ">=" and "<=" instead of "==" when checking loop counters against end conditions. It implies that the left side of the comparison is a value that increases/decreases and guards against bugs where the counter increases by two. Although if you were really paranoid you could add special check for that and throw an IllegalStateException (the new kids on the block would probably use assertations).

Now, if you want to go fancy with the solution, instead of burdening the algorithm with display functions (System.out.printlning the result), you could pass a BiConsumer to the function and let the caller decide what to do with the results (possibly with a nice lambda).

findSumPairs(
    array,
    sum,
    (a, b) -> System.err.println(a + " + " + b));


Python: wild card pattern matching with memoization

Take a look at styling and naming guide, namely; PEP-8. Class names should be CamelCased and method/attributes should be snake_case. Your variables are named like s, p, c etc. which does not make it clear at first glance what they represent, nor is there a docstring available for reference.

That aside, running your code gives me:

         string         pattern    result    counter
=======================================================
                             *      True         2
              a              *      True         4
              b              *      True         4
             ab             a*      True         5
              a             *b     False         1
            aba            a*a      True         6
             aa           *?*?      True         5
            cda          c*d?*      True         6
            xx0         ?*?*?*      True         7
              a              a      True         2
              a                    False         1
              a      ******a*a     False        10
             aa      ******a*a      True        10
              a      ******?*a     False        10
              a    ******a*a**     False        35
        ababaab     ******a*a*      True        21
         ababaa     ******a*a*      True        19

where I noticed that your counter reached \$35\$ for the pattern ******a*a**. In this case (and a few more similar cases), you can simply return False if your patter, after removing all * characters is still longer than the given string. Because then your string would never be able to cover the pattern.

As right now, you only have * and ? characters; for any length of characters and exactly one character, the above method reduces your recursion by a lot in several given cases:

def match(self):
    if len(self.s) < len(self.p.replace('*', '')):
        return False

and the result:

         string         pattern    result    counter
=======================================================
  [=======================SAME======================]
              a                    False         1
              a      ******a*a     False         0
             aa      ******a*a      True        10
              a      ******?*a     False         0
              a    ******a*a**     False         0
        ababaab     ******a*a*      True        21
         ababaa     ******a*a*      True        19

The above snippet can also be placed inside your recursive f call. I still have to figure out under which section will it make more sense, but basically for any certain match fixed from pattern onto your string, if the remaining pattern satisfies the above length restriction, you can simply skip the rest of iterations.

For tests, make use of the python's own unittest module to create mocks. Have a set containing patterns and strings, and iteratively run the assertions on expected values.


Processing image blocks using a task runner

IMO, inlined functions add clutter. I think it's clearer and cleaner to use a named function.

function makeBlockFunc(i) {
    return function(){
        var blockLen=Math.min(32768,len-(i*32768));
        stream.push(i==(blocks-1)?0x01:0x00);
        Array.prototype.push.apply(stream, blockLen.bytes16sw() );
        Array.prototype.push.apply(stream, (~blockLen).bytes16sw() );
        var id=imageData.slice(i*32768,i*32768+blockLen);
        Array.prototype.push.apply(stream, id );
    };
}

Then invoke the function in the loop, passing i.

var tr = new taskRunner();

for(var i=0;i<blocks;i++){
    tr.AddTask(makeBlockFunc(i));
}

Also, you didn't really need an inner and outer function. You could have done the .AddTask() directly. Here the returned function is added directly into the tr.


Pulling data from multiple excel files in Python

One possible solution is using zip(). This allows you to iterate, in your case, through multiple lists at a time. You can also condense creating the lists into one line. And, you can remove assigning dynamic_viscosity_#/Density_PE_298k to a variable, just append that to the lists. Consider the following:

kinematic_viscosity, kinematic_viscosity_1, kinematic_viscosity_2 = [], [], []

for dynamic_viscosity, dynamic_viscosity_1, dynamic_viscosity_2 in zip(DV, DV_1, DV_2):
    kinematic_viscosity.append(dynamic_viscosity/Density_PE_298k)
    kinematic_viscosity_1.append(dynamic_viscosity_1/Density_PE_298k)
    kinematic_viscosity_2.append(dynamic_viscosity_2/Density_PE_298k)

While it looks more blocky, it allows you to only loop through the lists once.

Another solution is to keep the three loops, but append the returns directly into the list. Consider the following:

kinematic_viscosity = [dynamic_viscosity/Density_PE_298k for dynamic_viscosity in DV]

kinematic_viscosity_1= [dynamic_viscosity_1/Density_PE_298k for dynamic_viscosity_1 in DV_1]

kinematic_viscosity_2= [dynamic_viscosity_2/Density_PE_298k for dynamic_viscosity_2 in DV_2]


Couple of things I noticed:

The serialize members:

void read(std::istream& stream);
void write(std::ostream& stream);

I don't particular mind them but I also would prefer to have operator<< and operator>> defined (Note you can simply make these call write/read respectively).

With the stream iterators defined this becomes less useful.

void print(int indent = 0);

The following seem like very simialer.

int8_t byteValue() const;
int16_t shortValue() const;
int32_t intValue() const;
int64_t longValue() const;
float floatValue() const;
double doubleValue() const;
ByteArray byteArrayValue() const;
IntArray intArrayValue() const;
UTF8String stringValue() const;

I think we can replace all of them with:

template<typename T>
T const& get() const;

I like this better as we do not need to guess that byte maps to int8_t or short maps to int16_t as we can explicitly get the type we want:

 int8_t  val = t.get<int8_t>();

But there is already something very similar defined in boost:

boost::any


Detecting if two given strings are isomorphic using Java data structures

Your build two HashMap<Character, Integer>, then two ArrayList<Integer>, then sort the lists, then compare the lists.  Your logic is too complicated, I think.  Furthermore, you aren't taking advantage of the symmetry in the problem — nearly every line of code appears in duplicate. Even worse, the code doesn't even do what you claim; rather, it tests whether the inputs are isomorphic anagrams of each other.

Going by the definition, we can just build a character-to-character map from one string to the other, and fail as soon as we encounter an unexpected character.  This should be O(n), and possibly faster if a mismatch is detected early.

The code works equally well on any pair of CharSequences, not just Strings, so we might as well generalize.

import java.util.HashMap;
import java.util.Map;

public class IsomorphicStrings {
    public static boolean areIsomorphic(CharSequence s1, CharSequence s2) {
        return isSurjective(s1, s2) && isSurjective(s2, s1);
    }

    private static boolean isSurjective(CharSequence s1, CharSequence s2) {
        if (s1.length() != s2.length()) return false;

        Map<Character, Character> surjection = new HashMap<>();
        for (int i = 0; i < s1.length(); i++) {
            char c1 = s1.charAt(i);
            char c2 = s2.charAt(i);
            Character prev = surjection.put(c1, c2);
            if (prev != null && prev != c2) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(areIsomorphic(args[0], args[1]));
    }
}