Tuesday, June 16, 2015

RubyKoan: test_creating_hashes

This Koan is to get you to understand a Hash.

  def test_creating_hashes
    empty_hash = Hash.new
    assert_equal Hash, empty_hash.class
    assert_equal({}, empty_hash)
    assert_equal 0, empty_hash.size
  end

Hash.new and {} creates an empty hash.
Curly brackets {} encapsulate a hash.
When you create a hash this way, by default is has no size


  def test_hash_literals
    hash = { :one => "uno", :two => "dos" }
    assert_equal 2, hash.size
  end

Creates and add values into the hash.


  def test_accessing_hashes
    hash = { :one => "uno", :two => "dos" }
    assert_equal "uno", hash[:one]
    assert_equal "dos", hash[:two]
    assert_equal nil, hash[:doesnt_exist]
  end

Creates a hash, adds two key, value pairs.
Calls asserts that verify the data is inserted in the correct place.


  def test_accessing_hashes_with_fetch
    hash = { :one => "uno" }
    assert_equal "uno", hash.fetch(:one)
    assert_raise (IndexError) do
      hash.fetch(:doesnt_exist)
  end

This one is the same as above except is uses fetch to call the value of :one
It repeats this for an IndexError to be raised for a fetch that doesn't exist.

    # THINK ABOUT IT:
    #
    # Why might you want to use #fetch instead of #[ ] when accessing hash keys?
    # Using fetch can raise an error while using #[ ] would return nil if there was no key found.

  def test_changing_hashes
    hash = { :one => "uno", :two => "dos" }
    hash[:one] = "eins"

    expected = { :one => "eins", :two => "dos" }
    assert_equal expected, hash

    # Bonus Question: Why was "expected" broken out into a variable
    # rather than used as a literal?
    # Good question! I don't know, someone please comment and explain.
  end

  def test_hash_is_unordered
    hash1 = { :one => "uno", :two => "dos" }
    hash2 = { :two => "dos", :one => "uno" }

    assert_equal true, hash1 == hash2
  end

This is to test that hashes do not keep an order.  If they have the same key, value pairs then they are equal.  This means you can move things around inside a hash, they don't have to be neatly organized in any order as long as they remain in their key, value pairs.


  def test_hash_keys
    hash = { :one => "uno", :two => "dos" }
    assert_equal 2, hash.keys.size
    assert_equal true, hash.keys.include?(:one)
    assert_equal true, hash.keys.include?(:two)
    assert_equal Array, hash.keys.class
  end

  def test_hash_values
    hash = { :one => "uno", :two => "dos" }
    assert_equal 2, hash.values.size
    assert_equal true, hash.values.include?("uno")
    assert_equal true, hash.values.include?("dos")
    assert_equal Array, hash.values.class
  end

The first test, tests for the keys being where they should be and the second test is for the values.

  def test_combining_hashes
    hash = { "jim" => 53, "amy" => 20, "dan" => 23 }
    new_hash = hash.merge({ "jim" => 54, "jenny" => 26 })

    assert_equal true, hash != new_hash

    expected = { "jim" => 54, "amy" => 20, "dan" => 23, "jenny" => 26 }
    assert_equal true, expected == new_hash
  end

This test merge.  When you call merge, any new hashes are added.
Any hash that matches a key of the previous hash will have its value over written by the merge.


  def test_default_value
    hash1 = Hash.new
    hash1[:one] = 1

    assert_equal 1, hash1[:one]
    assert_equal nil, hash1[:two]

    hash2 = Hash.new("dos")
    hash2[:one] = 1

    assert_equal 1, hash2[:one]
    assert_equal "dos", hash2[:two]
  end

The default value for a new hash is nil.  When you create a hash and pass a value, then all keys will have that default value.  You can over write it.  Useful if you have many hashes with the same value.


  def test_default_value_is_the_same_object
    hash = Hash.new([])

    hash[:one] << "uno"
    hash[:two] << "dos"

    assert_equal ["uno", "dos"], hash[:one]
    assert_equal ["uno", "dos"], hash[:two]
    assert_equal ["uno", "dos"], hash[:three]

    assert_equal true, hash[:one].object_id == hash[:two].object_id

  end

When you create a hash using hash = Hash.new([ ]) you create a Hash with a default value that is the same for all key instances. So when you pass a key that doesn't exist, you get the same default value, in this case an array. In this case, you get the array created inside the method ["uno", "dos"]. If you push(<<) "tres", then each hash([:one], [:two], [:three] will have the value of the entire array ["uno", "dos", "tres"].


  def test_default_value_with_block
    hash = Hash.new { |hash, key| hash[key] = [] }

    hash[:one] << "uno"
    hash[:two] << "dos"

    assert_equal ["uno"], hash[:one]
    assert_equal ["dos"], hash[:two]
    assert_equal [], hash[:three]
  end

