Kamila Matla-Tomczyk

A newb in the coding world, Graphic Designer challenged with Front-End adventure. Spending her free time admiring the beauty of the the ugly.

All Post by Kamila

Coders Lab: an alumn's opinion

To my great surprise I have discovered lately a huuuge controversy around preparing to a developer’s job in a way other than: a) graduating from a University of Technology; b) self-study. The c) option are coding schools that in the most common case run programming bootcamps preparing freshmen to their first Junior Developer position. I am the one that went for the c) option (which does not exclude self-study, quite the opposite: it forces unassisted work as much as possible).

My choice was Coders Lab due to its long-term reputation - and because I had kept their handout for 3 years as a fallback plan for my career. Coders Lab offers two paths: Front-End / Back-End, in a pace of your choice: full-time (which takes 6 weeks) / weekend (15 weeks). I enrolled to a full-time Front-End bootcamp that I finished in the end of January 2017.

Prerequisites

In fact, anyone can enroll to the bootcamp, regardless of their coding skills (or the lack of them). There are two tests to pass though: one for logical thinking, the other one for English. They are absolutely passable, no worries. If your English is good enough to read documentation and communicate well, this should do. The logical test might be tricky to get 100% of but as far as I’m concerned, more than 50% is OK. Check it out, this could have changed. Having both tests passed, you’ll need to tell a bit about your background and motivation.

Bear in mind that you’ll probably need to enroll to the bootcamp way before your edition will start - and there are two reasons for that:

  1. There’s a long list of applicants.
  2. You need to spend some 60 hours with Prework materials and then solve a series of coding tasks on GitHub. Don’t even think of starting the course with no knowledge at all because you didn’t feel like buckling down to study or just went through the Prework briefly and had somebody help you solve the tasks. That will not work and you’d realize this fact the very first day of the bootcamp. Waste of your money. :)

The Schedule

In Coders Lab full-time is full-time. Plus, afterhours, lots of afterhours. No mercy, you paid (a lot!) for the hard time. You’ll have an hour of lunch break which you might end up spending mostly with your nose in the code. No outer pressure, though. ;) Each day consists of a theory parts interspersed with practical tasks. Or rather, practical tasks interspersed with theory, since the former eats up some 80% of the time. You will be sent all the presentations so that you can get back to them at any time.

Every week is dedicated to one basic topic, for instance Advanced HTML & CSS, JavaScript, Sass & RWD etc. The program is being adjusted dynamically since, as we all know, IT profession is all about changes, changes and even more changes. A day without a new framework being born is a lost day. ;) At the end of every learning block (Fridays) you will sit an exam. It takes a series of tasks and you can use any help you need as long as it’s not your neighbours’ help. ;) Internet allowed - but no real-time communication. That’s kind of obvious, though.

After the exam you will use the rest of the day for a workshop. You’re actually bound to finish it during the weekend. Plus, homework, every day. Again, practice, practice, practice - and if you don’t have enough, no worries, you’ll be given some extras. :)

Mentors

Each group (around 10 students) is assigned a mentor, plus, some weeks will probably be guided by other mentors. Mentors are your wells of knowledge and motivation, use it but not overdose, especially in the later weeks. The more independent you try to get, the better for you. On the other hand, don’t be shy asking for help if you get really stuck, mentors are there for you and will do their best to give you hand. However, expect a fishing-rod rather than a fish itself. :)

I had luck to had been led by Mateusz Rojecki whom I owe true passion to JavaScript and an ambitious idea for the final project. Thanks, Boss! :) I still keep in touch with him and other Coders Lab mentors, still can ask their advice or just have a nice random talk.

Bear in mind that your mentor may be (and probably is) overloaded with work so don’t worry if your email does not get immediate response. In the meantime, try to seek solution by yourself - if you succedd, you’ll be proud and likely not to forget the lesson learned.

Final Project

The last week is devoted to your own project: you can come up with your own idea, take up one of the ready-to-go propositions or go for a charity project. I’d recommend the first or last option but no matter what you choose, if your mentor approves of it, you will definitely learn A LOT. This will probably the most intensive week of all. You don’t have to finish the project by the official end of the course, you will have two more weeks to bring it to a production version - but you have to be able to present your work in front of the audience. This is because during the official day of completion each student will demonstrate their project to all the rest of the group. It’s a kind of a final exam or a “thesis defence” after which you can officially receive a certificate of completion. Plus, a glass of champaigne. ;)

Your first job!

Having your project completed, resume prepared (the CL Human Resources Department will need to approve it first) - you can set forth searching for your first job in the Developer’s profession. Coders Lab sends out the group’s resumes to their partner companies once the edition is finished. However, it is still a good idea to take the initiative and search yourself. I personally was on a one review with a CL partner and didn’t like the company too much. I found a place where I currently work on my own and am more than happy about that, I couldn’t have landed a better place. I will write something more about my first steps as a Junior Developer in the nearest future.

Shortcomings

Are there any flaws on this idyllic picture? Sure there are! Coders Lab has developed tremendously during the last years so we experienced some organizational issues such as problems with getting thorugh to counselors on telephone, sometimes misleading information, unexpected changes in classrooms etc. I also regret that my group was the last one that was tought PHP and Wordpress instead of ES6, React.js and Webpack, I’d really prefer the freshly introduced front-end program. Mentors differ as differ people, they are all nice but you may (and probably will) have personal preferences. It’s a good idea to make a little reserach before your edition starts and find out more about the person who will guide your group. You may want to wait for someone else.

For most of people, the biggest drawback of Coders Lab courses is their price. Let’s put it clear: they are expensive as hell. I paid 9 000 PLN which is an equivalent of around three decent monthly wages in Poland. It took me a long time of saving but I believe that the investment will return in the years to come.

Last but not least, if you want to try getting a refund from the Polish Labor Office, good luck! It’s doable but extremely obtrusive. A friend of mine has succeeded with that but I’m not sure you’d enjoy her story… She may want to write a political thriller based on it.

Conclusion

In conclusion, if your choice is a bootcamp rather than self-study, go for Coders Lab. As far as I am concerned there’s no better option currently on the market (correct me if I am wrong). Just pure statistics: 80% of CL graduates get’s their first developer’s job soon after completing the course. I have also heard recruiters repeat that Coders Lab graduates have a good reputation among employers - and I am a living proof of that. So, yes, I do recommend CL. If your ready to commit your saving, time and tons of effort, it’s one of the best options to start.

Kamila Apr 20, 2017

Taking it slower

If you follow along the Boids project, you might have notice it slowed down notably in the last time. This is because of various reasons:

  • I have recently started my first job in the profession so you can imagine I feel a bit overwhelmed and try to keep focused on daily tasks as much as I can
  • Planning the posts and writing them takes a massive amount of time, especially as my English is not perfect and I need to research some phrases
  • Last half a year was extremely active for me (changing profession and tons of coding work) and I assume I might be a bit tired, even though I am not happy accepting this fact

That leads me to some afterthoughts on motivation issues, organizational skills and “just-sudo-it” approach.

The general message

We all hear it, read it and maybe even keep repeating ourselves every day. Your only limit is you. Wake up with determination, go to bed with satisfaction. Don’t stop when you’re tired, stop when you’re DONE. And, yep, just sudo it on top of that. Already motivated? Slightly bored and doubtful? Or simply sick of the bullshit behind? If you’ve reached the last level, I have good news for you: you really don’t need to push any harder. Listen to your inner voice. There are times when less is more. And, yes, that applies to your work, projects and goals too.

The quiet message

Several years ago I was overcoming one of the toughest times in my life. There was a huge self-work that I needed to do, urgently, as I believed. And even though I was extremely motivated, trying to find a fix, trying as hard as I could - I was stuck. And then I met somebody who told me something I wouldn’t expect at all: Kamila, your motivation level is too high. I thought I misheard. But I did not. You see, if you drew a chart with motivation level on its X axis and efficiency of your efforts on its Y axis, guess how the line would look like? Would it be a simple ascendant bar? Absolutely not, it would look more like a gaussian curve with its highest point something in between of your motivation’s potential. That means that too much motivation is equally crippling as none of it. If you push yourself too much, ignoring your fatigue and emotions, you’re bound to fail. There are points where taking a break or slowing things down brings much better results in the end than never ending pressure. Consider that next time you feel overwhelmed and things are just starting to be much too much. Maybe you should overcome the crisis and keep going. Or maybe it’s high time to take things really easy. You know the answer if you start listening to yourself more than to the outer world.

Balancing it all out

The hardest thing is to balance the two concepts. I was just about to give up this project: there’s a huge amount of learning awaiting me in my job (I am lucky enough to be paid for undergoing a programming training now :)), I need to remind myself how to charge my batteries after work, my house asks for some care at last, et cetera, et cetera. However, I am giving the project a chance. There is already an explicit plan for further steps and some corrections of the code and I plan to re-run Boids in the days to come. Your fingers crossed will help! :)

Kamila Apr 16, 2017

Why I changed my career path

