Friday, December 19, 2014

Assasins Creed: Pirates HTML5/JS/WebGL demo

Another demo that caught my eye is Assasins Creed: Pirates Demo made by the IE engineering team, with HTML5, JavaScript, WebGL and more specifically Babylon.js Here is a web page that explains how to start working with Babylon.js and create 3D virtual worlds in a browser.


I played the demo several times in Firefox 34 and I can say it looks fantastic coupled with nice pirate music. There are nine weather conditions between you can choose to play, and each has its own specifics, like day or night, rainy or sunny etc... Use A, D to keys to turn the ship left or right and W, S to speed up or slow down. Use V to switch camera from third person view to first person view and vice versa. Use mouse to rotate the camera around the ship.

Note: To enable and use these new browser technologies you must have IE11 and Windows 7 Service Pack 1 or other advanced browser like Google Chrome, Opera and Firefox. Safari 5.1.7 does not support WebGL.

More info here: https://www.modern.ie/en-us/demos/assassinscreedpirates
Other IE demos: http://ie.microsoft.com/testdrive/Default.html
Babylon.js Challenge: http://www.babylonjs.com/cyos/acpr/#OKULH#1 

Assasins Creed: Pirates Demo
Assasins Creed: Pirates Demo
Intro Comic
Intro Comic
Controls
Controls
WebGL lighting effect
WebGL lighting effect
Beautiful environment
Beautiful environment
I have won the game
I have won the game
First person view. Beautiful foggy effect
First person view. Beautiful foggy effect
Moon shines
Moon shines
Rotate the camera with the mouse
Rotate the camera with the mouse
Rotate the camera with the mouse
Rotate the camera with the mouse

Tuesday, December 16, 2014

List of JavaScript libraries

How many JavaScript libraries can you think of? :D http://en.wikipedia.org/wiki/List_of_JavaScript_libraries
  1.  Angular.js Web Apps
  2. Backbone.js
  3.  Ext.js Web Apps
  4. Jquery.js
  5.  Ember.js Web Apps
  6.  Express.js
  7. Node.js Server side JavaScript
  8. React.js
  9. Underscore.js
  10. Box2d.js 
  11. yui.js
  12. SWFObject.js
  13. Three.js 3D in Browser/WebGL
  14. Modernizr.js
  15. Jasmine.js 
  16. Dojo.js
  17. Midori.js
  18. Prototype.js 
  19. Create.js 
  20. PDF.js  Decode PDF files in Browser with JavaScript
  21. Spry Framework 
  22. Babylon.js  3D in Browser/WebGL
  23. Gamepad.js 
  24. Mobify.js 
  25. Phantom.js 
  26. hapi.js 
  27. chai.js
  28. thaw.js 
  29. parallax.js 
  30. cannon.js 
  31. kinetic.js 
  32. sprite.js 
  33. zepto.js 
  34. GSAP.js
  35. Agile Toolkit
  36. ScrollReveal.js 
  37. Superscrollorama.js 
  38. Sly.js 
  39. Transit.js 
  40. Slidr.js 
  41. physics.js 
  42. Matter.js 
  43. Box2Dweb  Flash like 2D Physics engine in browser
  44. ClickStream.js 
  45. Durandal.js

Useful links: 
http://kangax.github.io/compat-table/es5/
http://blog.rodneyrehm.de/archives/27-Dialog-for-Unsupported-Browsers.html
https://github.com/es-shims/es5-shim
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
http://www.sitepoint.com/ie11-developer-tools/
http://www.amazon.com/Pro-Internet-Explorer-Development-Applications/dp/1430228539
http://msdn.microsoft.com/en-us/library/ie/hh673549%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/ie/bg182636%28v=vs.85%29.aspx
http://www.vcaa.vic.edu.au/Documents/vass/Windows7-IE10.pdf
http://code.tutsplus.com/tutorials/documenting-javascript-with-yuidoc--net-25324

Links for testing web apps on different browsers and mobile devices:

http://www.sitepoint.com/building-the-best-browser-test-suite/
http://blogs.adobe.com/browserlab/2013/03/13/browserlab-is-shutting-down-on-march-13-2013/
http://browsershots.org/
https://github.com/yui/yui3/wiki/Graded-Browser-Support
http://www.browserstack.com/start?cbsid=browserlab
http://saucelabs.com/
http://sauceio.com/index.php/2013/03/sauce-labs-welcomes-adobe-browserlab-customers/
https://creative.adobe.com/products/inspect
https://www.blackbaud.com/files/support/guides/infinitydevguide/content/webshell/webshelagradebrowsers.htm
https://spoon.net/browsers/
http://www.my-debugbar.com/wiki/IETester/HomePage

Sunday, December 14, 2014

Cube Slam

Nice demonstration of available technologies that exist in todays browsers. It is a game called Cube Slam. Technologies used in this game are: WebRTC, Web/HTML5 Audio API, WebGL and CSS3, Google Cloud Platform.

"If you play Cube Slam on Chrome or Firefox, you’ll see real-time 3D rendering enabled by WebGL and three.js. If you don’t have WebGL, you can still play Cube Slam in 3D thanks to CSS3, with the same game engine running under the hood. All the graphics run on your GPU, freeing the CPU for other tasks."

