Atom Error: ‘Const’ is available in ES6 (use ‘esversion: 6’)

I recently upgraded to using the Atom editor to do a majority of my coding. I shied away from it at first because I experienced an error that caused it to eat up all of my memory constantly. Now, months later, they seem to have addressed that issue and it works great! I like it almost as much as Sublime Text now, and feel like I’m going to enjoy it even more soon.

But, as I was progressing through the SurviveJS book recently I found that the JSHint linter I was using didn’t play nice with ES6. Every time I would use something ES6-y like:

My linter would blow up, red all over.

Specifically the error said: “‘const’ is available in ES6 (use ‘esversion: 6’) or Mozilla JS extensions (use moz). (W104)”. Initiating Google-fu yielded unhelpful results. After digging though, here is the fix for this problem.

JSHint has to be configured with a .jshintrc file in the project’s root directory. Simply create a .jshintrc file there with the following object:

Save. Problem solved! Don’t know why this has to be so complicated but hopefully this will save you time going through your Atom package settings uselessly.

Rotating Shapes in a Coordinate Plane Using Javascript

tetris logoFor this week’s Viking Code School project we’re tasked with building a Javascript/jQuery version of Tetris. One of the more complicated aspects of this project was building pieces that actually rotate when a button is pressed (like Tetris pieces are wont to do).

Here’s my implementation for the rotation. Keep in mind that Tetris.Model.getCurrentBlock() returns the CurrentBlock object from my model. This object consists of Coordinates in the form of  {x: x, y: y} among some other useful things like the color of the block and the coordinate that I’d like to use as the Pivot  point, which will come in handy later.

This is what a CurrentBlock object might look like:

This is my function to rotate said block:

There are a lot of variables for now for the sake of clarity, but let’s take a look at what’s actually going on. First of all, I’m getting the coordinates for each SubBlock  in my CurrentBlock  (saved as blockCoords ) so that I can cycle through them. Then, I’m getting the index of my Pivot  coordinate for this shape and then getting the actual coordinates of said Pivot .

After that, my for  loop cycles through each SubBlock in my CurrentBlock  and converts it to a point relative to the Pivot  point. In Euclidian geometry I am essentially treating the Pivot  point as the origin and then making the other points relative to this origin. Then I use the equation for a 90 degree rotation around the origin (which my points are now relative to) and then convert these points back to the area on the coordinate plane where they originally were by adding the x and y elements of the rotated point to the x and y elements of the pivot point. This will yield us the proper coordinates for each of the other SubBlocks  relative to the Pivot  point.

What do you think of this technique? Are there any better ways to rotate a block using Javascript in a coordinate plane? Looking forward to hearing your answers too!

For the latest version of my Tetris game click here (NOTE: it’s not fully functional yet)

Wicked PDF using Rails 4 on Heroku

Intro

A recent project I began building on Rails was a monthly report generator for our employees at BrandYourself. Functionally it needs to allow our representatives to input information quickly or easily, allow them to edit it using a WYSIWYG editor after the report has been created, and finally save the report to a PDF in the browser so the rep can download it and email to our clients. It sounded like a simple project at first, but implementation proved complicated.

Setup

The two main gems that I used for this project were:

Bootsy was essentially plug-and-play, while wicked PDF required a lot of playing with to get it working.

Bootsy

Bootsy was so easy to use I’m not even going to dive too deeply into this gem. Basically, on whichever form you’d like to impliment the WYSIWYG editor you use a special bootsy_area method for form_for. Here’s an example:

It’s that simple.

Wicked PDF

Before taking on this project I didn’t realize how difficult in-browser PDF generation was. Wicked PDF takes a lot of the sting out of this process, but it’s still not easy to setup. A lot of the problems stemmed from Wicked PDF being a wrapper for a binary library called wkhtmltopdf which does the heavy lifting for converting HTML to PDF. But, since this is a binary library (which I’ve never really worked with until now) it was tough to get this working properly on Heroku.