OK, time for a coming out. I am 33 years old and I have just started my career as a Junior Developer. My former position? Senior Graphic Designer. I have been working in the design industry for 9 years, after completing 5 years long studies in the Graphic Design faculty. Adding 2 years of pre-study preparations, it gives me 16 years that I have just turned into dust. Sounds gloomy but, believe me, I feel really happy and excited. Many people ask me why I quit a stable, well-paid job, with no after-hours and familiar environment to… work much more for less (which is obvious at the beginning). Why did I then spend a big part of my savings to get into a full-time programming bootcamp that was eating up to 11-12 hours a day? And how come I find it really cool as opposed to designing, which people believe is more play than work? Well, the answer demands a whole story.

The choices

I was struggling with career choices from a young, actually too young age. The world seemed so inspiring that I wanted to do everything, preferably, everything simultaneously. ;) And yet, everybody around told me I needed to pick up just one thing and concentrate on that since, they explained, I’d have only one profession in my adult life. Trying to figure out what to choose from the growing amount of possibilities, one thing was obvious to me: it had to be something creative. I ended up going for graphic design - not that I had any special manual skills - but I have always loved arts of any kind and designing seemed really alluring. Plus, since the collapse of Communism in Poland, the advertising industry was thriving. Finishing our studies on 2007, me and almost all my fellow students dreamed of working in a “real” advertising agency, imaging it as the coolest and most rewarding job in the world.

Imagination vs reality

When I started my first job as a Junior Graphic Designer in a small advertising agency, the first signals of the upcoming economic crisis were already discernible. At the same time, Poland was still rushing ahead to make up for dozens years lost for our Eastern Big Brother. In consequence, the advertising industry was incredibly hungry for more work done but at the same time, not rich enough to reassure decent working conditions, especially for the newbies to the design job - at least that’s how it looked like in most of the cases. It still does. It was normal to work several hours a day, leave the office at night or even early in the morning, be bullied by your boss and Account Managers, always afraid of being fired. Trainings? Development? Sure, you have to do it somehow. At your own cost. After hours.

Designing was cool during studies when we created things that mattered, even if only to us. Put eye to eye with the market’s needs we had to forget about the ideals. What counted was the satisfied client and his money, not the project that you probably wouldn’t like to sign with your name. All of that is a perfect prescription for burnout.

Obviously, this is only the black side of the advertising industry. I know happy designers who love their job, grow as professionals and would tell here an exact opposite story. I also had many bright days and times when I designed with true passion. However, much too often was I confronted with the dirty side of the business. So often that, year by year, my fear of the future and uncertainty about my career choice were growing.

Catching the balance

Years were passing, I was changing the workplaces, slowly figuring out my own ways in the designer’s profession. After periods of storms and stillness, I landed up in a nice small company ran by my former boss. Already experienced, I started to feel really well, appreciated and respected. The environment was friendly, salary was very good, “nine to five” did mean “nine to five”. And all would be great if not for the nagging thought: “what would I do if I lost it? where would I go?”. I was scared by the fact that beyond the cosy walls of this one-off company there was no place for me. How come, you could ask. Well, as I mentioned before, there is a professional development problem in the industry. For 9 years, even though at every job interview I highlighted how important professional development for me was (more even than wages), even though I was promised trainings and development - I wasn’t offered any. Ever. Pardon, once, in a huge corporation, I went through a procedural training. I learned from my colleagues which was fine until 2011. From then on, I was working as the only designer in a company and my growth just stopped. At the same time, the industry’s expectations have skyrocketed. So many new technologies, so much to learn - I didn’t even know what to start with. The longer it lasted, the more anxious I was. I felt like I was getting detached from the world, as if it all raced forward leaving me far behind. I simply could not accept this situation. And though, I had no idea how which way to go.

The coding story

Why coding? Why not just choose to learn more great design tools, sharpen my skills etc. Well, there were a few problems with that.

First, I never felt that designer’s job is a best fit for me. I didn’t want to admit even before myself but there were many times when doubted my career choice. It might have been because of unpleasant experiences in my former workplaces, or it was just an intuitive signal.

Second, when you work as a designer, it’s not professionals who judge your work. It’s the client. Client who often believes that it’s just knowing Photoshop tools that makes one a graphic designer. Client who forces their ideas which often result in a work that is, to put it bluntly, ugly as hell. Guess who’s gonna be blamed for that? ;)

And third, I was just tired of struggling with forces that were undeniably unsurmountable. Tired of getting things forever “more catchy”, “more dynamic”, “crazy but not too crazy”, “just not like this…” etc. I’m no fortune-teller, I don’t read minds. I missed explicit expectations, clear evaluation criteria, chances to grow in my profession.

It’s a funny thing with coding in my life: looking back I see that since I got the first experiences with the Internet, I wanted to learn to write websites (I absolutely had no idea that coding goes far beyond that). Now this one will take you aback: I didn’t know how to deal with Internet until the age of 20. True story. It was 2004 when I moved to my own apartment and got myself a broadband, then I learned how to use basic communicators, make do with Yahoo!, Google and Netsprint, manage emails and so on. 2 years later, after completing a short EU-funded training, I wrote my very first website using XHTML and table-based layout. It was a present for my dad who needed a website with an overview of his trainings’ offer. Actually, as for those days, it looked really nice. :)

As a designer, I needed some coding stuff for myself too: online portfolios, Wordpress blogs etc. I completed a few courses, some of them on-line, the others stationary, even finished postgraduate studies on Polish-Japanese Academy of Information Technology, two semesters on “Advanced Multimedia”, again, EU-funded. Honestly, I didn’t learn much on programming there, yet I reasserted my conviction that coding is really cool.

A breaking point came in 2013 - and 3 years must have passed before I realized that. I stumbled upon an announcement on Rails Girls workshops in Warsaw. I didn’t even know that there is a programming language called Ruby but since the workshop was dedicated to beginners, and it was about CODING, I applied and got approved.

The workshop lasted two days - definitely not enough to learn Ruby but enough to get to know the basics of programming, hear stories of people who have retrained and became developers, and finally - how to change one’s career path. I still keep pics from that time:

Rails Girls 2013
Rails Girls 2013

It was also at Rails Girls where I got to know there is a place called Coders Lab, an intensive full-time bootcamp that takes 6 weeks of hard work, costs a fortune - but actually guarantees you will find a job as a Junior Developer after completion. I asked my mentor what he thought about that and he told me that, yes, that’s a hard deal but for those ready to commit - it’s worth it. I took a discount flier for Coders Lab and kept it in a cabinet so that I saw it every day. Remember I told myself: “if anything else fails, I’ll go for it”.

May 2016, I woke up one morning, having a really tough year behind me, and it dawned on me quite mightily: “actually, isn’t NOW the right time”? I do not believe in stories of “one day change” of one’s life, I guess there was a huge subconscious process behind but the truth is: it was this morning when I took the decision. I quit my job. Enrolled to Coders Lab. Learned as hard as I could. And you know what? That was reaaaalllly cool. I simply couldn’t break away from coding, it turned out to be the most engaging, rewarding - and, yes, creative activity I’ve ever experienced. Obviously, it’s also wearing at times, as any job, I guess. But I feel that a developer’s profession is just a great fit to me.

…and what now?

Well, I started working as a Junior Developer a few days ago. So actually - it all just began. Once I settle down a bit, I plan to write a bit more on that. Keep your fingers crossed!

Kamila Apr 10, 2017

6 ES6 features I use in the Boids project (and work great anywhere!)

The introduction of ECMAScript 2015 standard, also known as ES6, is a quantum leap for JavaScript that the language hadn’t seen since 2009. I didn’t realize the significance of the changes until very recently when I started to learn the new ES6 features. Some of them are pretty self-explanatory, the others took me more time to comprehend - and there’s still a bunch of stuff I have only blurry idea about. Since the best way of learning to code is actually… to code, I decided to introduce ES6 to the Boids project. And you know what, it considerably simplified and clarified the work. So I decided to share some insight with you. Here are the 6 ES6 features I have used when programming Boids.

1. Block-Scoped Constructs: Let and Const

ES6 has introduced two new ways of defining variables. Apart from var we have also now let and cost. Now what are let and const for and why was var not enough?

The main problem with var was its scope, which is a function scope, whereas let and const are block-scoped. It means they only exist within the current block represented by a pair of curly braces: {}: it may be a block within an if statement, a loop - or you can simply create one and put your let or const inside. This helps avoid common developers’ problems and makes JavaScript behave more predictably to those used to work in other languages, such as Java, C or C++.

Also, when using let and const you do not fall into the hoisting trap, which you may welcome with relief as many people find the hoisting idea pretty distressing. This is because let and const remain uninitialized until they are declared. The timespan before let or const initialization is called “Temporal Dead Zone” (TDZ). For more in-depth explanation, have a look here.

Next, let and const declarations cannot be reassigned. So you won’t accidentally overwrite your variables. You can only update the value of let. By contrast, const declaration is created to keep values that will not be changed. Some programmers say it’s best to use const by default and let only in special cases, when the value of the variable is bound to be changed (such as the counter in your for loop).