"Cube Slam is built entirely on Google Cloud Platform. The app is hosted on Google App Engine with a backend written in Go, and the Channel API is used to set up the connection with your opponent. If one of the players is behind a firewall, the game uses a STUN/TURN server hosted on Google Compute Engine to exchange data. PageSpeed helps things load quickly, and AppCache lets you play offline."

The game is not complete as you can play until level 4, right at the moment when it gets interesting :)
Also I reccomend closing other tabs that might download data, because it might break the connection oppened for the game. It happened on Firefox several times.
It also worked on Safari 5.1.7 without using WebGL but with CSS 3 3D alike tricks 

For more info on the details check this link https://www.cubeslam.com/tech

Level 1
Level 1
Breaking an object that holds a video area
Breaking an object that holds a video area
Beautiful effect of blurring the window when you loose
Beautiful effect of blurring the window when you loose
Cube Slam - Main menu
Cube Slam - Main menu
The game is working with CSS3 instead of WebGL in Safari 5.1.7
The game is working with CSS3 instead of WebGL in Safari 5.1.7

Thursday, December 11, 2014

HTML5 Audio API

Several years ago this wasn't really possible without Flash. A fully functional sound spectrum visualizer player made fully in HTML5 and JavaScript/WebGL

3D audio spectrum visualizer
3D audio spectrum visualizer
3D audio spectrum visualizer
3D audio spectrum visualizer
3D audio spectrum visualizer
3D audio spectrum visualizer
A web based piano made with HTML5/JavaScript. Well done!

HTML5/JavaScript piano
HTML5/JavaScript piano










Old timer russian radio replica made with HTML5 and JavaScript

Old timer russian radio device replica.
Old timer russian radio device replica.
Meow Peow player in a browser

Fully functional MP3 player in a browser.
Fully functional MP3 player in a browser.
Links:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API
http://webaudioapi.com/
http://shop.oreilly.com/product/0636920025948.do
https://developer.mozilla.org/en-US/demos/detail/beyer-music-player/launch
https://developer.mozilla.org/en-US/demos/detail/oscillators
https://developer.mozilla.org/en-US/demos/detail/musical-mines-and-rails
https://developer.mozilla.org/en-US/demos/detail/touch-turntables
https://developer.mozilla.org/en-US/demos/detail/classical-music-jukebox
https://developer.mozilla.org/en-US/demos/detail/soundbox-lite
https://developer.mozilla.org/en-US/demos/detail/html5-piano

Face Detection/Analytics with HTML5 video tag


Face Detection/Analytics with HTML5 Video from Daniel Goodwin (@dsg) on Vimeo.

https://developer.mozilla.org/en-US/demos/detail/facial-recognition-and-analytics-with-html5s-video/launch

Monday, December 8, 2014

Canvas Mark 2013 - test your browser performance

Check out this nice tool that tests your browser performance: Canvas Mark 2013
Github Source

Tests the HTML5 <canvas> rendering performance for commonly used operations in HTML5 games: bitmaps, vectors, shapes, text, shadow, alpha blending, pixel blur, Math, canvas shapes, polygon fills, image transformations, getImageData, putImageData.

So the tests should be made on the five most popular browsers: Firefox, Chrome, Opera, IE9/IE10, and Safari. You can run them one by one, closing all other applications that might drain CPU/GPU processing power. Also you should run these test on the same machine as running them on different machines will produce different results. The browser window should not be minimised.

I couldn't find a flag called GPU VSync in chrome://flags (Chrome 40) so I couldn't disable it. Apart from that, all other GPU related flags were disabled except One-copy-rasterizer.

I am using Firefox 34, Opera 26.0, Chrome 40, IE9 and Safari 5.1.7 on Windows 7.
Also I am using middle class Asus laptop. Ask me for more hardware details (not sure if I should share this information).

Note: not sure why but the tool detects that Opera 26.0 is actually Chrome 39. I have tested other similar tools and they also say that Opera 26.0 is Chrome 39. Perhaps it is something with the engine of Opera.

Note: running the test twice in the same browser without refresh uncovers a bug, so the second run might go until the blur image test and stop there. Therefore I recommend closing and opening the browser after each test.

 The results from my testing are:
  1. Safari 5.1.7 with 7034
  2. Chrome 40 with 6072
  3. Opera 26 with 5787
  4. Firefox 34 with 4790
  5. Internet Explorer 9 with 4504
canvas mark 2013
Canvas Mark 2013

Tower Diffence web game

Turns out you can build fully featured HTML5/JavaScript games.
Check this demo of a Tower Diffence web game. Made with WebGL and three.js

Browsers: Firefox 34, Chrome 40, Opera 26.0, Internet Explorer 9 and Safari 5.1.7


On Opera, Firefox and Chrome it worked perfectly, while on IE9 and Safari it just displayed white area where the game should happen. I finsihed the game and on Opera and Firefox it used about 40% of the processor power while on Chrome it had two processes that worked hard, on 30% and on 40%. Not sure why? Maybe Chrome works that way.

The game is not a proper test for HTML5 audio API since it doesn't have a single sound effect or music.

internet explorer 9
IE 9
safari 5.1.7
Safari 5.1.7
opera 26.0
Opera 26.0
opera 26.0
Opera 26.0
chrome 40
Chrome 40
Two working processes for Chrome
Two working processes for Chrome
Utilizing WebGL and three.js
Utilizing WebGL and three.js
Utilizing WebGL and three.js
Utilizing WebGL and three.js
Last wave finished on Chrome 40
Last wave finished on Chrome 40
about the game
about

