Implementation of glass filter for images

Interesting exercise and nice implementation, few suggestions on my side:

The method chooseRandomNeighbor is only used by filter, so it can be set to private
The name filter is too general for a method, a better name might be applyGlassFilter
In Java the name of a class starts with a capital letter

Optimization

random neighboring pixel (whose pixel coordinates both differ from p’s
coordinates by at most 5).

The method chooseRandomNeighbor picks an adjacent random neighbor (which differ by at most 1) and then gets called 4 times. That implies creating 4 full images in memory. Wouldn't be better to directly pick a neighbor with maximum distance 5?
To do that the method chooseRandomNeighbor needs to accept the width or height:
int neighborColIndex = chooseRandomNeighbor(col,width);
int neighborRowIndex = chooseRandomNeighbor(row,height);

And this is chooseRandomNeighbor refactored:
private static int chooseRandomNeighbor(int index, int max) {
    // Random delta between -5 and +5
    int randomDelta = (int) ((Math.random() * (10)) - 5);
    // Add delta to index without overflowing the limit
    int neighborIndex = (index + randomDelta) % max;
    // If index is negative return 0
    return neighborIndex < 0 ? 0 : neighborIndex;
}

Now the method filter can be called only once and only the new image will be created in memory.
Side note: you are getting better and better, keep up the good work!
Code Refactored
public class Test {

    public static Picture applyGlassFilter(Picture inputPicture) {
        int width = inputPicture.width();
        int height = inputPicture.height();
        Picture outputPicture = new Picture(width, height);
        for (int col = 0; col < width; col++) {
            for (int row = 0; row < height; row++) {
                int neighborColIndex = chooseRandomNeighbor(col,width);
                int neighborRowIndex = chooseRandomNeighbor(row,height);
                Color c = inputPicture.get(neighborColIndex,neighborRowIndex);
                outputPicture.set(col, row, c);
            }
        }
        return outputPicture;
    }

    private static int chooseRandomNeighbor(int index, int max) {
        // Random delta between -5 and +5
        int randomDelta = (int) ((Math.random() * (10)) - 5);
        // Add delta to index without overflowing the limit
        int neighborIndex = (index + randomDelta) % max;
        // If index is negative return 0
        return neighborIndex < 0 ? 0 : neighborIndex;
    }

    public static void main(String[] args) {
        Picture inputPicture = new Picture(args[0]);
        Picture outputPicture = applyGlassFilter(inputPicture);
        outputPicture.show();
    }
}


You can either write a method that is bound to the global scope and takes two arguments, the onClick element and the slideToggle element, and does just what you want (without writing redundant code).

function bindToggleTwo(cElem, tElem) {
   $(cElem).click(function() {
      $(tElem).slideToggle(1200, 'easeInOutQuart');
      $(".hideable").slideToggle(1200, 'easeInOutQuart');
   });
}

jQuery(document).ready(function($) {
    bindToggleTwo("#alles", ".abutton");
    bindToggleTwo("#voorbeelden", ".bbutton");
    bindToggleTwo("#contact", ".cbutton");
});

Alternatively, you could write a jQuery function that is called on a jQuery object to do the very same. Basically this is a function that expects to be scoped such that this is  a jQuery object. Anyway, both of these methods work, and will simplify your code. :)

jQuery.fn.bindToggleTwo = function(tElem) {
  $(this[0]).click(function() {
     $(tElem).slideToggle(1200, 'easeInOutQuart');
     $(".hideable").slideToggle(1200, 'easeInOutQuart');
  });
}

jQuery(document).ready(function($) {
    $("#alles").bindToggleTwo(".abutton");
    $("#voorbeelden").bindToggleTwo(".bbutton");
    $("#contact").bindToggleTwo(".cbutton");
});


Throwing exceptions from a constructor is not only a perfectly legitimate pattern to use. It is also necessary to correctly implement Resource Acquisition Is Initialization (RAII) for some classes (this appears to be the case in your code). And trust me, you really do want RAII :)

However, please be aware of the caveat that the destructor of the object will not be executed if the constructor throws. But the individual members of the class will be destructed.

On a related note, it is also okay for the constructor to perform work if the work is necessary for RAII. Again under the caveat that you adhere to Single Responsibility Principle (SRP) and Dependency Injection (DI). See this question: https://stackoverflow.com/questions/7048515/is-doing-a-lot-in-constructors-bad


BlockingQueue Implemetation using ReentrantLock

These seem mixed up:

    while(queue.size() == limit.get()) {
        put_condition.await();
    }
    put_condition.signal();

and

    while (queue.size() == 0) {
        take_condition.await();
    }
    take_condition.signal();

when putting if queue is full you wait until someone takes
and when taking if queue is empty you wait until someone puts.

You should have test cases with 11 puts followed by 1 take.
and 1 take followed by 1 put. To see they do not deadlock.

What do you know, the example code for Condition is actually Bounded buffer. And you can see it here:
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/locks/Condition.html

But I like their condition names better;)

Limit is a constant as it is, hence does not need atomic integer or any other synchronization. Just declare it final. best way of making something threadsafe is to make it immutable.


VBA macro - searches through a filtered table, stops when entry passes criteria

First, I'd just like to say: This is decent code for someone who's brand new to VBA. Great work.

That aside, let's begin:

Option Explicit

If that's not at the top of all your code modules, put it in. Go to Tools --> Options --> Require Variable Declaration to have it auto-inserted into every new module you create.

Easy Performance Improvements

Sub DoThing()

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
        .StatusBar = False
        .Calculation = xlCalculationManual
    End With

    ...

    ...

    Code

    ...

    ...

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .StatusBar = True
        .Calculation = xlCalculationAutomatic
    End With

End Sub

Each of those settings will provide large performance improvements. Especially ScreenUpdating. Always check that you're not reliant on the thing you're disabling though. For instance, DoFind() is relying on a formula to change, so you shouldn't disable Calculation.

Consistent Indenting

Pick an indenting rule and stick to it. Personally, I use a single Tab for each logical level (If, While, With, etc.) and it's a widespread convention with VBA. This way, I can easily identify which statements are operating at what level.

Something like this is particularly confusing:

               If Sheets("Calculations").Cells(17, "M").Value = "PASS" Then
    Exit Do
               Else
               End If

It's much easier to "see" what's going on when it's expressed like this:

If Sheets("Calculations").Cells(17, "M").Value = "PASS" Then
    Exit Do
End If

I would re-indent your DoFind sub like so:

Sub DoFind()

    Dim i As Long
    i = 1

    Do While Sheets("Temp").Cells(i, "A").Value <> Empty

        Dim BearingArray(6) As String
        BearingArray(0) = Sheets("Temp").Cells(i, "A").Value
        BearingArray(1) = Sheets("Temp").Cells(i, "B").Value
        BearingArray(2) = Sheets("Temp").Cells(i, "C").Value
        BearingArray(3) = Sheets("Temp").Cells(i, "D").Value
        BearingArray(4) = Sheets("Temp").Cells(i, "E").Value
        BearingArray(5) = Sheets("Temp").Cells(i, "F").Value
        BearingArray(6) = Sheets("Temp").Cells(i, "G").Value

        With Sheets("Calculations")
            .Cells(17, "K").Value = BearingArray(0)
            .Cells(19, "O").Value = BearingArray(1)
            .Cells(20, "O").Value = BearingArray(2)
            .Cells(23, "O").Value = BearingArray(3)
            .Cells(22, "O").Value = BearingArray(4)
            .Cells(26, "O").Value = BearingArray(5)
            .Cells(17, "L").Value = BearingArray(6)
        End With

        i = i + 1

        If Sheets("Calculations").Cells(17, "M").Value = "PASS" Then
            Exit Do
        End If

    Loop

    If Sheets("Temp").Cells(i, "A").Value = Empty Then
        MsgBox "No available bearing."
    End If

End Sub

Much easier to follow.

Naming

I recommend the Excellent, Classic article on naming by Joel spolsky.

Naming is, famously, one of the 2 hardest things in software development. It's also one of the most important. Code should be written for other people (including future you) to understand as easily and completely as possible.

Names should be descriptive, then unambiguous, and only then concise.
Variables should sound like what they are. I should be able to tell from the name of a Sub/Function exactly what it does.

DoFind. This tells me nothing.

FindBearing would be better. I'd offer you an even better name, but there's not enough context to be sure what the rest of your code/workbook is doing and why.

Create_Sheet_Temp. Don't use _ in procedure names. _ in VBA is used for event triggers e.g. Workbook_Open or Button_OnClick. Avoid it in your own names to avoid confusion.

Copy_Paste. Useless. Copy what? Paste what? Paste where?.
PasteBearingDataToTempSheet. Sure, it's a bit verbose, but it's also useful. You should always aim for useful names. If you can make them short as well, great, but it's not the priority.

Use the Object Model

The great power of VBA for manipulating MS Office is the extensive Object Model it's integrated with.

There are objects for everything. Workbooks, Worksheets, ListObjects, Ranges etc.

Take this for instance:

        BearingArray(0) = Sheets("Temp").Cells(i, "A").Value
        BearingArray(1) = Sheets("Temp").Cells(i, "B").Value
        BearingArray(2) = Sheets("Temp").Cells(i, "C").Value
        BearingArray(3) = Sheets("Temp").Cells(i, "D").Value
        BearingArray(4) = Sheets("Temp").Cells(i, "E").Value
        BearingArray(5) = Sheets("Temp").Cells(i, "F").Value
        BearingArray(6) = Sheets("Temp").Cells(i, "G").Value

What happens if/when your temp sheet has a different name than "Temp"? How about if someone renames the "Calculations" sheet? Not only will your code break, but you'll have to change those strings everywhere in your code. Maybe you'll get them all. Maybe you won't. Chances are, it will introduce new errors.

Instead, make some Worksheet objects and use those:

Sub NewTest()

    Dim tempSheet As Worksheet
    Set tempSheet = ThisWorkbook.Sheets.Add

    Dim calculationSheet As Worksheet
    Set calculationSheet = ThisWorkbook.Sheets("Calculations")

    PasteBearingDataToTempSheet tempSheet, calculationSheet

    FindBearing tempSheet, calculationSheet

End Sub

Sub PasteBearingDataToTempSheet(ByRef tempSheet As Worksheet, ByRef calculationSheet As Worksheet)

    calculationSheet.Activate

    Dim NewTable As ListObject
    Set NewTable = calculationSheet.ListObjects("Full_Bearings_List")

    NewTable.Range.SpecialCells(xlCellTypeVisible).Select
    NewTable.DataBodyRange.SpecialCells(xlCellTypeVisible).Copy

    tempSheet.Range("A1").PasteSpecial xlPasteAll

    Application.CutCopyMode = False

    'This sub copies all visible cells from a filtered table and pastes them to the new sheet called "Temp"