Last but not least, let and const do not become properties of the global object, in case you defined them globally (which you should never do by the way). The same is true for the new ES6 Classes - and I’ll tell you more about them later in this post.

Of course, you can still use var if you want, there’s nothing wrong with that. Just be aware of it’s characteristics and give the new constructs a try too see if you feel commfortable working with them.

2. Arrow Functions

A cool new feature of ES6 are arrow functions, also referred to as fat-arrow functions. Their name stems from the token they use: => which looks… well, like a fat arrow. Arrow functions are just a more concise syntax for writing function expressions. They also handle this bindings in functions in a different way which takes two issues. First, they don’t rebind the value of this when you use an arrow function inside of another function. Second, the value of this inside of a function can never be changed.

Let’s see how it works in practice. We’ll use a map method on an array of numbers to sum them up:

var nums = [10, 20, 30];

nums.map(function(num) {
return num + num;
});


Now with the use of ES6 standard we can simplify it to just:

var nums = [10, 20, 30];

nums.map(num => num + num);


Whoaa, what has just happened here? Well, first, we’ve got rid of the function keyword. Next, we’ve replaced the {} curly braces with the fat-arrow token: =>. Then, we’ve made use of the fact that arrow function have so-called implicit returns, which means that we could omit the return keyword if it was a simple one-liner. We couldn’t have done this if the return expression had multiple lines. And last, since we’ve had just one parameter in the function, we could omit the parentheses around it as well. Doesn’t it look gorgeously nice and clear?

What you need to bear in mind when using arrow functions is the behaviour of this that I mentioned in the beginning of this section. So, remember that in an arrow function this does not get rebound, it is just inherited from its parent’s scope. Imagine for instance a situation when you want to trigger an event on an element using the addEventListener() method. You pass this method a function as a second parameter and this in such function gets rebound to an element on which the event was performed. If you tried now to exchange the regular function expression inside of an addEventListener() method and printed this to the console, you may find out, it directs you to the Window object! This would be true if you created a function in a global scope. Conclusion: when working with events or whenever you WANT this to get rebound, go for a regular function expression. On the other hand, in situations when you’d write something like var self = this, thus needed a fixed this, using an arrow function will makes things much cleaner.

And the last thing to remember about arrow functions: they are really handy when working with anonymous functions. You cannot use this shorthand if your function is named.

3. Default Parameters

Another cool new feature of ES6 are default functions parameters. By declaring the defaults for a function you initialize it with default values of your choice. They get passed to a called function when an argument is either omitted or undefined.

Let’s say you want to initialize a simple sum function with default values. This is how you do it:

function sum(a=10, b=2) {
  console.log(a+b);
}
sum(5, 4); // => 9

add(); // => 12


That simple! You just assign the default values to the function you declare with the use of an equal sign. Nice, easy and really handy at times.

4. Template Literals

This one is easy to grasp as well. You have surely done things like this in the past:

function hello(name) {
    console.log("Hello " + name + ", nice to meet you");
}


The + thing looks pretty awkward especially to the newbies. Now we can handle such issues much simpler using string interpolation (you may be familiar with this idea if you use Sass). What you need is a pair of backticks `code` to wrap your expression and a dollar sign followed by a pair of curly brackets which keep an expression (of any kind), parameter or variable. The above code could thus be rewritten like so:

