Finding the Overlap of Two Rectangles in Ruby

In our 3rd-to-last week at General Assembly, we spent an entire week learning about Computer Science basics including sorting algorithms, tree structures, and how to solve puzzles with code.

In the process of studying this material, I came across the following puzzle: Create a function that prints out the overlap of two rectangles based on two diagonal coordinates of each rectangle.

Input:

$ square = [[2,3],[9,8],[7,-4],[11,5]]
$ check_square(square)

Expected output:

$ [[7, 3], [9, 5]]

Or for those who are visually inclined:

To solve this problem, we need to first check the coordinates provided to ensure that they both represent the bottom left and top right corners of each rectangle. To do so, we check if the x value from the first coordinate (2 in this case) is larger than the x value from the second coordinate (9 in this case). If it’s larger, the coordinates represent the top left and bottom right coordinates (not good!) so we need to switch those coordinates. The same goes for the y value of each coordinate.

Once the coordinates are fixed, we call bound_box() which determines the overlap. To do so, we first find the max x and y values from the bottom left corners of each rectangle. Then we find the min x and y values from the top right corners of each rectangle. The result is the coordinates for the overlap rectangle.

Here’s my solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def check_square(square)
  #Ensure coordinates make a rectangle (not a line)
  if square[0][0] != square[1][0] && square[0][1] != square[1][1]

    #Switch coords if x value from 1st coord is > than x value from 2nd coord
    if square[0][0] > square[1][0]
      square[0][0], square[1][0] = square[1][0], square[0][0]
    end

    #Switch coords if y value from 1st coord is > than y value from 2nd coord
    if square[0][1] > square[1][1]
      square[0][1], square[1][1] = square[1][1], square[0][1]
    end

    bound_box(square)

  else
    puts "Coordinates do not make a rectangle"
  end
end

def bound_box(square)
  #Create two squares for easier traversing of array
  square_1 = [square[0], square[1]]
  square_2 = [square[2], square[3]]

  #Return array with max points for bottom left, and min points for top right coordinates
  [
    [[square_1[0][0], square_2[0][0]].max, [square_1[0][1], square_2[0][1]].max],
    [[square_1[1][0], square_2[1][0]].min, [square_1[1][1], square_2[1][1]].min]
  ]
end

Quotables: Linus Torvald on Open Source Projects

Some wise words from the man behind Linux excerpted from Dreaming in Code by Scott Rosenberg.

In June 2004, Linux Times published an interview with Linus Torvalds, Linux’s Benevolent Dictator.

“Do you have any advice for people starting to undertake large open source projects?” the interviewer began.

“Nobody should start to undertake a large project,” Torvalds snapped. “You start with a small trivial project, and you should never expect it to get large. If you do, you’ll just overdesign and generally think it is more important than it likely is at that stage. Or, worse, you might be scared away by the sheer size of the work you envision. So start small and think about the details. Don’t think about some big picture and fancy design. If it doesn’t solve some fairly immediate need, it’s almost certainly overdesigned.”

Lederfeier: Making Conversations Happen

For our second Web Development Immersive project at GA, we were tasked with working with a group of fellow students to build a web app. The first challenge we faced was coming up with an idea. In preparation for that, we decided, as a group, to utilize design thinking to brainstorm project ideas, and then refine those ideas into something that we would all be proud of at the end of the 8 days allotted to building the app.

The final idea was to build a social party app, which we later called Lederfeier that provided fun prompts to people to spark real-life conversations. While seemingly ironic, we wanted to use smart phones to help people put down their smart phones and have a real conversation! The features were simple: a party planner would be able to create a party, select a prompt rating, and invite participants by entering their phone numbers. Participants could also join by texting a passphrase to a dedicated phone number. Once the party was officially started, all participants would receive a conversation prompt via text message, that they could pass or complete. See below for some prompt examples.

Prompt Examples:

  • Almonds. Discuss.
  • If you could make something that’s not socially acceptable, acceptable. What would it be?
  • Describe the best meal you’ve ever had
  • Describe the characteristics of a perfect pair of socks

Working in a group project was exciting as it allowed each of us to focus on certain parts of the project while learning from eachother’s expertise. I’ve included some thoughts on core aspects of the project below.

TDD:

To distribute text messages, we used Twilio. The integration was seamless and honestly a charm to put together. However, we quickly realized that testing all the potential participant responses and edge cases via a phone keyboard would be not only expensive (Twilio credits cost money), but VERY time consuming. Fortunately, we made the decision to leverage TDD to test all of the Twilio messages and responses. This decision turned out to be an incredible time saver, and it allowed us to confidently make changes to the app without fear of breaking things.