End Sub

Sub FindBearing(ByRef dataSheet As Worksheet, ByRef calculationSheet As Worksheet)

    Dim i As Long
    i = 1

    Do While dataSheet.Cells(i, "A").Value <> Empty

        Dim BearingArray(6) As String
        With dataSheet
            BearingArray(0) = .Cells(i, "A").Value
            BearingArray(1) = .Cells(i, "B").Value
            BearingArray(2) = .Cells(i, "C").Value
            BearingArray(3) = .Cells(i, "D").Value
            BearingArray(4) = .Cells(i, "E").Value
            BearingArray(5) = .Cells(i, "F").Value
            BearingArray(6) = .Cells(i, "G").Value
        End With

        With calculationSheet
            .Cells(17, "K").Value = BearingArray(0)
            .Cells(19, "O").Value = BearingArray(1)
            .Cells(20, "O").Value = BearingArray(2)
            .Cells(23, "O").Value = BearingArray(3)
            .Cells(22, "O").Value = BearingArray(4)
            .Cells(26, "O").Value = BearingArray(5)
            .Cells(17, "L").Value = BearingArray(6)
        End With

        i = i + 1

        If calculationSheet.Cells(17, "M").Value = "PASS" Then
            Exit Do
        End If

    Loop

    If dataSheet.Cells(i, "A").Value = Empty Then
        MsgBox "No available bearing."
    End If

End Sub

Now, if either of those names change, you only have to change the declaration in one place, and the rest of your code will continue running perfectly. Notice how we don't even have to name the tempSheet. We just create it directly into a worksheet object.

And how about this:

        If calculationSheet.Cells(17, "M").Value = "PASS" Then
            Exit Do
        End If

What is the significance of the particular cell? How do we know what it's supposed to be? And how do we check that it is what it's supposed to be?

Depending on your workbook, my first suggestion would be to make that cell a Named Range.

If we named that cell "ValidateBearing" then we could do the following:

    Dim validationCell As Range
    Set validationCell = ThisWorkbook.Names("ValidateBearing").RefersToRange

    Const VALIDATION_PASS_TEXT As String = "PASS"

    Do While dataSheet.Cells(i, "A").Value <> Empty

        ...

        ...

        If validationCell.Text = VALIDATION_PASS_TEXT Then
            Exit Do
        End If

And now, not only have we made it clear what that cell is and what it's doing, but that cell can now move around as much as it likes. As long as nobody actually deletes the row/column/sheet it's in, that code will always point to the right place.

Other tips & Tricks

Do While dataSheet.Cells(i, "A").Value <> Empty

should be

Do While Not IsEmpty(dataSheet.Cells(i, 1))

    If dataSheet.Cells(i, "A").Value = Empty Then
        MsgBox "No available bearing."
    End If

This is hacky. Add a proper Boolean variable to check for conditions:

    Dim foundBearing As Boolean
    foundBearing = False

    Do While Not IsEmpty(dataSheet.Cells(i, 1))

        ...

        ...

        If validationCell.Text = VALIDATION_PASS_TEXT Then
            foundBearing = True
            Exit Do
        End If

    Loop

    If Not foundBearing Then
        MsgBox "No available bearing."
    End If

You can drop .Select everywhere and always.

A.B.Select
Selection.DoThing

Is always the same as just doing

A.B.DoThing

Here:

    NewTable.Range.SpecialCells(xlCellTypeVisible).Select
    NewTable.DataBodyRange.SpecialCells(xlCellTypeVisible).Copy

You can drop the first line entirely and it will still run perfectly fine.

Get used to using Sheet.Cells(row, column) instead of Sheet.Range("[Address]"). Not only is it faster, but it's semantically closer to what cells actually are, and you can't do things like this anywhere near as easily with addresses:

Dim startRow As Long
startRow = 1

Dim finalRow  As Long
finalRow = [Get final Row]

Dim startColumn As Long
startColumn = 1

Dim finalColumn As Long
finalColumn = [Get final Column]

Dim iRow As Long
Dim iColumn As Long

For iRow = startRow To finalRow
    For iColumn = startColumn To finalColumn

        With [Sheet].Cells(iRow, iColumn)

            [Do Stuff]

        End With

    Next iColumn
Next iRow


Welcome to Code Review!

Algorithm

Since you specifically asked how to optimize the code, I'll put this part first.  You are using a divide-and-conquer algorithm.  This algorithm is \$\operatorname{\Theta}(n \log n)\$.  There's a better \$\Theta(n)\$ algorithm which works like this: go through the array, from index i = [0, n).  Keep track of two variables:

max_sum: maximum subarray sum so far.
max_end_sum: maximum subarray sum ending at index i.

Initially, both can be considered to be "negative infinity".  At each element, these variables can be updated in constant time with the following formulas:

new_max_sum     = max{max_sum, array[i], max_end_sum + array[i]}
new_max_end_sum = max{array[i], max_end_sum + array[i]}

Readability

Code is read more than written.  Here are some tips to improve readability:

Always put a space after a comma and around binary operators.  Instead of

int c=MaxAcrossSubArray(arr,l,mid,r,sC,eC);

Use

int c = MaxAcrossSubArray(arr, l, mid, r, sC, eC);

Always put the opening and closing braces of a function body on separate lines.  Instead of

int Max(int a,int b){return (a>b)?a:b;}

Use

int Max(int a, int b)
{
    return (a > b) ? a : b;
}

Put a space after control keywords like for or if.  This helps visually distinguish them from functions and operators (sizeof, typeid, etc.).
Be consistent with indentation.  Bad example:

if(Maximum==a)
{
    Start=sA;
    End=eA;
    return a;
}

else if(Maximum==b)
    {
        Start=sB;
        End=eB;
        return b;
    }

The standard library facilities

The function Max is already available in the standard library as std::max.  For example:

std::max(42, 420) == 420
std::max({42, 420, 4200}) == 4200

(You may noticed that you need to use braces if the number of arguments is not exactly two.)

The following loop:

for(int i=Start;i<=End;++i)
{

    cout<<arr[i]<<"\t";
}

can be replaced by a call to std::copy with std::ostream_iterator.

In C++, raw C arrays are not recommended.  You are advised to use standard library containers like std::array instead.  Indexes should be of type std::size_t or std::ptrdiff_t instead of int.

Here's how the code may look like in modern C++, with iterators and tuples: (just a rough idea, not particularly optimized)

template <
    typename ForwardIt,
    typename Value,
    typename BinaryOp = std::plus<>,
    typename Compare = std::less<>
    >
std::tuple<ForwardIt, ForwardIt, Value>
maximum_subarray(ForwardIt first, ForwardIt last, Value init,
                 BinaryOp combine = {}, Compare compare = {})
{
    auto max_sum = std::make_tuple(first, first, init);
    auto max_end_sum = std::make_tuple(first, init);

    for (; first != last; ++first) {
        auto& [it, value] = max_end_sum;
        value = combine(value, *first);
        if (compare(value, *first)) {
            it = first;
            value = *first;
        }
        if (compare(std::get<2>(max_sum), value)) {
            max_sum = {it, std::next(first), value};
        }
    }

    return max_sum;
}

template <typename ForwardIt>
auto maximum_subarray(ForwardIt first, ForwardIt last)
{
    using Value = typename std::iterator_traits<ForwardIt>::value_type;
    return maximum_subarray(first, last, Value());
}


Breaking down a dollar amount into bill and coin denominations

Stylistically:

just write std:: instead of using namespace std; (which you didn't show but was implicit)
use a regular if() instead of the ternary operator ?
use compound assignment operators like dollars %= 10; instead of dollars = dollars % 10;
I'm not a big fan of end-of-line comments, but at the very least, try and put them inside the 80 column mark (most editors will show a marker)

Furthermore, it's a good exercise to make your code more general:

put the bills (1, 5, 10, 20, 50, 100) and their strings in a std::map, and write your code as a loop over that map. This way you can start to test with only small bills, and then expand to the general problem
a propos, where are your tests?


Why do you want it serialized specifically in that form? Just use the universal, built-in JSON serialization:

var serialized = JSON.stringify(myvar);
var reconstituted = JSON.parse(serialized);

Done, reconstituted is a normal object again.


Turning a Java console app into a server

General:

Commandline handling in any application is a PITA.... My recommendation is that you change both the client side, and server side, to put each argument on a different line so that you don't have to 'split' it on the Server. This would be relatively simple to do.

OOP:

This is a 'for future improvement' thing. It is a common pattern in Java for servers to handle different 'clients' in different threads. It is really easy if you have the basic infrastructure in place. Simply creating a class called "ClientManager" or something is a start, and having the following:

class ClientManager {
    private final Socket socket;
    ClientManager(Socket socket) {
        this.socket = socket;
    }

    public void processSocket() {

        // do all your things for the socket in here.

    }
}

With this simple class, your Java server becomes:

while (true) {
    // Establish a connection
    ClientManager client = new ClientManager(welcomeSocket.accept());
    client.processSocket();
}

This has some advantages. The first is that it becomes easier to separate Server problems from client problems, and the second is that the client.processSocket() can be easily moved off to any thread we want to use.

Right now, using a single thread is probably fine, but, the Error handling would be much better with this distinction. Consider the following:

try {
    while (true) {
        // Establish a connection
        ClientManager client = new ClientManager(welcomeSocket.accept());
        try {
            client.processSocket();
        } catch (Exception e) {
            // this is unusual to catch `Exception` but it is done intentionally!
            // Any exception in the client code is specific to **that** client.
            // Clients should be better behaved and manage their own exceptions
            // but no client is perfect.
            // Log the issue, and wait for the next customer.
            e.printStackTrace();
        }
    }
} catch (IOException serverexception) {
    // this is an exception in the **server** code, and thus the server dies:
    serverexception.printStackTrace();
}

OK, so we have a Server that is well isolated from the client code it runs.

The client handler

The client code is handled by a ClientManager class. What happens in there.... this is a copy/paste of the relevant code:

    BufferedReader input = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
    DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());

    // Hook System.err
    System.setErr(new PrintStream(output));

    try {
        // Run Batik as if we ran console app, but without the launch overhead
        (new Main(input.readLine().split(" "))).execute();
    } catch (Throwable t) {
        // Normally, we shouldn't get here (as Batik should not crash).
        // If we *do* get here, print to stderr, which we redirect to output stream anyway.
        t.printStackTrace();
    }

    // Let the client know how it went
    if (output.size() == 0) {
        output.writeBytes("OK");
    }

    output.close();

    // Restore stderr
    System.setErr(defaultStderr);