function hello(name) {
    console.log(`Hello ` ${name}, nice to meet you`);
}


Moreover, template literals support multiliners. That means you no longer need to write weird things like:

var helloEs5 = 'Hello\n' +
'  World\n';


ES6 will understand you’d like to keep line breaks if you rewrote the above declaration in this way:

const helloEs6 = `Hello
  World
`;


Again, clean, simple and self-explanatory snippet of code. And again, just a piece of syntactic sugar, yet since most of us like sweets - why not help yourself? :)

5. Destructuring

At this point I actually ended up dropping out destructuring from the project but who knows where the further work will bring me. Anyways, destructuring is a really nifty way of extracting data from arrays and objects and assign them to variables. Let’s have a look at the following example:

let names = ["Sally", "James", "Ben"];
let [name1, name2, name3] = names;

console.log(name1);  //"Sally"

console.log(name2);  //"James"

console.log(name3);  //"Ben"


Instead of referring each object in the array with the use of its index value, we can simply destructure the array, passing to the square brackets the names of the variables. If we passed less names than the amount of elements in the array, nothing will happen - the excess elements will be ignored.

Destructuring works pretty the same way with objects.

const person = {
  firstname: "John",
  lastname: "Smith",
  country: "Canada" 
  }

let { firstname, lastname, country } = person;

console.log(firstname);  //"John"

console.log(lastname);  //"Smith"

console.log(country);  //"Canada"


Again, the output code is clean, readable and easy to maintain. Of course, there’s much more you can do with destructuring (as with any other feature I present in this post), so go ahead and check it out. I will also show you some resources in the Internet which go deeper into ES6 in the sum-up section.

6. Classes

Last but not least, classes. I’ve found this feature particularly helpful in my project. Classes will replace the ES5 constructor functions and take JavaScript closer to fully object-oriented languages. Classes are just a bit of syntactic sugar over prototypal inheritance in JS but they make the syntax much cleaner and more readable. JavaScript still keeps its prototypal way of object inheritance, so ES6 classes do not work exactly like in classic OOP as, for obvious reasons, JS has to maintain backward compatibility.

To define a class we simply use the class keyword followed by its name and a pair of curly braces which keep the class’ body. Here, we can set a special constructor method which initializes every instance of the class with a defined logic. For example:

class Car {
    constructor(brand, year) {
        this._brand = brand;
        this._year = year;
    }
}

let toyota = new Car("Toyota", "2012");

console.log(toyota); //Car {_brand: "Toyota", _year: "2012"}


We can also set methods for a class, again, in a much more concise and clean way. Let’s add a drive() method to our class:

class Car {
    constructor(brand, year) {
        this._brand = brand;
        this._year = year;
    }
    drive() {
        console.log("vroom");
    }
}

let toyota = new Car("Toyota", "2012");

toyota.drive(); //vroom


You can also make use of inheritance and create subclasses (also referred to as “derived classes”) with the new extends keyword. Now let’s imagine we would like to create a subclass that inherits the properties of the Car and extends them with yet another “model” property. In this case, we can make use of the super keyword which calls the parent class. Let’s see this in action:

class Model extends Car {
    constructor(brand, year, model) {
        super(brand, year);
        this._model = model;
    }
}

let prius = new Model("Toyota", "2012", "Prius");

console.log(prius); //Model {_brand: "Toyota", _year: "2012", _model: "Prius"}

prius.drive(); //vroom


Bear in mind that a subclass cannot contain an empty constructor. Even if the constructor would only call super(), it still needs to be there.

Babel

Now here’s the key issue: “Can I use…?”. Although most of the modern browser do not have problems with understanding ES6, there are some features of the standards that still are problematic. You might also need to support dinosaurs (if so, accept my sympathy). This is where so-called transpilers come in handy. What they do is convert your ECMAScript 6 code to ECMAScript 5 compatible code. One of the most popular, actually a standard now, is Babel. Go ahead and visit its site. In the top menu you will find a “Try it out” tab which allows you to see how Babel handles your ES6 code. When you paste a snippet of your code on the left, its ES5 representation will show up on the right. Babel does a really good job here!

An instruction for using Babel could actually take a whole new and quite long tutorial(and I consider preparing one for you) so for now please just refer to the great Babel documentation or try out the tool live here.

Summing Up & Learning Resources

Despite the substantial length of this post, this was just a very brief introduction into the ES6 features described, let alone the whole bunch of other stuff that ES6 has in its offer. I assume you’d feel like diving deeper into the subject so I created a list of nice resources for you. A few free once to start:

And for those who want even more and are ready to sacrifice some pennies, here are two video trainings that I gave a try and found helpful:

  • A fabulous course by Wes Bos, whom you may know from his free 30-day ES6 challenge
  • A nice training on Udemy. There are often huge discounts there so I’d advice you to wait for one, as you can get the course for as little as 10-15 Euro.

In case you were curious, how are Boids doing, please be invited to the GitHub repo. Thanks for reading, see you later! :)

Kamila Apr 7, 2017

A Gulp of Node.js

Working on a website project is not only about writing code in HTML, CSS and JS. When it comes to deployment or using preprocessors for instance, you need some tasks to be done repeatedly, like:

  • concatenating and minifying CSS and JavaScript files
  • compiling Sass to CSS (I highly recommend writing in Sass rather than pure CSS, especially if you work on a little bit bigger project)
  • reloading your browser each time you introduce changes to your styles
  • compressing images
  • watching Sass for changes
  • …and so on :)

This is when tools like Gulp or Grunt come in handy. In this tutorial I will show you some basics of Gulp which I find easier than Grunt, with API is a bit cleaner and faster performance. That doesn’t mean it’s overall better, it’s just what I work with on a daily basis and can tell you something about.

All cool but what is Gulp actually?

In simplest terms, Gulp is an automation tool, or a JavaScript task runner, that takes tons of tedious, repetitive work off your hands. It is built on Node.js so you will define your task in JavaScript in so-called gulpfile.js. Pretty nice for a Front-End Developer.

Let’s get started

You will get a clear impression of how it all works if you just try yourself - and it’s pretty simple. What we need to do is install Node first. Node is a platform that lets you run JavaScript outside of a browser. Node itself is a C++ program but don’t worry about that, you only need JavaScript to handle your tasks. What’s cool about Node is its modules which you can also refer to as kind of plugins or files that keep specific functions to run them when needed.

Now let’s go ahead and install Node. It is possible you already have Node on your machine so open up your console and run:

node --version


If your console answers with a version number, you’re good to go. If not, go to the Node.js website, download and install Node. The Node Package Manager (npm) should have been installed too, so run this command to check it:

npm -v


As before, your console should answer with the npm’s version number.

Installing Gulp

Now that we have our Node platform ready, let’s proceed and install Gulp. Simply type this in your console:

npm install -g gulp


to install Gulp globally. If you are on Mac or Linux you should precede this command with sudo. This is something you do once and for good. You will also need to install Gulp locally in your project’s folder, so navigate there in your console (nice trick: type cd + space and then simply drag & drop your folder inside the console; hit enter and you’re there!).

Gulp is a Node Package Manager module so let’s initialize npm like this:

npm init


Given this command, the console will ask you a series of questions. You can give them specific answers or simply keep hitting Enter for the defaults until the process is finished. You will probably need to stop the task manually once you see this line:

Is this ok? (yes)


Hit Ctrl + C to finish. Alternatively, if you want to go with the defaults and omit the questions’ part, simply run:

npm init --yes 


At this point in your directory’s root your will see a new file called package.json, containing initial .json configuration. Here’s where next modules required will be added as so-called dependencies. This will help you build reusable package.json file that will install all the dependencies in your next projects once you simply run npm init. This is also why you will need to add --save-dev to the following installations commands. I will show you exactly how in a moment.

Now let’s move on to install Gulp locally in your project. Go ahead with the command below:

npm install --save-dev gulp 


If you take a look at your package.json file, you’ll notice Gulp added to devDependencies. Good, let’s create our first task!

“Hello World” with Gulp

In order to create Gulp tasks we need a special file called gulpfile.js. Open your editor, ask it for a new file and save it as gulpfile.js. As per the old programming tradition, let’s build a “Hello World” task to get acquainted with the environment. In order to define it, go ahead and type this at the beginning of your gulpfile.js:

var gulp = require(gulp); 


The string in the parenthesis stands for the name of the plugin. This way we are asking Node to look inside the node_modules (you will notice this folder created in your project’s file once you’ve installed Node) and search for a given module (in this case it’s Gulp). Now to actually set our task we need the following syntax:

gulp.task();


There will be two parameters inside this function:

  1. the name of a task as a string (the name is up to you)
  2. the function to perform

So, if we would like to log “Hello World” in the console and we want to call the task “hello”, this is how we will build our task:

gulp.task(hello, function() {
	console.log(Hello World!);
});


Try it out! In your console run:

gulp hello


And the console will answer logging “Hello World!” just as expected.

Below you can see a table explaining 4 simple Gulp APIs.
Isn’t it super nice and easy?

API Purpose
gulp.task Define a task
gulp.src Read files in
gulp.dest Write files out
gulp.watch Watch files for changes


Now that you have the basic knowledge of creating tasks in Gulp, let’s try something more practical.

Compiling Sass to CSS

If you work with preprocessors like Sass or Less, you need your .scss files to be compiled to .css so that the browser understands what you want. It can be easily done with Gulp. First, you need to install the special module for that:

npm install --save-dev gulp-sass


Now in your gulpfile.js after the first gulp variable declaration add another one:

var sass = require(gulp-sass);


Let’s define our task. I called mine “sass”. Here’s how it looks like in my case, we will go through this snippet in a second:

gulp.task("sass", function() {
    gulp.src("src/scss/main.scss")
        .pipe(sass())
        .pipe(gulp.dest("src/css/"));
});


In the gulp.src() you put your input path. In my case I have following structure project_folder > src (a folder where I put my working files which I then deploy for production into the dist folder) > scss (where I keep my Sass folders and main.scss file) > main.scss (keeping all the imports from Sass folders). Adjust the path to match your project’s structure.

The pipe method is used to chain multiple tasks together. The consecutive “pipes” are put in new lines for readability.

The gulp.dest() part defines where your final .css file will go.

Once you’ve set the task ask the console to compile your Sass like this:

gulp sass


The sass method can take a configuration object as a parameter. Let’s do that:

gulp.task("sass", function() {
    gulp.src("src/scss/main.scss")
        .pipe(sass({
            outputStyle: 'expanded',
            errLogToConsole: true
        }))
        .pipe(gulp.dest("src/css/"));
});


What’s happening here is we ask Gulp to compile Sass files to expanded style in .css and we also want to see errors in our console, if they occur. So what is this output style issue? It is simply how our final .css will look like: whether it will be minified or more human-friendly. We have four options to choose from:

  • :nested
  • :compact
  • :expanded
  • :compressed

Here is how each of them looks like.

I usually go for expanded style which seems most legible to me but the choice is completely up to you.

Sourcemaps

The next thing I’m going to cover is sourcemaps. Having sourcemaps built into your sass task is a must when it comes to debugging your code. Imagine having an issue in your .css file and trying to fix it with your browser’s Dev Tools. If you try to inspect an element on your website now, you will see a specific line in the .css file. This may not be what you want, especially if you use a compressed output style. You’d rather wish the Dev Tools to point out the .scss file and specific line number inside. This is what you need sourcemaps for. Let’s install them and add to devDependencies:

npm install gulp-sourcemaps --save-dev


Now we need to rebuild the “sass” task like this:

gulp.task("sass", function() {
    gulp.src("src/scss/main.scss")
        .pipe(sourcemaps.init())
        .pipe(sass({
            outputStyle: 'expanded',
            errLogToConsole: true
        }))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest("src/css/"));
});


Once you’re done, try to inspect a chosen element of your site with Dev Tools. You should see them pointing to the source .scss file and a code line inside of it.

Listening for changes

When working on your Sass project you probably wouldn’t like to be forced to run gulp sass each time you save changes to the stylesheet. I assume you’d rather have your changes introduced to the .css file each time you change one of your .scss stylesheets. You can achieve this with a Gulp watcher that will keep track of the changes and introduce them immediately into the destination .css.

Let’s define this task:

gulp.task("watch", function() {
    gulp.watch("src/scss/**/*.scss", ["sass"]); 
});


As you have probably guessed, the first parameter is a source path ( ** means I want Gulp to look for all of the files in my scss folder and then get all of the files with the .scss extension). The second parameter is an array of tasks for the watcher to keep track of. In our case, we only want to watch for “sass”.

You already know how to run this task:

gulp watch


This way we start the watch mode. If you want to stop it, hit Ctrl + C.

Synchronized browser testing

The last thing I am going to cover is something which I hope you’ll find really neat: live reloading your web project on your browser. We can handle this with a BrowserSync plugin. It is not a Gulp module but it doesn’t matter, we can use it anyhow. Let’s install it:

npm install browser-sync gulp --save-dev


…and define as a variable in our gulpfile.js:

var browserSync = require(browser-sync);


Time to create a task called “sync” (or anything you like) which will look like this:

gulp.task("sync", function() {
    browserSync.init({
        server: "src/"
    });
});


Inside the browserSync.init() function we define a configuration object which in this case contains simply the path to our project. Since I usually keep all my source files in a folder called “src” (as mentioned above), I have declared server: src/. If you decided to put all your files directly within your main project’s directory, your task may look like this:

gulp.task(sync, function() {
    browserSync.init({
        server: {
            baseDir: "./"
        }
    });
});


The last thing to do here is adding browserSync to our chain in “sass” task:

gulp.task("sass", function() {
    gulp.src("src/scss/main.scss")
        .pipe(sass({
            outputStyle: 'expanded',
            errLogToConsole: true
        }))
        .pipe(gulp.dest("src/css/"))
        .pipe(browserSync.stream()); 
});


Let’s try it out! Run:

gulp sync


You’ll notice your website open up in a new tab of your default browser, on localhost:3000. Try entering any changes to your stylesheet - they will be introduced immediately without the need to reload your page. Cool, isn’t it?

Default series of tasks

Or maybe you want to run more than one task at a time? No problem, you can do this with a default task (this time the name of the task does matter, it has to be called “default”). Let’s give it a try and define a default to run “sass”, “sync” and “watch” in a row. It’s a simple one-liner:

gulp.task("default", ["sass", "sync", "watch"]);


Guess what? Now you simply run:

gulp


and that’s all, Gulp will perform the array of tasks one by one.

Summary

OK, so here’s the final contents of your gulpfile.js if you followed along. The paths and tasks’ names may differ, of course, but you get the idea:

var gulp = require("gulp");
var sass = require("gulp-sass");
var browserSync = require("browser-sync");
var sourcemaps = require("gulp-sourcemaps");

gulp.task("sass", function() {
    gulp.src("src/scss/main.scss")
        .pipe(sourcemaps.init())
        .pipe(sass({
            outputStyle: 'expanded',
            errLogToConsole: true
        }))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest("src/css/"))
        .pipe(browserSync.stream());
});

gulp.task("sync", function() {
    browserSync.init({
        server: "src/"
    });
});

gulp.task("watch", function() {
    gulp.watch("src/scss/**/*.scss", ["sass"]); //table with a list of tasks

});

gulp.task("default", ["sass", "sync", "watch"]);


Note that if you followed this tutorial and saved all dependencies in your package.json file, then in your next projects, given that you will need the same npm modules, you can simply copy package.json to the project’s root, navigate to the main project’s folder in your console and run npm init to install all the modules. Then, of course, you’ll need an analogous gulpfile.js - just remember to check all the paths, folder and tasks names to avoid errors.

I am aware I covered just a small part of what Gulp is capable of. What you can do more is, for example, optimizing your images, concatenating and minifying your files, preventing your watcher from stopping on error and much more. At this point however I believe you’re tired enough. :) If not, take a look at the documentation, really nice and clear:

That’s it for today, hope you enjoyed fiddling with Gulp. Test it yourself, play with the variety of possibilities, learn by trial and error: this way you’ll get best understanding and courage, both indispensable in any aspect of developer’s job. See you soon, happy coding! :)

Kamila Apr 4, 2017

The canvas API

Two posts ago I promised to tell you something more about the HTML5 technology that I use to draw and animate Boids, that is the <canvas> element. As you have probably guessed, it is basically just an HTML tag - but its possibilities are truly impressive. With the use of a simple <canvas> element and JavaScript you can create advanced games, multimedia applications, charting - and much more. This is because canvas is very fast and efficient so it can perform complicated calculations and animations. Since canvas is a pixel-based API, you can go as far as manipulating pixels, creating for instance some impressive filters for your photos. The possibilities are endless!

Overview

The canvas API itself is not really complicated in terms of the amount of knowledge to grasp. All the methods and properties are nicely put together on the w3schools reference. Yes, I am aware of the controversy behind w3schools and I admit it’s definitely not the ultimate choice for learning but when it comes to getting to know HTML5, especially if you’re fresh to some of its features, it’s a nice start. Having said that, you should definitely check out the MDN documentation for canvas which provides you with in-depth information on all the API’s features.

Basically, the canvas API consists of a set of functions and properties. Functions can be divided as per their purpose like so:

  • line and shape functions (for example: arc, fill, rect, stroke etc.)
  • text functions (fillText, measureText, strokeText)
  • transform functions (save, restore, rotate, scale, transform, translate)

In addition to the functions, canvas API provides you with a set of properties that are basically designed to let you style the elements before they get drawn on canvas. Some of these properties are: width, height, font, fillStyle, globalAlpha, globalCompositeOperations.

OK, let’s get down to actual coding so that you can check yourself how to make use of canvas. Once you get the knack of it, I promise, you’ll have fun!

Basic usage

First, let’s insert canvas on our website. In a place of your choice simply put:

<canvas id="myCanvas" width="400" height="400"
	Your browser does not support canvas
</canvas>


No need to say that the above id, width, height and fallback text is up to you. You might be tempted to omit width and height and choose to style those in CSS but don’t do that, it won’t work. You need to define width and height directly inside of the <canvas> tag - or in JavaScript. Anyways, it’s best to start from setting initial values here, in HTML. I would also suggest adding some basic styling to the canvas so that you can see clearly where it is. Let’s move to the stylesheet and add some CSS declarations like:

#myCanvas {
    border: 1px solid black;
}


Now that we have our bare canvas placed on the layout, it’s time to jump into the JavaScript file. First, we need to catch our canvas to a variable. Let’s make use of the new variable declarations introduced by ES6 (more on that in the future post, I plan to show you all the ES6 features I use in the Boids project).

const canvas = document.getElementById("myCanvas");


Now we need to define the context in which we want to work. In most of the cases, you will need a 2D context. The canvas element has a special method for that called getContext.

const ctx = canvas.getContext("2d");


Finally, let’s draw something simple like a rectangle:

ctx.fillRect(200, 200, 100, 100);


The fillRect() method takes four parameters: x, y, width and height. The x and y coordinates define the rectangle’s upper-left corner’s position. The default color is black, that’s why you can see a black rectangle on your canvas now even though you didn’t set any styling. Actually if you do want to style your components anyhow, you should define the visual side first. Let’s add some colour to our rectangle, say, orange for example. Now the code will look like this:

ctx.fillStyle = "#ffa500";
ctx.fillRect(200, 200, 100, 100);


The same way, you can create a rectangle with a stroke, defining its color first:

ctx.fillStyle = "#ffa500";
ctx.strokeStyle = "#005aff";
ctx.fillRect(200, 200, 100, 100);
ctx.strokeRect(200, 200, 100, 100);


This will add a blue stroke to your initial rectangle. You might want to alter the stroke’s width - and that’s simple too. The only thing it takes is a lineWidth method where you define the line’s width in pixels and pass it as a numeric value like so:

ctx.fillStyle = "#ffa500";
ctx.strokeStyle = "#005aff";
ctx.lineWidth = 10;
ctx.fillRect(200, 200, 100, 100);
ctx.strokeRect(200, 200, 100, 100);


Cool, you get the point! The very introduction is behind us, let’s move on to other shapes.

Run rings around the squares!

Time for something slightly more complex: curves. In the case of Boids I initially wanted to represent them as simple circles. To do that, we need the arc method that lets you draw curves, ovals and circles. As you remember, we need to define styles first. How about some spring colors and stroke of 5px?

ctx.fillStyle = "#bcd664";
ctx.strokeStyle = "#54a244";
ctx.lineWidth = 5;


Now we need a method to start the path:

ctx.beginPath();


…and draw a curve using the canvas arc method. The arc method takes 5 obligatory parameters and 1 optional. These are:

  • x (the x-coordinate of the center of the circle)
  • y (the y-coordinate of the center of the circle)
  • r (the radius)
  • sAngle (the starting angle, in radians, where 0 is at the 3 o’clock position of the arc’s circle)
  • eAngle (the ending angle, in radians)
  • counterclockwise (this one is optional and takes a boolean value: true or false)

Let’s imagine we’d like the arc to be drawn in the middle of the canvas, with the radius of 20px, taking 90 degrees. Calculating radians may be a bit counterintuitive for you (it is for me!) so why not get ourselves a little helper function that will take degrees and return radians? Like so:

function calculateRadians(degrees) {
    return degrees * Math.PI / 180;
}


Now let’s move back to our arc and draw it!

ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height / 2, 80, 0, calculateRadians(90));
ctx.stroke();
ctx.closePath();


A riddle for you: how to draw a circle with fill only, no stroke, as in the case of rough-and-ready Boids. Yeah, I know that you know. :)

ctx.fillStyle = "#bcd664";

ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height / 2, 40, 0, calculateRadians(360));
ctx.fill();
ctx.closePath();


Let’s animate it!

Last thing I’m gonna show you is a simple animation that will get you familiarized with some concepts of moving elements around on canvas. Basically, drawing on canvas consists in sequential clearing the canvas and redrawing the element on a new position. In case you perform any transformations on the element while animating it, you will also need to store and restore the canvas. We won’t transfigure our circle anyhow so we can skip these steps.

To schedule the updates you can use one of the following functions: setTimeout(fn, delay), setInterval(fn, delay) or requestAnimationFrame(callback). I suggest you go for the third option since it’s best in terms of performance of your animation. Paul Irish explained very nicely the way requestAnimationFrame() method works and why to choose it over setTimeout() or setInterval. The post is old but still valid, just the support of the browser is now almost complete. It’s just Opera Mini that doesn’t understand the deal. Anyways, has anyone of you ever used Opera Mini? Personally, I don’t even know how dude looks like!. ;)

OK, so how to use the requestAnimationFrame() method? We use it on a global object (that is, in our case, window) and we pass it a callback function which will run each time the browser performs drawing on the screen. So here’s the basic syntax:

window.requestAnimationFrame(callbackFunction);


Which is, as you know, the same thing as:

requestAnimationFrame(callbackFunction);


With that in mind, let’s write a core for our animate() function which will run the requestAnimationFrame() method, calculate next position and then re-draw it.

function animate() {
    requestAnimationFrame(animate);
        // calculate next position

    draw();
}


Next, let’s define the draw() function. It will be running in a multiple sequence so the first thing you need to do is clear the canvas before re-drawing the element on the next position. To clear the canvas, you need to run the clearRect() method on the canvas’ context (as you remember, we keep it in a variable called ctx). The clearRect() method takes the following parameters:

  • x (the x-coordinate of the upper-left corner of the rectangle to clear)
  • y (the y-coordinate of the upper-left corner of the rectangle to clear)
  • width (of the rectangle to clear, in px: in our case this will be the width of the whole canvas)
  • height

Now, the foundation of your draw() function will look like this:

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
	    //drawing goes here

}
animate();


Having this basis, let’s think of how we will actually deal with moving our element around. For the very beginning, we’ll move the element on x-coordinate only asking it to revert the direction of the movement once the element hits the border of the canvas. We need three variables: x and y for initial position and speed for… yeah, the speed. :) Let’s declare these at the very beginning, above the animate() and draw() functions:

let x = 40;
let y = 40;
let speed = 5;


At this moment we can complete the draw() function and make it draw a circle like we did before in this tutorial:

function draw() {
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	ctx.fillStyle = "#bcd664";

	ctx.beginPath();
	ctx.arc(x, y, 40, 0, calculateRadians(360));
	ctx.fill();
	ctx.closePath();
}


Finally, we will move the circle on the x-axis by incrementing the x variable which defines the circle’s horizontal position:

function animate() {
    requestAnimationFrame(animate);
    x += speed;

    if (x <= 40 || x >= 360) {
        speed = -speed;
    }

    draw();
}


OK, what’s going on here and where do these 40 and 360 values come from? As you remember, the canvas width and height are both equal to 400px. The circle’s width is 40px and we start to draw the center of it at (40, 40) position. This means the circle will hit the left border of canvas at (40, 40) position and the right border at (360, 40) (the canvas’ width minus 40px). These two are the moments when we want to revert the direction of the movement.

Let’s have a look at the final code:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

function calculateRadians(degrees) {
    return degrees * Math.PI / 180;
}

let x = 40;
let y = 40;
let speed = 5;

function animate() {
    requestAnimationFrame(animate);

    x += speed;

    if (x <= 40 || x >= 360) {
        speed = -speed;
    }

    draw();
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "#bcd664";

    ctx.beginPath();
    ctx.arc(x, y, 40, 0, calculateRadians(360));
    ctx.fill();
    ctx.closePath();
}

animate();


At this moment you should see your circle rolling around your canvas from one side to another - and back. Now you can play with the speed, y-axis position and much more. Have fun! :)

Further reading

I have only touched the very surface of canvas’ possibilities and I’m sure you’ll want much more. Here’s a generous handful of really nice recourses that will help you dive deeper into canvas’ features:

How are Boids flying on canvas?

If you’re curious how I’m doing with the Boids, check it out here:

  • the source code on GitHub. You can find out how I applied the methods described in the above tutorial to animate Boid instances on canvas. I will be glad to hear your tips on that!
  • Boids online

That’s it for now, hope you’ve enjoyed this little playground, see you back soon! :)

Kamila Mar 30, 2017

Strange case of Dr Jekyll and Mr Windows / Part II

If you follow me along on “Just sudo IT”, you remember the post about setting up Jekyll. We have ended up with a basic set-up of a default Minima-themed blog. Great for beginning but now time has come to customize it to your liking. You will probably want to adjust the layout, install a chosen template (you can also style your blog completely from scratch but we’re not going to cover this case here), add custom domain etc. Let’s see how to do it.

Basic configuration

First, we’ll have a look at the _config.yml file that lives in your project’s root. Open it up with your editor. Change the default values of the title, email, description, url and baseurl (the subpath of your site, e.g. /blog).

The url will be your GitHub .io home page and the baseurl will be the name of the repository which we’ll create later on. Here’s how it looks in my case:

baseurl: "/testjekyll"
url: "https://ka1130.github.io/" 


You can find a very extensive explanation of all the configuration options on the Jekyll documentation page but you probably won’t need most of this stuff. Good to know, however.

As you will see in the Build settings section, the default template is minima: that’s what you can see at the moment once you run jekyll serve and open up your browser on http://localhost:4000.

Pushing your blog to GitHub pages

Now let’s create a new repository on GitHub. As mentioned above, I decided to go for a testjekyll name. Check the Initialize this repository with a README box, otherwise you’ll be directed to the setup page.

Starting a new repository

At this point my exemplary repo lives under this address:

https://github.com/ka1130/testjekyll


Now push the project to GitHub pages (remember to change the address to the one of your blog!):

git remote add origin https://github.com/ka1130/testjekyll


Next, add a special branch that has to be called gh-pages:

git checkout -b gh-pages


Still on gh-pages branch, make your first commit:

git add .
git commit -m Initial commit.


And finally, push the commit to GitHub pages:

git push origin gh-pages


In your browser, navigate to the new project:

https://ka1130.github.io/testjekyll/


No need to add that in the address there will be your username instead of ka1130, and the uri will be the name of your project. :) Here we are, your blog in already online, hosted on GitHub pages. Cool!

Setting up your theme

Time for some work with the visual part of your project. As mentioned before, you can style it all by yourself and there are many nice walkthroughs to check, like for example:

However you might choose to go for a ready-to-go theme, just as I did, since I was running out of time and needed something “here and now”. In this case you can opt for a free or premium template. I personally recommend you the second option, simply from my own experience. I might have had bad luck but having tried to install a free theme, I failed. The first problem was the outlook: as a (more or less former) designer, I just couldn’t bear something I found ugly in terms of fonts, layout, colors etc. ;) This point is kind of funny in a coding world, I know - but wait, there’s more! The tricky thing is that free templates are often not-that-great in terms of documentation and adjustability. For me, being very fresh to Jekyll, that was a pain in the ass. A few hours wasted and I moved back to the good old Theme Forest. Don’t yell at me, I know their downsides but, on the other hand, their themes are well tested, you get almost immediate support for any issue - and they simply look good. Again, presumably no one will write your template better than yourself but… yeah, you know my but. ;)

So here’s the deal: once you get your theme (you choose the source, it may well be true, that there are far better options that Theme Forest, I’ll be happy to get to know them!), you need to get familiar with the Jekyll’s structure. At this moment your project’s structure looks probably like this:

  • .git // folder
  • _posts // folder
  • _site // folder
  • _config.yml // file
  • about.md // file
  • Gemfile // file
  • Gemfile.lock // file
  • index.md // file

I have bolded the files and folders that need to stay where they are, the rest will be replaced with your theme files. In my case, that was enough to get the template up and running. If you chose a free theme, it may end up being a bit more tricky so choose wisely - paid or not, your theme should have clear installation guides, unless you already are a Jekyll ninja. :)

Now what are these folders for exactly? Let’s have a look at an exemplary basic structure of a Jekyll site:

├── _config.yml
├── _drafts
|   ├── begin-with-the-crazy-ideas.md
|   └── on-simplicity-in-technology.md
├── _includes
|   ├── footer.html
|   └── header.html
├── _layouts
|   ├── default.html
|   └── post.html
├── _posts
|   ├── 2007-10-29-why-every-programmer-should-play-nethack.md
|   └── 2009-04-26-barcamp-boston-4-roundup.md
├── _sass
|   ├── _base.scss
|   └── _layout.scss
├── _site
└── index.html // or index.md


We already know what _config.yml is. And we’ll come back to some more adjustments here in just a moment.

The _drafts folder is optional. As its name suggests, here’s where you store draft files for your posts. You will not see them published on your public blog but you can preview them locally once you run jekyll serve command on your console.

The _includes folder stores the partials such as footer or sidebar. These are the sections that get duplicated on respective sites.

The _layouts keeps, you guessed it, the layouts for individual sites, such as home, page, post, contact or category. You may well have only the default.html and post.html here, all up to you and/or the theme chosen.

The _posts are also pretty self-explanatory. It’s basically post files, each of them keeping a single post with its date, title and contents.

If you’re working with Sass, it will be no surprise to you to encounter the _sass folder. In case you don’t know this preprocessor (I strongly recommend you to familiarize yourself with Sass, it will enhance your workflow tremendously), these are the source files for your stylesheets. Something like CSS on steroids. ;)

And finally the _site folder where the whole generated site is placed. Stay away from fiddling with this one, it’s not where you edit things, it’s just the final outcome to display in the browser.

Now basically how you modify the way your sites display is by editing the so-called YAML front matter. This section is always at the beginning of the file containing your page or post and it allows you to control how Jekyll processes and builds pages. The YAML front matter is put between triple-dashed lines and can look like so:

---
layout: default
title: My first post
date: 2017-03-15 10:34
author: John Smith
---


In the above example we ask Jekyll to display this specific post using the default.html layout, to give it a specific title and author, and to publish it on a specific date. These are just four examples of predefined global variables that you can use at this point. Some of the others are:

  • permalink: allows you to override the default permalink settings
  • category or categories: puts your post into a specific category / categories (simply put as an array with spaces; no brackets, no commas)
  • comments: a boolean (true/false) stating whether or not you want the comments to be displayed; Disqus is a recommended solution for introducing comments’ feature on a Jekyll blog
  • published: another boolean value that allows you to keep your post unpublished, if set to false
  • tags: pretty much like comments, tags allow the posts to fall under a given tag
  • and more

Depending on your theme and needs you will probably mainly need to adjust only front matter. When it comes to styling the contents, it boils down to mastering (joking, some basics will do) Markdown. I will cover some of its syntax in the next section.

Done with the fundamentals of Jekyll structure, let’s switch back to the _config.yml file for a minute. You may want to manage how to handle permalinks here. Most often, you will want them to point at the post’s title. In this case go ahead and add this line:

permalink: :title


You can also set up your top navigation and footer here. In my case, here is the final _config.yml for this blog:

Final _config.yml

Don’t forget that you need to re-serve jekyll if you introduce any changes to the _config.yml, otherwise you won’t be able to track the changes.

jekyll serve


Meanwhile, I run up against two really promising FREE Jekyll themes. Seem to be well documented and hopefully they will prove to be a counterexample of my former thesis on the supremacy of premium themes. Check them out, I will be happy to hear your feedback!

Formatting your posts with Markdown

The actual content of your Jekyll posts and pages is written in Markdown, a simple text formatting engine that you probably got familiar with when creating your README.md file for your GitHub repositories. However, in case you did not, here are some basics:

  • Headers
    You simply use hashtags for that. The numbers of hashtags determines the size of the header. You can think of adding hashtags as incrementing the number in your <h…></h...> tags. For instance, if you write # Header1 the result will be a big header, ## Header will be a bit smaller and so on.
    Note two things:
    • The single hashtag headers (the biggest ones, equivalent to <h1></h1>) are reserved for blog titles, don’t use them in your content.
    • Make sure there is a space after the hashtag. For some reason Jekyll cares about that.
  • Inline markup styles
    • To make a phrase render as italics you put it in between of single asterisks: *italics*.
    • To make a phrase bold you need to put it in between of double asterisks, like so: **bold**.
    • To make your phrase render like code(), you put it in between of backticks: `code()`.
  • Lists
    • Unordered lists
      Unordered lists’ items start with * or + or - . Don’t forget the space afterwards!
      • Nested list items
        For a nested list item hit Tab followed by - and space. You can exchange - with + or * or even number (followed by dot and, of course, space)
    • Ordered lists
      This one is simple: press number followed by dot and space, like so: 1. list element. That’s it!
  • Links To create a link put its title inside square brackets first, then the actual address inside round brackets, like so:
    [Google](http://google.com)
  • Images Placing images follows a rule similar to the links, you only need to precede the whole stuff with an exclamation mark. In the round brackets you either put a relative path to the image on your server, or an absolute path to an image hosted elsewhere. Example:
    ![Image title](img/my-image.jpg)

That was just some very basics of Markdown, enough for the very beginning but in the nearest future you might need a more extensive resource. In this case, have a look at what I found for you:

Using a custom domain with Jekyll

The last thing I’m going to cover is setting up a custom domain for your Jekyll blog. Once you’ve purchased your domain there are three steps to follow in order to redirect your blog which is currently hosted under your-login.github.io/your-project.

  1. In your project’s root create a new empty file and save it as CNAME (with no extension). Inside of this file enter your domain’s name. For the sake of this example I have got myself a free jekyll.cf domain and that’s exactly and only thing that goes into the CNAME file. No http://, www or so, just the plain name.
  2. Now login to your GitHub account and navigate to your project. Choose the Settings panel (top right option). Once you’re there, scroll down to the GitHub Pages section. You will find here a place to type in your Custom domain like on the image below: Custom domain on GitHub Pages
  3. Point your DNS to GitHub Pages. Login to your domain provider’s panel. Add a new CNAME record and target it at your base user’s github.io site. Here is how it looks like in my case: DNS
    Wait for the DNS to propagate. You’re there, nice and simple. :)

Final word

Whew, you’ve done that! If you’ve read through both parts, congratulations, you are a patient reader. A great feature for a programmer! If you stumble upon any issues (pretty sure you will as every project is different, our needs too), the best places to dive deeper into Jekyll are:

Have fun working on your project. :)

Kamila Mar 28, 2017

Boids: planning the project


Failing to plan is planning to fail.

Alan Lakein


Before I decided to register to the “Get Noticed” contest, I had read a whole bunch of posts and articles by attendees of the 2016 edition. They were describing how the participation itself helped them grow as developers, why it is all worth time and effort - and how to prepare yourself to the challenge. Not surprisingly, they all emphasised the significance of having a good, thoughtful plan, factorizing the problem and getting into details of every single step. With that in mind, I started coding with… several sheets of paper and tons of bookmarks open in my browser to analyze what actually needs to be done and how to start. Here is what I have come up with.

Stage 1: Choosing tools and technologies

This one was quite obvious: HTML & CSS(Sass) for the project’s shell, JavaScript for the engine. Since there are many cool features introduced by ECMAScript 2015 (wider known as ECMAScript 6 or simply ES6), I will try my first steps here, taking advantage of the newly introduced classes, arrow functions, destructuring etc. The Boids themselves will be animated on HTML5 canvas and I plan to prepare an introduction to the canvas API in the nearest future.

Stage 2: Preparing the environment

Another warm-up thing: preparing a visual platform at which Boids will be flying. I have created a palette of swatches (an old designer’s habit) and decided to divide the layout vertically, leaving a left-hand aside for some basic information on the Boids idea and a simple manual. All the rest will be taken up by canvas. Initially I wanted to start with a single bird-oid form animating itself but then I changed my mind and chose a roughly straightforward solution to begin with. The elementary Boids will be simply small circles drawn directly on canvas. Once I figure out all the animation’s algorithms, I will try to think of a way to turn circles into something more complex. First things first.

Stage 3: Maths!

Now here comes the hardest thing for me, or at least at this point it seems so. Getting into counting! Vectors, numbers, algorithms… getting together three seemingly simple rules of flocking put me hardly off. Still, it had to be done. OK, a pile of blank paper sheets and a pen and let’s dismantle the sucker!

I will need a 2D coordinate system and an array of starting positions of Boids (X and Y). Thereafter, Boids will be placed on the given coordinates and put into motion. At this point there has to be a function that takes the initial coordinates and counts the next position of each Boid as per the rules described in the former post. A quick reminder:

  • separation: steer to avoid crowding
  • alignment: steer towards the average heading of local flockmates
  • cohesion: steer to move toward the average position of local flockmates

Let’s break these apart.

I decided to start with cohesion. To calculate it, I will need to find the center of mass for the flock. This will be the average of coordinates of all the boids except for the one, for which I will calculate the movement. I assume I will move the Boid towards the new position by 10% of the distance between the current and calculated position, just to keep the whole animation smooth and concise. In order to count the distance, I will need the Pythagorean theorem, a nice reminder of good old times in my primary school. ;)

Next, I will handle the separation rule. This rule needs a constant of the maximum distance between the boids. When a Boid gets too close to its colleague, it will need to steer away.

And finally, the alignment rule forcing all Boids to follow the average direction of the flock and adjust the speed of each Boid to its neighbours.

When breaking these rules apart, I came across a nice explanation of the problem by Conrad Parker. He decribed the calculations using pseudocode. This was a great help in my implementation, having understood this thing was enough to get down to coding in JavaScript.

Stage 4: Creating a Boid class

One of the cool new features of ES6 is the introduction of classes. Something for you, JS-despisers! JavaScript classes are actually just a bit of syntactic sugar over the Objects and prototypes but they make our code much cleaner and simplify working with inheritance. I will harness this new feature by creating a simple Boid class that keeps the instance’s position and speed.

Stage 5: Initial animation for a group of Boids

Having the initial group of boids on canvas, I will define the first basic animation. It can be simply running on the X-axis. Once a boid hits the canvas’ border, the direction of the movement will be reverted. Thereafter, I will make boids fly on the Y-axis as well so that they make use of the whole canvas’ area.

Stage 6: Counting next position

I will need a function that makes use of the previously defined cohesion, separation and alignment rules. This way the function will perform calculations of the next position of a Boid, then clear the canvas and redraw the whole flock on a new position. At this point I can tell I’d have released the projects’ .beta version. :)

Stage 7: Changing the circle into bird-oid form

Now it’s time to play: circles look dull so I will think of something more creative, probably in a form of bird. It would be great if every single boid would also animate itself, as if it was flying. If I get stuck, I will continue with the next steps and come back here after resolving the rest of the issues.

Stage 8: Adding controls

At this point I can hand over the control to the user, letting them decide on the boids’ amount, speed, distance etc. I will need a way to get data from the user: it can be a set of range sliders, buttons or other types of inputs.

Stage 9: First roadblock

Time for a first roadblock! I will put a static circle imitating an obstacle and write a function that steers boids away of it. More calculations ahead…

Stage 10: Dynamic roadblocks on user’s click

Now that I have a working roadblock, I will put the user in charge of adding and deleting the roadblocks. Guess the simplest option will be by clicking on the canvas to create a roadblock, then another click on the roadblock created would delete it. I may want to change the way the roadblocks look, perhaps add some randomness here too.

Stage 11: Getting it nice!

Once all is working fine and tested, I’ll get back to my Sass and add some styling so that the whole thing simply looks good. It’s also time to develop the aside part, put some more information here and maybe think of some kind of introductory part that tells the story behind the project. I hope to get back to this point before the planned 10 weeks pass.

Where am I now?

At this moment things are going quite fine. I got to the Stage 6 and the boids are flying as planned. You can check the current status here. In case you were curious, all the code goes to a GitHub repo. Wish me good luck! :)

Kamila Mar 24, 2017

Strange case of Dr Jekyll and Mr Windows / Part I

For many years I have been using Wordpress as an obvious choice when choosing a blogging platform. Wordpress is by far the most popular CMS on the market, supported and developed for 14 years, powering around 8% of all pages in World Wide Web. That speaks for itself. However, since I’ve been keeping my projects on GitHub pages for the last few months, I’ve discovered it might be much easier to run the next blogging project directly on GitHub server and make use of Jekyll due to its native support in GitHub pages.

So what is Jekyll?

As the recurring definition states, Jekyll is a simple, blog-aware, static site generator based on Ruby language. By saying “static” we mean it’s flat-file and ready for deployment. No databases needed, no security headaches, no maintenance issues. It’s ultra-fast, cheap (your blog can be hosted for free on GitHub pages) and manageable. The contents are written simply in HTML/CSS/Markdown so if you’ve had any blogging experience, switching to Jekyll should be duck soup. :) At least when you’re running it on Mac OS or Linux platform.

…but I am not.

And here’s where things go a little bit trickier. As the majority of Poles, I am a more or less happy user of a mundane Windows 7 (yes, 7, in 2017 I find it funny too). As it turned out, running Jekyll on Microsoft’s child was not as smooth as I hoped. I will try to guide you through the process and prevent you from running into some stumbling blocks I’ve needed to force through myself.

Some of the steps below look probably alike on systems other than Windows, however, since I have tested the process on Win7 only, I can not specify the exact differences.

Step 1. Ruby installation

Assuming that you have some basic knowledge of command line and are familiar with Git (and have Git ready to use on your platform), you can proceed with setting up our GitHub-hosted, Jekyll-powered website. First, we need to install Ruby. It is likely you already have Ruby on your machine so go ahead and type in your console:

ruby -v


In my case I got the following answer:

ruby 2.3.3p222 (2016-11-21 revision 56859) [x64-mingw32]


If your version is lower than 2.0.0, you can update it. If you don’t have Ruby yet, just visit this place and download the most suitable installer as per suggestions on the right-hand side. Don’t close the tab yet, we’ll go back to this page in a minute.

Now simply run the .exe files and keep clicking “next” until you see the screen below.

ruby-installer

Make sure to check the option in the middle, “Add Ruby executables to your PATH”. Click “install” and you’re done! Restart your console and run

ruby -v


again to ensure you’re good to go.

Step 2. Ruby Dev Kit

Since Ruby was not built to be used on Windows (although it is, surely, possible), it can be difficult to install some of the Gems (which you can think of, generally speaking, as a specific kind of library or plugin; more in-depth description here). Go back to the Ruby Installer page and scroll it down. On the left-hand site there is a “Development Section.” Choose the one appropriate for your system’s version and download it. Create a new folder called RubyDevKit directly in your C:\ ** directory. Select to extract Ruby Dev Kit’s .exe file in **C:\RubyDevKit (the folder you have just created). Now navigate to this path in your command line:

cd C:\RubyDevKit


Then go ahead and run the commands below:

ruby dk.rb init
ruby dk.rb review
ruby dk.rb install


If you encounter any trouble at this point, check up this place for a solution. That’s it! If all went fine, you’re ready to proceed and install Jekyll Gem.

Step 3. Setting up Jekyll and Bundler

To get your Jekyll up and ready you simply run:

gem install jekyll


You will need a package manager called Bundler to get all Jekyll dependencies installed properly. Your console needs the following commands:

gem install bundler
bundle install


There you go! You can now start your first Jekyll project. That simple.

Step 4. Get your Jekyll blog

Assuming that you know the basics of Git and GitHub, choose a path on your machine where you want to keep your new Jekyll project. Navigate there in your console. Now if for instance your project will be called coolblog, you need to run the following command:

jekyll new coolblog


Move to this directory…

cd coolblog


…and intialize your Git repo:

git init


In your project’s folder you will find a file called “Gemfile” (with no extension), open it up and comment the following snippet by simply putting # before:

# gem "jekyll", "(your version here)"


Now uncomment the “github-pages” gem below by deleting the # from the beginning of the line:

gem "github-pages", group: :jekyll_plugins


…and have a look at the end of the file which should say something like this:

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem 'wdm', '>= 0.1.0' if Gem.win_platform?


At this point bundler needs to be updated so run:

bundle update


You are now ready to get your blog life. Go ahead and type in in your console:

jekyll serve


to put Jekyll in kind of “watch” mode where all your changes to the blog’s files (apart from .yml configuration files) will be instantly introduced.

Now, in your browser go to http://localhost:4000. You will see your freshly created blog which will look like this:

your-awesome-blog

Congratulations! You’re ready to go!

Bear in mind that once you hit Ctrl + C or close the console, Jekyll server will stop and you will be unable to see your site on localhost. I myself was not aware of this initially and lost much too much time stack-overflowing why my blog stopped working. ;)

Further reading and tips

This has been a long post, however you may find it insufficient. To learn more about working with Jekyll I encourage you to visit the following places:

In the next post we will take a look at customizing your blog and running it on your own domain if you preferred it over the Git Hub default one.

Now get down to work, I keep my fingers crossed for your awesome project! :)

Kamila Mar 21, 2017

What the Boids?

What is this project about?

Ever heard about artificial life programs? Sure you have, Internet is full of information, projects and games based on natural life’s simulation. Consider Conway’s Game of Life, for instance, which simulates “colonies” growing or dying depending on how crowded or lonely the single cells are. It is still purely math-based but it very believably resembles a kind of natural life patterns, where cells are forming generations connoting almost a kind of collective intelligence, especially if they are given a really big space to colonize. Since I have lately programmed JavaScript implementation of Game of Life, I decided to challenge myself with something presumably much more demanding.

The “Boids” idea

As per Wikipedia’s definition, Boids is an artificial life program, developed by Craig Reynolds in 1986, which simulates the flocking behaviour of birds. I have encountered two derivations of the term “boids”. One says it is a shorthand for “bird-oid”, in other words, “bird-like” objects. The other suggests it stems from the way that New Yorkers pronounce the word “birds”. Leaving aside the story of the term, Reynold’s Boids model (also referred to as flocking algorithm) follows three simple rules:

  • separation: steer to avoid crowding
  • alignment: steer towards the average heading of local flockmates
  • cohesion: steer to move toward the average position of local flockmates

What is phenomenal about Reynold’s model is that using these plain rules only on single units it generates behaviour strongly resembling a real flock’s one. Just as in the Game of Life the result is surprisingly complex and realistic. Boids are one of many experiments in the field of so-called swarm intelligence characterized by the lack of centralized control agent: each boid follows its own rules, still resulting in a surprising group behaviour.

Here is a nice visualization and further explanation of the idea:

My goal

The purpose of my project is to create a JavaScript implementation of boids. I know I am definitely not the first one to try - there even are whole libraries and scripts available to use freely. However, I will try to figure the thing out myself, preferably with pure Vanilla JS. We’ll see what I’ll end up with. Keep your fingers crossed, I will report you soon about the project’s state!

Kamila Mar 18, 2017

Get Noticed! / ed.2017

..Ds - what?

You might be wondering what the heck is this Dsp2017 in the categories’ section and what actually am I doing here, starting yet another programming blog with little experience in front-end development. Well, what got me going with all this stuff is a competition opened by Maciej Aniserowicz, founder of Devstyle blog, one of the best of the kind in Poland. “Dsp” is a Polish acronym for “Get Noticed” and this is exactly the name of the competition. It is targeted at literally all programmers, no matter how experienced they are. Anyone can join, work on their own project, blog about it, share their knowledge and learn at the same time.

Believe me, I’m scared to death. I have defined my project (more about it in the following posts), gathered necessary materials but, as a newbie in the industry, I know I will need to work really hard to make my readers benefit from the posts here. That said, I know there are thousands of people like me and I hope to encourage them to step out of the shade and believe that if I can become an IT blogger, they too have valuable knowledge to share.

So why would anyone want to stay here?

Little experience does not mean having nothing to contribute. I’ve made sure my project would be ambitious enough to get some programmers interested. I will definitely stumble upon problems some programmers will encounter (or already did in the past) too and hope the solutions I come up with will prove helpful.

Schedule

The posts will appear at least twice a week for minimum 10 weeks continuously. Each week I will issue a post with some information related strictly to the project, and another one associated with coding / IT environment.

Technologies

You can expect me to write about JavaScript, as well as HTML/CSS/Sass issues. The blog is powered by Jekyll and hosted on GitHub pages so I plan to walk you through the process which turned out to be a bit tricky on Windows. ;)

OK, are you finished?

Yes. Not going to bore you to death. ;) If you wish to keep track of this blog, just make use of the RSS button on the home site.

Kamila Mar 15, 2017