Mobile-First and AJAX requests:

To ensure that the user experience was easy to use from a smart phone, we spent a lot of time working on the UI and user flow. We made an effort to minimize user interaction by using ajax requests to refresh page data on a set interval. We also made the buttons big enough to click on from a mobile browser, and only rendered buttons when necessary using jQuery selectors.

Github: (Lederfeier Repo)

As familiar as we had become with Github during WDI for personal projects, working with Github in a multi-user team presented a new set of challenges. Following best practices, we created a central repo and each team member forked that repo to make changes. Once those changes were ready, a pull request was made and another team member reviewed and accepted the pull request. We quickly learned to rebase off the master on our local forks before sending the pull request to avoid serious version control issues!

Refinery Gem: Content Management in Rails

In my previous life I was a marketer and website manager. It’s safe to say I spent A LOT of time building and updating site content in many different content management systems. Wordpress, Typepad, Drupal, Joomla and others all became good friends of mine, some more than others. Wordpress was always my favorite for many reasons. It’s relatively easy to manage and update content, even for non-technical people. There’s a huge community of designers and developers who build templates for Wordpress implementations, not to mention countless plugins that make integrations fairly easy – although admittedly I’ve had plenty of problems with those WP plugins.

As a newly minted developer however, my perception of a CMS has changed significantly. While Wordpress may be great for static content sites with minimal functionality, Wordpress can quickly reach its limitations when it’s asked to manage large data sets or perform complex functions.

It was for these reasons that I was excited to learn about the open source Refinery CMS gem for Ruby on Rails. The platform incorporates the front-end ease of use of Wordpress with the powerful MVC backend of Rails, all bundled up (yes, I’m going there) in a developer friendly gem. In my opinion this makes for a winning combination. There is also a large community supporting Refinery which makes integrations a snap. In fact, here’s a list of some of the Refinery engines. And of course there’s the ability to scale a rails app quickly and efficiently, including data integrations, account management, secure payment processing and much more.

A quick google search on Refinery will also brought up a long list of favorable reviews (here’s one of many) about Refinery. Other developers who have implemented the Refinery Content Management System claim that it’s fast, reliable and scalable, all wrapped in a easy to use novice-friendly UI. Did I also mention that Refinery is a completely open source project?

All in all, Refinery is definitely a gem that I’ll consider the next time a CMS type project comes along. If you’re interested, go check out Refinery CMS for yourself.

A Failure’s Learning

As many smart people before me have said, failure is a necessary evil on the path to success. I personally could not agree more with that statement. I believe failure is absolutely necessary not only to help one learn and grow, but also to appreciate success. In much the same way that happiness can only be appreciated by those who have experienced sadness, success can only be appreciated by those who have failed.

While looking for an article about failure, I came across many references to the ‘failure rates’ of startups. While the number of unsuccessful startups is quite high, the successful ones often more than make up for it in the returns investors receive. In my research, I came across an interesting blog post, written anonymously, titled “My Startup has 30 Days to Live”. The post describes a situation in which the founder finds his company in a spiral towards an inevitable failure with, you guessed it, only 30 days to live. The author reflects on the mistakes he made along the way, including building a team of people he loved, but people that couldn’t build a sustainable company, and joining an accelerator followed by rounds of VC funding. Interestingly the exercise seems very therapeutic and the author in the end realizes that he’s happy he quit his job and decided to start a company. While the fear of not being able to pay his staff is certainly terrifying, he still manages to see the bright side of things.

I’ve come to realize that many people in the US especially, are generally pretty good at taking failure on the chin and continuing on. The US has a culture where failure is acceptable, and in a lot of cases, even desired. There are countless stories of people in professional settings who have been rewarded for failing, from the VCs who will only invest in founders who have failed, to the managers who refuse to fire employees that made a big mistake because in their eyes, they just spent $X to train that person and to make sure they won’t make the same mistake again.

On a personal note, I can think of many failures of mine, both professionally and personally. But I’ve always made an effort to not dwell on those failures as negatives, but instead look at them as positive learning experiences. On the professional side, I spent many years in positions where I wasn’t entirely happy, but stayed in those positions for fear of falling behind in the great race to success. I’ve also spent time working on multiple projects that ultimately failed for a variety of reasons ranging from inexperience, lack of vision and a desire to make things perfect thereby missing the market entirely. Each of those experiences have taught me many valuable lessons that I will be able to use forever.

In the end, I leave you with this quote by Obama:

“You can’t let your failures define you you have to let them teach you. You have to let them show you what to do differently next time”