Now, this client/server setup is simple. It is a call-response type only, with a 'success' indicated by 'OK'. Anything else is a problem.

The protocol can be set up that the client pushes the arguments, and then closes that stream.... and then waits for results. Closing the stream has the advantage that we can read the arguments nicely (wait for end-of-stream):

List<String> arguments = new ArrayList<>();
String line = null;
while ((line = input.readLine()) != null) {
    arguments.add(line);
}

Let's introduce the Java7 try-with-resources system. This has a number of advantages, but, in this case it makes sure that, if there's a problem, the client side of the process knows immediately instead of hanging around waiting for a socket to die (get garbage collected).

Note, never catch Throwable.... it will catch all sorts of things you don't want to, like ThreadKillError, etc.

First up, we manage the input/output streams:

PrintStream defaultStderr = System.err;
try (  BufferedReader input = new BufferedReader(
           new InputStreamReader(socket.getInputStream()));
       DataOutputStream output = new DataOutputStream(socket.getOutputStream());
       PrintStream stderr = new PrintStream(output);
) {
    // at this point, the input/output is guaranteed to close
    List<String> arguments = new ArrayList<>();
    String line = null;
    while ((line = input.readLine()) != null) {
        arguments.add(line);
    }

    // Hook System.err
    System.setErr(stderr);

    try {
        // Run Batik as if we ran console app, but without the launch overhead
        Main batik - new Main(arguments.toArray(new String[arguments.size]));
        batik.execute();
    } catch (Exception t) {
        // Normally, we shouldn't get here (as Batik should not crash).
        // If we *do* get here, print to stderr, which we redirect to output stream anyway.
        t.printStackTrace();
    }

    // Let the client know how it went
    if (output.size() == 0) {
        output.writeBytes("OK");
    }
    output.flush();
} finally {
    // note, we close the socket explicitly when we are done.
    // even if the input and output are closed, you should still close the socket.
    this.socket.close();

    // Restore stderr
    System.setErr(defaultStderr);
}

note that this handling of System.err is a problem.... you will never be able to multi-thread until you fix this.

All the best, I hope this makes sense to you.


More important than the performance, your code is very likely vulnerable to SQL Injection. (I can't say for sure without looking at your PHP code)

If $viewingUserId or $userId is chosen by the user in any way, then you have a problem. And even if it is not, I would highly recommend using prepared queries.

I don't know if you're using the mysql_* methods or mysqli_* methods or the PDO extention, but you should be aware that the mysql_* methods are deprecated (That means: Don't use them) and that you should either use mysqli (note the i) or PDO.


Turning a byte array into a C# object whose type is unknown at compile time

I think, it can be simplified just a little bit:

static object Deserialize(byte[] buffer, Type type)
{
  using (StreamReader sr = new StreamReader(new MemoryStream(buffer)))
  {
    return JsonConvert.DeserializeObject(sr.ReadToEnd(), type);
  }
}

NB: StreamReader releases/disposes MemoryStream, so you don't have to encapsulate that in a using()

Or You could even do:

static object Deserialize(byte[] buffer, Type type)
{
  return JsonConvert.DeserializeObject(System.Text.Encoding.UTF8.GetString(buffer), type);
}

or:

static object Deserialize(byte[] buffer, Type type)
{
  return JToken.Parse(Encoding.UTF8.GetString(buffer)).ToObject(type);
}


Because neither row nor board.height depend on col, you could save two comparisons and an and in your getMatrixNeighbors function:

for(var row = y - 1; row <= y + 1; ++row) {
    var isInBounds = (row >= 0 && row < board.height);
    for(var col = x - 1; col <= x + 1; ++col) {
        if ( col >= 0 && col < board.width
                      && isInBounds) {
            neighbors.push(board.at(row, col));
        }
        [...]
    }
}

Note also that I removed the unneeded cell variable. It will probably not increase performance, but the code is nicer, I think.

I don't know what values x and y could possibly have, but I would assume that you can somehow save checking col >= 0 (and possibly some of the other bounds checks) each time.

You could also try to save x + 1 and board.width in a local variable to save the computation/accessing, but I would assume that either the compiler optimizes this for you, or that the introduction of an additional variable offsets the performance gain.

I don't think that getBodyDir is the bottleneck (although it would be good if you would profile this), but here you could also save the result of isSnake(top) etc in a local variable, instead of saving top as you are currently doing (top is never used anywhere except as argument for isSnake, so this would actually make sense and should result in nicer code).


Counter GUI in Swing, updating the count in the background

To answer your question:

  Q. Is this a bad idea?

A. No, it's fine in your case, but creating a new Thread is easier, like this:

private void createButton() {
    button = new JButton("Start counter");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            button.setEnabled(false); // can't click while counter is running
            Thread background = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i <= 50; i++) {
                        try {
                            Thread.sleep(100);
                        } catch(InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(i);
                        count.setText(Integer.toString(i));
                    }
                    button.setEnabled(true); //click-able after the counter ends
                }
            });
            background.start();
        }
    });
}

There are some things you can fix in your code to improve it:

Use of throws Exception in your doInBackGround method. throwing Exception is not good to use because it is vague, and unnecessary in your case. Just throw InterruptedException instead.

@Override
protected Void doInBackground() throws InterruptedException {
    //...
}

Error. This line: text.setText(Integer.toString(i)); throws an Error: "text cannot be resolved." I believe you meant to do: count.setText(Integer.toString(i));
activate() method. Make your life easier by cutting down a few lines: Just set the frame visible in your constructor, like this:

public CounterView() {
    customizeFrame();
    createMainPanel();
    createCountText();
    createButton();
    addComponentsToFrame();
    frame.setVisible(true);
}

This removes the need for your activate method completely.
Notice that if you click the button twice, then 2 counters start? I don't think you want that. disable the button after it is clicked to avoid this. Example:

private void createButton() {
    button = new JButton("Start counter");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            button.setEnabled(false); //added this line
            //...

Other than those, your code looks good. good indentation, variable names, method names, etc.


Just a small point to start:

new List<T>(new[] { itr.Current });

You don't need the array too, you can just do:

new List<T> { itr.Current };

I'd suggest that you aim for consistency with your generic type names too. Why X vs PK? I'd suggest TKey for both.

You could do it just with a foreach:

public static IEnumerable<IEnumerable<T>> Partition<T, TKey>(
    this IEnumerable<T> items,
    Func<T, TKey> keySelector,
    IEqualityComparer<TKey> comparer)
{
    List<T> currentPartition = null;
    foreach (var item in items)
    {
        if (currentPartition != null
            && comparer.Equals(keySelector(item), keySelector(currentPartition[0])))
        {
            currentPartition.Add(item);
        }
        else
        {
            if (currentPartition != null)
            {
                yield return currentPartition;
            }
            currentPartition = new List<T> { item };
        }
    }
    if (currentPartition != null)
    {
        yield return currentPartition;
    }
}

Is it clearer than your code? I'm not convinced it is.


Find the common elements of the lists in a list of lists

This problem is just a matter of folding using the intersect function of Data.List, then deduplicating the result using nub.


Converting anki-furigana to HTML-furigana without parser libraries

Building a list like ((... ++ [_]) ++ [_]) ++ [_] takes quadratic time, break doesn't.

parse :: String -> [Tag]
parse lss = case break (`elem` "[ \n") lss of
  ([],         []) -> []
  ([],     '[':ls) -> parseUpText ls
  ([],     ' ':ls) -> Blank     : parse ls
  ([],    '\n':ls) -> Newline   : parse ls
  (kana,       ls) -> Kana kana : parse ls

parseUpText :: String -> [Tag]
parseUpText lss = case break (== ']') lss of
  ([],         []) -> []
  (kana,       []) -> [Kana (' ':kana)]
  ([],     ']':ls) -> parse ls
  (uptext, ']':ls) -> Uptext uptext : parse ls


The confirmation prompt is a self-contained chunk of code with a specific purpose.  It deserves to be extracted into a function:

def confirm(prompt='Y or N: ', yes='YES', no='NO'):
    while True:
        response = raw_input(prompt).upper()
        if yes.startswith(response) and not no.startswith(response):
            return True
        elif no.startswith(response) and not yes.startswith(response):
            return False
        print "Invalid choice. Try again."

(Technically, this is more lenient than your original code, in that it accepts strings like 'yE' as a yes.  I think that's OK.)

Then, in your main program, you can write:

print "Do you want to continue to run these commands?"
if not confirm():
    print "Exiting..."
    quit()

Any call to open() should almost certainly be done using a with block.  You wrote with open('switchlist') as infile, which is good.  However, you also wrote commands = open("commands", "r") and incmd = open('commands'), neither of which you close properly.  But why are you calling incmd = open('commands') at all, when it's just supposed to be commands_to_commit?


If your intention is to let users adjust the values used for the fizz and buzz values (3, and 5), then it is possible that they may choose numbers that break your logic quite badly. For example, if they chose '3' and '3', then we would expect all multiples of 3 to be 'FizzBuzz', but, instead, only multiples of 9 would be 'FizzBuzz'. This is because you need to find the lowest common multiple (LCM) of the fizz and buzz values, not just the product of them.

Either you need to calculate the LCM, or you can do them independently using a double test like:

if ($counter % $fizzNumber == 0 && $counter % $buzzNumber == 0) {
    echo $fizzWord . $buzzWord;
....

Notice how I have also removed the redundant (...) braces you had around the conditions. The % operator has a higher precedence than == so it does not need to be elevated.


Getting a count of correct and incorrect test attempts

You don't need the second Date in your select or grouping.  Other than that, the query itself looks fine.

I'm a bit more worried about how your table is built, though.

There appear to be duplicate records.  How would you go about selecting a specific record?
Correct and Incorrect are functionally dependent: if one has 0, the other must have 1.

If you have control over the structure of this table, you may want to look into normalising it.


Graph representation using adjacency list for BFS, DFS, and Karger's algorithm

In general your code is good. There are some small issues I dislike, and there's an issue with the Adjacency list that's small too. Basically, if this was a real review, I would probably say: fine - but small things to work on next time.

Constructors

I have no reference for this, but I much prefer convencience constructors to call canonical ones. In your code, you have... hmmm, you don't have an actual canonical constructor - you can't construct with a VertextColor:

public Vertex(int label, int distance, Vertex parent) {
    this(label);
    this.distance = distance;
    this.parent = parent;
}

public Vertex(int label) {
    this.label = label;
}

Here, you have a canonical constructor (int, int, Vertex) calling a convenience one (Vertex). I would prefer the opposite, and have code like:

public Vertex(int label, int distance, Vertex parent, VertexColor color) {
    this.label = label;
    this.distance = distance;
    this.parent = parent;
    this.color = color;
}

public Vertex(int label, int distance, Vertex parent) {
    this(label, distance, parent, VertexColor.WHITE);
}

public Vertex(int label) {
    this(label, 0, null, VertexColor.WHITE);
}

This way it makes it obvious what is what, and also, the actual fields are only set in a single constructor too.... Additionally, it opens up an easier way to make the fields final, if you wanted to.

Finally, I don't like code that relies on using the not-supplied default values of declared fields, and the Canonical constructor solves that (what I mean here, is that your current constructor Vertex(int label) does not set any other fields, but relies on the default values for private int distance; and private Vertex parent;.

toStrings

Your toStrings are using string concatenations. This is not horrible, but I would prefer to see string formatting.

This code:

public String toString() {
    return "Vertex{" +
            "label=" + label +
            ", color=" + color +
            ", distance=" + distance +
            ", parent=" + parent +
            '}';
}

would be better as:

public String toString() {
    return String.format("Vertex{label=%d, color=%s, distance=%d, parent=%s}",
        label, color, distance, parent);
}

equals & hashCode

Your two methods appear to follow the equals/hashCode contract, which is great. I would suggest two changes though in each.... in the equals, you have:

public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Vertex vertex = (Vertex) o;

    if (label != vertex.label) return false;
    if (distance != vertex.distance) return false;
    if (color != vertex.color) return false;
    return !(parent != null ? !parent.equals(vertex.parent) : vertex.parent != null);

}

You should use instanceof instead of o == null || getClass() != o.getClass(). instanceof will return false for a null value, and, it is more clear what its intent is. Additionally, you should use Objects.equals(a,b). Your code could be:

public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (!(o instanceof Vertex)) {
        return false;
    }

    Vertex vertex = (Vertex)o;

    return label == vertex.label
        && distance == vertex.distance
        && color == vertex.color
        && Objects.equals(parent, vertex.parent);
}

In the hashCode method, I suspect this is auto-generated code. It's OK, but I thought there would be a way to integrate Objects.deepHashCode(...) but there may not be.

AdjacencyList

This code looks fine too. The one comment here is that I would prefer to see a more batch-oriented integer conversion of each line.

I would have a method like:

private static int[] lineToInts(String line) {
    String[] parts = line.split("\\s+");
    int[] numbers = new int[parts.length];
    for (int i = 0; i < parts.length; i++) {
        numbers[i] = Integer.parseInt(parts[i]);
    }
    return numbers;
}

If you have Java 8, I would make that:

private static int[] lineToInts(String line) {
    return Stream.of(line.split("\\s+"))
           .mapToInt(Integer::parseInt)
           .toArray();
}

Then you can simplify the other code...

Also, in this class, use printf for the toString...


Mailmerge from Excel to premade template in Word

There's no need to Call anything, it's obsolete. Instead just use Sub argument, argument.

What's this

Kill "L:\....MailMergeTEMPDB.accdb"

Is this closing the access object? Is this deleting the file? Be explicit - Kill isn't something you generally want to see in any code.

FSO.Deletefile strPath


You can use output.isEmpty() instead of checking its length.
You might want to use a LinkedHashMap which presists the order of the elements as well. Right now the ordering will be seemingly random (Will it be BuzzFizzFuzzBiffBizz? Or FizzFuzzBiffBizzBuzz?) (technically it's deterministic, but it's based on the hashcodes of the strings, which is seemingly random)
Your exception handling System.err.println(e + "Was thrown"); doesn't tell you anything about why the exception happened. I would recommend using a logger (Slf4j / Log4j) and log the exception properly, or use e.printStackTrace() to make it easier for you to debug the problems.

In your final version however, you should not need any exception handling as all the bugs that could cause them to appear should have been fixed - as this is an application based on pure logic and no network calls and stuff.
String output; // Avoid recreating String each iteration technically, the string is recreated each iteration anyway. There's nothing you can do to avoid that.

You're only declaring it once. It's best practice to declare it in a small scope as possible, so I would recommend declaring it only when you initialize it.
You could create another method to return a single string for a single number, instead of having one method to process all the 100 numbers.
// Avoid negative numbers I don't see how that comment is relevant at the location it is written. Negative numbers are prevented by the for-loop in your code.


General logic and flow

I recommend removing not x and instead just originally setting x = LOW_NO-1 for your while

x = LOW_NO - 1
while HIGH_NO < x or x < LOW_NO:

Next, I recommend you just keep the while loop instead of recursively calling getno if the user enters and invalid int. You could just use pass to tell the loop to skip onto the next loop. The old value of x will be preserved so you the condition is still true. Though I do recommend informing the user why their input was rejected.

try:
    x = int(x)
except ValueError:
    print ("That's not a valid number")

Lastly, just return x, no need for brackets.

In your approxhalf, there's no need for abs. Your LOW_NO and HIGH_NO values should prevent wildly off numbers, and if you ever want to use negative numbers there's no need to prevent it like this. I do recommend using int() here just so that it prints without decimal places, since the actual result is based on whole numbers. You also don't need to assign x just to return it. Return the value directly.

def approxhalf(lowno, highno):
    # Find integer approx halfway point between two values.
    return int(round((lowno+highno)/2))

The reason rounding has confused you is probably to do with how floats work. For example 0.1 is actually 0.1000000000000000055511151231257827021181583404541015625. This can affect rounding in cases where you think a number is x.5 but it's actually represented in memory as x.49942342341, leading to a number that rounds down instead of up.

In your checking system, I think you should rearrange the flow.

It's confusing to check if compguess is right and at the same time check if it's more than 2 off. You should do each distinct condition as it comes, my preference is to start with the correct answer and broaden out from there:

if compguess == userno:
    print('%s. I guess %s' % (count, compguess))
    print("Got it!")
    break

A note, you used while compguess != userno. But you break out of the loop for other conditions later down. I'd recommend instead using while True and then use break for the various points you actually want the loop to be over.

if abs(no2-no1) <= 2:
    # For when the low and high numbers are consecutive
    if no1 == userno:
        print('%s. I guess %s' % (count, no1))
        print("Got it")
    elif no2 == userno:
        print('%s. I guess %s' % (count, no2))
        print("Got it")
    else:
        print("ERROR: Neither %s nor %s == %s" % (no1, no2, userno))
    break

About that last else. If you're going to have a condition for a seemingly impossible situation, then you should at least output some relevant data to understand what went wrong. Also I put the break outside the if branches because it should break regardless of which condition is True. Note that now we don't need an if for the next part, we know it has to evaluate since no other condition (which would end the loop) was True.

if compguess > userno:
    no2 = compguess
elif compguess < userno:
    no1 = compguess

Style advice

Reading PEP0008 will tell you all about what I'm saying here and more. It's highly recommended reading.

You should name your functions using underscores, as that's the recommendation. So you'd have get_no(), guess_no() and approx_half(). As for variable names, CamelCase is better for compGuess and userNo.

You almost but not quite have docstrings. You have comments explaining what each function does but formatting as an actual docstring has a practical usage.

def approx_half(lowno, highno):
    """ Find integer approx halfway point between two values."""
    return int(round((lowno+highno)/2))

Enclosing the text in triple quotes when it's at the start of a function will make it a docstring, which means that people can access it in code or in the interpreter to investigate your description of it.

>>> help(approx_half)
Help on function approx_half in module __main__:

approxhalf(lowno, highno)
    Find integer approx halfway point between two values.


Should I create an empty string and append through a foreach loop or should I use StringBuilder?

Strings in C# are immutable which means that this:

 resouces += string.Format(...);

will create 2 strings: one from string.Format and then the new string created by appending it to the existing string.

A StringBuilder will just keep a list of all the strings to append and create one result string at the end when you call ToString(). So instead of 2*n strings you only create n+1 strings. The Aggregate has the same problem.

There are some optimizations in the C# compiler which can transform string + string + string + ... sequences into Append calls on a StringBuilder but you should not really rely on this.

In the end it doesn't matter too much if your strings a short. However when you hit the 85kb limit then the strings will be placed on the large object heap which can cause problems because it doesn't get compacted and you can get holes. This can lead to weird out of memory situations (you can find more with google).


Push Entity Framework exceptions to business layer

I think this is not a good idea for the following few reasons.

You write

  I don't want my business layer to know if I am using EF under my DAL.

and yet the ExecptionType enum contains all the values strictly related to Entity Framework.
Also the name of the EfResponse object already suggests it's Entity Framework related too with its Ef prefix.
Then the public class MyDbcontext : DbContext is derived from DbContext which agian is Entity Framework.

This means that the EfResponse and the MyDbcontext aren't abstract enough and they don't separate you from either Entity Framework or any other DAL. They just use different names for some EF types.

Other things that aren't implemented correctly are the two detail properties. We don't use the Get prefix for them. Only for methods. The way they work is also a little bit strange. I first need to check the type of the exception to know which property I'm allowed to use or otherwise it'll might throw. They should return null if there is no exception of this type. The only exception they are allowed to throw is the InvalidOperationException if a EfResponse object is in the Success state.

The property RowsModified should not be publically settable. This should be a part of the constructor.

Some time ago there was a question about something similar that you might find interesting: Refactoring away from exceptions. I think what you are trying to do is virtually the same. I tried it and it's a real mess when you once start using it. You're better off with a simple repository encapsulating all db operations an their exceptions.


HashMap is overkill here.

Depending on the constraints of the problem (mainly the minimum and maximum allowable years), you could simply use an array instead of a HashMap.

Sure HashMaps have a O(1) complexity, but nothing is going to beat just indexing an array.

Better algorithm

Coming up with a better algorithm is very tricky.

Your solution is O(NL) where N is the number of people and L is the average lifetime. But keep in mind that L is practically a constant, so it does not really matter that much.

You could most certainly come up with a O(NlogN) solution, based on creating a sorted list of relevant dates. This would outperform your current solution for small values of N, but better performance at the low end is rarely useful (it can be, but that's the exception, not the rule).

Edit Thinking about this, I suspect that's the "trick" part of that interview question. Overlapping intervals is a classic interview problem. However, making the intervals happen on a fully discretized space makes the hashmap solution viable, whereas it can't be used when dealing with "traditional" float-bound intervals.


Basic form to create, load and edit entries (server-sided stored in a text file)

First of all, welcome to the world of PHP. It seems you are on the right track. I have a few pointers I can give you though:

I don't know if you pasted this all together for the question, but all that code should not be in a single file. While it is fine for this 'test' page, it will very quickly become a big mess if you start building real sites or applications. There are some nice patterns you can use to structure your code. MVC is the most popular in PHP, and I would recommend looking into that.
You start of very well with your User class, but then you resort to 'old school' functions. I would recommend you go OOP all the way. You will have to use built in functions when working with php unfortunately, but all the code you write should be in classes! Better to learn it the right way from the start.
I am not sure why you wrote that show_user_radio_button function. It could just as well be inside your view (the HTML bit at the bottom). Whenever you write a function with only a single line of code, you should wonder whether it is worth putting it inside a function.
All those functions that handle reading and writing Users to and from your text file should be in a class. I would call it my UserMapper, and it would have an API that looks something like this:

class UserMapper {
    private $_users = array();

    public function getById($id) { ... }
    public function getByName($name) { ... }
    public function getAll() { ... }
    public function save(User $user) { ... }

    private function _textLineToUser($line) { ... }
    ...
}

If you ever decide to store your Users in a different way, you could create a class that implements this same interface and just replace it in your application, and all should keep working.

The way you load and save users right now is not very performant. You have to go over your entire array of users when you save or look for a specific user. It would be much better to use your id (the name in your example) as a key in your array of users. That way you can easily:

check if a user exists with array_key_exists
load a specific user with $users[$name]
update a user by just setting $users[$name] = new User($name, $info). No need to check if it exists as it will overwrite the array value automatically if that is the case.

There is probably a lot more that could be said about your code, but I leave that up to others. This should already give you some food for thought and point you in the right direction. Do feel free to ask if anything I wrote isn't clear, and happy coding!


Your function will always report that 2 and 3 are prime factors of your number.

Trial division is a fine strategy for this problem, and it can find the factors of 600,851,475,143 quite quickly.  You have to do it smartly, though.  If your main loop is for num in range(start, integer): … or for num in xrange(start, integer): …, and there's no break for that loop, then you're going to be counting up to 600 billion.

Another important detail is that when you find a factor, you should use that information to reduce the integer as much as possible.  If you do it correctly, then you won't need that inner loop for primality testing anymore.

Another useful tip is to test candidates 2, 3, 5, 7, 9, 11, 13, … — in other words, 2 followed by just the odd numbers.  You can write that as

from itertools import chain, count

for num in chain([2], count(3, 2)):
    …


The implementation is correct, but not efficient. The problem are the calls to last and init, which are both O(n), which makes the whole function O(n^2). On the other hand, lst == reverse lst is just O(n).

See Finding palindromes in a linked list.

Also the pattern

isPalindrome [a,b] = a == b

is redundant, you can omit it and let it be handled by the generic case.


You could try to write your app in callback passing style. That means methods that take a while (e.g. methods for fetching data from the web) take a callback argument that contains the code that will run once the operation is finished.

This program uses two ExecutorServices. One processes everything in one single thread. The other one runs stuff in parallel. All the code you run with the parallel ExecutorService should never access any objects that are modified by the rest of the program unless you know how to do synchronization correctly. But you don't need any synchronization at all here. Just ensure all the code that modifies the state of your program runs only in the single threaded ExecutorService and everything will be fine.
You may notice that final is used a lot in this code. That's because variables that are implicitly passed to an anonymous class need to be final.

class Tools {
  public final static ExecutorService async = Executors.newSingleThreadExecutor();
  public final static ExecutorService parallel = Executors.newFixedThreadPool(8);

  public static void shutdown() {
    Tools.async.shutdown();
    Tools.parallel.shutdown();
  }

  public static void getImageFromUrl(final String urlString, final Async<Bitmap> async) {
    Tools.parallel.execute(new Runnable() {
      public void run() {
        try {
          System.out.println(Thread.currentThread() + " - Loading image: " + urlString);
          async.send(null);
          /*
          URL url = new URL(urlString);
          HttpURLConnection connection = (HttpURLConnection) url.openConnection();
          connection.setDoInput(true);
          connection.connect();
          InputStream inputStream = connection.getInputStream();
          async.send(BitmapFactory.decodeStream(inputStream));
          */
        } catch(Exception e) {
          async.error(e);
        }
      }
    });
  }
}

abstract class Async<T> {
  abstract protected void accept(T t);
  public void send(final T t) {
    final Async<T> self = this;
    Tools.async.execute(new Runnable() {
      public void run() {
        self.accept(t);
      }
    });
  }

  public void error(Throwable err) {
    err.printStackTrace();
  }
}

class Ref<T> {
  private T value;
  public Ref(T value) {
    this.value = value;
  }
  public T get() {
    return value;
  }
  public void set(T value) {
    this.value = value;
  }
}

class Test {
  public static void main(String[] args) {
    Tools.async.execute(new Runnable() {
      public void run() {
        mainProgram();
      }
    });
  }

  private static void mainProgram() {
    final ArrayList<Movie> movies = new ArrayList<>();
    final Ref<Integer> numImages = new Ref<>(10);
    for(int i = 0; i < 10; i++) {
      final int imageNr = i;
      Tools.getImageFromUrl("http://image-website/image" + i, new Async<Bitmap>() {
        public void accept(Bitmap image) {
          System.out.println(Thread.currentThread() + " - Creating movie object for image: " + imageNr);
          movies.add(new Movie("", "", "", "", "", 0, 0, 0, image));
          numImages.set(numImages.get() - 1);
          if(numImages.get() == 0) {
            allMoviesLoaded(movies);
          }
        }
      });
    }
  }

  private static void allMoviesLoaded(ArrayList<Movie> images) {
    System.out.println("All movies loaded");
    Tools.shutdown(); //ends the program
  }
}


PEP-0008: your method names should follow snake_case style, and there should be a space between arguments. So change your method singature to:

def breadth_first_search(self, root):
    # remaining code

You maintain a list called as visited, however the nodes added in it are ones which are yet to be visited. Call it to_visit instead. One should use the variable name visited to keep track of nodes that are visited already.

to_visit = []
if root:
    to_visit.append(root)
    print( root.value)
# remainig code with to_vist replacing visited

You assign the node at the end, and pop the current node just before that. Better to do this in the beginning of the loop, and iterate over the existence of elements within the list. This way, your code gets much concise and clean:

while to_visit:
    current = to_visit.pop(0)
    if current.left:
        print( current.left.value)
        to_visit.append(current.left)
    if current.right:
        print( current.right.value)
        to_visit.append(current.right)

You pre-check and print the value of the left and right child, and that of root as well. It would be better if these statements could be reduced:

while to_visit:
    current = to_visit.pop(0)
    print( current.value)
    if current.left:
        to_visit.append(current.left)
    if current.right:
        to_visit.append(current.right)

So now, your function looks like

def breadth_first_search(self, root):
    """In BFS the Node Values at each level of the Tree are traversed before going to next level"""

    to_visit = []
    if root:
        to_visit.append(root)
    while to_visit:
        current = to_visit.pop(0)
        print( current.value)
        if current.left:
            to_visit.append(current.left)
        if current.right:
            to_visit.append(current.right)

But this gets called as t.Breadth_first_search(t.root), since root is already present, we can use a default value here. Also, the list can be initialized with an element, so we save the append call:

def breadth_first_search(self, root=None):
    """In BFS the Node Values at each level of the Tree are traversed before going to next level"""

    root = self.root if root is None else root
    to_visit = [root]
    while to_visit:
        current = to_visit.pop(0)
        print(current.value)
        if current.left:
            to_visit.append(current.left)
        if current.right:
            to_visit.append(current.right)

And now, you can call it as t.breadth_first_search().
But wait, if it is breadth_first_search, shouldn't you be searching for something? Well no, your question states to do a breadth first traversal, so you should rename your method to:

def breadth_first_traversal(self, root=None):
    # remaining code as above


Extract contiguous elements from an array in JavaScript

Remarks on the provided implementation:

The code is already well structured and easy to follow along, even though it is not immediately clear what you are actually trying to accomplish.

The chosen function, argument and variable names could be more concise. Example:

ranges.push([range.join(' '), currentOutcome]);

Here, you push a 'range' and an 'outcome' into an array of 'ranges'. So 'range' actually represents two different things which should probably have their own names:

A subsequence of reference
A pair consisting of a joined 'range' as per 1. and an 'outcome'.

Moving the while loop condition to its own function with somewhat self-documenting name withinBoundsAndSameOutcome is an interesting idea. However, it disrupts the visual parsing of your code as the reader has to jump back to the definition in order to gain a complete understanding of that loop condition. As the condition itself is pretty standard, I'd prefer inlining it.
Terminating statements with semicolons instead of relying on JavaScript's semicolon auto-insertion is the norm as it avoids some ambiguities.

Alternative implementation:

  I'm wondering if there is a more elegant way of doing this:

  I'm trying to extract contiguous elements from an outcome array and
  print their equivalent elements in a reference array.

So you already identified two tasks:

Partition an array into intervals of equal values
Map those partitions to reference values

I recommend to follow this 'natural' structure and solve these two tasks independently.

Generator functions are a great tool for untangling your seemingly interwoven code and pushing individual functionality into their own reusable, testable functions. They are especially useful when you are not interested in storing intermediate results but rather want to directly process (e.g. print) them:

// Partition array into intervals of equal values:
function* partitions(array, start = 0, next = start + 1) {
  while (next < array.length && array[start] === array[next]) next++;
  if (next <= array.length) {
    yield [start, next];
    yield* partitions(array, next);
  }
}

// Return reference strings for partitions of outcome:
function* ranges({reference, outcome}) {
  for (let [start, end] of partitions(outcome)) {
    yield [reference.slice(start, end).join(' '), outcome[start]];
  }
}

// Example:
let data = {
  reference: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
  outcome: [true, true, false, false, true, false, false, true]
};

for (let range of ranges(data)) {
  console.log(range);
}

But even without generators, your implementation could benefit from the suggested split.


What does the Bob say? (clojure version)

First, working top-down, your triggers at the top should be in sets (#{}), not vectors (you'll see why a little farther down):

(def sure-triggers
  #{"Does this cryogenic chamber make me look fat?"
    "4?"})

(def whatever-triggers
  #{"Tom-ay-to, tom-aaaah-to."
    "Let's go make out behind the gym!"
    "It's OK if you don't want to go to the DMV."
    "Ending with ? means a question."
    "1, 2, 3"})

(def chill-out-triggers
  #{"WATCH OUT!"
    "WHAT THE HELL WERE YOU THINKING?"
    "ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!"
    "1, 2, 3 GO!"
    "I HATE YOU"})

