Using Regular Expressions to Convert Text to “Cat Mode”

This week, I added “cat mode” to my personal website, rachelsalois.com. Essentially, I used jQuery to create a page that would dynamically load text. If a visitor clicks the “cat mode” link, the text reloads, replacing all words with “meow,” except for links. I also decided to maintain punctuation and capitalization.

While building out the feature, I created a few helper functions–isPunct, isLink, and isWords–that would return boolean responses and help determine whether to leave a text segment in its current state or convert it to meows using my meowify method. (You can check out the methods on my Github.)

This lead me to revisit Regular Expressions, a programming tool I’ve sometimes been wary to use because–let’s face it–compared to the readability of Ruby, Regular Expressions are hieroglyphic. In reality, though, they’re not that tricky to use, and sometimes extremely helpful.

Today, I checked out Britt Ballard’s excellent blog post about Regular Expressions, and was inspired to clean up the Regular Expressions I used in my functions, for practice and perhaps future reference. My project didn’t require particularly complex expressions, so be aware that there’s much more that can be done with Regular Expressions than I’m covering here. (Check out Britt’s post for some examples, keeping in mind that his use Ruby while mine were incorporated into a Javascript project.)

Four Easy and Useful Regular Expression

  1. Letters
JS letters
Return an array of all letters, case insensitive.

The [a-z] in this example could be replaced with any string or letters. Removing the “i” from the statement would make it case sensitive, so that, in this example, only [“y”, “a”] would be returned. Removing the “g” from the statement would mean only the first match would be returned.

2. Punctuation

JS match punct
Return the first punctuation found in a string.

This can be customized by adding or removing any punctuation or special characters.

3. All Punctuation

JS globally match punct
Return an array of all punctuation in a string.

I used this to save all punctuation from a string before splitting that string at punctuation.

4. Finding a link

JS match index
Return the starting index of a match in a string.

This could be used to find the start of a link in a string of text.

Using these regular expressions I was able to majorly simplify my code (though I’m finding that trying to convert my sentences while maintaining proper spacing and formatting is still quite a challenge!) I’ve still got some work ahead of me with the site, but I’m hoping that the work I’m putting in to automate my cat mode conversion will be helpful in later parts of my project as well.

 

 

 

Ruby’s Object Ancestors

Two weeks ago, I completed the Flatiron School web development immersive (woot!), and three weeks from now, I’ll be starting a position as an instructor at Flatiron, coaching students through Ruby  fundamentals (among many other topics) that I was learning four months ago.

51qtp4nzjrl-_sx258_bo1204203200_In the meantime, I’ve been taking a deeper dive into Ruby and reading The Well-Grounded Rubyist to make sure I’ve solidified the most foundational information in my mind.

That’s how I stumbled across Object ancestors again, and more specifically, became curious about Kernel.

Don’t know what Kernel is? Open up irb in your terminal and type Object.ancestors. This is what you should see (as long as you have ruby installed):

Object ancestors

So, what is Kernel (and, while we’re at it, what is BasicObject)?

David Black first mentions Kernel in chapter 4, Modules and Program Organization, of The Well-Grounded Rubyist. This is a hint to answering the question I posed, because, first of all, Kernel is a module. As Black says, Kernel is “the module where the majority of the methods common to all objects live.”

Just like any other module, Kernel is mixed in to a class to extend that class’s functionality. More specifically, Kernel contains the instance methods such as integer, loop,  rand, and puts, which every Ruby object has access to upon creation.

Meanwhile, BasicObject is a parent class. As the Ruby documentation plainly puts it, “BasicObject is the parent class of all classes in Ruby.” It only has a few methods, such as equals (“==”) and new.

So, essentially, when you create a new object in Ruby, what you’re doing is inheriting methods from BasicObject and then mixing in Kernel methods. Cool, right?

 

For a closer look at “puts” in the Kernel module, check out this cool blog post by Vaidehi Joshi.

 

 

 

Using the Spotify API

Last week, I completed my final project at Flatiron, a React-Redux app with a Rails API.*

My team decided to also make use of the Spotify API for our app, PlaylistPal, so that visitors could make playlists using the very cool metrics that Spotify stores about each of its songs, including danceability, valence, and amount of vocals.

Part 1: Requests without Authentication

Early into our project, we discovered that the Spotify API gives some information, such as an artist’s top ten songs, without any authentication. To get top ten tracks, we first took the user input of an artist’s name and made a get request for Spotify’s data on that artist.

From there, we parsed the unique artist id from our response, and made a second request to Spotify, this time returning the top ten tracks.

After that we could parse through the response from Spotify and grab any data we needed, including the track name, preview URL, and album title.

Part 2: Requests with Authentication

Making authenticated requests was quite a bit trickier, but after a few hours of fiddling we made our first successful request. Our first step was registering our app with Spotify in order to get our client secret and client id. These are simply strings of random letters and numbers that must be put in a secret file, so that they aren’t stored on Github and made publicly accessible.

In our app, we created sliders for users to select the danceability, emotional valence, etc, of songs that would be returned to them. The Spotify API requires requests to include an artist id or musical category along with the danceability and valence parameters, so we prompted users to enter an artist name before letting them manipulate the sliders and send a request.

In order to make our request for song recommendations to Spotify, we first had to get a token from Spotify (essentially another secret code!) using our client id and secret. The header of this post request contains a base 64 encoded string with the id and secret.

The returned token is then put in the header of the get request to Spotify, which has a url that includes the formatted query containing the artist id and other parameters.

Finally, the Spotify-recommended tracks are returned!

I should also mention that sites can use OAuth to authenticate individual user accounts with Spotify in order to get data such as albums saved to the user’s account or post tracks to a playlist. Check out the Spotify API docs for more info.

Overall, it took quite a bit of legwork to figure out how to properly format our requests to Spotify, but once we got it set up, we had tons of fun playing around with the data Spotify returned to us, and it added tons of value to our project.

 

 

**(For those who don’t know what React and Redux are, I’ll explain further: I built an app that uses the Javascript library React to build page components (such as a nav bar), along with the Redux framework, which manages the state of the application (such as the last item that was selected from a list). User information is stored in a Postgres database in my Rails API, so when I need to update my database, I make a post request from the React-Redux side to the Rails side. When I need to grab information from my database, I make a get request to Rails, which renders JSON, and allows me to parse the data I need.)

Chrome JS Console Basics

My Flatiron cohort has switched from “Ruby mode” to “Javascript mode” for the second half of our program, and among the many changes that come with programming in a different language, one that immediately stood out to me was my set of debugging tools.

Using debugger to pause my functions or console.log to print variable values isn’t so different from Pry and “puts” in Ruby, but the Chrome console–where I have been spending lots of time lately–is quite a change from the Terminal.

There’s a lot to take in when you first open the Chrome Javascript DevTools (press cmd+option+j while in a Chrome window)–html elements, a console, network status codes–all crammed into a side panel. So far, I’ve only made use of a small portion of its functionality, but this weekend I discovered Google’s extensive DevTools guide, and ran through some basic tools that I can make use of right away.

The Google guide is an excellent resource, so I’ll just focus on a few features that help illustrate the power and ease-of-use of some of the basic debugging tools: breakpoints, event listener breakpoints, and step buttons.

A breakpoint can be used to pause the code (just like debugger), but can be set without typing debugger into the js file, refreshing the page, and running the code.

set-breakpoint

In the above example, my code is paused in a debugger that I wrote into my js file. At this point, I can set a new breakpoint on line twenty by simply clicking on the line number. The line will be flagged in blue when the breakpoint is set. I can then press play to resume script execution until it hits my breakpoint. Play to next breakpoint.png