Learncode: My First Project as a Web Developer

With four weeks of GA’s Web Development Immersive under my belt, it came time to embark on my first official Rails project. I knew I wanted to build something that leveraged a publicly accessible API and a map. Fortunately, I stumbled upon Code.org and their awesome Local School Database API. After some brainstorming, I wanted Learncode to achieve the following: – Inspire visitors to learn to code – Help those visitors find relevant self-study information – Display all the physical schools where one could learn to code

For my MVP, I focused on implementing the following features: – Access Code.org’s Local Schools Database – Install Leaflet maps – Add map markers using address-to-Lat/Long conversion with Google Maps – Embed school data in a map marker popup – Add search-by-address functionality to move the map to the entered address – Create an aesthetically pleasing UI

I was able to move quickly with implementing many of the MVP features, but encountered a few challenges that required some creative problem solving and help from my instructors to overcome.

Challenge 1:

The Local Schools Database was temporarily down meaning I could not access the JSON schools data with a simple Ajax request.

Solution: Developed a Nokogiri rake task to scrape a data sample for a handful of cities as a proof of concept for the MVP. With the sample data in my database, I developed a second rake task to convert each school’s address to lat/long and stored that in the Database. I later implemented the Rails Geocoder Gem for this.

Challenge 2:

Render the map-markers using Javascript to avoid routing the user to a new view after each search.

Solution: Implemented an Ajax request to pull in the markers from the Database and render them on the page. To do so, I created an API using a respond_to query in my Rails controller. I’ve included the ruby code snippet below.

Ruby on Rails Controller Index Function:

#Select all offline schools from Database and assign to variable
offline_schools = OfflineSchool.all

#API to render data accesible via an AJAX request
respond_to do |format|
  format.html
  format.json {
    lat = params[:lat]
    lng = params[:lng]
    render json: OfflineSchool.near([lat, lng], 50, :order => :distance)
  }
end

After the MVP was complete, I spent time improving the front-end, while implementing a few more controllers and views with relevant content to inspire users to learn code and help them find self-study resources.

Looking back, building my first real website from scratch was an incredibly rewarding experience. I challenged myself to learn new things while leveraging everything I had learned in the previous 4 weeks at General Assembly. But more importantly, I achieved a major life goal of mine (to build a web app on my own) and sparked what I know will be a life-long passion for web development.

Here’s a link to my Heroku deploy and the Github Repo. I’ve also included some screenshots of Learncode. I plan to soon release some updates to resolve some of the JavaScript and CSS bugs.

To Fingerprint or Not

In light of Apple recent announcement to include a fingerprint scanner in the iPhone 5s, a lot of discussion has taken place around how secure biometric readers really are. The biggest question detractors ask is, do you really want your password being something that you leave virtually everywhere and you can never change? The logic is hard to deny. In an article by Dustin Kirkland on his blog From the Canyon Edge, Dustin makes the point that fingerprints should be reserved for usernames only. In his opinion, “Biometrics cannot, and absolutely must not, be used to authenticate an identity.” While it may seem like something form a spy movie, recreating a fingerprint from a picture is easier than it seems, as the Chaos Computer Club recently proved. The author goes on to say that a passphrase that is independently chosen, changed and rotated is the only true way to maintain security.

The only value Dustin sees in the biometrics scanners is to customize experiences on a device shared by many users. Or in other words, having your fingerprint act as a username.

While most commentors on Dennis’ article agree wholeheartedly that biometric scanning is un-secure, there are a few who bring up valid points in disagreement. For example, one commentor relates this to the locks on your home which require a key which can easily be stolen by someone. Even more, that someone could watch you enter a passcode, or even hold you at gunpoint if they really want something. Another commentor adds that this is more of a convenience factor the majority of people. He states that 50% of iPhone users don’t even use the PIN lock on their phone. The most logical reason being that it’s to inconvenient to type in a passcode every time you want to use your phone.

In my opinion, it’s more important to look at this issue from a relative perspective. In the end, nothing will ever be 100% secure. So we must ask, what is comparatively more secure and convenient enough that people will actually use it. Is it better to have someone not use a passcode, or use a biometric scanner this is super convenient (assuming that it works) and that realistically is not “easy” to hack. I think many of the detractors of using biometric technology are not considering “everyone else” in their analyses. They go so far as to say, “Well, I’m a techie and I wouldn’t use it in the .0001% chance that someone could recreate my fingerprint, so that means no one should use it.” Such blanket statements are dangerous in my opinion and fail to recognize that not everyone is the same and not everyone sees value in NSA level security (or insecurity) to access their stuff.