Account Slider

Account slider. I cannot recall making a sliding accordion before, without using Flash. This is made with HTML5/JavaScript. Well done!

Browsers: Firefox 34, Chrome 40, Opera 26.0, Internet Explorer 9 and Safari 5.1.7

On Opera/Firefox/Chrome works perfectly. On Safari works but it is a bit sluggish. On IE9 it shows a bulleted list instead of accordion.



Geometric Photo Filter - Web browser application

 Fantastic web browser application Geometric Photo Filter by http://zd3n.com http://satori.sk
I run this application in Opera 26.0 on my Asus middle class laptop. It was run on 100 steps per frame and it performs well, not overloading the processor. Give it a day maybe it will redraw the complete image.




You can run this application on Firefox, Chrome and Opera perfectly. I have Firefox 34, Chrome 40, and Opera 26.0 I also tried on Safari 5.1.7 and Internet Explorer 9. Turns out they do not support File API and Filereader.

Safari 5.1.7

IE 9

Wednesday, December 3, 2014

HTML 5 3D, 2D canvas demos

http://batiste.dosimple.ch/games/rpg/game.html
http://blog.rodneyrehm.de/archives/27-Dialog-for-Unsupported-Browsers.html
https://developer.mozilla.org/en-US/demos/detail/convolution-matrix/launch
https://developer.mozilla.org/en-US/demos/detail/context-aware-image-resizing
https://developer.cdn.mozilla.net/media/uploads/demos/c/a/calvin/054e17c76b19a054d20d6b313ca1d62f/fractal-explorer_1367242706_demo_package/index.html#500/-0.37/0.6/julia
https://developer.mozilla.org/en-US/demos/detail/webworkers-attractors
https://developer.mozilla.org/en-US/demos/detail/ball-pit
https://developer.mozilla.org/en-US/demos/detail/playroom
https://developer.mozilla.org/en-US/demos/detail/apple-hls-javascript-player/launch
https://developer.mozilla.org/en-US/demos/detail/balls-with-gravitation
https://www.cubeslam.com/
https://developer.mozilla.org/en-US/demos/detail/bombcarrier
https://developer.mozilla.org/en-US/demos/detail/just-spaceships
https://developer.mozilla.org/en-US/demos/detail/opendepth-point-cloud
https://developer.mozilla.org/en-US/demos/detail/moon-wars
https://developer.mozilla.org/en-US/demos/detail/geoqr/launch
https://developer.mozilla.org/en-US/demos/detail/gravedad
https://developer.mozilla.org/en-US/demos/detail/minesweeper
https://developer.mozilla.org/en-US/demos/detail/achtung-die-kurve
https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Bootstrapping_a_new_locale
https://developer.cdn.mozilla.net/media/uploads/demos/p/a/pavloschris/74018e092d31c4610d4ddea786aaf883/lethargy_1343507075_demo_package/index.html
https://developer.cdn.mozilla.net/media/uploads/demos/e/l/elfoxero/c17223c414d8ddafb7808972b5617d9e/html5-notifications_1400214081_demo_package/index.html
https://developer.mozilla.org/en-US/demos/detail/remixing-reality/launch
https://developer.mozilla.org/en-US/demos/detail/the-letter-heads/launch
https://developer.mozilla.org/en-US/demos/detail/trangle/launch
https://developer.mozilla.org/en-US/demos/detail/space-break
https://developer.mozilla.org/en-US/demos/detail/role-playing-game/launch
https://developer.cdn.mozilla.net/media/uploads/demos/L/a/LaNsHoR/e4c139569f1038b21c52cebfac9e4134/fruits_1326101404_demo_package/index.html
https://developer.cdn.mozilla.net/media/uploads/demos/d/r/dragongraphics/0bca6526258ac28e1e900882bc11d333/media-query-mario_1351726916_demo_package/index.html
https://developer.cdn.mozilla.net/media/uploads/demos/c/h/chamb/3c55ddc67e35bc7bee1e7388c9bd5393/comic-gen_1354466686_demo_package/index.html
https://developer.mozilla.org/en-US/demos/detail/beyer-music-player/launch
https://developer.mozilla.org/en-US/demos/detail/classical-music-jukebox/launch
https://developer.mozilla.org/en-US/demos/detail/3d-pong
https://developer.cdn.mozilla.net/media/uploads/demos/n/e/nestoralvaro/d2ab81ed6c13b9bcbb401d7575ad63d5/touch-turntables_1361965544_demo_package/index.html
https://developer.mozilla.org/en-US/demos/detail/3d-assembly
https://developer.mozilla.org/en-US/demos/detail/one-whale-trip/launch
https://developer.mozilla.org/en-US/demos/detail/get-motion-media/launch
https://developer.mozilla.org/en-US/demos/detail/penguin-jump
https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API
http://webaudioapi.com/
https://dvcs.w3.org/hg/gamepad/raw-file/default/gamepad.html
https://developer.cdn.mozilla.net/media/uploads/demos/M/t/Mte90/b10107b9880f5d2c00133ea92c42b396/boxes-wot-shoot_1410529470_demo_package/index.html
https://developer.cdn.mozilla.net/media/uploads/demos/f/u/fusionchess/dc976f147bc37a683f48928b181e08d5/html5-2d3d-chess_1322872921_demo_package/index.html
https://developer.cdn.mozilla.net/media/uploads/demos/v/i/viliusl/07f948b9638c01cec40270c4f1ad522d/moon-wars_1378491054_demo_package/index.html
https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Mozilla_Extensions
http://trac.webkit.org/wiki/Applications%20using%20WebKit
en.wikipedia.org/wiki/List_of_web_browsers#WebKit-based
https://www.mozilla.org/en-US/firefox/developer/?utm_source=firefox-com&utm_medium=referral&utm_content=fxdev-mdn&utm_campaign=FX10
http://www.w3.org/2010/webperf/
http://www.chromeexperiments.com/
http://html5readiness.com/
http://ie.microsoft.com/testdrive/Performance/msPerformance/Default.html?loaded=0
http://ie.microsoft.com/testdrive/Default.html
http://ie.microsoft.com/testdrive/Performance/BUILDPerformanceTricks/Default.html
http://race.assassinscreedpirates.com/
http://www.fishgl.com/
http://ie.microsoft.com/testdrive/Performance/FishBowl/Default.html
https://developer.mozilla.org/en-US/demos/detail/zen-photon-garden/launch
http://codepen.io/suffick/pen/KrAwx
http://codepen.io/pixelgrid/pen/ECrKd
http://codepen.io/ara_node/pen/nuJCG
http://www.chromeexperiments.com/detail/gesture-based-revealjs/
http://www.freeriderhd.com
http://codepen.io/soulwire/pen/Ffvlo
http://www.craftymind.com/factory/html5video/CanvasVideo.html
https://developer.mozilla.org/en-US/demos/tag/tech:canvas
http://www.hongkiat.com/blog/48-excellent-html5-demos/
https://developer.cdn.mozilla.net/media/uploads/demos/M/a/Martin/a3bd6127543a304658fc3e61904f1dba/unreal-engine-4-stra_1415835062_demo_package/index.html
http://html5demos.com/canvas
http://www.kevs3d.co.uk/dev/
http://www.canvasdemos.com/top-100/