has-phrase has a couple things that can be improved:

Clojure ends predicates with a ? by convention. I'd rename it to has-phrase?.
some already returns a truthy/falsey value. (if pred? true false) is unnecessary.

Just reduce it to:

(defn has-phrase?
  "Return whether or not the given phrase is found in the collection"
  [phrase coll]
  (some #(= phrase %) coll))

BUT, now that you're using sets instead of vectors, this whole function is unnecessary:

(whatever-triggers "1, 2, 3")
=> "1, 2, 3" ; Truthy

(whatever-triggers "Not in the set")
=> nil

Sets themselves can be used as functions. If the item is in the set, they return the item back (a truthy result), else they return nil (falsey). This will also be much faster, since now you don't need to have some iterate potentially the entire vector (although obviously speed isn't a factor here). This changes reponse-for to:

(defn response-for
  "return `true` if the given phrase is found in the collection, `false` otherwise"
  [phrase]
  (cond
    (whatever-triggers phrase) whatever
    (chill-out-triggers phrase) chill-out
    (sure-triggers phrase) sure
    (= (clojure.string/trim phrase) "") fine))

This could be changed using some some trickery. some returns the first truthy value returned by its predicate. If you pass it pairs of [trigger-set response], you can iterate over the the pairs to find the first one that satisfies it, then return the response:

(defn response-for2 [phrase]
  (some (fn [[trigger-set response]]
          (when (trigger-set phrase)
            response))

        [[sure-triggers sure]
         [chill-out-triggers chill-out]
         [whatever-triggers whatever]
         [#{"" " "} fine]]))

Now, in this particular example, I wouldn't recommend doing this. It's not as clear as what you already had. I have used (some #(when ...)) before though, and it works great in some cases. I just thought I'd show you it here in case you run into a similar problem where this can be applied.

I'm sure something could be done using a map mapping triggers to responses, but I just did another Clojure review, and my brain's tapped out.


Nice solution.  This code is pretty legible, which is great if you have to debug anything.  There are a few simple ways you can make your program more user-friendly and resistant to user error.

Input:

For the user, it can be tedious to type in their values on every line, always being asked for

Num:
Operator:
Num:
Operator:
   ...

Can you use in.nextDouble() and in.next(".") to read in all of your numbers and operators at once, from a line like 10+9-7 or 10+9-7=?  in.next(String pattern) matches a regular expression, and . is the pattern for any single character.

Error Handling:

What happens if the user types in a bad operator?  If someone tries to ask for 11+10_9, the operation is ignored in this case.  Instead of getting the result of 11+10-9 = 12, they could get a result of 21 without realizing there was a mistake.  A good way to protect against that is to use a default: statement in your switch block.  A way to handle these errors and let the program or the user know there was a mistake is by writing

default: throw new IllegalArgumentException(equ + " is not a valid operator");

Object Oriented Programming:

Generally, static variables should be reserved for variables that are shared between multiple instances of a class, and any other variables should be made local or non-static.  The static variables you've defined here work properly, but reorganizing the methods and changing the variables into local ones will make it easier to add functionality to this calculator later.

public static double answer;

Rather than saving the answer in a static or object-level variable, you can return it from your functions.  This lets you keep more careful track of what makes changes to it.  Imagine if you had a lot of different functions like calculate that incrementally update the answer every time they execute.  If you started seeing the wrong answer due to a bug in the code, it could be difficult to trace it to the broken function.

To handle answer the object-oriented way, rename main() to whatever you like, change both of your functions from void to double type, and return the partial answer and the end answer from each of them, handling them locally.  You can make a new main() that calls your renamed function and handle the printing of the answer in main() instead of the function that does the work.

public static boolean done = false;

done is never actually changed or used.  while(true) is functionally equivalent to the loop that you wrote.  This is a fairly common pattern, and there are a few ways to go about organizing it.  Yours is handy because the variable done communicates that this loop will continue until something is 'done'.  The best place to explain to the reader how a while() loop is supposed to terminate is right there in the condition.

One more descriptive (but also less clean) way to write that condition would be

String operand;
while((String operand = in.nextLine()) != '='){

This assigns the operator to operand and performs the comparison without the need for a break statement.  You can use a do-while loop to handle the first number and print "Operator: " to the console before reading operand, if you like.

public static Scanner in = new Scanner(System.in);

This is often tolerated as a static variable, since we're very unlikely to change the fact that we're reading from System.in in the middle of our calculations.  On the other hand, in doesn't need to be static, and since it's a resource that should be closed when we're done with it, the best practice is to make it a local variable or manage it carefully as needed.  The object-oriented approach is to use a loosely-coupled function like readExpression() for your input, and then let all of the calculation happen in a different function.

You might also want to be consistent with your arguments in

public static void calculate(double num1, String equ, Double num2){

double is a primitive type, while Double is a class.  That distinction won't cause a logical error here, but consistency always helps when a program grows larger and more complex.

Order of Operations:

Your program handles each step of the calculation correctly, but it doesn't understand Order of Operations.  That's a more complex concept that you'll have to look at a whole expression for instead of being able to handle each operation piece by piece.

The fully object-oriented solution is to treat the expression and the individual operations as their own objects and apply logic to those objects piece by piece.  You could, for instance, create a list of numbers and operations, and scan through that list, applying the highest-priority (multiplication and division in this case) operations first.

The fully functional solution is to scan the expression and use recursion to decide which numbers need to into calculate() first, returning the results of each calculate() step up until the base function returns the final answer.

There are many ways to do it, and you can think about how you'd like to implement it in your calculator


Dijkstra's algorithm is slow. (For loops)

As most of the detail needed to workout what is going on, is missing, (See my comment on question) one can only review what one can see.
Your request to resolve laggy code is impossible to address without makes a lot of guesses.
Bugs.
There is no path through the function pathfindLoop that does not call its self. This will cause you problems, however your intent is unclear and the exact nature of the problem depends on your intent.
Unclear awaiting
When you call sleep you await it.
However the recursive call pathfindLoop() is not awaited. It is completely unclear if this is an error only your part (a bug) or deliberate (a problem).
Oh... the infinity of it all
Your function will crash the page as your code does not allow the call stack to pop calls when exiting pathfindLoop
To call pathfindLoop means an infinite list of calls to self.
Guessing your intention one could see this as a way of creating an ongoing polling like system (similar to setInterval or an animation loop using requestAnimationFrame). Wait 10 (what ever's) then process data and repeat.
If this is your intention it is very flawed as you fail to take into account the call stack.
Each call to pathfindLoop adds a new context to the call stack. Each promise creates a new entry on the promise stack.
As the function is async the context can not be removed from the stack until the context of async calls it has made, are resolved. This will never happen and eventually calling pathfindLoop will crash the page, well before that the page will become very unresponsive (laggy).
Maybe this is the lag you mention in your question. Though without further details one can only guess.
General points
Further points noticed when reviewing the code.

Poor naming.

JS convention is not to use snake_case for variable names. It is generally only used in js when defining names in UPPERCASE_SNAKE

Inconsistent use of semicolons.

Odd placement of semicolon. You have a semicolon at the end of an if clause. eg if (foo); {... the semi colon is ignored, but one is left to wonder as to your intent here?

Too heavily reliant on higher scope. Particularly because you mutate pgrids, and realPgrids. This may or may not be bad but again without further information one can only guess.

Unclear use of higher scoped or undefined variables. Is the variable build defined??? Will adding "use strict" to your code cause it to crash??

Unsafe use of for...in loops. In modern JS there really is no reason to use for...in  loops. Rather use for...of  loop
Example of using for of rather than for in. From your code...

for (build in builds) {
    if (dist4(builds[build][1], builds[build][2], res.x, res.y) < GRID_SPREADING.b_col) {
        go = false;
        break;
    }
 }

Assuming builds is an object
  for (const build of Object.values(builds)) {
      if (dist4(build[1], build[2], res.x, res.y) < GRID_SPREADING.b_col) {
          go = false;
          break;
      }
  }

Or assuming builds is an array
  for (const build of builds) {
      if (dist4(build[1], build[2], res.x, res.y) < GRID_SPREADING.b_col) {
          go = false;
          break;
      }
  }

  // OR

  go = builds.every(build => dist4(build[1], build[2], res.x, res.y) >= GRID_SPREADING.b_col);

ref to Array.every

Rewrite??
I can not fully rewrite your code as I can not code unknown details.
The rewrite will address the call stack problem and assumes pathfindLoop to be akin to a polling function.
"use strict"; // Always use this directive.

const pathfindLoop = () => { // do not use async here
    // ... the rest of your code here

    setTimeout(pathfindLoop, 10); // assumes 10 from sleep(10); is ms
}

Refs

strict_mode
setTimeout


Joining and resolving two paths while keeping them relative conditionally

You can use the System.IO.Path.Combine Method.

  This method is intended to concatenate individual strings into a single string that represents a file path. However, if an argument other than the first contains a rooted path, any previous path components are ignored, and the returned string begins with that rooted path component.

$combined = [IO.Path]::Combine($Base, $Chained)

Also, it seems more natural to use System.IO.Path.IsPathRooted() method instead of Split-Path to see if the path is absolute.

$isRelative = ![IO.Path]::IsPathRooted($combined)

There is a way to pass parameter values by appending a colon after the parameter name in cmdlet. You can also pass values to the switch type parameter this way.

Verb-Noun -ParameterName:Value

Resolve-Path basically outputs a PathInfo object, but when the -Relative switch is set the output will be string.
Both types have a ToString () method, so you can get a path string without using an if statement. (The ToString() method of the PathInfo object outputs the value of the Path property)

function Chain-Path($Base, $Chained) {
    $combined = [IO.Path]::Combine($Base, $Chained)
    $isRelative = ![IO.Path]::IsPathRooted($combined)
    (Resolve-Path $combined -Relative:$isRelative).ToString()
}


Unit Testing Datalayer written in ADO.net

I think this ID should be generated at database level (autoincrement). But let's ignore this, for testing you have to make sure your methods do not have a dependency on eachother.

It would be better if you write it like this

public void DoSomething(long someValue, long id)
{
     // Insert new value
}

public long GetInsertId()
{
     // Return ID
}

Now you can test these methods independently

public void GetInsert_ShouldReturnNewId()
{
     // Your requirements for a new ID should be tested here
}

public void DoSomething_ShouldInsertNewRecord()
{
    var sut=new ConcreteImplementation();
    var id = sut.GetInsertId();

    sut.DoSomething(13, id);
}

By using this approach the developer MUST provide an ID. The developer can obtain an ID by calling your new method. Just keep in mind that if you want to make your code more testable you have to make your methods independant. They must work on there own.


Iterating through each grid row and matching elements to largest height

Can't say if this is much faster, but it's more concise

jQuery(document).ready(function($) {
    "use strict";

    var firstItems = $('.item.first');

    firstItems.each(function() {
        var $first, row, headings, heights, maxHeight;

        $first = $(this);

        // Get collection of "columns"
        row = $first.add($first.nextUntil(firstItems));

        // Find each column's heading
        headings = row.find("h2");

        // Get the heights of the headings
        heights  = headings.map(function () {
            return $(this).outerHeight();
        }).toArray();

        // Get the maximum
        maxHeight = Math.max.apply(null, heights);

        // Set the heading heights to the maximum
        headings.css("height", maxHeight);
    });
});

--Edit--

In my particular instance, the above script had conflict issues with prototype, since it lives inside a Magento install. I sought help and found this improvement.

/Jezen


Creating a count inversion array of an unsorted array of unique integers

Thanks for an interesting, well-posed question.  Before we get to issues of performance, let me make some other suggestions for your code.

The way you have broken down the code into three functions is reasonable and logical.  Nice!
The functions you wrote don't have docstrings, so it is hard to know how to use them.  I couldn't get your count_inversion() function to run initially, for example, because I didn't know what N was supposed to be.  Adding docstrings would make this clear.
For the specific case of the N parameter in count_inversion, why do you need it?  When I used the function I did it like this:

arr = [2, 3, 1, 4]
arr2 = [2, 1, 4, 3]
arr3 = [20]
arr4 = [1, 2, 3, 4, 5, 6]
arr5 = [87, 78, 16, 94]

arrs_to_test = [arr, arr2, arr3, arr4, arr5]

[count_inversion(test, len(test)) for test in arrs_to_test]

That to me suggests that you don't need N as a parameter, instead just do something like:

def count_inversion(arr):
    # docstring goes here
    N = len(arr)
    # <<rest of code>>

I usually dislike when people are sticklers for PEP8 variable-naming conventions in mathematically oriented code, but I think your naming could use some work.  For example I had to read dct = {i:0 for i in arr} multiple times to understand that i was not an index but the data.  So dct = {el:0 for el in arr} would have been more natural to me.  Plus dct isn't the best name either.  If I understand the code correctly, perhaps result would be better?
Possible bug: Related to the above, do you really want to create a dictionary keyed on the elements of arr?  Doing so means that the behavior when integers are repeated in the input is probably not what you want:

>>> repeated = [3, 2, 1, 0, 3, 4, 5]
>>> count_inversion(repeated, len(repeated))
 '3 2 1 0 3 0 0'

Is the fifth element in this array really supposed to be "3"?
Right now the code functions because of the mutability of dct.  I'm not 100% sure it could be done cleanly, but if possible I'd suggest re-writing merge_sort and merge to return dct instead of returing None.  That way the initialization of dct could happen in those functions too, which feels more natural to me.
You are using your (mysteriously named) dct variable in a way that looks like a Counter, so you might consider using this built-in datatype of Python.
Now, to issues of performance.  In Python, line-profiler is an easy to use package for assessing the performance of your code.  I use this package in a Jupyter notebook like this:

from random import randint
%load_ext line_profiler

big_test = [randint(0, 10000) for _ in range(1000)]
%lprun -f count_inversion -f merge_sort -f merge count_inversion(big_test, len(big_test))

The output of this operation is at the end of my answer.  It shows that you are right, and the slowest part of the operation is indeed the nested for loops in merge().
Dictionaries, unlike lists, can't be mutated using slice notation.  The only reason you need the for x in xrange(index, left_hi+1): nested loop is because you can't change whole swaths of the dictionary at once.  With lists, you can.  Thus, if you agree that the possible bug I described above is in fact a bug, you can switch to storing the output values in a list instead of a dictionary, and get rid of the nested loop.  The speedup is very small for short input arrays but grows with array size.  On my machine it led to a ~2-10× improvement at input arrays of 10,000 elements.  I'll put the output of my line profiling below too.
Using numpy for applications like this makes sense because python doesn't have a mutable fixed-type data structure.  Interesting, using numpy only to represent the dct variable in your original code, while leaving in place all other for loops, speeds up the execution another 2× or so for lists of 10,000 elements.

for index in res:
        sublist_length = left_hi+1 - index
        out[index:left_hi+1] += np.ones(sublist_length, dtype = int)

Original code timing

from random import randint
big_test = [randint(0, 100) for _ in range(10000)]
%lprun -f merge count_inversion(copy(big_test), len(big_test))

Results in:

Timer unit: 1e-06 s

Total time: 26.9413 s
File: <ipython-input-1-77a541281305>
Function: merge at line 4

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     4                                           def merge(arr, left_lo, left_hi, right_lo, right_hi, dct):
     5      9999         4407      0.4      0.0      startL = left_lo
     6      9999         4315      0.4      0.0      startR = right_lo
     7      9999         5812      0.6      0.0      N = left_hi-left_lo + 1 + right_hi - right_lo + 1
     8      9999         8330      0.8      0.0      aux = [0] * N
     9      9999         4401      0.4      0.0      res = []
    10    143615        72509      0.5      0.3      for i in range(N):
    11
    12    133616        60250      0.5      0.2          if startL > left_hi:
    13      5778         2956      0.5      0.0              aux[i] = arr[startR]
    14      5778         2700      0.5      0.0              startR += 1
    15    127838        57380      0.4      0.2          elif startR > right_hi:
    16      7503         3822      0.5      0.0              aux[i] = arr[startL]
    17      7503         3507      0.5      0.0              startL += 1
    18    120335        64095      0.5      0.2          elif arr[startL] <= arr[startR]:
    19     61505        31935      0.5      0.1              aux[i] = arr[startL]
    20     61505        28853      0.5      0.1              startL += 1
    21                                                       # print aux
    22                                                   else:
    23     58830        30780      0.5      0.1              aux[i] = arr[startR]
    24     58830        34221      0.6      0.1              res.append(startL)
    25     58830        28077      0.5      0.1              startR += 1
    26                                                       # print aux
    27
    28     68829        35529      0.5      0.1      for index in res:
    29  24750922     11838525      0.5     43.9          for x in range(index, left_hi+1):
    30  24692092     14464132      0.6     53.7              dct[arr[x]] += 1
    31
    32    143615        76619      0.5      0.3      for i in range(left_lo, right_hi+1):
    33    133616        73794      0.6      0.3          arr[i] = aux[i - left_lo]
    34      9999         4362      0.4      0.0      return

Improved Code Timing (list slicing)

Timer unit: 1e-06 s

Total time: 3.11468 s
File: <ipython-input-2-224c772db490>
Function: new_merge at line 4

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     4                                           def new_merge(arr, left_lo, left_hi, right_lo, right_hi, out):
     5                                               # docstring goes here
     6      9999         4566      0.5      0.1      startL = left_lo
     7      9999         4491      0.4      0.1      startR = right_lo
     8      9999         6601      0.7      0.2      N = left_hi-left_lo + 1 + right_hi - right_lo + 1
     9      9999         7904      0.8      0.3      aux = [0] * N
    10      9999         4571      0.5      0.1      res = []
    11    143615        69607      0.5      2.2      for i in xrange(N):
    12
    13    133616        62294      0.5      2.0          if startL > left_hi:
    14      5778         3044      0.5      0.1              aux[i] = arr[startR]
    15      5778         2804      0.5      0.1              startR += 1
    16    127838        59349      0.5      1.9          elif startR > right_hi:
    17      7503         3945      0.5      0.1              aux[i] = arr[startL]
    18      7503         3673      0.5      0.1              startL += 1
    19    120335        67720      0.6      2.2          elif arr[startL] <= arr[startR]:
    20     61505        33280      0.5      1.1              aux[i] = arr[startL]
    21     61505        30419      0.5      1.0              startL += 1
    22                                                       # print aux
    23                                                   else:
    24     58830        31818      0.5      1.0              aux[i] = arr[startR]
    25     58830        34578      0.6      1.1              res.append(startL)
    26     58830        28988      0.5      0.9              startR += 1
    27                                                       # print aux
    28
    29     68829        37996      0.6      1.2      for index in res:
    30     58830        31690      0.5      1.0          sublist_length = left_hi+1 - index
    31     58830       164834      2.8      5.3          ones = [1]*sublist_length
    32     58830      2264227     38.5     72.7          out[index:left_hi+1] = map(add, out[index:left_hi+1], ones)
    33
    34    143615        73228      0.5      2.4      for i in xrange(left_lo, right_hi+1):
    35    133616        78612      0.6      2.5          arr[i] = aux[i - left_lo]
    36      9999         4440      0.4      0.1      return

Improved Code Timing (numpy)

Timer unit: 1e-06 s

Total time: 0.979072 s
File: <ipython-input-33-e2db83e49c93>
Function: d_merge at line 4

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     4                                           def d_merge(arr, left_lo, left_hi, right_lo, right_hi, out):
     5                                               # docstring goes here
     6      9999         4439      0.4      0.5      startL = left_lo
     7      9999         4360      0.4      0.4      startR = right_lo
     8      9999         5728      0.6      0.6      N = left_hi-left_lo + 1 + right_hi - right_lo + 1
     9      9999         8283      0.8      0.8      aux = [0] * N
    10      9999         4511      0.5      0.5      res = []
    11    143615        69717      0.5      7.1      for i in xrange(N):
    12
    13    133616        62436      0.5      6.4          if startL > left_hi:
    14      5778         2955      0.5      0.3              aux[i] = arr[startR]
    15      5778         2779      0.5      0.3              startR += 1
    16    127838        59843      0.5      6.1          elif startR > right_hi:
    17      7503         3916      0.5      0.4              aux[i] = arr[startL]
    18      7503         3645      0.5      0.4              startL += 1
    19    120335        66024      0.5      6.7          elif arr[startL] <= arr[startR]:
    20     61505        32834      0.5      3.4              aux[i] = arr[startL]
    21     61505        29695      0.5      3.0              startL += 1
    22                                                       # print aux
    23                                                   else:
    24     58830        31913      0.5      3.3              aux[i] = arr[startR]
    25     58830        34546      0.6      3.5              res.append(startL)
    26     58830        28552      0.5      2.9              startR += 1
    27                                                       # print aux
    28
    29     68829        36887      0.5      3.8      for index in res:
    30     58830        31918      0.5      3.3              sublist_length = left_hi+1 - index
    31     58830       303818      5.2     31.0              out[index:left_hi+1] += np.ones(sublist_length, dtype = int)
    32
    33    143615        72165      0.5      7.4      for i in xrange(left_lo, right_hi+1):
    34    133616        73672      0.6      7.5          arr[i] = aux[i - left_lo]
    35      9999         4436      0.4      0.5      return

Note:

All the code I used (both mine and the original) is in a Jupyter notebook hosted at GitHub.


You could just do both operations inside the anonymous function (that you are sending as third parameter).

$('body').on('click', 'img', function() {
   modal(content[$('li.active a').attr("href")].images[$("img").index(this)]);
   closeM();
});

Also, I would consider simplifying the first instruction by breaking it down into smaller pieces.
All compressed together as it is, it is some serious black magic and should be quite tough to read or maintain by anyone else.

But $("body").on("click", "#close", closeM); is very simple, and also much more contained because it applies to the only element with id #close in the HTML, instead of to all the images. So I would prefer to leave it separate.


You maintain old_url as well as past_links. You probably don't need old_url at all because everything you process will be added to past_links.

You are reading past_links as one giant string with embedded newlines. That won't be very efficient when doing clipboard not in past_links because it will have to search through the whole string.

When you run past_links += clipboard, you are sticking the data on to the end of past_links with no newline at the end, so new links added there will be jammed together.

You should probably set up past_links as a set, and use set operations. You can still read and write it as a plain text file.

You create a new thread for each download request, which will download multiple files in parallel. It's not clear that is what you really want to do.

Your use of a recursive call to get_image() is a very strange way to implement a loop.

You are reading the entire download into memory in one giant string, and then writing it out to disk. If you were to download a very large file, your script would require a corresponding amount of memory during downloading. Use urllib.urlretrieve to read directly into a file.

Use clipboard.startswith("http") instead of clipboard[:4] == "http"

Finally, use the standard Python Queue module instead of implementing your own:

The Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads.


Typesetting A* in LaTeX using algorithm2e - follow-up

Nice.  I mean if you're going for perfection I'm going to write
something but otherwise that looks really good.

The
documentation for algorithm2e
mentions that every line should be terminated with \; - and then has
a flag to disable showing that semicolon, \DontPrintSemicolon - take
that how you will.  At least Emacs highlights that less garishly than
the forced newline.
The variables could be marked via \SetKwData.  If you want to keep
the same style, modify it via \SetDataSty{textnormal}.  Similarly
for the functions via \SetKwFunction.
The style for the captions could also just be set to smallcaps
globally via \let\AlCapNameSty\textsc (works and should be correct,
but I'm not a \$\LaTeX\$ expert by any means.
Also there's the procedure environment (instead of algorithm) that
has some more shortcuts.  Note that I added procnumbered and
\SetAlgoProcName to set the names and numbering back to what is the
default algorithm settings.

Looks like this:

\documentclass[10pt]{article}

\usepackage{amsmath}
\usepackage[ruled,vlined,linesnumbered,procnumbered]{algorithm2e}

\SetArgSty{textnormal} % Make the While argument non-italic
\SetDataSty{textnormal}
\SetFuncSty{textsc}
\let\AlCapNameSty\textsc
\DontPrintSemicolon
\SetAlgoProcName{Algorithm}

% Define special keywords.
\SetKw{Nil}{nil}
\SetKw{Is}{is}
\SetKw{Not}{not}
\SetKw{Mapped}{mapped}
\SetKw{In}{in}
\SetKw{ChildNode}{child node}
\SetKw{Of}{of}
\SetKw{Continue}{continue}

\SetKwData{Open}{OPEN}
\SetKwData{Closed}{CLOSED}

\SetKwFunction{ExtractMinimum}{ExtractMinimum}
\SetKwFunction{TracebackPath}{TracebackPath}
\SetKwFunction{Insert}{Insert}
\SetKwFunction{DecreaseKey}{DecreaseKey}

\begin{document}

% A*.
\begin{procedure}
        $\Open = \{ s \}$ \;
        $\Closed = \emptyset$ \;
        $\pi = \{ (s \mapsto$ \Nil $)\}$ \;
        $g = \{ (s \mapsto 0) \}$ \;
        \While{$|\Open| > 0$}{
        $u = \ExtractMinimum(\Open)$ \;
        \If{$u$ \Is $t$}{
            \KwRet \TracebackPath{$u$, $\pi$} \;
        }
        $\Closed = \Closed \cup \{ u \}$ \;
        \ForEach{\ChildNode $v$ \Of $u$}{
            \If{$v \in \Closed$}{
            \Continue \;
            }
            $c = g(u) + w(u, v)$ \;
            \If{$v$ \Is \Not \Mapped \In $g$}{
            $g(v) = c$ \;
            $\pi(v) = u$ \;
            \Insert{\Open, $v$, $c + h(v)$} \;
            }
            \ElseIf{$g(v) > c$}{
            $g(v) = c$ \;
            $\pi(v) = u$ \;
            \DecreaseKey{\Open, $v$, $c + h(v)$} \;
            }
        }
        }
        \KwRet $\langle \rangle$
        \caption{AStarPathFinder($s$, $t$, $w$, $h$)}
\end{procedure}

% Traceback path.
\begin{procedure}
        $p = \langle \rangle$ \;
        \While{$u$ \Is \Not \Nil}{
        $p = u \circ p$ \;
        $u = \pi(u)$ \;
        }
        \KwRet $p$
    \caption{TracebackPath($u$, $\pi$)}
\end{procedure}

\end{document}


Refactoring a collection of if statements that contain 2 arguments.

We can start looking at what is duplicated.  For example, the only difference between the two blocks of code is the string "Color1" and "Color2" in the if statement, and the variable new_colour1 which is replaced with new_colour2.

From here I'd suggest something like the following:

//This should be declared once - e.g. class level not method level.
var colorDict = new Dictionary<string, NewColorType>
                    {
                        {"Colour1", new_colour1},
                        {"Colour2", new_colour2}
                    };
NewColorType newColor;
if(start_time > look_at_time && colorDict.TryGetValue(hit.collider.gameObject.tag, out newColor))
{
   newColor.ChangeObjectMaterialColour(hit.collider.gameObject.renderer.material.color);
   var colums = GameObject.FindGameObjectsWithTag("column");
   foreach( GameObject c in colums)
      c.GetComponent<MeshRenderer>().materials[1].color = newColor.orignalMaterial;
}


Here are some things I see that may help you improve your code.
Shouldn't a compressed file be smaller?
Imagine my surprise when I discovered that a 2037-byte file (the lzw.cpp source code itself) became 3524 bytes when "compressed!"  The original LZW algorithm encoded 8-bit values into 12-bit codes.  This appears to be encoding 8-bit values as 32-bit codes which is unlikely to offer much compression for short files like this.  I did, however, try it on the plain text version of Bram Stoker's Dracula and, as expected, the resulting file was about 75% of the size of the original.  Because it's a stream and you don't have access to the length of the source, there may not be much you can do about it, but it's probably a good thing to warn potential users about.
Rethink the interface
In order to use the compression, one must first create an object and then use it, perhaps like this:
lzw::lzw_encoder lzw(in, out);
lzw.encode();

Wouldn't it be nicer to just be able to do this?
lzw::encode(in, out);

Write member initializers in declaration order
The lzw_encoder class has this constructor
lzw_encoder::lzw_encoder(std::istream &is, std::ostream &os)
    : is(is), os(os), current_code(0) {
  for (current_code = 0; current_code < 256; ++current_code) {
    codebook[std::string(1, static_cast<char>(current_code))] = current_code;
  }
}

That looks fine, but in fact, current_code will be initialized before is and os because members are always initialized in declaration order and current_code is declared before is in this class. To avoid misleading another programmer, you could simply omit current_code since it is already initialized by the declaration:
uint32_t current_code = 0;

Use standard algorithms where appropriate
Initializing the codebook uses this:
for (current_code = 0; current_code < 256; ++current_code) {
  codebook[std::string(1, static_cast<char>(current_code))] = current_code;
}

This can be improved in a number of ways.  First, we already know how large the codebook will be so we can reduce the number of memory reallocations by telling the compiler that information:
codebook.reserve(256);

Next, we can avoid the cast and gain a bit of efficiency by using emplace:
for (current_code = 0; current_code < 256; ++current_code) {
    codebook.emplace(std::string(1, current_code), current_code);
}

I'd also recommend replacing 256 here with a static constexpr initial_codebook_size.
Beware of endian-ness differences
The code currently contains these lines:
auto code_val = codebook[current];
os.write(reinterpret_cast<char *>(&code_val), sizeof(code_val));

There problem is that depending on whether this is a big-endian or little-endian machine, the encoding will be different.  If the compressed stream is intended to be sent to a different machine, this needs to be consistent.  Consider using something like the POSIX htonl function here.
Consider restructuring loops
The problem with while(true) is that it hides the loop exit condition.  Instead of this:
while (true) {
    is.read(buffer, ENCODER_BUFFER_SIZE);
    auto read_length = is.gcount();
    if (read_length == 0)
      break;
    // etc
}

Consider something like this:
while (is.read(buffer, ENCODER_BUFFER_SIZE)) {
    // handle full block
}
if (is.gcount()) {
    // handle final partial block
}

Understand the use of streams
It's possible that the caller has set one or both streams to throw an exception on encountering a failure such as end of file on read.  Either override this or handle it appropriately.
Consider adding convenience functions
The handling of blocks for encode and for decode could both be made into functions within the namespace.  This would make the restructuring of loops as mentioned above a bit easier and cleaner and would isolate the handling of the data structures from basic stream I/O.  That may make things a bit easier when you convert to a trie.  Here's my rewrite of the loop:
while (is.read(buffer, ENCODER_BUFFER_SIZE)) {
  encode_buffer(buffer, ENCODER_BUFFER_SIZE);
}
encode_buffer(buffer, is.gcount());