In the last test, each key is being assigned the default value, which is its own array. They are no longer referencing to the same object/array, which is why the array doesn't appear to grow like in the previous example.


Brought to you by KENYACODE. Can you code?

Wednesday, May 20, 2015

FizzBuzz Solved

To solve FizzBuzz we started with a for loop from FizzBuzz Part 1, added an if else statement from FizzBuzz Part 2, now we will finish off with the logic and math to proclaim this FizzBuzz Solved.  I know, just reading it get me a little amped.

for (i = 1; i<=20; i++){
    if (i%15==0)                              This says take i and if you divide by 15 and there is no remainder
    { console.log("FizzBuzz")         puts FizzBuzz to the console.
    }
    else if (i%5==0)                         This says take i and if you divide by 5 and there is no remainder
    { console.log("Buzz")                puts Buzz to the console.
    }
    else if (i%3==0                          This says take i and if you divide by 3 and there is no remainder
    { console.log("Fizz")                 puts Fizz to the console.
    }
    else                                            Otherwise
    {
    console.log(i);                           puts i to the console.
    }
}

Ok so did I do it as cleanly as it looks right there... uh sure I did.

What why don't you believe me ... because you know me right.






Yeah it wasn't that easy.  I started with if i%3==0; "Fizz".  It worked, then when I added %5; Buzz, it both worked and didn't work which equals "Failure".  So I had to figure out that I needed to add else if because I have two conditions; %3 and %5.  Then when I added %15; Fizz buzz... you guessed it! Whomp whomp whomp.  I had to reverse the order from 3,5,15 to 15,5,3.
You said  
Whaaat?

I said
Yeah it didn't make sense, but if you squint and think about it, then it will.

Let me explain.  The condition has to check for (i%15==0) first because if it doesn't it will log Fizz on i=15 because it comes to that bit of code first.  It will never log FizzBuzz because 15 satisfies if (i%3==0) which is first on the stack.

So by putting (i%15==0) first, it will log "FizzBuzz" then for every other number it will log the correct fizz or buzz.
Wow it is so clear to me now.  Don't worry if it isn't clear yet, just re-read this blog or start again from the first FizzBuzz Part 1. (That's the one with Morpheus)

This tutorial shows just one of many ways to solve FizzBuzz.  Each language has one as well.  I think a good coder should be able to write FizzBuzz in each language s/he is proficient in.

Brought to you by KENYACODE, Can you code?

FizzBuzz Part 3

Today i'm going over using a for loop in javascript to do a countdown from 10 - 0 and printing "Blast Off!" when the counter gets to zero.

for ( i = 10; i >=0 ; i-- ) {
    if (i == 0)
    {
        console.log("Blast Off!");
    }
    else
    {
        console.log(i);
    }
}

So the for loop starts at i = 10; then for all numbers > than or = to 0, counting down in each loop i--.

The if else statement says when/if i gets to 0 (i==0) the program will log to the console the string "Blast Off".  For all other numbers that i is == to (each number ( i )) just log to the console that specific number.

*Note: Use the double = (==) to mean equals.  I sometimes forget too so don't worry if you did remember.  Since this is javascript, make sure the { has a closing } and that you use semi colon ; in the right place.

Next we will use this knowledge to solve FizzBuzz.

Post comments or questions below.  Have fun with it and most importantly learn some new code today.

Brought to you by KENYACODE. Can you code?

Wednesday, May 13, 2015

RubyKoan: test_parallel_assignments_with_splat_operator

Today's RubyKoan is all about that Splat.


def test_parallel_assignments_with_splat_operator
    first_name, *last_name = ["John", "Smith", "III"]
    assert_equal "John", first_name
    assert_equal ["Smith", "III"], last_name
end

You can use a splat in a method definition to gather up any remaining arguments. So if an array has three arguments and you have called the first argument, a splat will allow you to call the rest of the arguments. To check this I added a third last name just before "Smith" and asserted_equal to include that third last name and it worked.

Hope you have been enlightened.

If you find this insightful, please comment below.

If you don't find this helpful, go ahead and comment anyway. Let me know if there is any way I can write these to make them more clear.

Brought to you by KENYACODE. Can you code?

Monday, May 11, 2015

FizzBuzz Part 2

In my last blog I set out a challenge: Can you write a for loop with an if else statement. If you haven't read the last post, go now and then come back here for the answer.

The challenge is to Square just the ODD numbers between 1 and 50, and print each number in the console.

In order to accomplish this feat, you need a for loop that counts all numbers between 1 and 50. If the number is odd, print the square of the number. Otherwise, just print the number. Here is the solution.

for (var i=1; i <= 50; i++)
     {
     if (i % 2 == 1)
         console.log(i * i);
     else
         console.log(i);
     }

If you figured this out then it means you know that % is a modulo. An operator that gives you the remainder when two numbers are divided together and the remainder is only in whole numbers. So if i=1, there is a remainder of one but if you square 1 you get 1. If i=2, no remainder and if i=3, remainder of 1 and the square is 9, etc.

If you figure that one out try to square the EVEN numbers between 1 and 50. (HINT: %) figure out what % is and how to use it.

for (var i=1; i <= 50; i++)
     {
     if (i % 2 == 0)
         console.log(i * i);
     else
         console.log(i);
     }

Did you see the change? Keep looking

Ok, in line 3 if you set the remainder equal to 0 then the if statement will evaluate to true only for the even numbers.

To square the result I used i * i or i x i.

Hope you see where this is going. My next blog will get even closer to understanding and passing FizzBuzz. For the next challenge, try to start your counter at 10 and count down to 0, when you get to 0 console.log Blast Off!.


Special note: I did get hung up on the for loop because I was thinking Ruby and did not put the if else statement inside the { }

Brought to you by KENYACODE. Can you code?

FizzBuzz Part 1




This weekend I started looking at FizzBuzz.  I have to be able to do this in a code interview so I went to Code academy (spelled codecademy) and I'm going through their tutorial.  I will write down what I find helpful so you guys can master the infamous FizzBuzz.  I will assume you found this blog because you know what fizzbuzz is and want to learn how to solve it.  


First thing is to understand a for loop.  The most common way I found it written is:
for (i = 1; i <= 5; i++ )
{
But that didn't help me understand it.  I found a more verbose way to write it.
(//) explains what is happening in each part of the for loop.

Start at 3 count up by 1 and for each number do some code in the brackets { }. // for (start; stop; how much to change each time)
for (var counter = 3; counter <= 5; counter = counter + 1)
{
    // Everything in the code block starting with '{' and
    // ending with '}' will run once each time through the loop
    console.log(counter);
    // console.log will print to the console what you pass inside the ( ).
}
var counter = 3; starts the counter at the number 3.
counter <= 5; go through all the numbers less than(<) or equal(=) to 5.
counter + 1; after you run the code, add 1 to the number and do it again.

So this for loop will start at 3, run the code, console.log the result, then add 1 and run through the for loop again until it gets to a number that is not less than or equal to 5, like 6. When it gets to 6 it will exit out of the for loop.

I had to read this several times and do a few examples of for loops to feel like I understand it completely.  After you understand the for loop, then we tackle the if, else statement below.

if (this condition is true) 
{
    // do this code
}
else
{
    // do this code instead
}

This one was a bit easier to understand.  If (the code in here evaluates to true) {do this code in here} else (if the code evaluates to false) {run this code in here}



So if you think you've got it try this test:

Square the ODD numbers between 1 and 50.
Add an if...else statement to your for loop block that looks at each number. If it is odd, print the square of the number. Otherwise, just print the number.





If you figure that one out try to square the EVEN numbers between 1 and 50. (HINT: %) figure out what % is and how to use it.

I will put the result in this blog article later today.  Don't look for the answer online unless you have spent at least 10 min finding out what % is and trying to write the logic code for odd numbers.

Brought to you by kenyacode, Can you code?

Saturday, May 9, 2015

Today's RubyKoan comes from the letter "Array" and the numbers ....

Today's Koan comes from the letter "Array" and the numbers ....

An array is an ordered arrangement.
Array of cars: (Audi, Corolla, Tesla)
Array of numbers: ( 1.2, 1.5, 1.9)

class AboutArrayAssignment < Neo::Koan
  def test_non_parallel_assignment
    names = ["John", "Smith"]
    assert_equal __, names
  end

Solution
  def test_non_parallel_assignment
    names = ["John", "Smith"]
    users = ["John", "Smith"]
    assert_equal users, names
  end

What I did here is make a new array with the same names and made that array assert equal to the first array.  As long as the contents of the two arrays match, then I satisfy the call to assert_equal.

Brought to you by KENYACODE. Can you code?

Friday, May 8, 2015

RubyKoan: Assert Equality Koans

I am finishing up the last two Assert Equality Koans.  They are similar so I put them together on this blog.

  # Some ways of asserting equality are better than others.

  def test_a_better_way_of_asserting_equality
    expected_value = __
    actual_value = 1 + 1

    assert_equal expected_value, actual_value
  end

  # Sometimes we will ask you to fill in the values
  def test_fill_in_values
    assert_equal __, 1 + 1
  end

Solution
 def test_a_better_way_of_asserting_equality
    expected_value = 1 + 1
    actual_value = 1 + 1

    assert_equal expected_value, actual_value
  end

  # Sometimes we will ask you to fill in the values
  def test_fill_in_values
    assert_equal 2, 1 + 1
  end

These two are essentially the same.  When you look at the third line of the first Koan, it says  assert_equal expected_value, actual_value.

Assert_equal is asking the next two values that you pass in will be equal.  So you look at where the two variables are defined.

Expected_value, actual_value,

you see that the solution is to write a value to expected_value that is equal to actual value and the last line will equate to true.

There are two ways to set two values to equal each other.  Using the == operator and to call Assert_equal and pass two variables that are equal. (Assert_equal __ , __ )

Brought to you by KENYACODE. Can you code?

Thursday, May 7, 2015

RubyKoan: Test_Assert_Equality

Today's Koan is to Assert Equality.  

def test_assert_equality
    expected_value = 2
    actual_value = __
    assert expected_value == actual_value
end

Solution
def test_assert_equality
    expected_value = 2
    actual_value = 1 + 1
    assert expected_value == actual_value
end

This koan has an expected value and an actual value.  Then they are set equal to each other using the == operator.  In order to equal each other you just put a value equal to 2, like 1+1.

If your wondering what assert means just check out my last post. Ruby Koans

Brought to you by KENYACODE. Can you code?

Wednesday, May 6, 2015

RubyKoan: Test_Assert_Truth

I am going through the Ruby Koans. Each day or so, I will post one Koan and explain how I got to the answer. I hope this is helpful to the many programmers out there like me who don't just want an answer but want to understand how to understand the answer. 

To get set up with Ruby Koans, go to Ruby Koans here is the URL: http://rubykoans.com

# We shall contemplate truth by testing reality, via asserts.
def test_assert_truth
assert __ # This should be true
end

Solution
def test_assert_truth
assert true # This should be true
end

My thought process started with the note (# This should be true).
Then I read the word asserts. Assert means to state a fact or belief confidently and forcefully.
It was asking for the function to assert true so I put true in the blank. It therefore read Assert true.
Looking at it now I could have put a statement that equals to true and that should also pass the test.

What do you think?

Brought to you by KENYACODE.  Can you code?

Discourse - Open Source blog platform


Hello Discourse Dev community, I am a new web developer who just graduated from general assembly's web development full stack program. I have written some small apps and I want to jump into a more robust full feature app like Discourse. Another developer told me about Discourse and here I am. I installed discourse onto my machine and I would love any guidance on writing tests. I also go by the name kenyacode.

That was my first post at discourse, an open source blog platform. Today I'm going to go through the steps I went through installing Discourse, Virtual Box, & Vagrant. If your a new programmer and don't know what these are, don't worry I will go over each one.

Need to mention that I use a mac with OS X Yosemite 10.10.3, iTerm, and the Atom editor.

So what is Discourse and why did I want to install it?



Discourse is the 100% open source discussion platform built for the next decade of the Internet. It works as:
a mailing list
a discussion forum
a long-form chat room

To learn more about the philosophy and goals of the project, visit discourse.org.

Since I'm a Rubyist, I wanted a project that was written in Ruby. Discourse is built with:
Ruby on Rails — Our back end API is a Rails app. It responds to requests RESTfully in JSON.
Ember.js — Our front end is an Ember.js app that communicates with the Rails API.
PostgreSQL — Our main data store is in Postgres.
Redis — We use Redis as a cache and for transient data.


Plus lots of Ruby Gems, a complete list of which is at /master/Gemfile.As programmers we learn by doing and what better way than to work on a great app written in a programmer friendly language like Ruby On Rails and a modern front end like Ember.js. I hope to learn a lot about the code and also how to collaborate with other developers.
Alright now that you know why, here are the other three things I installed:
I used brew cask to install. If you don't know what brew is go here: caskroom.io/ Brew cask installs mac software in one line from your terminal.

1. VirtualBox

I don't set up environments on a regular basis, so it can be intimidating to set up a *nix flavored environment. (What is *nix? I believe it stands for Unix.)

This is where VirtualBox comes in. VirtualBox is a Virtual Machine, a doorway into an entirely different operating system. It’s free, open source, and runs on Windows, Linux, Mac and Solaris.

2. Vagrant

With VirtualBox installed, it’s now time to bring a VM to life. Discourse maintains all the
information necessary to wire up a VM within the Discourse codebase itself!
It does this through the magic of Vagrant, another free open-source tool which is used to both package and initialize a VM with all the necessary configurations in place. Thanks to Vagrant, there’s no need to figure out if you have the correct version of Ruby, or if Rails is up-to-date, or even how to install nginx, thin, or any of the other bits and pieces that make up Discourse.

It’s all in Vagrant, stored within the Vagrantfile, and comes up with with the ease of a single command line. For the purposes of working with Discourse, you’ll need Vagrant 1.7.2 or higher.

After installing VirtualBox and Vagrant, check to make sure you have the most recent version. In your terminal
vagrant -v => Vagrant 1.7.2

3. Next you will need to install Git.  I skipped this step because I already have git.  I went to Discourse's github repo and forked the repo, which means I copied it to my Github.  Then I cloned the repo to my mac.

4. Running the VM and Connecting to it. In iTerm: (to make sure I didn't miss a step, I copy and pasted these directions from http://blog.discourse.org/2013/04/discourse-as-your-first-rails-app/
vagrant up
This will kick the VM into motion. Vagrant will connect to the official Discourse site, download the VM image we’ve prepared (note: this may take a while), extract it, and enable all the subsystems necessary to bring the environment to life. VirtualBox may prompt you a few times, so go ahead and accept its requests.
Once the VM is up, you’ll be back at the command prompt.
Now, it’s time to connect to the VM and start up the Rails server. From the shell you already have open in the project folder, type:
vagrant ssh
Once inside, a few more commands is all it will take. Change to the vagrant directory:
cd /vagrant
Now it’s time to interact with Ruby on Rails. Invoke the Rails installer, like so:
bundle install
Next, tell Ruby on Rails to migrate the development database schema into your local repo. We do this via rake, which is Ruby’s version of make, boasting Ant-like features.
bundle exec rake db:migrate
At long last, it’s time to bring up the Rails server, ready to accept HTTP requests.
bundle exec rails s
Our VM config causes this Rails server to begin listening for requests on port 4000. So once the server is up, open up a web browser on your local workstation and navigate tohttp://localhost:4000
Voila! As you can see in the screenshot above, Discourse is indeed running locally off of port 4000, and in the background, you can see the guts of Discourse working away within the SSH client that you used to launch the server.
The initial request may take a while as Discourse begins to initialize its subsystems and start the caching processes; first page loads of 5 to 10 seconds are not uncommon. However, if you’re seeing page load times well beyond this, let us know what your PC configuration is. The Discourse community is actively looking for tweaks and improvements for better VM performance.
Step 5: Shutting Down

When you’re done for the day, Ctrl+C will kill the Rails server, exiting you back to the command prompt from within the VM. To finish up, type:
exit
vagrant halt
This will exit your SSH session, then end the VM and free up its resources.
Congratulations! You now have a working copy of Discourse, ready for you to hack away at any time, and a complete Ruby on Rails environment to facilitate said hacking.

Step 6: PhantomJS on Ubuntu

Ok so you have Discourse up and running.  Do you want to write tests? Well of course you do.  Well I do anyways.  So I looked and searched, by search I mean I read the Advanced developer Install Guide, its at the bottom.

You will need PhantomJs in order to run javascript tests he said.  Ok I replied.
Here is the only part I ran into a problem.  The directions on Discourse's Github page is for a 64-bit version and we installed a 32bit version of the Ubuntu linux .  Not to worry, here is how its done.

I went to http://phantomjs.org/build.html and followed the steps.  I know that running sudo commands can be scary so I put the link in case you wanted to copy and paste directly from the phantomjs.org site.

We are in a Linux environment, so we use the Debian-based distro.
On Debian-based distro (tested on Ubuntu 14.04), run:

sudo apt-get install build-essential g++ flex bison gperf ruby perl \ libsqlite3-dev libfontconfig1-dev libicu-dev libfreetype6 libssl-dev \ libpng-dev libjpeg-dev python
Note: It is recommend also to install ttf-mscorefonts-installer package.
sudo ttf-mscorefonts-installer
Then, launch the build:
git clone git://github.com/ariya/phantomjs.gitcd phantomjsgit checkout 2.0./build.sh


Whoa... that was quite an afternoon.  It was fun seeing the blog up and running and now I get to read all the code and start contributing.  I plan on writing a blog post everyday about what I'm learning.

Feel free to reply to this post with anything you discovered in your install, or any general comments.