Wednesday, November 19, 2014

JavaScript notes - Part 2

This post is in continuation of this one http://tunephp.blogspot.com/2014/11/javascript-notes-part-1.html. It will contain notes about JavaScript Inheritance, Arrays, Regular Expressions, Style, Beautiful Features, Awful parts and Bad Parts.

Inheritance

  1. JavaScript being a loosely typed never casts. What matters about object is what it can do, not what it is descended from.
  2. Every function gets a prototype object because the language does not provide a way of determining which functions are intended to be used as constructors. The constructor property is not useful, it is the prototype object that is important.
  3. If all of the state of an object is private then the object is tamper-proof. Properties in the object can be replaced or deleted, but the integrity of the object is not compromised.
  4. If we create object in functional style and all of the methods of the object make no use of "this" or "that" then the object is durable. A durable object is simply a collection of functions that act as capabilities. A durable object cannot be compromised.

Arrays

  1. JavaScript has an object that has some array like characteristics. It converts array subscripts into string that are used to make properties. It is significantly slower than a real array.
  2. Arrays have useful set of built in methods than objects.
  3. Arrays in JS can contain any mixture of values. example: var myArray = ['', 0, undefined, "hello", null, {'key': 'value'}, [0, 1, 2, 3]];
  4. Every array has a length property and length is not an upped bound. If you store an element with a subscript that is greater than or equal to the current length the length will increase to contain the new element. There is no array bounds error.
  5. The length is the largest property name in the array plus one, but not necessarily the number of properties in the array. example: var myArray = []; myArray[1000000] = true; myArray.length = 1000001; // myArray contains one property
  6. The length can be set explicitly. Making then length larger does not allocate more space for the array. Making the length smaller will cause all properties with a subscript that is greater than or equal to the new length to be deleted.   A better way to add new element is to use push() function.
  7. Arrays are objects so the delete word can be used to delete element in an array. That leaves a hole but you can use splice() method to cleanly remove it from an array or to replace it with new one.
  8. Since arrays are objects "for in" statement can be used to iterate over the elements. The order is not necessarily incremental, so properties from the prototype chain can be dredged up. Use "for" statement instead if the order is important.
  9. Common rule when property names are small sequential integers is to use array, otherwise use object. 
  10. JavaScript cannot differentiate between arrays and objects since arrays are objects. Also we can add custom functions to Array.prototype
  11. It is not useful to use Object.create() on arrays since it creates object but not array. It will not have the length property or other functions that have arrays. 
  12. You can use Array.prototype.slice() method to create shallow copy of a portion of an array into a new array object. example: var myNewArray = myOldArray; myNewArray is not new object containing the same values from myOldArray, it is just a reference to the same myOldArray in memory. That means, changes to myNewArray affect myOldArray. To create new array object with the same values of myOldArray use this command: var myNewArray = myOldArray.slice(0);

Regular Expressions

  1. Many JS features were borrowed from other languages. The syntax is from  Java, functions from Scheme, prototypal inheritance from Self. JS regular expressions were borrowed form Perl.
  2. Regular expressions have significant performance advantage over equivalent string operations in JavaScript.