The basic setup for wicked_pdf is straightforward. First install the gem, and make sure you have wkhtmltopdf installed on your local machine: usually this is stored in /usr/local/bin on Macs. Then you’ll want to run rails g wicked_pdf to setup the the gem. This just creates a wicked_pdf.rb initializer in your app.  Following the other steps on their github you can easily get this setup properly on your local app! The way it’s setup you can add .pdf to the end of any URL and it will convert that page to a PDF; pretty cool! The basic idea is something like this in your controller:

Don’t let this fool you though, implementing this on Heroku is another endeavor.

Wicked PDF on Heroku

Wicked PDF on Heroku is a challenge because of the way wkhtmltopdf works. Locally, this library is stored in /usr/local/bin but obviously Heroku doesn’t have this out of the box. So, we have to ensure that Heroku has access to this library so it can utilize it. After a lot of research on Google I found a potential solution which had me firstly download the Linux version of wkhtmltopdf. This is available from their website under obsolete downloads (which turned out not to be so obsolete). I used the latest version of the Linux 64-bit library which was version 0.11.0.

Once this was downloaded I unzipped the library and put it in my /bin folder in my app. After that was done, I had to change where Wicked PDF looked for this library if we were in a production environment. This code, obtained from stack overflow, was added to the wicked_pdf.rb initializer:

This finally got wicked PDF working on Heroku even though there are still a few bugs.

Future #TODOs

