Articles in learning
July 08, 2008 at 10:47 AM · Posted under learning, programming, quicklinks
From Cut and paste one line of code to make any website editable:
javascript:document.body.contentEditable='true';
document.designMode='on'; void 0
What’s that you ask? That is an awesome small chunk of JavaScript that allows you to make the text of any website editable within the browser window. Just:
- Copy the code to the clipboard
- Browse to the site you want to edit
- Paste the code into the address bar and press return
- Edit the site’s text however you like
Let the pranking begin.
Comment
May 26, 2008 at 11:33 AM · Posted under learning, programming
Notes I took while watching the second video of Douglas Crockford’s JavaScript lecture
Statements
JavaScript has all the statements that you’d expect to find in any of the other C langauges. e.g. if, switch, while, do, for, break, continue, return, try/throw; but there are some differences in how they are used.
You can label loops and then break out of them by label. Handy if you want to break out of a nest of loops.
The for statement can loop through an array and through the members of objects.
Unfortunately for looping through an object will take you through all the kys of all the objects that the object inherits from. To prevent this you have to test that the object being looped through itself has that property. This is highly recommended to avoid strange behavior.
Switch values don’t need to be numbers, can be strings
Case values can be expressions – handy
You have to explicitly terminate case clauses, as usual.
Switch statements allow a default case.
Throwing exceptions behaves typically, as does try/catch.
You can generate exception objects by calling its new constructor, or use with object literal
JavaScript comes with the following exceptions:
- Error
- EvalError
- RangeError
- SyntaxError
- TypeError
- URIError
You can, of course, make up your own exceptions.
Avoid using the with statement. It was designed to be a convience for dealing with objects, but there is an error in its design leading to ambiguous statements.
There is a function statement used for declaring functions.
The var statement defines variables within functions. JavaScript is loosely typed so you just declare the variable and optionally initialize.
Without initialization variables are undefined.
Unless you limit the variable scope with var they are assumed to be global. :-/
Unlike most C languages, blocks do not have scope. There is only function scope.
Return can return an expression or just return;
return; doesn’t return nothing, it returns undef
When used in constructors they will return the new object.
Objects
Objects contain data and methods.
Objects only inherit from other objects, there is no concept of a Class.
Objects in JavaScript are an unordered collection of name/value pairs. Names are strings, values are anything including other objects or expressions.
Every object is essentially a tiny database
Object Literals
Object Literals are an easy way of creating a new object. The are data wrapped in { }. ”:” separates names and values. ”,” separates pairs. An object literal can be used anywhere a value can appear.
Object Literal Example: var myObject = {firstName: “Stephen”, ‘lastName’:’Ball’, middleInitial:’A’, age: 29};
// These syntaxes are interchangable
var theName = myObject.firstName;
var destination = myObject['firstName'];
Maker functions can be used to build objects. Pass material to maker function and it will make an object and return it
Object Literals can have nested objects, or object literals, as values.
If we pass an object literal to a function, the function doesn’t know if the object already existed or was a literal declared with the call.
Rather than define a function that takes a lot of parameters (e.g. more than two or three), think about passing an object instead.
Objects in JavaScript can be augmented at anytime with new methods and data. There is no class, so obviously no need to define a new one. Just modify the object you want to expand directly.
// to add data to an object simply set it
existingObject[newKey] = newValue;
existingObject.newKey = newValue;
Object Linkage
When objects are created they have a secret link to another object. This is how inheritance is achived.
If a member is requested from an object and the object doesn’t have it, JavaScript silently follows the link to the secret object and sees if it has the member and, if so, returns it. The child object now has the data member locally. Odd side effect: if you delete a data member of a child object that is set in the parent object then the child object’s data isn’t really deleted. If requested the “deleted” data will be fetched from the parent object again without notice.
The secret link is not used for storing new values in the parent object. Data is only retreived.
Obviously this means that there is only single inheritence in JavaScript. Also that there is truly no Class equivalent in JavaScript. Objects only inhereit from objects.
We can use the object function to make a new empty object that has that linkage to an existing object. ex: var myNewObject = object(myOldObject);
Some languages have classes, methods, constructors, modules: JavaScript has functions, and functions do the work of all of those. This allows greater expressive power, but requires a different way of thinking.
There is garbage collection in JavaScript.
All objects are linked directly or indirectly to Object.prototype that has some basic methods, but no copy method and no comparison method.
You can see if two objects are, in fact, the same object; but not tell whether they are equivilent.
Object Construction
There are three ways to create a new, empty object:
- new Object{}
- {}
- object(Object.prototype)
All three return exactly the same object, {} is recommended for conciseness.
Objects can be passed to functions as arguments and returned from fucntions.
Objects are always are passed by reference.
=== between objects will only return true if both objects are the same object.
The delete operator will remove members from objects, delete myObj[key] by changing the value to undefined.
Arrays
Arrays are unusual:
- array inherits from object
- array indexes are converted into strings and then used as names for retrieving values
- very efficient for sparse arrays, but not for everything else
- arrays aren’t typed
- arrays have length member, it is always 1 larger than the highest integer subscript which may not be its actual length (!)
- it does allow a for loop to go through the array easily by just saying less than array.length
- do not use for…in with arrays
Array Literals
- uses []
- can contain any number of expressions
- new items can be appended, arr[arr.length] = value
- can’t use dot notation with arrays, subscript notation instead
- [] is the preferred method to create a new array, not the new array construct
Array Methods
- concat
- join
- pop
- push
- slice
- sort
- splice
Deleting from array: delete array[number] removes element but leaves a “hole” in the array as an undefined value. To completely delete a value and index you need to splice it out.
Use Object or Array?
Since objects and arrays are so similar, when do you use which?
Use objects when names are arbitrary strings, e.g. associative array.
Use arrays when names need to be sequential.
Arrays all inherit from array.prototype.
If you get a value, there are two methods to tell whether it is an array or an object:
- value.constructor === Array
- value instanceof Array
BUT neither of those methods work when value comes from a different frame, a bug in the language.
You can’t inherit from an array because the value produced will be an object, not an array. You can augment an individual array by adding methods to it. You can also assign methods directly to Array.prototype to change all arrays in the program.
Comment
May 26, 2008 at 11:26 AM · Posted under learning, programming
Notes I took while watching the first video of Douglas Crockford’s JavaScript lecture
Language Outline
“script” suggests that JavaScript isn’t a real programming language, Douglas posits that not only is it a real programming language, but a pretty good one.
The language does contain some design errors.
Early bad implementations resulted in JavaScript getting a bad reputation. The implementation are now good.
Programming for the browser and DOM is extremely difficult. A lot of people think that the problem is javacsript itself, but it’s more the environment.
Books on JavaScript are almost (as of 2007) universally bad. The Definitive Guide from O’Reilly is the “least bad” book.
JavaScript standard defined by ECMA, but the standard is not very good. Very difficult to read which led to the bad book problem – no good authoritive source to reference.
JavaScript is a functional language like lisp and scheme.
JavaScript’s History
1992: Jim Gosling started working on a language he called C++ then changed to Oak. Gosling go into a new startup, Oak was used in applications. Company fail. Moved back to Sun. What to do with Oak? Needed new name, Java. Application to demo new language would be web browser, HotJava.
Meanwhile at Netscape. They looked at Java but decided that it was too heavy for browsers. Brendan Ike had idea to do dialect of scheme in the browser, but management said to make a scripting language that looked like Java. That became Livescript. First scripting language to be put into a browser, and first to be put on a server.
Reason Netscape and Java so exciting at the time was that they were envisioned as a way to escape from Microsoft: applications on the net. They decided to ally. Sticky part: what to do with Livescript. A divide between those that wanted Java to be the language of the web, Netscape refused for above reasons. So Livescript name changed to JavaScript and then Sun took naming control of the language.
Microsoft didn’t like this so they reverse engineered the language into JScript.
Netscape didn’t care for this at all. To prevent Microsoft from assuming control of the language they decided to make JavaScript a standard. They took it to the European Computer Manufactors Association (ECMA) because they thought that their language standard would just be rubber stamped there. Unfortunately Microsoft was a member of ECMA, so from the first day Microsoft dictated the standardization. Microsoft had made some errors while reverse-engineering JavaScript into JScript, and they insisted that those errors become part of the standard. It was very important to Microsoft at that time to never do anything to cause anyone’s programs to break. ECMA agreed.
What is JavaScript?
JavaScript is not a web toy language, it is real, useful, and sophisticated. Also very effective.
JavaScript’s key set of ideas:
- load and go delivery: programs are delivered to the execution site as source code. Reasoning is that it was intended to be embedded in webpages, which are text. This is, of course, no longer the preferred way to getting programs to browsers but the legacy remains.
- Loose Typing
- Objects are general containers: unification of objects and hash tables
- Prototypal inheritance: much different than Class inheritance. Objects can only inherit from other objects. There are no Classes.
- Lambda: functions are first class objects.
- Linkage through global variables. Because of “load and go” JavaScript doesn’t have any kind of linker. Separate compilation units are combined into a global namespace, which is a really bad idea.
JavaScript has a small set of possible values
- Numbers
- Strings
- Booleans
- Objects
- null
- undefined
JavaScript doesn’t have multiple number types (e.g. Integer, Float). There are, in fact, no integers. All numbers are represented as 64-bit floating point (i.e. doubles). This means that common arithmetic can act strangely: .1 + .2 != .3
If dealing with decimals need to multiply by 100 for the operations, then scale back.
NaN is a value that is “not a number”. It is returned as the result of undefined or erroneous mathematical statements, e.g. 0/0. It is toxic: any arithmetic operation with NaN as an input will return NaN. NaN is not equal to anything, even itself. NaN === NaN is false. NaN is also not less than NaN or greater than NaN. But if you get typeof NaN it is Number.
Number function converts string into a number. Produces NaN if it has a problem. Similar to + operator.
parseInt function parses integers from a string. Generally you should include radix argument to specify the base we are parsing.
Like Java, JavaScript has a separate Math object. This is an unfortunate idea. The Math object contains a number of useful functions e.g. abs, floor, log, random, round, sqrt.
JavaScript has Strings. They are a sequence of 0 or more 16-bit characters encoded in UCS-2 (not UTF-16 as it has no awareness of pairs for extended character range). The extra characters of UTF-16 are very rarely used, but it is something to be aware of.
No character type in JavaScript. A “character” is a string of one character.
Strings are immutable.
Similar strings are equal with
String literals can be written with single or double quotes, they are the same.
All Strings have a "length" method that returns the number of 16-bit "characters" in the string. This won't necessarily be the number of unicode characters in the string.
String function converts a number into a string.
Strings are objects and so have methods, e.g.:
- charAt
- concat
- indexOf
- lastIndexOf
- match
- replace
- search
- slice
- split
- substring
- toLowerCase
- toUpperCase
Two boolean values in JavaScript: true and false.
Boolean function will take a value and returns its boolean value.
Null is the value that isn't anything.
Undefined is the value that isn't even null. It is the default value for variables. This is confusing because if you define a variable without initializing it it will have the value "undefined".
Undefined is the value you get when you extract a member from an object that doesn't have that member. It is the "missing value" value.
Values that evaluate as false, everything else evaluates as true:
- false
- null
- undefined
- empty string
- 0
- NaN
After these simple values, everything else in JavaScript is Objects. JavaScript is actually an object-oriented language.
Dynamic Objects
- unification of Object and Hashtable
- new Object() produces an empty container of name/value pairs
- Name can be any string, value can be any value except undefined.
- Object members can be access with dot notation or subscript notation: myObj.key or myObj['key']
- Although they are hases, no hash nature is visible: no hash methods
JavaScript is loosely typed, which means that any variable is capable of receiving any value. The values do have a type (so the language isn't "untyped"), but variables aren't bound to them.
JavaScript is syntactically a C family language. Differs from C with its type system which allows functions (which are objects) to be values.
Identifiers follow same rules as most C languages.
Variable names match: /^[A-Za-z_$]*$/
By convention everything is lowercase except for constructors.
Using the initial _ should be reserved for implementations, but are very popular. Initial $ should be reserved for machines: macro processors, etc. Ajax programmers use $ variables a lot for some reason.
JavaScript has a LOT of reserved words, but only a few are used.
Two comment styles: // or /*
Common operators that you’d expect for a C language.
+"42" = 42, just like Number("42")
Division of two integers can produce a non integer result
and != do type coercion, so always use === and !== which confirm variables are same value and type.
&& is the guard operator or “logical and”. If first operand is truthy then the result is the second operard, otherwise result is first operand. Can be used to avoid null references.
return a && a.member;
does the same as:
if (a) {
return a.member;
} else {
return a;
}
|| is default or “logical or” operator. If first operand is truthy then result is first operand, otherwise second operand. Can be used to fill in default values.
// if formField is true, then userInput = formFieldValue
var userInput = formFieldValue || default_value;
! is “logical not” operator. If operand is truthy the result is false and vice versa. From this if you do !!value you will get its boolean representation.
JavsScript has Bitwise Operators
& | ^ >> >>> <<
The bitwise operators convert the operand into a 32-bit signed integer, do the operation, then convert the result back into a 64-bit floating point. Unlike normal bitwise operation, this isn’t faster. So unless you really need a bitwise operation don’t use them.
Comments (2)
May 15, 2008 at 03:32 PM · Posted under learning, programming, quicklinks, techtips
Javascript Video Lectures
The videos are extremely well done. I rank them right up there with the videos of Knuth lecturing about TeX for clarity and flow.
Comment
March 13, 2008 at 11:49 PM · Posted under learning, math, quicklinks
Is 91 prime?
Comment
January 25, 2008 at 02:30 AM · Posted under essays, learning, programming, techtips
MVC stands for “model-view-controller”, a programming paradigm where the application is split into three interconnected yet disparate parts (as interpreted by Django):
- the model: the data of the application
- the view: the presentation and selection of data to present to the user
- the controller: the brains of the application that connects the user to the correct view
Note, the MVC paradigm is interpreted differently by the popular “Rails” framework (used for this very blog!). In Rails there are multiple controllers that decide what data to present to the user, and the view is left to simply display the data. In this interpretation Django’s views would be seen as controllers, and Django’s templates would be views.
To best describe how MVC helps us do our jobs as web programmers better, lets look at a simple PHP webpage application written as a script:
<?php
$page_title = "Ten most recent blog entries";
include_once($include_path.'/header.php');
// setup $db
include_once($include_path.'/db_connection_for_this_application.php');
$recent_blog_posts = mysql_query("SELECT
posts.post_date,
posts.post_title,
posts.post_content
FROM
posts
WHERE
posts.post_status='publish'
ORDER BY posts.post_date DESC LIMIT 10, $db);
echo '<h1>Recent Posts</h1>';
while($posts_data = mysql_fetch_array($recent_blog_posts)) {
echo '<div class="post">';
echo '<div class="blog_date">' . $posts_data['post_date'] . "</div>\n";
echo '<div class="blog_entry_title">' . $posts_data['post_title'] . "</div>\n";
echo '<div class="blog_entry">' . $posts_data['post_content'] . "</div>\n";
echo '</div>';
}
include_once($include_path.'/footer.php');
?>
Simple enough. That’s actually the big advantage of writing web applications as scripts. They are (almost) entirely self-contained and easy to understand. You start reading at the top and finish at the bottom, with no file jumping or object modeling required.
Unfortunately, this simpliciy is also very limiting:
- The content and the programming are combined. This means that, aside from CSS, if any web designers want to update the look of the page then they’ll have to modify the same file that contains the application. That’s a great opportunity for things to go wrong.
- The header and footer are fixed. This means altering something like the title of the page forces the application to declare prespecified variables (e.g. the $page_title), that the header file assumes are in place. A bunch of these variables can quickly clutter an application. At a simple level, including headers and footers makes sense, but as pages get more complex they get harder to maintain. What if you have a standard header/footer, but want slightly modified versions for other sections? Using header/footer includes means that you’ll have to create separate include files for each. Without a clear organizational structure things can get confusing pretty quickly.
- Low-level programming is involved. The programmer has to build database queries by hand, which is a great place for bugs to hide.
- No object oriented programming. You can’t wrap up functions and data into logical blocks with specific interfaces (e.g. objects). In a better system, we’d just ask the “Blog” object directly for the ten most recent posts with something like {{ blog.posts | ‘limit’: 10 }}
As you can see, there is room for something better. That something is an MVC framework such as Django or Rails. Let’s look at how one (Django) solves the problems with our PHP script. I’ll show you the code first, then get into the explanation:
### models.py (the *model*) ###
from django.db import models
class Blog(models.Model):
entry_title = models.CharField(maxlength=50)
blog_date = models.DateField()
entry = models.TextField()
### views.py (the *view*) ###
from django.shortcuts import render_to_response
from models import Blog
def recent_posts(request):
post_list = Blog.objects.order_by('-blog_date')[:10]
return render_to_response('recent_posts.html', {'post_list': post_list})
### urls.py (the *controller*) ###
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
(r'^recent/$', views.recent_posts),
)
### recent_posts.html (the *template* (part of the view))###
<html><head><title>Recent Blog Posts</title></head>
<body>
<h1>Recent Posts</h1>
{% for post in post_list %}
<div class="post">
<div class="blog_date">{{blog_date}}</div>
<div class="blog_entry_title">{{entry title}}</div>
<div class="blog_entry">{{entry}}</div>
{% endfor %}
</body></html>
Ok! That seems a little confusing compared to the script doesn’t it? Let’s dive in:
recent_posts.html
Take a closer look at the “recent_posts.html”. Think of how lucidly clear that file is to a web designer? There’s hardly any code! While of course no templating language can eliminate programming constructs Django’s system does a great job of only giving the template designers what they need to get the job done. The template “programming” is using its own programming language, not straight Python. There are two big reasons for this: 1) the language is meant to be simple and only provide the features needed to select or present the proper data, 2) the language doesn’t allow templates to do anything that the application should handle (e.g. a template can’t tell the database to delete itself).
Yes, my example doesn’t demonstrate how Django helps with header/footer includes, that’s coming up so be patient!
models.py
This is simply describing to Django how to organize the data object that we’ll be dealing with.
urls.py
This is routing a user’s request for the web address ‘recent/’ (e.g. mysite.com/recent) to the recent_posts function in views.py.
views.py
This is the best part, take a look again:
def recent_posts(request):
post_list = Blog.objects.order_by('-blog_date')[:10]
return render_to_response('recent_posts.html', {'post_list': post_list})
That’s it? That’s it! Our complex SQL query is now a higher level abstraction where we tell Django to tell the blog to give us the latest ten posts. Done!
Now lets look at that last piece: header/footer files.
Django does allow us to build templates that pull in header/footer includes, but it also lets us solve the common data problem with template inheritance. With template inheritance we don’t abstract the pieces of our web pages that are the same, we pull out the pieces that are different. Let me explain with a very simple webpage:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>My Website</title>
</head>
<body>
<h1>Page Title</h1>
<p>Customized content!</p>
<hr>
<p>This is my footer</p>
</body>
</html>
Done using header/footer includes:
### header include file ###
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>My Website</title>
</head>
<body>
### footer include file ###
<p>This is my footer</p>
</body>
</html>
### custom page ###
include(header_file)
<h1>Page Title</h1>
<p>Customized content!</p>
include(footer_file)
Now done with Django’s template inheritence:
### base.html ###
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<h1>{% block pagetitle %}{% endblock %}</h1>
{% block content %}{% endblock %}
{% block footer %}
<p>This is my footer.</p>
{% endblock %}
</body>
</html>
### page.html ###
{% extends "base.html" %}
{% block title %}Customized Title!{% endblock %}
{% block pagetitle %}Customized page title!{% endblock %}
{% block content %}
<p>Customized content!</p>
{% endblock %}
See what we did there? The parts of the page that will change are pulled out of the base. Django’s template system lets you declare “blocks” that indicate that that part of the page may change. If an extending template declares a block that matches that of the parent template, then the parent’s block is overwritten. If a block isn’t declared by the sub-page, that is in the parent page then the parent page’s block is used. Notice in our “page.html” the footer isn’t discussed at all. Django sees that we are “extending” base.html and that we haven’t specified our own footer block so it defaults to the footer block that was in base.html.
Perfect! We can create base templates that allow for child pages to overwrite any part that we explicitly allow! No more locked headers or footers!
Templates can go through multiple levels of inheritence as well. We could easily have a base template that is then extended into “section” templates that are then extended to specific pages. With a clear and logical chain of command it is easy to see how the webpage templates work together. Much better than a couple dozen header/footer files lying around. We get all the advantages of reusing designs without the headaches!
So there you have it. Sorry for the rambling/unedited nature of this post. It’s 2:30am, I can’t sleep, but I felt like sharing.
Comment
January 08, 2008 at 12:55 PM · Posted under learning, quicklinks
Flash Guitar Tutorials
Comment