Style

  1. If a program is able to clearly communicate its structure and its characteristics it is less likely to break when it is modified in the never too distant future. 
  2. JS code is often sent directly the the public. It should always be of publication quality.
  3. Put spaces around all infix operators except for dot (.) and square bracket ([) because they have higher precedence.
  4. Put space after every comma and colon. 
  5. Put at most one statement per line. If statement doesn't fit in one line break it after comma or binary operator.
  6. Always use blocks {} with structured statements like while and if because it is less error prone.
  7. With JS you should always use Kernighan and Ritchie style, putting the { at the end of a line instead of the front because it avoids a horrible design blunder in JS's return statement.
  8. Declare all variables at the top of each function. JS doesn't have a block scope but it has a function scope. 
  9. Never allow switch cases to fall trough to the next case.
  10. Use single global variable to contain one application or library. Every object has its own name-space. Use of closure provides information hiding increasing the strength of your modules.

 Beautiful Features

  1. JS good stuff includes: functions as first class objects, dynamic objects with prototypal inheritance, object literals and array literals.
  2. Features have a specification cost, a design cost and a development cost. There is a testing cost and a reliability cost. The more features there are the more likely one will develop problems or will interact badly with another.
  3. In software systems there is a storage cost which become negligible but in mobile is becoming significant again. (Ascending performance cost because Moor's Law doesn't apply to batteries). Features have documentation cost which increases training cost.

Awful Parts

  1. A global variable is a variable that is visible in every scope. Because global variables can be changed by any part of the program at any time they can complicate the behaviour of the program. Use of global variables degrades the reliability of the programs that use them.
  2. JS requires global variables. JS doesn't have a linker. All compilation units are loaded into a common global object.
  3. Always use var keyword before declaring a variable. It links the new variable with the global "this" if var is not present.
  4. Always out { after return since JS will try to add semi colon after return which can produce bugs. There is no warning, return will return undefined value.
  5. If you have a need to name properties or objects using reserved words use quotes or brackets {} like this object = {case: value}
  6. JS characters are 16-bit  wide. Today Unicode contains characters that can be 32-bit wide. JS considers them as two distinct characters.
  7. typeof null returns 'object'. A better check is my_value === null. null is falsy, all objects are truthy.
  8. typeof /a/ returns 'object' or maybe 'function', it should return 'regexp' but it doesn't.
  9. Always provide parseInt() with radix parameter. example: parseInt("08", 10); It stops when it sees nondigit so parseInt("16") and parseInt("16 tons") produce the same result 16.
  10. The plus (+) operator can concatenate and can add numbers. If you plan to add numbers make sure both operands are numbers.
  11. 0.1 + 0.2 is not equal to 0.3. This is a consequence to having adopted the IEEE Standard for binary  floating point arithmetic (IEEE 754). Fortunately integer arithmetic in floating point is exact, so decimal errors can be avoided by scaling.
  12. NaN is a special quantity defined by IEEE 754. It stands for Not a Number. If NaN is operand in arithmetic operation than NaN will be the result. NaN === NaN returns false while NaN !== NaN returns true.
  13. JS does not have real arrays. There is no need to give them a dimension and they never generate out of bound errors. But their performance can be considerably worse than real arrays. The typeof operator thinks that arrays are objects.
  14. The arguments array is not an array. It is an object with length property and it lacks the array specific methods.
  15. undefined and NaN are not constants. They are global variables and you can change their values. That should not be possible, yet it is. Don't do it. :D
  16. hasOwnProperty() of Object.prototype is a function and it can be replaced with different function or with value that is not a function. Don't do it :D

Bad Parts

  1. Don't use == and !=, use === and !== instead. == and != do a type coercion while === and !== do check the type of operands but don't do type coercion.
  2. "with" statement was intended to provide shorthand when accessing properties of an object. Its results can be unpredictable so avoid it.
  3. eval is evil, don't use it.
  4. Don't use continue
  5. Never leave a fall trough in switch statement.
  6. Avoid using ++ and --, use += and -= instead.
  7. JS is rarely used for bit manipulation. Bitwise operators are far from the hardware and their result is processed slower than in other languages.
  8. Avoid using "new Object" and "new Array", use {} and [] instead. Don't use "new Boolean", "new Number" and "new String"
  9. Avoid using "new" keyword. If you forget to create new object with "new" keyword, the new object will be bound to the global name-space, which is bad.
  10. Avoid using void keyword.

Friday, November 14, 2014

"JavaScript: The Good Parts" - book review

In this post I'll explain my thoughts on "JavaScript: The Good Parts" written by Douglas Crockford. It is fairly old book written in 2008 but still does the good job of teaching you what to use and what not to use from JavaScript. As the author says, this book has lot of information packed in about 150 pages, which means you have to read at least twice each chapter. Yes I passed each chapter twice and also spent some time writing the code from the book in Firefox/Firebug just to see how it goes. I think more examples to practice would be much better for the book as it lacks them. But in the end you would certainly need to read another book to learn how to code proper JavaScript modules, patterns, etc... I am planning to read another book because this one is not enough to get you going with JS. My recomendation for next book would be this one: "JavaScript Patterns" - by Stoyan Stefanov, it has about 240 pages which is enough.

The book is structured in 10 chapters and with 5 appendices, A-E. My suggestion is to read all chapters includding the appendices. Appendix D is just the railway diagrams, so you may skip it.
Chapters:
  1. Good Parts. This chapter contains basic info about JS and how to set up testing ground for other code examples in the book. Don't skip it. 
  2. Grammar. Contains basic information about reserved keywords in JS, data types, expressions, functions etc...
  3. Objects. Explain how to work with Objects in JavaScript, how to create new object, how to retrieve infrormation from object, object prototype, reflection, enumeration, delete operator, etc...
  4. Functions. Dives into JavaScript function basics. How to create new function, how to invoke a function, this and arguments objects of a function, its connection with objects. Each function is an object so you can add a function to its prototype. Function scope, closure, function modules, cascade (builder pattern), curry and memoization.
  5. Ineritance. Inheritance types, implementing standard OOP in JS (pseudoclassical) inheritance, prototypal and functional inheritance. Very important chapter, don't skip it.
  6. Arrays. Array basics, length property, useful array methods, delete operator, enumeration, etc...
  7. Regular Expressions. Dives into JS regular expressions, what are they and how to use them. Couple of basic rules how do RE work. Very useful thing, especially when processing strings. 
  8. Methods. This chapter explains implemented methods that come with JavaScript itself. You may want to skip this chapter but it would be helpful if you read it. 
  9. Style. This chapter explains some techniques how to write error prone JavaScrtipt code. My suggestion is to not skip this chapter. 
  10. Beautiful features. Read this chapter to learn what are the best parts of JavaScript that you should use. Functions as a first class object, Dynamic objects with prototypal inheritance and Object litrals and array literals.
  11. Appendix A. Awful Parts. Explains all of the worse parts in JS and how to avoid them.Global variables, scope, semicolon insertion, reserved words, unicode, typeof operator, parseInt function, + operator, floating point, NaN, phony arrays, falsy values, hasOwnProperty function and Object.
  12. Appendix B. Bad parts. Things you can live with but still should avoid. == vs === operators, with statement, eval function, continue statement, switch fall trough, block-less statements, ++ and -- operators vs += and -= operators, bitwise operators, function statement vs function expression, typed wrappers, new operator, void keyword.
  13. Appendix C. JSLint. An online tool build by Douglas himself. Use it whenever possible to debug your JS code. You may find this tool also useful, http://jsbeautifier.org/
  14. Appendix D. Syntax Diagrams. If you are beginner at programming, these railway diagrams will help you get going. 
  15. Appendix E. JSON. Explains what is JSON, JSON syntax, how to use it securely and a complete script of JSON parser in JavaScript.
 I think this book is not recommended for beginner programmers, but it is good if you are learning JavaScript. Still it lacks more code examples and practices, so you have to read another JS book. My opinion of this book is 4.5/5. It does the job for what is meant to do, aka teaching you pros and cons of JavaScript and how to use or avoid them. You must read this book if plan to code JS programs in future.

Tuesday, November 4, 2014

JavaScript notes - part 1

Hello. In this post I will share some notes I made while reading this book JavaScript: The Good Parts by Douglas Crockford. So it is nothing new or special, this post will serve simply to cover the most important properties of JavaScript. The notes are taken, copied or modified from the book itself. I didn't write them, Douglas did. :)

For part two visit this link: http://tunephp.blogspot.com/2014/11/javascript-notes-part-2.html
 

Good Parts

  1. I can be a better programmer by using only the good parts of a language and avoiding the bad parts.
  2. The API of the browser, Document Object Model (DOM) is quite awful and JavaScript is unfailry blamed.
  3. JavaScript is a language with enromous expressive  power. It is even better when you know what you are doing.
  4. Very good ideas on which JS is build upon are: functions, loose typing, dynamic objects, and an expressive object literal notation. Bad ideas include global variables.
  5. JavaScript has more in common with Lisp and Scheme than with Java. It is List in C - clothing.
  6. JS compilers are unable to detect type errors because JS is loosely typed.
  7. Objects can be created by listing their components (inspired by object literal notation mainly for the creation of the JSON format).
  8. JS has class free object system in which objects inherit properties directly from other objects (prototypal inheritance).
  9. Implementing classical design  patterns in JS can be frustrating but using prototypal inheritance can be rewarding.
  10. JS depends on global variables for linkage. All top level vars are tossed together in a common namespace called global object.

Grammar

  1. JS supports two types of comments, block comments made by /* .. */ charaters and line - ending comment made by two forward slashes // . Comments should be updated and should always describe accurately what the code does. Obsolete comments are worse than no comments.
  2.  Block comments should be avoided as it is unsafe to comment out a block of code. Use line ending comments instead.
  3. The list of reserved words should include theese: undefined, NaN and Infinity but unfortunately it doesn't have them. It is not permited to use reserved word as a name of a variable. Be careful with the three mentioned above.
  4. JS has a single number type. Internally it is represented as a 64 bit floating point number, same as Java's double number type.  There is no separate number type, 1 and 1.0 are the same thing.
  5. 1e2 = 100 = 1 * 10 ^ 2
  6. NaN is a number value produced as result of operation that cannot produce normal result. NaN is not equal to any value including itself. You can detect a NaN value with isNaN(value) function, or you can use isFinite(value) function which returns false if the value is +Infinity, -Infinity, or NaN (Not-a-Number), otherwise it returns true.
  7. Infinity represents all values greater than 1.7976931348623157E+10308
  8. Numbers have methods. JS has Math object that contain set of methods to work on numbers.
  9. A string literal can be wrapped  in single or in double quote. (\) backslash is the escape character. 
  10. All characters in JS are of 16 bit character set (JS was built when Unicode was 16 bit). There is not character type. Today Unicode has more than 65536 different characters represented by 32 bits. Be aware that JavaScript decodes them as two characters instead of single one.
  11. The \u convention allows specifying characters numerically. "A" === "\u0041";
  12. Strings have length property. A string is immutable constant. Once set a new value you cannot change it. However new strings can be made by concatenating two separate strings with + sign.
  13. Unlike many other languages blocks of code surrounded by curly braces {} do not create a new scope, so new variables should be defined at the top of the function, not in blocks.
  14. Falsy values in JS are: false, null, undefined, the empty string '', the number 0, the number NaN. All other values including true, the string 'false' and all objects are truthy.
  15. Use object.hasOwnProperty(variable) function to determine whether the property name is truly a member of the object or was found instead on the prototype chain.
  16. The = operator is used for assignment. Do not confuse it with equality operator ===.

Objects

  1. The simple types of JS include numbers, strings, booleans, null and undefined. All other values are objects.
  2. Numbers, strings and booleans are object like and they have methods but they are immutable.
  3. Objects in JS are mutable nested collections of properties. In JavaScript arrays are objects, functions are objects, regular expressions are objects and of course objects are objects.
  4. Objects in JS are class free. Objects can contain objects.
  5. JS includes prototype linkage, which allows object to inherit properties from another objects. When properly used prototype linkage can reduce object initialization time and memory consumption.
  6. The quotes around a property's name in an object literal are optional if the name would be legal and not a reserved word. Quotes around "first-name" are required but optional around first-name.
  7. If a string expression is a constant and a legal JS name and not a reserved word than the dot ( . ) notation can be used instead.
  8. Attempting to retrieve undefined values from object will throw a TypeError exception.
  9. If there is already a property with given name in an object, new value will just replace the old value. If the propery does't exist the object is augmented with new property. 
  10. Objects are passed around by reference, they are never copied.
  11. Every object is linked to a prototype object from which it can inherit properties. All objects created from object literal are linked to Object.prototype.
  12. The hasOwnProperty() method does not look at the prototype chain of an object.
  13. The "for in" statement can loop over all of the property names in an object. It will include functions and prototype properties as well. The order of the properties/functions listed using "for in" is not necessarily incremental. If the order is important use "for" statement instead. "for" does not cover the prototype properties.
  14. delete operator can be used to remove a property from an object. It will not touch any of the objects in the prototype linkage. So removing a property from object may uncover a property from the prototype object with the same name.
  15. Avoid using global variables. Better create your own application namespace by creating your own global variable in which all your application structure will reside so that it will not interfere with objects/properties from other applications in the global namespace. 

Functions

  1. Functions are the best part in JavaScript. They are commonly used for code reuse, information hiding and composition. Functions in JS are objects linked with Function.prototype which is linked to Object.prototype
  2. Functions can be stored in variables, objects, arrays. Functions can be passed as arguments to function and functions can be returned from functions. Also since functions are objects they can have methods too. Unlike other objects in JS, functions can be invoked.
  3. Function literal has 4 parts. The first is the word "function". The second optional is the name of a function (used by debbugers to identify a function). Function without a name is called anonymous function. The third part is a set of parameters wrapped in braces (). The fourth part is a set of statements wrapped in curly braces {} (The body of a function).
  4. In addtion to the list of parameters in braces (), each function gets two additional params: this and arguments
  5. There are four patterns of invoaction in JS: method invocation, function invocation, constructor invocation and apply invocation (the patterns differ in how the bonus parameter "this" is initialized).
  6. There is no runtime error when the number of arguments and the number of parameters do not match. If there are too many argument values, the extra args are ignored. If there are too few arguments, the missing ones will be substituted with undefined. There is no type checking on the argument values, any type of value can be passed to any parameter.
  7. When a function is invoked with function invocation pattern, it is bound to the global object. If the language would have been designed correctly, the function would be bound to "this" of the outer function. A consequence of this error is that a method cannot employ an inner function to help it do its work because the inner function does not share the method's access to the object as its "this" is bound to the wrong value.
  8. If a function is invoked with the new prefix, then a new object will be created with a hidden link to the value of the function's prototype member and "this" will be bound to that new object.
  9. Functions that are intended to be used with the new prefix are called contrustors. By convention they are kept in variables with a capitalized name. If a contructor is called without the new prefix very bad things can happen without a compile time or runtime warning, so the capitalization convention is really important. The best way to cope with this is to not use new prefix at all.
  10. arugments array gives the function all the arguments that were supplied with the invocation, including excess arguments that were not assigned to parameters.
  11. Because of design error, arguments is not really an array. It is an array-like object. It has the length property but it lacks array methods.
  12. A function always returns a value. If the return value is not specified then undefined is returned.
  13. If the function was invoked with the new prefix and the return value is not an object then "this" (the new object) is returned instead.
  14. A try statement has a single catch block that will catch all exceptions. If your handling depends on the type of the exception, then the exception handler will have to inspect the name to determine the type of the exception.
  15. Unfotunatelly JS does not currently provide tail recursion optimization.
  16. JavaScript doesn't have a block scope but it has function scope. That means all variables should be declared as soon as possible or at the top of the function body.
  17. The good thing about scope is that inner functions get access to the parameters and variables of the functions they are defined within (exception are "this" and arguments object). This is called Closure.
  18. A module is a function or object that represents an interface but that hides its state and implementation.
  19. By using functions to produce modules, we can completely eliminate our use of global variables thereby mitigating one of the worst JS features.
  20. Use of module pattern can eliminate the use of global variables.
  21. JavaScript does not have a Curry method.
  22. Function can use objects to remember the results of previous operations making it possible to avoid unnecessary work. This optimization is called memoization.
  23. By devising functions that produce other functions, we can significantly reduce the amout of work we have to do. 

Sunday, September 14, 2014

SQLite 3.7.9 notes

In this post I will share my thoughts about SQLite database engine. You can search the net for tutorials and info and it seems lot of sites copy most of the documentation from the original site, so therefore in this post there will be my experiences with it.
  • You cannot output create statements with ".schema" command on attached database. It is only possible on the main and temp databases. So therefore you have to exit sqlite prompt and then enter it again using a line: "sqlite3 your-db-name.db" so that your database is now the main database.
  • You cannot use ALTER sql command to change a column in a table. It is only possible to rename a table and to add new column to an existing table. DROP COLUMN and ADD CONSTRAINT sql commands are also not supported.
  • RIGHT OUTER JOIN and FULL OUTER JOIN are not supported. Only LEFT OUTER JOIN is implemented.
  • SQLite database is CASE SENSITIVE. For example GLOB and glob have different meaning in SQLite statements.
  • The data type of a value is associated with the value itself, not with its container. Each value stored in SQlite database has its "Storage class": NULL, INTEGER, REAL, TEXT, BLOB.
  • SQLite, technically, has no data types, there are storage classes in a manifest typing system. Everything, internally, is stored as text. 
  • SQLite supports the concept of type affinity on columns. Type affinities: TEXT, NUMERIC, INTEGER, REAL, NONE.
  • Comments can be added with double hyphen "--" in front of a line of text or using C-like comment blocks with /* some text here */
  • Dot commands should not be terminated with semicolon (;)
  • Autoincrement keyword can be applied to a column only if that column is of type INTEGER
  • Any column in an SQLite version 3 database, except an INTEGER PRIMARY KEY column, may be used to store a value of any storage class.
  • SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).
  • The type affinity of a column is the recommended type for data stored in that column. The important idea here is that the type is recommended, not required.
  • Sorting of data types is achieved like this: (NULL < NULL or NULL < any other type),  (INTEGER or REAL) < (TEXT or BLOB), (between INTEGER and REAL types a numerical comparison is used), (TEXT < BLOB), (between TEXT values a collating sequence is used),  between two BLOBs a memcmp() function is used
  • Use this SQL construct to insert multiple rows into a table in one go: INSERT INTO 'tablename' ('column1', 'column2') SELECT 'data1' AS 'column1', 'data2' AS 'column2' UNION SELECT 'data3', 'data4' UNION SELECT 'data5', 'data6' UNION SELECT 'data7', 'data8';
  • Use ".header on", ".mode column" and ".width" dot commands to refine the output of the queries.
  • Use this command: select sql from sqlite_master where type='table' and tbl_name='table_name'; to select schema of the specified table. Much like ".schema" command shows create statements for the whole database, this shows only give table.
  • sqlite_master table contains 5 columns named in order: type, name, tbl_name, rootpage and sql
  • GLOB is a logical operator used to compare value to similar values using wild card operators. Also it is case sensitive unlike the LIKE comparison operator. GLOB uses "?" for one character and "*" from many, while LIKE uses "_" and "%" wild-cards correspondingly.
  • || operator adds two different strings and make new one aka concatenate.
  • Bitwise binary operators are: & (AND), | (OR), ~ (complement), << (left shift) and >> (right shift)
  • Values NULL, 0.0, 0, 'english' and '0' are all considered to be false. Values 1, 1.0, 0.1, -0.1 and '1english' are considered to be true. 
  • The IS and IS NOT operators work like = and != except when one or both of the operands are NULL.  
  • To use a string in a query you should use single quotes as the SQL standard specifies. Check image 4, using text="text" is identical to saying select * from proba where text=text; which is always true, so all rows will be returned. 
  • To escape a single quote in a string use another single quote, like this insert into table_name (my_string) values ('it is nine o''clock');
  • In the docs I couldn't find nor using .help command told me how to see current sqlite version. I however tried command .version which worked. Check image 5.
sqlite_master table
1. sqlite_master table contents after some sql coding. Mode is column and header is on

deleting column from existing table with temporary table in sqlite
2. Deleting a column from existing table using sqlite transation and temporary table to save the data
sqlite round function
3. I tried round(X,Y) function with value 9.95 and without Y parameter it gave correct result

sqlite - double vs single quote
4. To use a string in a query you should use single quotes as the SQL standard specifies
sqlite .version command
5. Use .version dot command to check current sqlite version