GC the Software Engineer

Code, algorithms and more

  • Home
  • About

Beating the Game of Go

Posted by Guillaume Croteau on February 20, 2016
Posted in: AI. Leave a comment

Well, there it is, it was just a matter of time, Google may have been able to create a program that masters the game of Go. The program, called AlphaGo, will try to replicate the triumph of Deep Blue, the first computer program that defeated the world master of chess, Garry Kasparov. AlphaGo will face the undisputed champion of the game of Go of the past decade, Lee Sedol, on March 9th-15th in Seoul.

If it were to defeat the champion, it will succeed where every other programs have failed. It will also mean that it has mastered one, if not the last game that humans were better than computers.

You want to know more? Go see Google’s announcement: http://deepmind.com/alpha-go.html

How to Add Variables to a String in JavaScript

Posted by Guillaume Croteau on December 12, 2015
Posted in: Web Development. Tagged: JavaScript. Leave a comment

The majority of modern programming languages offer the possibility to add variables to a string. For example, in Python, you can do the following.

s = "The number %d has been added to the string." % 5

If you want to do the equivalent in JavaScript, you will have to either create your own string parser, or use Template strings. Those are template literals allowing embedded expressions. To create a Template string, you simply have to use the grave accent (`) instead of the single or double quote around your string.

So, to reproduce the example above in its JavaScript equivalent, we would have something like this:

var myNumber = 5;
var s = `The number ${myNumber} has been added to the string.`

You can check out the documentation on Template strings here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/template_strings

How to Watch DOM Mutations

Posted by Guillaume Croteau on December 2, 2015
Posted in: Web Development. Tagged: DOM, JavaScript. Leave a comment

Lets say that you want to watch DOM mutations. How would you do that?

A DOM mutation is any change that can happen to the DOM.

Well, you can use MutationObserver. With this, you will be able to react to the DOM changes.

How about we do a little example? Lets say that a third party library adds a DOM element that has a specific class. You can’t predict at what point the element will be added, but you have to do some special treatment when it is added. The code to do that would look like this:


// Declare your observer
var mutationObserver = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        mutation.addedNodes.forEach(function(node) {
            if (node.className && node.className.indexOf('the-class-we-look-for') > -1)) {
                // Do the treatment when the element is added to the DOM

                // Stop to observe now or later
                // mutationObserver.disconnect();
            }
        }
    });
});

// ... Later, start to observe ...
var target = document.querySelector('#where-the-element-will-be-added');
var config = { attributes: true, childList: true, characterData: true };
mutationObserver.observe(target, config);

// ... Later, stop to observe ...
mutationObserver.disconnect();

You need to specify what is your target, in our case, it would be the element where the element we are looking for will be added. You also have to pass a config object. The three attributes listed above have to be set to true, otherwise an error will be thrown. You can find a list of all the available options right here: https://developer.mozilla.org/en/docs/Web/API/MutationObserver#MutationObserverInit.
On a final note, don’t forget to stop the observer at some point. Otherwise it will stay alive indefinitely.

For more details on MutationObserver, you can check out https://developer.mozilla.org/en/docs/Web/API/MutationObserver.

Keep Yourself Up to Date with Feedly!

Posted by Guillaume Croteau on October 31, 2015
Posted in: TheMoreYouKnow. Leave a comment

I don’t know about you, but I always had a hard time to follow all of the podcasts, blogs, news websites, whatever, that I am interested in. Yes you can subscribe to newsletters or the like, but let’s face it, with the number of emails we receive every day, it is hard to manage all that information. So you are left to manually look out if there is new stuff on the websites you are interested in.

Well, I recently discovered Feedly, and as far as I can tell, it efficiently solves this problem. You go there, you subscribe to any podcasts, blogs, or anything that you want to follow, and it will put them all in a single feed that you can easily follow. You can organize your feeds into categories, discover new feeds, and more.

So I suggest you take a look at it if you haven’t already, it is worth the try!

http://feedly.com

How to Find a Point on a Line Given a Point and a Distance

Posted by Guillaume Croteau on October 3, 2015
Posted in: Math. Leave a comment

I faced a little mathematical challenge recently. It is as follow:

Given a line with a known equation, a point (x_a, y_a) and a distance d, find the coordinates of the point (x_b, y_b) that is at a distance d from (x_a, y_a).

You can find (x_b, y_b) with this solution:

The equation of the line is:

y=mx+c

Which is equivalent to:

y=m(x-x_0)+y_0

The trick here is to use the circle formula:

x^2+y^2=r^2

In our case, the center of the circle is (x_a, y_a) and the radius is the distance d. Using this formula, we are able to find x_b. After that, it is as simple as using the line formula to find y_b.

Let’s start by finding x_b.

x^2+y^2=r^2
(x_b-x_a)^2+(y_b-y_a)^2=d^2
(x_b-x_a)^2+m^2(x_b-x_a)^2=d^2 \text{ (Replace with the line formula)}
(x_b-x_a)^2(1+m^2)=d^2
(x_b-x_a)^2=d^2/(1+m^2)
x_b = x_a + d/\sqrt(1+m^2)

Now that we have x_b, we can find y_b by using the line formula:

y_b = mx_b+c

And there you go, you have found (x_b, y_b)!

How to Mock a Static Method in Java

Posted by Guillaume Croteau on September 7, 2015
Posted in: Unit Testing. Tagged: Java, PowerMock. Leave a comment

As you know, at the time of writing, mainstream java mock libraries such as Mockito or EasyMock cannot mock static methods, final classes, constructors, etc. These limitations sometime force us to put aside good design for test implementation. Fortunately, there is a library called PowerMock that leverages the Mockito and EasyMock libraries. It allows us to do some very useful things, such as mocking a static method.

Please note that, since developers have much more liberty using PowerMock, putting it in the hands of inexperienced ones can be harmful for the design.

So, lets see how we can mock a static method using JUnit, Mockito and PowerMock.

Lets say that we have a deck of cards and we want to implement a method that shuffles the deck. Pretty simple right? We just have to call Collections.shuffle on the List that contains the cards.

public class Deck {
	private List<Card> cards;

	//… Class implementation …

	public void shuffle() {
		Collections.shuffle(this.cards);
	}
}

How do we test that?

Note: For the purpose of explanation, I think it is easier to understand if I show you first the production code. That being said I highly recommend you to practice TDD IRL 🙂

Note 2: You will see that I only test that the Collections.shuffle method is called, not that the list of cards is shuffled. This is bad, since it does not properly checks the wanted behavior. But I wanted to come up with a simple example. If you want to test that elements are not in the same order, you should use Hamcrest.

If we could mock static methods with Mockito, we would have something like this:

public class DeckTest {
	@Test
	public void givenADeckOfCards_whenTheDeckIsShuffled_thenTheCardsAreShuffled() {
		// given
		Deck aDeck = new Deck();

		// when
		aDeck.shuffle();

		// then
		Mockito.verify(Collections).shuffle(Mockito.anyListOf(Card.class)); // Doesn’t work
	}
}

Lets see how we can do this with PowerMock.

First you need to tell JUnit to run PowerMock’s runner instead of the one built into JUnit.

Second, you need to prepare the class that uses the static method calls. Therefore, if we were testing a class that implements a static method, we would write its class definition here. In our case, we test a class that uses a static method that comes from another class. For this reason we must specify the class that uses the static method. (Hopefully this will save you some troubles, I lost too much time on that detail ..).

After that, you are ready to write your test: mock the class that has the static method, verify that it has been called and tell PowerMock the expected method call.

@RunWith(PowerMockRunner.class) // Use PowerMock’s runner
@PrepareForTest({Deck.class}) // Prepare the class that calls a static method
public class DeckTest {
	@Test
	public void givenADeckOfCards_whenTheDeckIsShuffled_thenTheCardsAreShuffled() {
		PowerMockito.mockStatic(Collections.class);
        // given
		Deck aDeck = new Deck();

		// when
		aDeck.shuffle();

		// then
		PowerMockito.verifyStatic(Mockito.times(1)); // You can omit Mockito.times(1) when you expect only one call
		Collections.shuffle(Mockito.anyListOf(Card.class)); // The expected method call
	}
}

There you go. I’ll leave you with PowerMock’s Github link: https://github.com/jayway/powermock. You will find there all the documentation on the framework. You will find that it is a quite powerful tool.

How to Abort a HTTP Call with AngularJS

Posted by Guillaume Croteau on August 23, 2015
Posted in: Web Development. Tagged: AngularJS. Leave a comment

So, you use the $http service in order to do HTTP requests. But for some reason, you want to be able to cancel some of those requests. For example, you have an HTTP call that takes some time to complete, therefore you offer the user to cancel the request. It turns out that it is not as easy as with jQuery, but it is not rocket science either. So let’s take a look at how we can do that.

First, you must know that you can pass a config argument to the method call. For example:


$http.get(url, config); // config is optional
$http.post(url, config); // config is optional
$http(config); // config is mandatory

In this config object, you can specify a timeout attribute. This is the attribute that we are going to use in order to cancel the HTTP request. This attribute can take either a number or a promise.

The number represent a timeout in milliseconds. If the query is not completed when the specified timeout expire, then the query is aborted.

This can be useful, but we want to be able to abort the HTTP call when a specific condition is met, so how do we do that? We need a deferred object. To put it simply, a deferred object represents a task that will finish later during the life time of your web app. We use this deferred object to create a promise. That promise will be set to the timeout attribute of our config object. If the promise resolves, then the HTTP call is aborted.

So, enough theory, here is a simple example:


var canceller = $q.defer();

var config = {timeout: canceller};

$http.post(url, config);

// Somewhere else in the code, for example when the user cancels the operation

canceller.resolve("User cancelled the operation"); // HTTP call aborted

If, for example, your canceller object is an attribute of some custom service, you will have to reinitialize it to a new deferred object each time a query is aborted.

This should give you a good starting point, I am sure it will not be hard for you to come up with something more complex or more sustainable.

Learn Something New Today

Posted by Guillaume Croteau on June 28, 2015
Posted in: TheMoreYouKnow. Leave a comment

So, you have a little time on your own, maybe a 15-30 minutes before you go out to meet some friends or whatever. What should you do of these 15-30 minutes? Watch TV? Play video games? Or maybe its a good opportunity to learn one thing or two. In my case, I favor the latter. Here is a list of some of my favorite YouTube channels in this regard. Most of the videos are of 20 minutes or less and are filled of knowledge. Pick one and start learning new stuff!

Science

  • DeepSkyVideos: https://www.youtube.com/user/DeepSkyVideos
  • MinutePhysics: https://www.youtube.com/user/minutephysics
  • SciShow: https://www.youtube.com/user/scishow
  • SciShow Space: https://www.youtube.com/user/scishowspace
  • Sixty Symbols: https://www.youtube.com/user/sixtysymbols
  • Vsauce: https://www.youtube.com/user/Vsauce

Math

  • Numberphile: https://www.youtube.com/user/numberphile

Computer science related

  • Computerphile: https://www.youtube.com/user/Computerphile
  • LinusTechTips: https://www.youtube.com/user/LinusTechTips
  • Techquikie: https://www.youtube.com/user/Techquickie/featured

A little of everything

  • CrashCourse: https://www.youtube.com/user/crashcourse

There is a lot more to discover, but I feel that its a good entry point. I hope you find subjects that are of interest to you.

Feel free to share your favorite YouTube channels, I would be glad to learn new stuff!

themoreyouknow

Hackerone: Hacker-Powered Security

Posted by Guillaume Croteau on June 11, 2015
Posted in: Security. Leave a comment

Hackerone is a bounty platform focusing on security/reliability.

It can be a good alternative/complementary approach for enterprises to improve the protection of its users. Indeed, companies that post bounties on this platform benefit from the knowledge of an entire community. Many known enterprises post bounties on this site; Twitter, Dropbox, Shopify and many others.

For the hackers, it can be a good place to learn and to build a reputation. No doubt that a good profile on this platform would help for an interview.

So if you have a company and are concerned by the security/reliability of your products or if you are a hacker looking for good money, you should check this out.

https://hackerone.com/

Some Maze Generation Algorithms

Posted by Guillaume Croteau on May 16, 2015
Posted in: Algorithms. Leave a comment

Some time ago I wrote a program that generates mazes. For this purpose I explored a variety of algorithms and I will share with you the ones that I found the most interesting.

First things first, some terminology

  • Cell: a block that can be surrounded by at most four walls
  • Board: an m x n matrix of cells
  • Unless mentioned otherwise, the initial board has all its cells surrounded by walls

The algorithms

Binary tree

Probably the simplest algorithm you could use to generate mazes. Without surprise it is also the one that creates the most predictable mazes. In order to solve them, you simply have to follow a diagonal, every time. Therefore, the only reason I take time to write about this algorithm is its simplicity. The pseudo-code for binary tree is as follow:

    for each cell of the board
        if cell is in the last column
            Carve the wall below
        else if cell is in the last row
            Carve the wall to the right
        else
            Randomly carve the wall to the right or to the left

As you can see, the name of this algorithm comes from the fact that for each cell, we randomly decide to carve the walls to the right or bellow. This is what creates the diagonal shape on the board.

Recursive backtracker

This is probably my favorite algorithm for maze generation. It is simple, easy to understand, easy to implement and it generates a very nice maze. The algorithm is as follow:

    Choose a cell randomly
    Set the chosen cell as visited
    Add the chosen cell to a stack

    while the stack is not empty
        CurrentCell = top of the stack
        if there is at least one cell not visited around CurrentCell
            Choose randomly an unvisited cell around CurrentCell
            Carve the wall between CurrentCell and the chosen cell
            Add the chosen cell to the stack
        else // All cells around CurrentCell have already been visited
            Pop the stack

Recursive division

The interesting particularity of this algorithm is that, instead of carving its way in a board completely walled, it starts with an empty board and recursively adds walls (with a hole in them) to the board. For this algorithm, we use the concept of chambers. A chamber is an area where we will add a wall, in order to create two new chambers, which are linked by a hole. We also have to specify a desired resolution for the board. When a chamber reaches this resolution, the algorithm will go back to the previous chamber.

    Create the first chamber // The empty board
    Add the first chamber to a stack
    
    while the stack is not empty
        CurrentChamber = top of the stack
        if the desired resolution is reached for CurrentChamber
            Pop the stack
        else if CurrentChamber is already divided
            Pop the stack
        else
            Add a wall at a random position with a random orientation (vertical or horizontal) to CurrentChamber
            Carve a hole in that wall at a random position
            Add the two new chambers on the stack

This algorithm generates square shaped patterns on the board. With a bird’s-eye view, it is possible to know what part of the maze you can safely not explore in order to find the solution more quickly.

Eller

All the algorithms we have seen until now needed to know the entire maze. With the Eller algorithm, you build the maze row by row, discarding the last row when you are done with it. That’s a very good idea, but what is the magic element that makes it work? Well, each cells belong to a set. At first, each cell is in its own set. When the algorithm carves a wall between two cells, they will be regrouped in the same set, passing this information to the next row. The pseudo-code goes as follow:

    Put each cell in its own set

    while not all rows have been generated
        for each cell in the current row
            if two adjacent cells are not in the same set
                Randomly decide to carve the wall or not
        for each set in the current row
            Randomly decide where to carve a horizontal wall
        for each cell in the current row
            if there is a connection between the current row and the next row
                Put the cell in the next row in the same set as the cell above it
        Save the current row
        Put the next row as the current row

You will have to consider a special case for the final row, since the algorithm won’t have to carve horizontal walls. It is also possible to customize this algorithm. For example, given a big enough set, you could carve more than one wall.

That is pretty much it, there is a lot of other maze generation algorithms that you can try, these were only the ones that have stuck in my head.

Posts navigation

← Older Entries
  • Archives

    • February 2016
    • December 2015
    • October 2015
    • September 2015
    • August 2015
    • June 2015
    • May 2015
  • Get in touch!

    • View gcroteau2’s profile on Twitter
    • View guillaumecroteau’s profile on LinkedIn
    • View gcroteau’s profile on GitHub
  • I am reading …

    Failure is Not an Option - Gene Kranz
Create a free website or blog at WordPress.com.
GC the Software Engineer
Blog at WordPress.com.
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
  • Subscribe Subscribed
    • GC the Software Engineer
    • Already have a WordPress.com account? Log in now.
    • GC the Software Engineer
    • Subscribe Subscribed
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar
Loading Comments...
Design a site like this with WordPress.com
Get started