Following along with Free Code Camp’s Node course, I was playing with how-to-npm
from Node School, I followed the first exercise and ran how-no-npm verify
. My npm version was out of date and following the prompt, I ran npm install npm -g
. That seemed to complet successfully, however, running how-to-npm verify
subsequently gave me a lovely string of errors, the top one being
Error: Cannot find module 'process-nextick-args’
Running any npm command seemed to result in something similar.
To fix this, I did the following - first upgrade Node itself with nvm
:
Step 1 - upgrade node itself with nvm
:
nvm install v8.9.3
Step 2 - install how-to-npm again:
npm install how-to-npm -g`
Step 3 - upgrade npm
npm i -g npm
Now I can run how-to-npm verify
again and everything works
Having set middleman up to be a static blog, you might find yourself wanting to add some static pages outside of the blog structure. For example, if you install any analytics on your site, you often need to include a static file with an authentication code to your analytics provider. These pages are often barebones, with no common header or footer and no styling and you almost certainly do not need them to be processed from markdown. In other words, you want to create a page that does not use the layouts that the rest of your site uses.
To set these up, create the html
page and then edit your config.rb
to include something like the following:
page "my_barebones_page.html", directory_index: false, layout:false
Using layout: false
is reasonably self-explanatory; you are instructing middleman to forego any layout for this page. The inclusion of
directory_index: false
makes sure that the page is accessible with the .html
suffix. This is especially useful if you are using pretty
urls for your blog.
Rake tasks are easily listed from the command line with rake -T
. However if
you’ve written a rake task and neglected to provide a description for it with
the desc
as the first line, the task will not show up with the usual rake
-T
. These are essentially hidden rake tasks!
To display them, append -A
to your normal rake command; so:
rake -T -A
and hey presto, your hidden tasks are visible.
The simplest way to rename a branch in git is first to checkout that branch and then do something like this:
git branch -m new-branch-name
Technical blogs are usually going to have code examples and if you’re a Jekyll refugee exploring Middleman, you’ll be accustomed to creating fenced code blocks surrounded by backticks. Something like this:
```
code_block = Codeblock.new(:with_backticks)
```
Middleman uses kramdown to parse and convert Markdown into Html and kramdown by default expects tildes for fenced code blocks:
~~~
code_block = Codeblock.new(:with_tildes)
~~~
To get a backtick flavoured code block, you need to specify a Github Flavoured Markdown (GFM) parser in your config.rb.
To set up your Middleman powered blog so that kramdown accepts backtick fenced code blocks, follow the usual setup guides and then, in config.rb
add the following:
set :markdown_engine, :kramdown
set :markdown, fenced_code_blocks: true, input: "GFM"
Meta tags are, as the name suggests, pieces of html that you add to your web pages to provide meta data. In other words, meta tags describe your web page and can include things like who authored the page, the keywords to associate with the page, a general description of the page and various other pieces of data that apply to your web page but aren’t necesary for the end user to see
Meta tags are sometimes used to verify the ownership of a site. For example, if you want to hook up a Pinterest business account to your Shopify shop, Pinterest will ask you to add a meta tag to your site; the assumption being that only the owner of the site will have access to the underlying html and if you manage to shoe-horn your meta tag in, you’ve basically proven that you own the site.
The process of adding a meta tag to your Shopify site is pretty simple. It does, however, require you edit the template. Be warned, you’ll be diving into the actual code of your chosen theme and modifying that. This can seem scary, but it’s pretty simple in reality, and all you are doing is editing text.
Log in to Shopify, click on the Online Store
under Sales Chanel
in the left hand menu.
{: .center-block}
A secondary menu should slide in and Themes
should already be selected for you. If not, click on Themes
.
{: .center-block}
It’s always a good idea to backup your theme in case you break something so click on the elipses(three dots) towards the right hand side of the page near the Customize theme
button and select Download theme
to get a backup emailed to you.
Now you have your backup, click on the elipses again and this time select Edit HTML/CSS
.
{: .center-block}
You’ll see a file listing in and a helpful message saying ‘Pick a file from the left sidebar to start editing’.
In general, you’ll need to edit a file called theme.liquid
. Shopify uses a special type of markup or templating language which gets converted into HTML, which is why the file has a .liquid
extension. These template files are a combination of HTML and essentially ruby code which allows for things like loops and other coding constructs not normally available in plain HTML.
HTML pages (and by extension, liquid templates) contain various sections which are contained within opening and closing tags
. One of these sections is called the head
. As it’s name implies, the head
section sits at the top of the page and it’s here that meta tags are inserted. If you look at the template for your site, you’ll probably already have a few meta tags. That’s great.
To inlude your Pinterest meta tag, just copy the meta tag that Pinterest has supplied you and insert it somewhere between the <head>
and </head>
tags. If you have a few meta tags in your document, that’s great, just paste your new one in below those and hit the Save
button.
The Pinterest meta tag will probably look something like
<meta name="p:domain_verify" content="987e54321234a678909f7654321234"/>
Below you can see an example of the first few lines of a liquid template with a Pinterest meta tag included and highlighted in yellow.
{: .center-block}
Remember to save your work.
I’m playing with Phoenix and although postgres is supported by default, I wanted to tinker with n sqlite database for a project I’m working on.
It is simple enough to set up esqlite, however, when trying to run mix ecto.migrate
, I bumped into the following error:
c_src/esqlite3_nif.c:21:21: fatal error: erl_nif.h: No such file or directory
compilation terminated
Mix was also good enough to inform me
** (Mix) Could not compile dependency esqlite, /home/b/.mix/rebar command failed. If you want to recompile this dependency, please run: mix deps.compile esqlite
To solve this, I had to install the erlang-dev package
. I’m running Ubuntu so:
apt-get install erlang-dev
And all is right with the world again.
This is a simple one-liner. Open a terminal and install the font as follows:
sudo apt-get install fonts-inconsolata
With the font installed, you can now set your terminal’s font by clicking Edit->Profiles
in the terminal menu and then selecting the profile from the windown that pops up and clicking the Edit
button. Changing the terminal font should also change your vim font.
Javascript image slideshows or carousels are easy to find on the internet. In fact, you could argue that they are a solved problem and rolling your own is rather pointless. If you are using one of the more popular css frameworks such as Bootstrap or Foundation, you’ll already have an image slider/image carousel included in the framework’s javascript.
Why then, should you try your hand at coding your own?
Most carousels have everything but the kitchen sink. Navigation arrows, captions, keyboard support, slide numbers, slide bullets, play button, pause button, forward button, backward button, transition options, timer options…the list goes on. Infinitely customisable carousels are great, but they come with a cost; time spent learning to use them.
Sometimes you really just need a barebones carousel. Something that does nothing more than flip between an array of images. No configuration. No options. No problem.
We are going to lean on jQuery.
We need some minimal markup for our carousel. A container div
if you will. About as simple as I can think is as follows:
<div id="carousel">
</div>
Make the id
unique within your own DOM.
It’s a common pattern in carousels to place each image in it’s own container element - often an li
or a div
. For this example, I’m going to use div
elements as my image containers. Expand your markup to look like this:
<div id="carousel">
<div class="carouselImage">
<img src="images/images1.jpg">
</div>
<div class="carouselImage">
<img src="images/images2.jpg">
</div>
<div class="carouselImage">
<img src="images/images3.jpg">
</div>
</div>
You’ll need three images obviously. I’m using some I found on picture of the day.
There are several ways of creating the actual carousel/slideshow effect. One way is to position the three inner divs
absolutely in their container element at top and left of 0, 0. In this way, the images are directly on top of each other. To give a carousel effect, show one image at a time, hiding the others. This works well.
A different approach is to position the divs next to each other within their container, ensure the container has overflow:hidden
and adjust the left offset of the container to bring images into and out of view. This panorama approach trades managing visibility for managing position. This also works well.
We will work with the first approach, for no particular reason.
Our Javascript’s task is to control which image is on display. To do this, we will toggle a class on the relevant carouselImage
element. Our jQuery work starts off setting this class (let’s call it active
) against our first image:
$(function() {
$('.carouselImage').first().addClass('active');
});
All good carousels need a timer. Javascript provides the setInterval
function to help us create an event that fires at specified intervals. We will start off with once every five seconds. Append the following to your code from above:
setInterval(function() {
},5000);
});
Now we need to toggle the active
class of two images - we need the next image in the list to become active
and we need to remove the active
class from our current image. The added complexity here is if our current image is the last image in the set, we need to loop back round to the first image. Here’s the code we need:
setInterval(function() {
$currentImage = $('.carouselImage.active');
$nextImage = $currentImage.next();
// if our current image is the last in our group of images,
// our next image will not exist
if($nextImage.length === 0) {
$nextImage = $('.carouselImage').first();
}
$currentImage.removeClass('active');
$nextImage.addClass('active');
},5000);
});
We start by finding our currently selected image and stashing it in a variable $currentImage
. The first time we hit this it should be our first carouselImage
element because we explicitly set it to be active
earlier. Then we use jQuery’s next()
function to select the next sibling of our current image. jQuery’s next()
will try to find the next element sitting at the same hierarchical level of the DOM. In our case we have three siblings at the carouselImage
level of the DOM.
To determine whether or not we are displaying the last of our images, we need to test that there really is a next sibling. In jQuery, we do this by testing the length
of the object we’ve tried to find. If the length is 0, we have no object and in our code, that means our current active carouselImage
is the last one. Although in the above code, I’m explicitly testing for $nextImage.length === 0
, you’ll quite often see this code as !$nextImage.length
because in Javascript, 0
is a falsy value. Inside our if
statement, we use the handy first()
function to select the first carouselImage
element, just as we did earlier.
The final two lines of code simply remove the active class from our currently active carouselImage
element and add the active
class to the next carouselImage
element we want to become visible.
If you run this code now, nothing will happen because we still haven’t put any styling together. I say nothing, but if you pull up the developer tools on your browser, you can watch the active
class being set and removed against the carouselImage
elements.
{: .center-block}
All that remains now, is to set some styling.
<style>
.carouselImage {
position: absolute;
left: 0;
top: 0;
display: none;
}
.carouselImage.active {
display: block;
}
</style>
Great - we set each .carouselImage
to sit at the top left of its container element. Then we make sure they are hidden by setting display
to none
. We could use visibility
instead of display
, but setting the visibility
of an item keeps it’s position in the layout. Setting display
to none
actually removes the item from the layout so it essentially takes no space. The .active
class simply sets the display
to block
so that the element is shown.
Images grabbed from the wonderful Wikimedia image of the day archives.
a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type a given text, such as the complete works of William Shakespeare
I’m going to write a monkey sort in ruby. Although pretty much useless for any production systems, running through the practice of implementing a monkey sort will allow us to wonder into a lovely little ruby method called shuffle
while at the same time give us pause to consider what a correct monkey sort actually is.
I’m not sure monkeys deserve a bad rep on the sorting front. I suspect they can actually sort quite well. Unfortunately, the infinite monkey theorem has ensured the poor creatures are routinely used as a metaphor for inefficiency.
If you’ve never heard of a monkey sort before, it might be handy first to define it:
Bogosort or monkey sort randomly shuffles a collection until it is in order
This can be expressed in pseudo-code as follows:
while not isInOrder(input):
shuffle(input)
Let me assure you that you not the first to marvel at the stupidity of a monkey sort. In fact, among this method’s many names (slow sort, random sort, shotgun sort, bogosort), is the appropriately named stupid sort.
It’s a hopeful method of sorting - you can liken it to throwing a deck of cards in the air and then picking them up randomly, hoping they will end up in order. If not, throw the deck in the air again. Daft doesn’t begin to describe it.
At first pass, you might be tempted to write code to randomly sort an array yourself, ruby already has this functionality neatly encapsulated in the array#shuffle
method. Here’s the first implementation of the monkey sort in ruby that I came up with:
def monkey_sort(set)
sorted_set = set.sort
set.shuffle! until set == sorted_set
puts "Sorted: #{set.inspect}"
end
There’s not much to it - the method takes an array as its parameter. A sorted version of the array is assigned to the sorted_set
array. Using ruby’s shuffle!
(note the !
or bang
) method on the original array, continue shuffling until the array is equal to sorted_set
.
Remember the !
or bang
in this case will modify the array/object in place rather than return a new array. So while set.shuffle
would return a new array with the elements shuffled, leaving set
untouched, set.shuffle!
will mutate set
itself in place.
Having defined monkey_sort
, the next step is to test it. My first thought was to randomly pick five numbers between 0 and 100 and pass them in. There are, as always, many ways to skin a cat or make a monkey bash on a typewriter - here’s one:
arr = (0..100).to_a.shuffle[0..5]
monkey_sort(arr)
I create an array of all values between 0 and 100 using (0..100).to_a
. Then, using array#shuffle
, I put the array into a random order. Finally, calling [0..5]
, to select the first 5 elements of the randomly sorted array. This is assigned to a variable named arr
and then monkey_sort
is called, passing in the randomly selected 5 elements.
That’s a touch verbose. To see our monkey sort in action we really need nothing more complicated than the following:
monkey_sort((0..4).to_a.shuffle)
Lacking the panache of creating a random array of 5 elements between 0 and 100, this will, nevertheless, provide a reasonable array with which to test monkey_sort
. Although the very persnickety developer in me would say that it will work, pending shuffle
’s propensity to always return a different array to the one being acted upon. That is to say, as long as calling shuffle
on a sorted array will never return the array still sorted, we’re on to a winner. This depends on ruby’s implementation of shuffle. I’m not an expert on randomisation, but I think a random ordering of an array could potentially return the original array (please correct me if I’m wrong). I’ve not looked in to shuffle
’s implementation, so I’ll just leave it there, as a thought. A very, very picky thought.
One could argue that using shuffle
to mutate our array each time is incorrect, since we are shuffling a different array each time. This might be subtly wrong because our monkey sort has gone from:
randomly shuffling a set until it is in order
to
randomly shuffling an already random shuffle of our set until it is in order (at least after the first shuffle)
I think that’s a pretty valid concern. The convenience and beauty of an in place mutation should not get in the way of creating a correct algorithm. Let’s try this instead:
def monkey_sort(set)
sorted_set = set.sort
shuffled_set = set.shuffle
until shuffled_set == sorted_set
shuffled_set = set.shuffle
end
puts "Sorted: #{shuffled_set.inspect}"
end
Now we’re ensuring that each time we shuffle
it’s on the original array as passed in to our method. Technically, since I pass in an already shuffled array in my test code, I don’t need to call set.shuffle
on line 2 of the method. But I’ll call it anyway, just in case a shuffled array isn’t passed in. Is this code better? Is it more correct? I’ll leave that up to you.
That’s not terribly beautiful. It’s also, perhaps, not very idiomatic ruby. It’s readable though. Here’s a less readable, more concise version, though not entirely the same since we sort the set each time we do the comparison which could change the performance of the code:
def monkey_sort(set)
loop do
break if set.shuffle == set.sort
end
puts "Sorted: #{set.sort.inspect}"
end
You might prefer a recursive approach. That’s fine. A little less understandable for beginners, but go for it:
def monkey_sort_recursive(set)
monkey_sort_recursive(set) unless set.shuffle == set.sort
end
Stop! there are lots of ways of coding this. I’ll stick with the very verbose slightly less idiomatic version for readability.
Are those monkeys actually doing anything? Are they lazy? Are they just pretending to sort the array? My monkey sort implementation lacks any visibility that would allow anyone to actually see the sorting algorithm at work. Fix:
def monkey_sort(set)
sorted_set = set.sort
shuffled_set = set.shuffle
until shuffled_set == sorted_set
shuffled_set = set.shuffle
puts shuffled_set.inspect
end
puts "Sorted: #{shuffled_set.inspect}"
end
I’ve changed up the code a little - it should all be pretty readable - I’ve simply added a little output each time we shuffle
by printing out our shuffled array. Using inspect
just prints the array nicely. Now when I run the algorithm, I can see the various arrangements my monkeys decided to put the array in while attempting to sort it. Of course this sort of output is completely unnecesary, it merely serves to show the random iterations for interest’s sake.
Stressing the monkey sort with more elements is trivial - a small change to the calling code will pass in 7 elements:
monkey_sort((0..100).to_a.shuffle[0..7])
Now, monkey sort is rather inefficient and with larger arrays it tends not to perform very well. My completely unscientific trials on my machine suggests sorting 5 elements will usually occur in less than 100 iterations. Increasing the number of elements up to 11 basically rendered my sort useless, and returned unsorted. In theory, a monkey sort might never end even with only 2 elements.
When playing with larger array sizes, I like to have a get out of iteration free clause in my code. Something like this:
def monkey_sort(set)
count = 1
sorted_set = set.sort
shuffled_set = set.shuffle
until shuffled_set == sorted_set
shuffled_set = set.shuffle
puts "iteration: #{count += 1} #{shuffled_set.inspect}"
# hard exit if we sort for too long
if count > 4_999_999
puts 'wow, 5 million monkeys could not sort your array'
return false
end
end
puts "Sorted at last: #{shuffled_set.inspect}"
end
Here, a hard limit on 5 million iterations is in place - any more than that and we fail. You might prefer your hard limit in a block because blocks in ruby are cool:
def monkey_sort(set)
sorted_set = set.sort
(1..5_000_000).each do |count|
shuffled_set = set.shuffle
if shuffled_set == sorted_set
puts "Sorted at last: #{shuffled_set.inspect}"
return
end
puts "iteration: #{count} #{shuffled_set.inspect}"
return false
end
puts 'wow, 5 million monkeys could not sort your array'
end
This implementation isn’t my favourite because the happy path is tucked away in an if
statement and I rather have it as the default.
At this point, the code is becoming a little verbose. It would probably be a good time to step back and refactor. I’m not going to do that because I think that’s enough code for today.
Although the monkey sort itself is a rather ridiculous algorithm, what I found interesting is that even with this seemingly simple requirement, we can approach the problem two very different ways (one by continually mutating until we are sorted and one by randomly ordering an original array until it is sorted).
My initial stab of mutating an array in place until sorted was, I think, actually incorrect, but only through the process of writing and thinking about the code did I notice that. And that is why coding a monkey sort isn’t that stupid after all.