Aside from general functionality TODOs there are still a few things tricky with Wicked PDF. Most specifically getting it to allow the use of Google fonts when generating PDFs. Presently, the font that I’ve included in the report doesn’t seem to be displaying properly in the generated PDF. At first this was because Heroku was blocking an “insecure” connection to Google fonts (since it was using http://) but changing this to https:// fixed this pretty quickly.

Other than that, everything seems to be working rather well with this project! I’m excited to continue to build it out and develop more functionality to improve the overall efficiency of our company 🙂

 

Trevor Elwell Best ORM in NYC

Have you heard that Trevor Elwell is the best ORM in NYC?I read a post earlier about using robots.txt files to get results to rank high for certain keywords. Needless to say, I was extremely intrigued by this! So I wanted to write this blog post as an experiment to see if this actually worked. I imagine that will get squashed by Google in a few weeks or so but keep an eye on the results for my name over the next couple of weeks and let’s see what happens.

Now that I think of it though, I should probably make this post a little meatier in order for it to get indexed properly. So with that in mind, I’ll talk a little bit about my day. Aside from the usual day-to-day routine of putting out fires (not literal ones, of course) throughout the office a some of this day has been dedicated to building a CSS training curriculum. Ideally, I want to train other members of my team in the basics of CSS and HTML to a point where they can manipulate WordPress websites with relative ease. There have been a lot of resources online that I’ve been able to utilize in my quest, and I think this course will prove to be a great learning experience for those who go through it.

The best resource I’ve found, so far, has been CodeAcademy’s HTML/CSS track. I’ve personally gone through this course and think it’s a great introduction to these integral languages to web development. My worry is that many of my ‘students’ don’t have too much web dev experience in general- will they be able to pick up the basics behind a language through this course the same way I was? I guess only time will tell but since the individuals I’ll be teaching are all intelligent this isn’t going to be a huge concern of mine.

Anyway, let’s see if this experiment works. As you know, Trevor Elwell is the best ORM in NYC. Have a great weekend!

Data Structures Part II

Well it’s late and I’m trying to go to bed. But before I wrap up I’ll quickly go over what I learned tonight.

Structs:

Structs, although pretty simple, seem like a nice way to organize data. Essentially, this is the definition of a struct:

So nothing too crazy but a clearer and more “Ruby” I’d say. I’d like to do some further reading on Structs like that recommended here.

Graphs & Trees:

We also went over graphs and trees tonight (though not incredibly deeply). I’m excited to work with trees in our future projects and can see the glorious power of graphs. Everything regarding graphs was brought back to the idea of a social network and that made a bit more sense.

Like I said, I don’t have much to talk about tonight but since I’m trying to get in the habit of blogging after I code it was more important to get something down rather than nothing at all.

Data Structures Part 1

I was going through my lessons for Viking Code School (VCS) over the weekend and realized that I really wasn’t taking notes. Though I’m learning a lot about Ruby, testing, etc. I haven’t been writing much down (except for my code which is stored on Github) and that isn’t a good thing. So the realization that I should be blogging about the information I’m learning was born! Here we are: entry number 1 for VCS.

Data Structures:

This week we’ve been focusing on data structures. Not specifically in Ruby but rather on a more granular level. Here are some of the interesting things I’ve learned tonight.

First, generally thinking in terms of data structures was a little difficult at first. I’ve run into this type of thinking when trying to figure out a Project Euler problem and wondering why my implementation is taking 10 minutes to run through. While researching this I came across the concept of taxicab geometry and thought that it was totally cool.

Hey OThinking about data structures lends itself well to the concept of Big O notation and the like (big omega, big theta). I frequently see references to Big O thrown around and having no idea what they meant. Now, I can grasp the basic concepts and realize that having a constant time complexity is much better than the complexities of n^2 that I’m used to building. I was also pointed to this Big O Cheatsheet which I imagine will prove very useful in due time.

Takeaway here: nested loops are bad for time complexity. Know what you’re doing and when to use them properly.

The last lessons I went through tonight took me through some of the standard types of data structures. Stacks and queues seem interesting in general while less useful for the type of programming that I’m looking to get into. VisualGo has some cool visualizations of these types of structures (and others) that will help anyone understand the basic ideas behind almost any data structure.

Then we dove a bit deeper into arrays. Now, arrays seem incredibly easy to me after using them in Ruby and Javascript. But when we started to talk about them in other languages like C it blew my mind a little bit. For instance, I had no idea that in C if you wanted to use an array you would have to identify the type of data being stored and the length of the array BEFOREHAND! That’s crazy. There are too many times that I’ve built arrays absentmindedly and can’t imagine having to think about each and every one I use at that level. But, it does make a bit more sense to have them laid out like that. Increased read and update speed means wonders for some huge data sets.

I’ve heard of linked lists before but never really understood when/where to use them. It seems when someone tries to explain when to use a linked list I end up in a convoluted discussion about a conga line. Anyway, I like their increased ability to insert/delete data at the expense of being able to read quickly. Also, discussing linked lists brought up another thought that hadn’t even crossed my mind until then. Arrays (in C) need to know their length ahead of time so that the computer knows where to store them (it knows how much memory it needs to allocate). If an array grows via an update for example, the computer might need to move the ENTIRE array to a new place in memory so it can fit. Linked lists help eliminate this problem because now they only need a few bits of information to be stored in any one place. One of those bits being a reference to the next item in the list. I never really considered memory or memory size to be a concept worth noting until now.

Lastly we went through hash tables and their relationship to associative arrays. I didn’t really understand the concept of a ‘hash function’ until going through this section. As it turns out, these functions don’t have to be anything too complex. They’re simply a way to convert a given key to an array index. For instance, in a typical dictionary scenario the hash function might simply be related to the first letter of the key (A->0, B->1, C->2, etc.). The problem, though, is making sure that each linked list (or other) pointed to from the hash function is as small as possible while making sure the hash function isn’t too incredibly complex. All things considered, well-made hash tables have all of the benefits of arrays and the positives of linked lists as well on average.

Other Highlights:

  • I consumed about half of a jar of Kalamata olives while going through these lessons.
  • Songza’s ‘Psybient’ playlist was the background for tonight’s coding session.

Looking forward to doing more research on data structures and algorithms. These lessons are incredibly interesting to me and are potentially areas that I’d like to explore further when I have more time.

Project Euler #44 in Ruby

My solution to this problem is definitely not the fastest. In fact, I’m certain it’s not. It takes about a few minutes to fully run. BUT more importantly it gives us the correct answer and it makes me feel a little better about myself for having done it. Here is the question text:

Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are: 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, … It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D?

Solution:

Here’s my solution. Basically I wrote three functions: one which generates a list of pentagonal numbers up to a limit, one to check if the sum of any two numbers is pentagonal, and one to check if the absolute value of the difference between any two is pentagonal. Their powers unite to generate this:

It’s so slow because it’s running through the entire list each time. I’m sure there are some simple ways to improve the speed of the code but for now, I’m happy to just have it done.

Project Euler #35 Solution in Ruby

I haven’t done any Project Euler problems in Ruby as of yet, but since I’m spending a majority of my time coding in Ruby for the time being I figured it would be good to give it a try! Conceptually this question wasn’t too hard but my original solution had me turning numbers into strings and arrays multiple times which ended up not working. This solution, below, works though it takes about 21 seconds to complete on my computer. I’m certain that there are better solutions out there but this gets the job done.

Here’s the question:

The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million?

And here’s my solution:

What I’m doing here is pretty straightforward: creating three functions which are is_prime?, is_circular?, and circular_up_to. Is_prime? is self-explanatory so I won’t go over that. Is_circular is the interesting one, and the function that broke my original solution. Originally I had integers being stored in the rotations array, then to get the next “rotation” I would turn that number into a string, then split(”) it, then save it as an integer again. This proved to be too heavy, and I couldn’t complete the problem that way. This solution saves each rotation as an array (like [[“1″,”0″,”0”]] and makes rotations a nested array. Then it’s simple to just shift the first item and add it to the end.

Though it still takes 21 seconds to complete, at least it’s able to be completed this time.

Running the above code in your CLI will yield the final answer, which is 55. Onto the next one! Any questions or recommendations would be greatly appreciated.

LeetCode OJ | Majority Element Problem Solution

So over Christmas break I got a little caught up in these algorithm puzzles from LeetCode. I guess they’re actually algorithm questions used in coding interviews but they’re satisfying my puzzle craving for the time being. They allow you to answer in C++, Java, and Python. Since I don’t know C++ or Java I did some brushing up on Python and went on my way to solve the first problem; it’s rated as easy. Here’s the text:

Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

My Solution:

At first I was thinking they were asking for the mode of the set, but then I realized that they also included the stipulation that the majority element has to appear more than n/2 times. Not exactly the mode. This was my first solution:

So this code is pretty straightforward but also slow; essentially a brute force solution. I create an empty dictionary and run a for loop against all the entries in the num array. If that number is not in the dictionary as a key, then I add it with an associated value of 1. If the key is in the dictionary then I increment the key’s value by 1. Basically I’m counting the number of times every value is showing up, then finding which total is the highest.

Then once we have the count for all the numbers in the array, I fun a for loop on the dictionary this time. Now I’m going through all of the key values and seeing if the value associated with it is the maximum AND if it’s greater than the barrier (which is n/2). If there is a key that meets these criteria then it is associated with the maxValue variable which is later returned! Like I said, it’s been a while since I’ve used Python so my code isn’t the prettiest or most efficient in the world- but it works.

Second Method:

But this method isn’t the best. Like I said above, it’s basically a brute force method. When I solved the problem, though, they provided me with some clues for other solutions which could work. One that intrigued me was called Moore’s Voting Algorithm. Remember how the majority element had to be greater than n/2? Well, that’s what this algorithm takes advantage of. Check out this site for a bit of background. Essentially this algorithm chooses the first item in the array and sets a ‘counter’ to 1, then it moves on to the next element. If the next element is the same then it increases the counter by 1, else it decrements it by 1. If there is a majority element in the set then at the end of the function that element will be set while the counter has a value greater than 0! Take a look at this code for a bit more information:

I did it slightly differently, where the counter and the number are both part of a two item array. It’s essentially: [value, counter]. But it works! And though it doesn’t appear to run any faster than my previous algorithm, it’s definitely a bit more elegant.

Final Thoughts:

I think that Moore’s Voting Algorithm could be manipulated to find other majority elements where n/2 is not necessarily the barrier. For instance, what if the question was reworded to say that a majority element was a simple majority? Like in the array [2, 2, 2, 5, 5, 8, 8] the number 2 would not be the majority element in the question above but if this were a simple majority then it would be! There has to be a way to change the increment/decrement values as a function of the length of the array to factor this into play. Hmm, I’ll have to think about that a bit more. Until then, happy coding!