Monday, October 7, 2013

Overload

The last week or two has been a lot to take in and definitely too much for me to write about. I am reading script much more fluidly and I understand jquery (and other libraries), click handlers and the how to traverse the DOM. Functional programming is easy to grasp, but more difficult to master and consistently apply to all of your code. Often times there is an easy solution that involves impure functions, but the quest for purity pays dividends in the long run when your functions are contained and their side effects are easily trackable.

Here is an example from an exercise this week that illustrates the beauty and challenge of functional programming. The assignment was to alter the javascript .splice(arr) method so that it does not modify the array that is passed as an argument. What splice currently does:

arr.splice(indexToStartRemove, numToRemove, insert, insert, insert)
Splice starts removing values out of an array at "indexToStartRemove" and removes "numToRemove" values upwards through the array. It then inserts any values listed in the 3rd, 4th...nth parameters listed in the method. Below is a concrete example. An array with values ordered through the array is modified so that the 0th index is removed and replaced by the number value 99.

var array = [1,2,3,4,5,6,7,8,9,10] 
array.splice(0,1,99)
console.log(array) // returns [99,2,3,4,5,6,7,8,9,10]
The following is an example of a splice function that behaves in the same way while remaining pure and not modifying the existing array:


var array = [1,2,3,4,5,6,7,8,9,10]
var splice = function(indexToRemove, numToRemove, insert){
  newArray = []
  for(i=0; i<indexToRemove; i++){
    newArray.push(array[i]); 
  }
  for(i=3; i<arguments.length; i++){
    newArray.push(arguments[i]);
  }
  for(i=indexToRemove+numToRemove; i<array.length; i++){
    newArray.push(array[i]);
  }
  return newArray
} 

One line wonder. A few hacks involved. Array.prototype applies the .slice() method to the arguments "array-like object". For whatever reason JS decided that all functions should contain a native arguments property for all parameters, should look like array, but not have all the properties of an array, or for that matter be one. Mystifying.
var splice = function(){
  [].concat(array.slice(0,indexToRemove)).Array.prototype.apply().slice().concat(arguments.slice(3,arguments.length)).concat(array.slice(indexToRemove+numToRemove, array.length));
}

Wednesday, September 18, 2013

An Introduction to JavaScript, jQuery, and the DOM

The last two days were whirlwind of coding activity that included an introduction to JavaScript, jQuery, and the Document Object Model (DOM).

JavaScript is one of the more popular languages on the web. It has been used in tandem with HTML and CSS for quite a while and has changed little since its creation in 1995. I found this interesting because I have always thought of languages as fast-changing. In reality, only browsers and web standards (html, css) change frequently. JS is used primarily to create interactivity on a website, thus it has been called an "event handling" language.

In 1998, a technique that has since been dubbed Ajax (Asynchronous Javascript And XML) was introduced and was the dawn of "Web 2.0". Before Ajax, the page had to be refreshed in order to access additional information from the server. Every time you waste time scrolling down your facebook page and more information pops up, thank the folks at Internet Explorer for their pioneer work. JSON is the current JavaScript compatible "Ajax".

Enough history, let's get into some light lifting.

5 Primitive Types

There are 5 primitive "types" in JavaScript:

  1. string: a set of characters surrounded by ""
  2. number: a set of numbers. other languages often refer to this as "integer"
  3. boolean: logic based true and false
  4. null: lacking value, not 0
  5. undefined: An error
The basics: Variables are the most basic part of Javascript. They are used as placeholders for information. By doing this, you give the characters additional meaning so they are able to transmit information more efficiently. Below is an example

var name = "Brian"; //a statement that defines a new variable 'name' as "Brian"

console.log(name); //logs the contents of the variable 'name' into the console
This particular example is quite simple, but you could imagine a more complex variable, such as...

var era(runs, innings) = runs/innings;

console.log(era(4,2));
Here you are defining a variable 'era' which takes the parameters runs and innings. When arguments are entered in the parameters place holders and logged, the console would return 'runs' / 'innings', or in this case '2'.
Another example would use booleans. If someone is typing a phone number into a website, and you want to validate the information before submitting it, you might use the following function.

var number = prompt("What is your 10 digit phone number?\nFollow the form xxx-xxx-xxxx);
if((number.length === 12) && (number.charAt(3, 7) === "-"){
    console.log(number);
}else{
    alert("please enter a valid phone number");
}
Here we used If, the boolean "is" statement. If the number was 12 letters long and had a dash in its 4th and 8th character, we would enter the the number into the console. Otherwise an alert would pop up informing the person that they would need to enter a valid number.
If we wanted to get even crazier, we could define this as a function by doing the following...

phoneNumberFunction = function(){
var number = prompt("What is your 10 digit phone number?\nFollow the form xxx-xxx-xxxx);
if((number.length === 12) && (number.charAt(3, 7) === "-"){
    console.log(number);
}else{
    alert("please enter a valid phone number");
}}
We have now defined the function phoneNumberFunction and we can call it whenever we want to perform the task defined within the {}.
The function that we have created is"pure". This means that it does not lead to "side effects" within the rest of your code by redefining variables.

Let's look a bit more intently at functions as they are a core part of programming.
At its core a function is

  • An Input–Output Machine
  • Reusable
  • Encapsulates a piece of "functionality"
When a function is defined, any variables used within the function cannot be accessed outside of the function. Conversely, variables defined outside of a function can be used in the function. Variables used both outside and inside the function remain in their respective locations. This is called "scoping", and more specifically within JavaScript as Lexical Scoping.


jQuery and the DOM

The DOM sounds dangerous, large, and scary. It isn't. The DOM (Document Object Model) basically refers to the skeleton or 'table of contents' that your html tags form. On your computer, press Option+Command+I if you are on a Google Chrome Browser. The bottom of your browser window unfurls to reveal your "Developer Tools" If you wave your mouse over the bulleted html script that falls beneath the Elements tab you are very literally waving your mouse over the DOM.

The DOM is the browsers rendering of your code into elements that supercede characters within a document.

The reason why this isn't scary is because all of CSS is styling elements by selecting DOM elements. CSS is basic by now, so this realization was salvation. To make matters better, I learned that jQuery is a JavaScript library that selects DOM elements using CSS syntax. Hallelujah!

To access a DOM element using jQuery simply do the following. Provide a link to the latest jQuery API in your head tags. Then, in the bottom of your body tags, add your javascript and use $ or jQuery as variables to link to ids or classes of elements within your html code. Pretty basic, but from here, you can make a site interactive quickly and easily.

<head><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script></head>
<body><div id="example"></div>

test = $("#example');

</script></body>

Terms that we have learned:

var //keyword declare variable 
+ //the concatenation operator. Joins things
=== // boolean equal to. Use instead of ==
if // keyword that takes booleans. returns if true, passes if false
if else // keyword similar to if. 
else // keyword if 'if' and 'else if' are false, 'else' returns
. //access property
length //special property that finds length of a string
== // === but allows type coersion
! // "not" reverses booleans
typeof //keyword to check type of expression. bugged
.toLowerCase() // turns a string to lowercase
.toUpperCase() // turns a string to uppercase
.substring(from,to) // outputs the set of characters within a string corresponding to the defined numerical placeholders
return // completes function and breaks it
&& // boolean AND
|| // boolean OR







Monday, September 16, 2013

The New Normal

For those unaware, Boulder was decimated by a 500-year flood event that tore down bridges and buildings and caused numerous deaths (check out the site that my teacher put together for more info). Boulder received more rain in four days than it normally does in a year. As a result class was cancelled Thursday and Friday as we weathered the storm. The sewer line broke in our apartment complex, so our water has been shut off for about a week. But besides these obvious setbacks, things have improved dramatically in the past day.

Wednesday night. The underpass to Collin's had turned into a river.


It stopped raining mid morning and it has improved quite a bit since. Many roads are still closed or peppered with rocks, sand, silt, mud, or gross water, but this is changing. I had lunch on a picnic bench today and had to go inside after 40 mins because it was too sunny. It is time to embrace the new normal and shrug the past several days of hardship, boredom, and uncertainty.

And I am back to coding. Over the long weekend, I did some coding, but for the most part the internet was spotty, and I was distracted by other things. I did put together my first personal website brianshedberg.com. It is purposefully simple, and required little creative effort as I stole the template from my teacher, Matt Null's website, mattnull.com. The challenging part was hosting it in a way that would allow me to bypass using a template and use raw html/css. I discovered that github has a hacker hosting site called gh-pages, which allows you to use one of your github repos as a launch pad for a simple site free of any of the baggage that comes with a heavy-lifting CMS (drupal, wordpress, joomla!). They also have an additional blog platform called octopress, which is a simple blog site. I may transition this blog to that platform in the not-so-distant-future.

Enough yammering. I am getting increasingly confident with CSS (something that my brianshedberg.com doesn't reflect), and I can do some pretty nifty stuff at this point. Here are a few of the tips and tricks I have learned since my last post:

We focused quite a bit on the float: left, right, both;
Float is used to
1. position media with wrapping text.
2. Allow block images to stack horizontally while 'responding' vertically, similar to inline-block. *Inline-block should be used on items that don't have a fixed width but you want to treat like block elements. An example would be columns for a journal.

Float Facts:
1. Different from inline block, because float items are automatically set to display: block;
2. Float takes up vertical space, but does NOT occupy horizontal space

Below is an example of a "Clear fix", a way to avoid awkward text wrapping.
selector { 
float: right, left, both;
}

selector { //*important: When the browser renders text next to floats, it wraps text. Margins and padding don't remove the indentations created by text wrapping. This prevents the text from wrapping and creates a "nesting" effect.
overflow: none;
}
<div class="hello pink"></div>  
.hello { //an example of how a single div can contain multiple class or id tags
float: right;
}
.pink {
overflow: none;
}
//OR... concatenate the two to select for both classes at once
.hello.pink {
float:right;
overflow: none;
}
Centering Items


selector { //centers any kind block element (not just text) WITHIN a container
text-align: center;
}
selector { //automatically centers element
margin-left: auto;
margin-right: auto;
}
selector {
margin: auto 0;
}

Lists:
To understand lists, it is important to understand that all inline elements are anchored by line-height. Padding and margins push out from this central 2D line

selector { //removes bullets (or other styling)
list-style: none;
}

selector {//removes indentation left by ghost bullet
padding-left:0;
}

Wednesday, September 11, 2013

Rain

Today was all about rain. Boulder snapped its run of 90 degree days with a two day stretch of rain that is expected to continue all week. The roof at the class started to leak and buckets were placed strategically throughout the building. In a city that has 300+ days of sun a year, I can understand why a several day deluge of rain could lead to unexpected problems.

Boulder, CO

On a positive note, the rain has made it easy to focus on our exercises. We continued to hammer away at HTML and focused on the CSS basics. Here's what I learned today:

HTML

With the dawn of HTML5 and web standards, there has been a push to encourage a complete separation between HTML and CSS. To explain, it is possible to format a bit of text using CSS within an html document, or even embedded within a line of text. This may seem advantageous: you can see the stylistic changes that are being made to a particular line of text without searching for the corresponding .css file. The downside is that it can make already long documents longer, making it harder to edit files, and and can to conflicts when external .css files are used.

The follow up to this mentality is an emphasis on html tags that are semantic, meaning that they communicate a particular meaning that can be interpreted by computers. An example of this is the <time> tag. By surrounding "Valentine's Day" with <time datetime="2008-02-14"> and </time> tags, the computer interprets the text Valentine's Day as a date, not just text. On many devices, time or dates with this tag will have access to the device's calendar, which is useful for scheduling events.

Adding semantic tags to your website can enhance search engine optimization as well as internet "crawlers" from search engines will value certain tags more than others. An example of this would be the <article> tag, which flags news items.

On the CSS side of things...

We focused on the Box Model and basic element positioning using standard attributes and their most useful corresponding values.

Box Model


To be clear, the following is the standard for styling html elements using css. The selector applies the following attributes and values to the contents of its corresponding html tag.

selector { 
attribute: value;
}

Some useful CSS I learned:

* { //* applies to ALL html tags
attribute: value;
}

selector { //applies changes to margin & padding without effecting element dimensions
box-sizing: border-box;
} //****should be applied to all pages!

body { //makes content flush with browser
margin: 0px;
padding: 0px;
}

body { //makes content flush with browser
margin: 0px;
padding: 0px;
}

selector { //hides element from document. keeps their element dimensions
display: none;
}

selector { //renders on top of non-positioned elements. Controlled by z-index.
position: absolute;
} //

selector { //changes layer order amongst absolutely positioned elements.
z-index: 0;
}

selector { //positions element relative to parent container rather than body (browser)
position: relative;
}

selector { //fixed on screen. does not move with scroll bar
position: fixed;
}

selector { // centers element
margin: 0px auto;
}

selector { //elements width determined by content. Are "in line" horizontally
display: inline;
}

selector { //elements arranged vertically
display: block;
}

selector { //hides content outside of element box
overflow: hidden;
}

selector:link :visited :hover :active { 
//respectively: unvisited, visited, moused over, selected
}
To see the rudimentary website I made to include as many separate html tags as possible, check out the source code at my github.

Web News:
An interesting project is emerging in the development world. Former bigshot at Wordpress, John O'Nolan is prototyping ghost.js, the first cms and blog written fully in JavaScript. The project first surfaced as a kickstarter project, and is now being haled as the new big thing in the blogosphere.

At refactoru we are learning JavaScript, so I am very excited by the opportunity to be part of a big incoming boom.

Tuesday, September 10, 2013

Git Commits and HTML Basics

It was the second day of class and the pace of learning accelerated. We are still learning the basics, but even HTML and CSS can be quite involved. Case in point. 

We had two major tasks for the day. I completed one and a half of them.
1. Create a repository on our github account to receive the source code for the card flip website .css file that we made monday. To find the end result of the assignment, visit my GitHub or https://github.com/gemfarmer/card-flip for the source code.

  1. Log into github.com
  2. Name your new repository folder (card-flip for me)
  3. Open terminal
  4. Create a folder called Projects in your home directly (you can access your home directory by typing cd ~)
  5. Create a folder with the same name as your repository folder within your Projects folder.
  6. Copy and paste the code the file you want to upload (commit) to github into the newly created folder
  7. cd into the card-flip directory if you're not there already before following the next step.
  8. Use the following commands to initialize that folder as a local repo and add the github repo as a remote. Adding a remote allows you to use commands like 'pull' and 'push' to keep the code on your computer in sync with the code on github. (These same instructions appear on github.com after creating the repo.)
    Make sure you replace YOUR_GITHUB_ID with your actual github id.
    touch README.md
    git init
    git add .
    git commit -m "first commit"
    git remote add origin https://github.com/YOUR_GITHUB_ID/card-flip.git
    git push -u origin master
  9. Navigate to your card-flip repo on github.com (or refresh it if it's already open from a previous step) and verify that it contains the newly added files.
Congratulations! You can now execute git commands from the terminal to interact with a repo on your github account. You can use this technique to submit your homework exercises. Follow these instructions each time you wish to create a new repo for submitting an exercise solution.
2. Create a website that uses basically all of the basic <HTML> tags that you can imagine and styling it with internal stylesheets. This task has been a bear for me because I get the urge to style everything before completing the complete barebones html. When I finish the website tomorrow I will add it to my github repository. It will not be too showy or pretty, but it will have a functional nav bar, tables, lists, and the card-flip functionality that I constructed on monday.

In the afternoon we had a lecture by Clint Nash on adaptation within a fast-moving industry. The lecture focused on the importance of continuous learning, experimentation, curiosity, assertiveness, and the nature of innovation. Learning code is a technical skill, but it can also be a mentality that can be applied cross-industry and permeate every facet of your life.
Clint used the term iterative innovation to describe the incremental changes that ultimately progress and improve society. The tech culture embraces open-source, reducing time between iterations, and allowing these incremental changes to happen at lightning speed. Every day 16 new Node.js packages are released. That is 16 new projects a day that are (theoretically) providing solutions to previous problems. To quote Clint, it's a bit like drinking from a firehose. Constant learning and flexibility makes this task less painful.

Clint will be a weekend advisor and continue to give sporadic lectures throughout the next 10 weeks. Stay tuned...

Monday, September 9, 2013

First Day

The first day was primarily set up. We spent the morning getting to know one another and getting our computers set up with version control via github, installing node.js, Coffeescript, and dependencies. installing git, Coffeescript, and dependencies required using the Terminal, which I am fairly new to. The Terminal is the OSX Command Line, which is heart of the computer. Before computers had an interactive graphics interface, they were basically just the command line. Accessing the terminal allows you to access portions of your computer that are normally inaccessible.


For example, to access your root directory, essentially the file that houses all the files within your computer (including your local users), open a new shell in Terminal and write
cd /    *and press enter
ls        *and press enter

You will see in rudimentary form the core files within your computer.

In the afternoon we covered basic HTML and CSS to get everyone on even footing. We followed this exercise. The final goal of the project was to make the card


Gleaned knowledge:
Within terminal:
TAB auto completes any file name. godsend for long file names

CSS:
position: absolute;  pushes an element to the farthest corner of the screen.
top: 0px; can be applied in tandem with position:absolute; to create some space between the "absolute" corner of the screen.

z-index: (number); z-index creates layering between elements. if two elements are directly on top of one another, it becomes impossible for someone to browse over or click the element below. The higher the z-index, the closer to you!

-webkit- makes a given property accessible via chrome

 transform: rotateY(180deg)

flips an element along the y axis. To flip unit as if a card, apply to "front" and "back", :hover

Welcome

Welcome! I started this blog to document my transformation from a food and ecology enthusiast to junior web developer.

Just two short days ago I made the 13 hour voyage from Minneapolis to Boulder, CO to participate in refactoru, a web application development bootcamp. I am looking forward to learning a ton of code and taking as many hikes as possible in between!

Each day I will be reflecting upon the core concepts or abilities that I learned. Follow this blog to learn with me. Ready, set, follow me on twitter, I mean GO!