Once paused at a breakpoint, I can click the console tab and check the value of this.currentRound, for example.

The step buttons allow me move through the code without setting breakpoints. The down arrow steps into the next function call, which means that if the next line of code is a function call, the script will execute and stop at the first line of that next function.

The up arrow steps out of the current function, meaning that it executes the remainder of the function that it’s in, and then stops at the beginning of the next statement after the function call.

The step over (curved arrow) function call executes whatever happens on the next line and moves to that line. Step through.png

Aside from setting breakpoints at specific lines or using step buttons to traverse code, breakpoints can also be set with triggering events, such as a mouse click, or DOM mutation. In my below example, I’m creating a breakpoint to be set upon a timer being fired off.

Set timer.png

The script executes until it hits my function called “countdown” being fired from a setInterval method. From there I can click over to the console tab and do some debugging!

hit event.pngAs I mentioned, these are just a few of the available tools in the Chrome JS console. I highly recommend going through this demo for getting started with debugging JavaScript in Chrome DevTools, which goes through some of the topics I covered here, as well as introducing “watch,” another useful feature for checking changes in a variable.

 

Intro to APIs

Over the holidays, I built a mini Rails app using OMDb, a movie database, to find a summary, IMDb rating, and genres for a movie based on its title. Choosing an API for this project took a lot more work than I had expected. I had no idea how many APIs were out there and the variety of purposes they can serve. So I decided to look into what exactly an API is and how they came about.

First, what is an API?

An API (Application Program Interface) is code written for use by other applications, so that functionality and information can be reused or reinterpreted. The Google Maps API, for example, has been used to build applications such as a Zombie Outbreak Simulator and PlaneFinder, an app that shows realtime air traffic.

APIs provide information in a simplified format, such as JSON (JavaScript Object Notation), defined by W3Schools as, “a syntax for storing and exchanging data.”

“Unlike Web applications themselves, APIs are built for computer consumption rather than direct user interaction.” -Meg Cater,  A Brief History of API-Based Web Applications

And how did APIs come about?

In some ways, it seems counterintuitive for a company to give away their product for others to use. First, I’ll say: not all companies are “giving away” their product; there are plenty of APIs with monthly fees.

In regards to free APIs though, I’ve identified three forces (there are probably more) that push companies to offer them. One, the ethics of open data that has been embraced by tech companies probably more than any other major industry. Two, unofficial APIs often pop up when official ones don’t exist. And three, the API itself is now seen as a valuable asset that makes a product like GoogleMaps the web’s default map provider.

Some of the earliest APIs to launch were Salesforce and eBay, both in 2000 (though this Quora post indicates that the topic is up for debate). Flickr, Twitter, Amazon, Facebook, and Google soon followed.

“The Google Maps API launched was just shy of 6 months after the release of Google Maps as an application, and was in direct response to the number of rogue applications developed that were hacking the application.” –History of APIs, apievangelist.com

APIs are becoming more widespread and essential to web applications, which more than ever integrate multiple technologies. In 2009, the US government launched the website, data.gov, a major push toward open government data.

Social media APIs, such as Twitter, are some of the best known, but APIs are becoming more ubiquitous across all types of applications. Right now there are around 16,541 APIs listed in the directory Programmable Web.

For a further introduction to APIs, I recommend checking out the five-part blog series on Programmable Web entitled, What are APIs and How do They Work?. Programmable Web is also a great source for discovering APIs through their API directory.

Resources

 

 

Latency & Bandwith

While working on Udacity’s Intro to CS a few months ago, I first came across the term latency. This week, I looked back into the topic and discovered ‘latency vs bandwidth,’ an apparently oft’ misunderstood pairing of concepts that both relate to network performance.

So what are latency and bandwidth and how do they relate to each other? In the simplest terms, latency is the delay between sending and receiving data. Bandwidth is the amount of data that can be sent or received at one time. The blog Future Chips provides one illustrative analogy:

“When you go to buy a water pipe, there are two completely independent parameters that you look at: the diameter of the pipe and its length. The diameter determines the throughput of the pipe and the length determines the latency, i.e., the time it will take for a water droplet to travel across the pipe.”

(Throughput here is the same as bandwidth.)

This video provides another simple and informative–if somewhat awkward–example using balloons.

While throughput and latency could apply to many different situations (an example from Webopedia: “in accessing data on a disk, latency is defined as the time it takes to position the proper sector under the read/write head,”) in terms of the internet, bandwidth and latency determine the time between you entering a web address on your browser and the website loading on your screen.

Essentially, when you make a web request, you are sending a packet of data to the server and eventually out to the world at large. That packet has to make several steps on its journey, each with an opportunity for delay (yipee!). (For more info about what happens, this delightfully gimmicky ninja-themed infographic is a good start.)

In the book, High Performance Browser Networking: What every web developer should know about networking and web performance, author Ilya Grigorik defines four types of delays: propogation delay–the time your data spends hurtling through space to get to its destination and back (at near light speed); transmission delay–pushing data “on the wire,” determined by file size and bandwidth;  processing delay–checking to see where the data is going and if there are any errors; and finally, queuing delay–data waiting to be processed (using our pipe analogy from earlier, the pipe is already filled with water.)

To recap, bandwidth determines the amount of data that is processed at one time; latency  is the total time between the sending and receiving data.

51-7aadghul-_sx379_bo1204203200_Closing notes: From what I’ve read so far, High Performance Browser Networking is a gold mine of information and a surprisingly engaging read on this topicIlya Grigorik is a web performance engineer at Google and is a co-chair of the W3C Web Performance Working Group, AKA he’s a very knowledgable person. The books is totally worth checking out, and available for free online. It’s also part of a Definitive Guide series of books about web development (all with animal sketches on the cover; I don’t yet know how the animals relate).

Finally, I’m a student! If you notice any errors in my understanding or terminology here, comment, please!

Ruby: Using Directories

Until this past week, my coding hadn’t expanded much past a repl environment. Last Monday, that changed very quickly because I started an immersive web development program at the Flatiron School.

My first week at Flatiron expanded my scope far beyond coding in my beloved repl.it environment. I was using tools like Terminal and the text editor Sublime Text to do things like interact with directories. Here’s how to use Terminal, explained a bit in an earlier post, and a text editor such as Sublime to create a directory and then output an array of files from it.

A directory is a collection of files (maybe music files or photos, for example) that can be accessed from a Ruby method. Ruby methods Dir.entries and Dir.foreach use the directory file path to return file names:

Let’s pretend I want to create a directory filled with images I could use as profile photos. Some of the files are jpegs and others are pngs (of fun, customizable emojis that I design on madewithcode.com.) I’m going to build a method that will access my ProfileImages directory and output only files with a .png extension:

  1. In Terminal, I go to the place I want to store my directory: cd /Users/rachel/dev
  2. I Make a new directory, which will contain a directory of my images, as well as a Ruby file: mkdir “EmojiFinder”
  3. I change into the EmojiFinder directory: cd EmojiFinder
  4. I make a ProfileImages directory, where I’ll put my images: mkdir “ProfileImages”
  5. I change into the ProfileImages directory and copy in my photos: cp /Users/rachel/Desktop/emoji_mini.png /Users/rachel/dev/ProfileImages
  6. I change back into my EmojiFinder directory: cd ..
  7. I create a ruby file: touch “EmojiFinder.rb”

This method outputs an array of files from ProfileImages directory. From there, I could iterate through the array, outputting only files that contain the .png extension, but I think I’ll solve this a little differently.

This method iterates through the files in the directory, and will only output files with a .png extension. I called the method using the file path to the ProfileImages directory.

Et voila! Running ruby EmojiFinder.rb in Terminal outputs all image files with a .png extension.

Helpful resources: