Archive
Javascript 101 Week 1 Assignment
As I blogged previously, I am starting to learn Javascript via P2PU.org/Mozilla School of Webcraft. Here are my answers to the first week’s assignment.
Questions
The alliance of Netscape and Sun Microsystems did not use Java in the browser, because it was not suitable for that purpose. Why do you think Java was not suitable to be embedded in a browser?
I don’t think Java is suitable for embedding in a browser for a few reasons. Firstly, while the Just in time compiler does a great job at optimizing code that runs over and over again, there is a big cost to starting up the JVM, as it must load dozens if not hundreds of class files.
Furthermore, developing web applications in Java would be very slow for the developer too, as the code would have to be compiled into bytecodes before it could be run. Webapps written in Java have this problem already; if all the client side scripting were done in Java, this would be unbearable.
Furthermore, Java is not a good scripting language because it is too verbose, and the strict type checking is often overkill for simple scripts.
When parsing a String into a number using the parseInt() method, we are advised to always provide the radix. Why is it so strongly recommended?
We are advised to provide a radix, because Javascript stops parsing at the first nondigit number. If the number starts with 0, this makes Javascript believe the number is octal and that any character other than 0-7 is invalid. Thus parseInt(“09”) == 0.
What is a type, and why do you think types are useful in writing programs?
A type indicates the ‘flavor’ of a variable, i.e. what the ‘tentacle’ grasps (using the terminology of the Eloquent Javascript course. Types are very useful for ensuring that the operations we invoke on variables make sense. For instance, it makes sense to invoke the times binary operand on two numerical values, but it doesn’t make sense to invoke it on two Strings, or a String and a number.
Why do we lose precision when performing operations with decimal numbers in Javascript? Can you think of a few implications of why this would be a problem?
All numbers in Javascript are stored as doubles (64 bit floating point numbers), which have a finite precision. Certain numbers cannot be exactly represented in this format, such as 0.1 (it has a nonterminating binary representation, and thus cannot be exactly represented in a finite number of digits). This means we have to be very careful when working with numbers, because our intuitive sense is wrong.
.1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 = 0.9999999999999999
Do you understand why the following operation produces the given result 115 * 4 – 4 + 88 / 2 = 500
Yes – order of operations matters. * and / have higher precedence over +. If you want to change this, use parentheses to explicitly show the order you want.
What does typeof 4.5 do, and why does typeof (typeof 4.5) return “string”
Typeof returns a string representation of the type of the argument. typeof (typeof 4.5) returns string, because typeof returns the string “number”. The piece in parentheses is executed first, with that result becoming the argument to the outer typeof call.
Exercises
2.1
(4 >= 6 || "grass" != "green") && !(12 * 2 == 144 && true) (false || true) && !(24 == 144 && true) (false || true) && !(false && true) (true) && !(false) (true) && (true) true
2.2
function while_exponent(val, exp) { var product = 1; var counter = 0; while (counter < exp) { prduct *= val; counter++; } return product; }
2.3
function while_triangle(n_lines) { var line_counter = 1; while (line_counter <= n_lines) { var string = "" var inner_counter = 0; while (inner_counter < line_counter) { string += "#" inner_counter++; } print(string) line_counter++; } }
2.4
function exponent(val, exp) { product = 1; for (var i = 0; i < exp; i++) { product *= val; } return product; } exponent(2, 10) == 1024 function triangle(lines) { for (var i = 1; i <= lines; i++) { var string = "" for (var j = 0; j < i; j++) { string += "#" } print(string); } } triangle(10); # ## ### #### ##### ###### ####### ######## ######### ##########
2.5
var result = Number(prompt("What's the value of 2+2?")); if (result == 4) { alert("Excellent"); } else if (result == 3 || result == 5) { alert("Almost"); } else { alert("Idiot."); }
2.6
while (true) { var result = Number(prompt("What's the value of 2+2?")); if (result == 4) { alert("Excellent"); break; } else if (result == 3 || result == 5) { alert("Almost"); } else { alert("Idiot."); } }
2.
var name = prompt("What's your name?") || "Guest";
This is an example of using the OR binary op to return the second operand if the first is a Falsey value (e.g. the empty string). This allows you to provide sensible defaults
We can use the && as a guard against null values. For instance, if we want to invoke a method on an object, but not if it’s null, we could do
var result = X && X.someMethod()
since the && will only evaluate the second operand if the first is not a Falsey value (e.g. null), we are safe from executing undefined methods.
/*#p2pu-Jan2011-javascript101*/
Java annoyances
Asymmetry in standard libraries
String[] strings = ...; StringBuilder b = new StringBuilder(); for (int i = 0; i < strings.length; i++) { b.append(strings[i]); if (i != strings.length -1) { b.append(","); } } System.out.println(b.toString());
print(",".join(strings))
println(strings.mkString(","))
Different treatment of primitives and objects
It is a lot harder to deal with variable length collections of primitive types than it should be. This is because you cannot create collections out of things that are not objects. You can create them out of the boxed primitive type wrappers, but then you have to iterate through and convert back into the primitive types.
// Need a double[] but don't know how long it's going to be List<Double> doubles = new LinkedList<Double>(); for (...) { doubles.append(theComputedValue); } // Option 1: Use for loop and iterate over Double list, converting to primitive values through // auto unboxing // Bad: leads to O(n^2) running time with LinkedList double[] doubleArray = new double[doubles.size()]; for (int i = 0; i < doubleArray.length; i++) { doubleArray[i] = doubles.get(i); } // Option 2: Use enhanced for loop syntax (described below), along with // additional index variable. // Better performance but extraneous index value hanging around int index = 0; // Automatic unboxing for (double d : doubles) { doubleArray[index++] = d; } ... b[index] // Oops
Patchwork iteration support
Collection<String> strings = new ArrayList<String>(); Iterator<String> it = strings.iterator(); while (it.hasNext()) { String theString = it.next(); }
for (String s : strings) { // deal with the String }
class IterableIterator<T> implements Iterable<T> { private Iterator<T> iter; public IterableIterator(Iterator<T> iter) { this.iter = iter; } // Fulfill the Iterable interface public Iterator<T> iterator() { return iter; } }
Lack of type inference for constructors with generics
Yes, we all know we should program to an interface rather than to a specific implementation; doing so will allow our code to be much more flexible and easily changed later. Furthermore, we also know we should use generics for our collections rather than raw collections of objects; this allows us to catch typing errors before they occur. So in other words
// BAD: Raw hashmap and programming to the implementation! HashMap b = new HashMap(); // Good Map<String, Integer> wordCounts = new HashMap<String, Integer>();
Map<String, Integer> wordCounts = Maps.newHashMap();
Map<String, Integer> wordCounts = new HashMap<String, Integer>();
Map<String, Integer> wordCounts = new HashMap<>();
Conclusion
Scala – type inferencing gotchas
int x = 100;
as we would in Java, you can instead write
val x = 100
The setup
def calculateAverageColor(image:BufferedImage):Color = { var redSum = 0 var greenSum = 0 var blueSum = 0 // calculate the sum of each channel here val red = (redSum / numPixels) val green = (greenSum / numPixels) val blue = (blueSum / numPixels) new Color(red, green, blue) }
Problem #1
scala> java.lang.Integer.MAX_VALUE res0: Int = 2147483647 scala> java.lang.Integer.MAX_VALUE+1 res2: Int = -2147483648
If this happens, then we end up trying to construct a color with negative red, green, or blue values; this will result in an IllegalArgumentException.
def calculateAverageColor(image:BufferedImage):Color = { // Declare the sums as longs so we don't have to worry about overflow var redSum:Long = 0 var greenSum:Long = 0 var blueSum:Long = 0 // calculate the sum of each channel val red = (redSum / numPixels) val green = (greenSum / numPixels) val blue = (blueSum / numPixels) new Color(red, green, blue) }
java.lang.IllegalArgumentException: Color parameter outside of expected range: Red, Green, Blue
Problem #2
At this point, you might start debugging the process by printing out the values of red, green, and blue. Sure enough they’ll be in the range [0, 255], just as you need for the Color constructor. What is going on?
There are two related problems. The first is that the type of red, green, and blue are not integers, due to the Long value in the computation. The compiler sees the Long and (correctly) infers that the type of red, green, and blue must be Long.
”
The following 19 specific conversions on primitive types are called the widening primitive conversions:
- byte to short, int, long, float, or double
- short to int, long, float, or double
- char to int, long, float, or double
- int to long, float, or double
- long to float or double
- float to double
”
long redSum = ...; int averageRed = (int) (redSum/numPixels);
val redSum:Long = ... val averageRed:Int = (redSum/numPixels).asInstanceOf[Int]
var redSum:Long = 0 var greenSum:Long = 0 var blueSum:Long = 0 // calculate the sum of each channel val red:Int = (redSum / numPixels).asInstanceOf[Int] val green:Int = (greenSum / numPixels).asInstanceOf[Int] val blue:Int = (blueSum / numPixels).asInstanceOf[Int] new Color(red, green, blue)
Conclusion
One of the nice things about Scala is that you do not need to explicitly declare the types of your variables. In one sequence of unfortunate events, the variables that looked like ints were in fact longs, leading to an implicit conversion to the float primitive type, which in turn caused the incorrect constructor to be invoked, and an IllegalArgumentException. Hopefully you can avoid doing something so foolish as a result of reading this post.
NetBeans Platform – how to register a class as a provider of multiple services
The issue I ran into is that the documentation is not very clear how you can register your class as providing more than one service (again, implementing more than one interface). For instance, say I have two interfaces I want a class to fulfill:
public interface Foo { public String getFoo(); } public interface Bar { public String getBar(); } public class FooBar implements Foo, Bar { public String getFoo() { return "foo"; } public String getBar() { return "bar"; } }
// This is a mistake; you can't declare two annotations like this @ServiceProvider(service=Foo.class) @ServiceProvider(service=Bar.class) public class FooBar implements Foo, Bar {
@ServiceProviders(value={ @ServiceProvider(service=Foo.class), @ServiceProvider(service=Bar.class)} )
NetBeans – Reformat text
(Sourcecode taken from this stackoverflow post)
The other time it’s useful is when working on a project where someone is using very large tab settings (e.g. 8 spaces per tab instead of 4). This can make it very difficult to read. By invoking this command, you’ll put the code into a much more readable format.
P2PU – World of Webcraft
I signed up for the Javascript 101 course and was asked to watch a 30 minute introductory video, write a short blog post, and then write a simple javascript program that did some addition and displayed the result as an alert in the browser. Pretty simple stuff, but it weeds out those who are not willing to do some work on their own and would just slow down the class.
I also applied for, and was accepted into, the Introduction to Ruby and Rails course. Longtime readers of this blog might remember that I have dabbled in Rails before, and had an initially favorable impression. But like any skill, you must use your knowledge or it quickly fades away. I’m basically back to square one with Ruby/Rails due to not having used it in the past year, so I’m looking forward to the added impetus of a class to get me to learn it.
Given that the vast majority of my programming has been on desktop / mobile client applications, I am excited to learn some web programming languages and techniques. Technology changes quickly, and I can all but guarantee my expertise in Java Swing is not going to count for much in a few years.
I’ll be sure to write about my impressions as I go through the course; in the meantime, I urge you to sign up for these courses before they fill up.
Code Complete 2nd Edition e-book – $20
Hi all,
I’ve slowly been transitioning all of my tech book purchases to e-book formats, particularly due to O’Reilly’s daily e-book deal tweets (follow @oreilly if interested; they seemed to be posted less frequently recently, but there are some good deals once in awhile).
Anyways, today’s deal of the day is Code Complete 2nd Edition, which is $20 with discount code DDC2E. I got this as a paperback for Christmas a few years ago and literally read it cover to cover in a week or so. It’s great stuff, and a must read for any programmer. I’m half tempted to buy it again, as it’s a lot more convenient to have a digital version than a 1.5 inch thick tome.
Reset windowing system in NetBeans Platform
Clean and build
Remove Windows2Local
rm -rf /path/to/Foo/build/testuserdir/config/Windows2Local
NetBeans Platform – ModuleInstall ClassNotFoundException
In the NetBeans Platform, you can create an ModuleInstall class which handles the lifecycle of your module, and provides methods you can override to handle when your module is loaded and unloaded. The standard way of creating this class is to use the wizard that NetBeans provides for this purpose, accessible by right clicking on the project and choosing New -> Other -> Module Development -> Module Installer
If you decide that you do not want to use the ModuleInstall mechanism any longer (the NetBeans Platform folks suggest you do NOT use it, as it will increase the startup time of the application), you might think you can just delete the Installer.java file that the wizard created. Unfortunately, that’s not the case. When you run the project you’ll get an exception like the following
org.netbeans.InvalidException: StandardModule:net.developmentality.moduleexample jarFile: ... java.lang.ClassNotFoundException: net.developmentality.moduleexample.Installer starting from ModuleCL@482...
The problem is that the wizard modified the manifest.mf file as well, and you need to manually clean up the file before your project will work again.
Open the manifest.mf file and you’ll see a line in the file like the following:
OpenIDE-Module-Install: net/developmentality/moduleexample/Installer.class
delete that line, and rebuild. You should be ready to go.
In general, you need to be very careful about using any of the wizards that NetBeans provides. They are extremely useful, but they end up changing XML files that you will need to manually edit later if you decide to refactor. For instance, if you create an Action instance using the New Action Wizard, the action will be registered in the layer.xml file. If you rename the action using the refactor command, the entries in the xml file are NOT modified, and you will get an exception at runtime unless you remember to edit that file.
Fortunately, the wizards are smart enough to at least tell you which files they are modifying. It’s just a matter of remembering this further down the road when you need to refactor, move, or delete files. Look for the modified files section in the wizard dialog: