# Nairaland Forum

Welcome, Guest: Join Nairaland / Login / Trending / Recent / New
Stats: 1060342 members, 1229474 topics. Date: Saturday, 18 May 2013 at 10:10 AM

(0) (1) (of 2 pages)

 Programming / Re: Storing K largest numbers from a stream by kadeerna: 11:24am On Nov 11, 2012 ekt_bear: What is "length of value?"Like, what is the length of the value of say the number 50?Length here, is the number of characters in the value when converted to a string.->>>> ((string)12232111).LengthLength of 50 = 2 Programming / Re: Storing K largest numbers from a stream by kadeerna: 11:26am On Nov 10, 2012 In keeping track of the highest K values from a list of N values,- Start at value 1 and store the length of the value converted to a string.- On every other value in the list, check the length stored from 1 above against the length of the current value (converted to a string).- If the length of the current value is greater than the value from 1, update the variable with the current longest found length and save the value to longest[0].- Continue the same check through other values in the list- Where you find the length of the current value is equal to longest length variable, either do a greater than, less than or equality comparison. Another option might be to check the individual digits ex. longestValue = 122323213254354664323, longestValueLength = 20current(list) = 1290344355465742345, current(list).length = 20currentLonger = falsewhile i < 19 or currentLonger == false currentLonger = (longestValue[0] == current(list)[0]) <-- cross check condition.longestValue = (currentLonger) ? current(list) : longestValue;Expanding this to store the last K values will simply modifying the above to use arrays or K instead.This way, you don't store at least 2 data structures of N size. Programming / Re: Storing K largest numbers from a stream by kadeerna: 1:21pm On Nov 09, 2012 Maybe I don't completely understand what you guys are doing here, but exactly why are you sorting and comparing such a large stream of numbers using less than ( < ) and greater than ( > ) comparators?Have you thought of keeping a moving track of the ex. lengths of each entry instead? Programming / Re: File Copy Monitoring Using Vb.net - Pls Help by kadeerna: 9:50pm On Jul 29, 2012 The following code is for a console application that watches a specified folder e.g "C:\Test", or even "C:\" for creation of new files and writing the info to the Console. Run the application, type 'f' and hit enter at the "Enter a command (f, x)" prompt. Entering 'x' closes the application. Select a folder using the dialog that appears and click OK. The selected folder is echoed to the Console window. Copy and paste a file into the folder selected from the dialog and the pasted file name is written to the Console. Converting this to the a windows form application and/or logging the copy operation to a file or db is a trivial process. Using the FileSystemWatcher has its limitations. For one, tiny file copy operations notifications could quickly fill up the FileSystemWatcher buffer causing notifications to be lost. Read on StackOverflow and around on the web on increasing the buffer size and other effective methods of watching the file system for ex. coding a file system filter driver.`Imports System.Windows.FormsImports System.IOImports System.Security.PermissionsModule Module1 Private _folderToWatch As String Sub Main() Dim command As Char Dim exitCase As Boolean = False While (True And Not exitCase) Console.WriteLine("Enter a command (f, x)" command = Console.ReadLine() Select Case command Case "f" SelectFolder() Console.WriteLine("Watching: " & _folderToWatch) Dim watcher As New FileSystemWatcher() watcher.Path = _folderToWatch watcher.IncludeSubdirectories = True watcher.NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName Or NotifyFilters.CreationTime) AddHandler watcher.Created, AddressOf OnCreated watcher.EnableRaisingEvents = True Case "x" exitCase = True End Select End While End Sub Private Sub OnCreated(ByVal sender As Object, ByVal e As FileSystemEventArgs) Console.WriteLine("File: " & e.FullPath & " " & e.ChangeType) End Sub Public Sub SelectFolder() Dim dialog As New FolderBrowserDialog() With dialog .RootFolder = Environment.SpecialFolder.Desktop .SelectedPath = "C:\" .Description = "Select the directory to watch" If .ShowDialog = DialogResult.OK Then _folderToWatch = .SelectedPath End If End With End SubEnd Module` Programming / Deferred / Promise Explained (javascript) by kadeerna: 1:11am On Jul 22, 2012 jQuery 1.5 saw a rewrite of \$.ajax introducing Promises (sometimes called Deferreds) providing amongst other benefits, a cleaner way of managing callbacks on success/failure. Prior to the rewrite, the implementation of \$.ajax made scenarios like the following a mess. Making multiple AJAX requests in which the parameters of a request depended on the sucess and return value of the request before (nested callbacks). There was not a simple way to pass multiple callbacks to be called on success or failure of the request. Hacks like creating an array of functions to be called, creating a function that called the functions in the array, checking return values, and other operations made application code unclean and unmanageable polluting biz logic and bloating LOC unecessarily. Lets see some code to handle multiple callbacks on success or error of a request.Example:` var CallbackManager = function() { return { callbackList: [], callCallbacks: function(data) { for (var i = 0; i < this.callbackList.length; i++) { if (typeof this.callbackList[i] == "function" { // check for uniqueness using a === if this was a unique callback list this.callbackList[i](data); } } }, addCallback: function(func) { this.callbackList.push(func); // to make chainable return this; } } } successCallbacksManager = new CallbackManager() successCallbacksManager .addCallback(function() { console.log("Callback 1: Call me first" }) .addCallback(function() { console.log("Callback 2: Call me next" }); errorCallbacksManager = new CallbackManager() errorCallbacksManager .addCallback(function() { console.error("Callback 1: An error occured" }) \$.ajax ({ url: "example.com/createanexample", data: { param1: "kadeerna" } }, successCallbacksManager.callCallbacks, errorCallbacksManager.callCallbacks)`Developers saw a common pattern in recurring uses of methods like the above and factored out a proposal called the Promises/A proposal. The dojo library V0.9 was one of the first libraries to ship with a Promise/A implementation. The reasons I gave above are only some of the higher level reasons for factoring a common spec. Several lower level reasons exist. Check out the web for more on the Promise/A.In the example listing above, all callbacks for error and success had to be registered before initiating the AJAX request. The promise pattern allowed code to be written to say perform this/these set of operations (asynchronously), and call on me when you where done. The called code said, aight, take this promise from me that I would do just that. The promise pattern takes the concept further to say, if you ask me call more callbacks later, way way later after I have done and completed (or failed) the async operation, I will call the newly registered callbacks too. Tweaks can be made to call all registered callbacks all again when a new callback is added to the list, or just as described call only the newly registered callback. It is that promise that makes the following code possible using jquery > v1.5.(What is the world turning into eh? Computers can drive, think, speak, and now promise? Well, fear not. The kill switch is not far.)` var xhr = \$.ajax({ url: "example.com/createanexample", data: { param1: "kadeerna" } }); xhr.done(function() { console.log("Callback 1: Call me first" }) .done(function() { console.log("Callback 2: Call me next" }); xhr.error(function() { console.error("Callback 1: An error occured" }) // add a callback 5 seconds later even when this AJAX request might been done and returned setTimeout(function() { xhr.done(function() { console.log("Callback 3: Call me last" }) });`So this doesn't seem too juju'ish, lemme explain in code a bit of what happens inside of \$.ajax. When \$.ajax is called, it returns an xhr object that implements the Promise API. Actually, let's forget about the XHR API for now, and focus on the promise API. The promise API and object might look like the following.` var Promise = function() { return { // bad design, only for simplicity resolved: false, data: null, callbackManager: new CallbackManager(), resolve: function(data) { this.data = data; this.callbackManager.callCallbacks(data); this.resolved = true; }, done: function(callback) { this.callbackManager.addCallback(callback); if (!this.resolved) { return; } else { callback(this.data) } } } } var \$.ajax = function(options) { // no checking done here var url = options.url; var data = options.data; var promise = new Promise(); xhr = ... // create XMLHttpRequest object, // pass options, xhr.onload = function() { if (this.status == 200) { // parse the result data = JSON.parse(this.responseText); promise.resolve(data); } } xhr.send(); // this call is immediate return promise; }`If the above listing seemed complicated, imagine that was the following` var APromise = function() { var promise = new Promise(); // assume this is the async op. this one takes 5 seconds to complete setTimeout(function() { promise.resolve() }, 5000) // this runs immediately, even before the above LOC console.log("This is proof." return promise; }; var ap = new APromise(); ap.done(function() { console.log("Promises" }); // add another call back 8 seconds later setTimeout(function() { ap.done(function() { console.log("Promises" }); }, 8000);`A promise object holds a list of callbacks to be called. When the operation that returns that promise resolves (completes or fails), it asks the promise to fulfill itself by calling the Promise.resolve() function. Promise.resolve goes on ahead and calls all registered callbacks registered through the Promise.done(function).The various Promise pattern implementations improve upon the described method to provide powerful callback mechanisms that allow biz logic to be focused upon. An example is \$.when + \$.then in jQuery which allows you combine multiple deferred objects and wait for all of the to resolve before calling a callback.` // ... var ajaxToDebitAccount = \$.ajax ... var ajaxToCreditAccount = \$.ajax ... \$.when(ajaxToDebitAccount, ajaxToCreditAccount).then(function(statusDebit, statusCredit) { if (statusDebit.success && statusCredit.success) { console.log("Transfer successfull." } }); // ...`I hope I have been able to explain the concept of Promise / Deferred and you have a better understanding of why you or jQuery makes you use it in your code. Programming / Re: Problem with PATH on Windows 7(python) by kadeerna: 1:16pm On Jul 10, 2012 Windows Logo Key + R to open the run command/application dialog.Paste "rundll32 sysdm.cpl,EditEnvironmentVariables" to open the Environment Variables editor dialog.Find "Path" in the System Variables list (Double click to edit).Scroll to the end of the Variable Value field and add a ";" followed by the directory path to where the Python interpreter executable is installed on your computer ex. "C:\Python32" i.e add ";C:\Python32" to the end of the field.Click Ok.Click Ok.Restart all open command prompt windows to use new variables. Programming / Re: Need Help With Some Php Scripts by kadeerna: 10:03am On Jul 07, 2012 Hi, with versions of php_gd2, you have to append a ".ttf" to the font name passed to the imagettftext function.(http://php.net/manual/en/function.imagettftext.php) So your code becomes:` ... imagettftext ( \$img , 40 , 0 , 600 , 200 , 0 , "tarzeau_-_OCR-A.ttf", \$_POST['name'] ); imagettftext ( \$img , 40 , 0 , 600 , 275 , 0 , "tarzeau_-_OCR-A.ttf", \$_POST['auth'] ); imagettftext ( \$img , 40 , 0 , 600 , 355 , 0 , "tarzeau_-_OCR-A.ttf", \$_POST['home'] ); imagettftext ( \$img , 40 , 0 , 600 , 435 , 0 , "tarzeau_-_OCR-A.ttf", \$_POST['born'] ); imagettftext ( \$img , 40 , 0 , 600 , 510 , 0 , "tarzeau_-_OCR-A.ttf", \$_POST['hair'] ); imagettftext ( \$img , 40 , 0 , 600 , 590 , 0 , "tarzeau_-_OCR-A.tff", \$_POST['eyes'] ); ...`Also, the font file "tarzeau_-_OCR-A" has to be in the same directory from the one this script is run from.Needless to add, you can remove the font file to a variable.` \$font = "tarzeau_-_OCR-A.ttf" ... imagettftext ( \$img , 40 , 0 , 600 , 590 , 0 , \$font, \$_POST['eyes'] ); ...` Programming / Re: NL Programming Board Is Near Dead by kadeerna: 12:27am On Jun 16, 2012 Thank goodness there are other members who share similar feelings. @Seun, your suggestions are taken, but can only be fully applied where there are a number of top quality and well asked questions, request for comments, or shared experiences. Well, on the lookout for good questions. Programming / NL Programming Board Is Near Dead by kadeerna: 5:40pm On Jun 15, 2012 I am (used to be) a frequent visitor to this board. It is the only the board I visit on NL.But I can state now the following:THIS BOARD IS DRY, COMATOSE AND NEAR DEAD.I expect a programming board of a forum with near 1M members in "Nigeria" to MOSTLY discuss programming issues, problems (real) and solutions, not argue about differences between web hosts, offer advice about project topics or what course to study at the university.I understand that this is not Quora or StackOverflow, but why can't it be near? Are the brains not here? Or do the brains not exist?Before trollers attempt to wash the prerogative of this topic, think about it this way. This topic na ginger for the members of this board. Begin to create interesting stuff to talk about. If you think there is enough topic to discuss here then, this topic is not for you.What could we talk about or do?- Crazy use cases for tools you use.- New stuff out there you are finding help from in your development life and how you are using them with issue encountered.- Bootstrap the community knowledge with stuff you know and being open to learn.Stuff I hate seeing here,- When will Google buy facebook?Go yarn about that one on Techcrunch, Mashable, ...- What is language X, what are its uses? Seriously!? Try this http://lmgtfy.com or http://googleitfor.meKhalas. Programming / Re: Capture Image From Webcam And Store In Mysql Database From C Sharp Winform by kadeerna: 3:22pm On Jun 08, 2012 You did not mention what OS version the program will (be) run on. Programming / Coffeescript by kadeerna: 2:59pm On Jun 06, 2012 Languages that follow the C (C++) influenced syntaxes have been becoming more and more of a pain to write in, thanks to the rapid introduction and uptake of languages with easier semantics to understand, and easier to write on the fingers. The Javascript langugage used in billions of web pages today derives many of its constructs from C. In other words, it is a pain to write today. ` function() { var string = "Hello, World!"; alert(string); };`What is wrong with the above block, a lot!. - function <- what is that? It won't kadeerna, it won't be anything else.- { ... } <- OK?- ; <- Don't even get me started on this one. Follow the brouhaha over a single missing | left out in the comments on Github for the Bootstrap css library project- alert(...) <- (.)_(.)- var <- Resharper (in VS), and Webstorm don't gimme a break on this oneCompare the above written block to its equivalent in CoffeeScript.` () -> string = "Hello, World" alert string ` Does that look sexy or what?Coffeescript is a language (extension to javascript) for that brings Ruby styled constructs and ease of coding to the language we all love, Javascript. The language which drops a lot of the syntactical noise of Javascript compiles down to easy to read, compiled, and optimized Javascript which is read,and executed by the browser in client side usage or a Javascript engine like V8 in server-side usages like NodeJS environments.You cant try it out in you browser here: http://coffeescript.orgNoise like function keywords, parentheses, braces, semi-colons, var are eliminated allowing the developer code their application logic in sweet memories of last nights .... and not of tracking down a missing ;. In the speak of the languages' creators, "CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way."Quite a lot of Ruby style constructs have been imported to almost seamlessly supplement the Javascript language in a new way.For example,` teen = true if age < 16 && age > 12 # inversing assignments and declarations to make it better readeable # creating an object object = prop1: 1 prop1: 2 func_prop: () -> 3 greet = (name) -> alert 'Hello, ' + name # initialising a list and calling a function on its members greet name for name in ['kadeerna', 'seun'] _alert = (number) -> alert number # who doesn't need this, a countdown timer. BLAST OFF! _alert number for number in [3..1] # range [Top...Bottom] # some further advance looping and comprehension people = [{ name: 'kadeerna', gender: 'm' }, { name: 'finegeh', gender: 'f' }] _alert = (name, gender) -> salutation = if gender == 'm' then 'Mr' else 'Miss' alert "#{salutation} #{name}." _alert name, gender for {name, gender} in people # destructuring assignment [nairaland, twitter, facebook] = ["kadeerna", "abdulkadirna", "abdulkadir.abdulkadir"] # destructuring of nested assignment structure = [ { name: "kadeerna", posts: [ "NHibernate Brief", "Buidling Large Scale Apps with Backbone.js" ] } { name: "seun", posts: [ "Following Page And Less Annoying Notifications", "New Content Counters And Trending Topics Cleanup" ] } { name: "pc_guru", posts: [ "Dell Laptop For Sale", "Interswitch Api Pdf" ] } ] records = [name, posts:[]] = structure console.log records # object orientation as right as possible class Person constructor@name) -> addressSelf) => alert "Nothing O." class Manager extends Person addressSelf) => alert "I am #{@name}, a Manager." class Teller extends Person addressSelf) => alert "I am #{@name}, a Teller." manager = new Manager "seun" manager.addressSelf() teller = new Teller "kadeerna" teller.addressSelf()` Ok, thats plenty for 1 post me thinks. You should get the gist by now. CoffeeScript is simply amazing. It is indentation based too using whitespace to delimit blocks of code. It had reduced LOCs of our projects by as much as 1/3 in one instance. It is readable, easy on the eye, easy to hack, strongly in development. I left out a lot of really time saving features of the language. Programming / Nhibernate Brief by kadeerna: 12:18am On Jun 06, 2012 I thought I'd force myself to word a few on NHibernate this evening. NHibernate is a set of tools for mapping objects to persistent storage. It is implementation of an Object Relational Mapper (ORM) and a .NET port of the popular Hibernate ORM for Java platform (Java, ColdFusion, ....).It is a data mapper styled ORM as opposed to it's other competing and actively used mapping pattern called Active Record. Martin Folwer describes the Data Mapper pattern as "A layer of Mappers (473) that moves data between objects and a database while keeping them independent of each other and the mapper itself." Like arguments exist for use one design pattern over another, a few sides exist each pitching arguments on the best way to map an object (OOP paradigm is mainly where ORMs apply) to a persistent re-readable storage. I am writing about NHibernate, so that tells what side I am on.I am careful not to use the phrase ORMs map objects to databases only, hence the use of storage. Others might add ORMs can map from objects of 1 structure in memory to another structure in memory for examle DataMapper for .NET, but I still refer to that as storage.Read more on ORMs for more theory. NHibernate is a port on Hibernate that brings the advanced mapping and powerful capabilities to .NET. I am going to outline some of the features it has brought with it to the advantage me and my team's advantage. Some of these features I briefly describe are what we use in our day-to-day development.HQL (Hibernate Query Language), is an object query language similar to SQL but exposes (not the best word) the store as a virtual object database and provides query constructs to help developers maintain that thought. HQL is translated to SQL using a parser, lexer and compiler in the case that a database is being queried (which today is the most used back end case). Because HQL is a well defined language, its commands can be traslated to query other backends like MongoDB, CouchDB as done in Doctrine a php port of Hibernate. HQL understands complex data types in queries and can alsoreturn complex datatypes from query results while keeping the object orientedy relational constructs bolted on top. From an application design point of view, it stops the abstraction from seeping through I am talking about the flatness of relational structures.HQL allow queries to return complex types (lists, maps, ) as results or nested properties of result "objects".Complex projections are also another powerful concept HQL allow for developers. Instead of querying for a set of records and return flat schemaless results or try to parse the result into object domain, projections allow query results to be mapped into a complicated objects that closelyrepresent the domain model you are querying and persisting.An example:To return the list of orders for all customers in 1 "query" is impossible. Options include get all customers and loop through the result getting each order, or perform some sql jutsus like concat the orders in the query and de-concat into an array.In for ex. python:` select c.id, c.name, cast(group_concat(o.quantity) as char) from customer c join `order` o ON c.Id = o.customerID group by c.id ; list=[] for customer_orders in result: customer_order = collections.namedtuple("CustomerOrders", ["customer", "orders"]) customer_order._make(result[0], result[1].split(',')) list.append(customer_order) `the equivalent in HQL = ` from Customer as customer ` (.)_(.) Yeah.Polymorphic queriesThis may be a silly schema, but variations of this type of schema exist in real world apps. My team use such variations.` User Manager Teller Auditor ------ --------- ---------- ----------- firstname branch_id station_id zone_id lastname` HQL query: "From User u" returns all users of type Manager, Teller and Auditor HQL query: "From Manager m" returns users only of type Manager (This sort of functionality requires a prior mapping where inheritance is setup)Queries allowing versatile where clauses to reference any nested property within the queried object` from Customer c where c.orders[0].itemNumber == 3` This post does not completely mention many of the other really cool, useful and timesaving features of NHibernate we use like:- Object proxying (quasi AOP)- Lazy loading- Criteria queries- LINQ integration- Schema Generation- ....Tacked upon- Loquacious- FluentNHibernate Phones / Re: Google Buys Meebo by kadeerna: 12:08pm On Jun 05, 2012 Seun: No offence intended, but this is nonsense. Google is as "democratic" as Facebook. In fact, it's more democratic because it allows you to get information from the best source regardless of whether the source is somehow "related" to you or not. Using the social graph for search is foolishness. When I want information about something important, I want the best information in the world. I don't want the best information in my circle of friends; if I did, I would just ask them directly. My friends are not experts on every topic, and even where they are experts, there are people out there who know better than them. Google helps me to find the best sources of info.@seunBut judging by recent moves at integration G+ into Search, and mightily cross licensing all Google products mean they understand the Facebook vision of going to your circle of friends first for results and then the rest of the world for everything else. Your friends may not be experts on every topic, but the trust element in social is embedded in the very fabric of mankind that any technology which relegates it to the background will simply loose to automated non-social technologies.Lets not forget how much Google would kill to put a +1 on any and anything. 1 Like Programming / Re: Building Large Scale Apps With Backbone.js by kadeerna: 8:08pm On Jun 04, 2012 I wouldn't consider this an exhaustive list but they should be enough to bootstrap your knowledge.http://net.tutsplus.com/tutorials/javascript-ajax/getting-started-with-backbone-js/http://arturadib.com/hello-backbonejs/http://oneofthesedaysblog.com/backbone-js/http://liquidmedia.ca/blog/2011/01/backbone-js-part-1/ Programming / Re: Building Large Scale Apps With Backbone.js by kadeerna: 7:39pm On Jun 04, 2012 One of the advantages of developing with (or on, depending on how you use/see it) Backbone is the advanced use cases it allows us to support in our work while still being able to stay out of the way for the most part.The library is a tiny. Its source can be understood by an intermediate JS programmer. Its built to be easily extensible, _.extend(Backbone.Model.prototype, { newFunction: function() { // do something } })Objects extend one of Model, View, Collection or Router (not controller, and yes, not shown in the previous code) which are defined roles for not just Backbone supported applications but existing well used and understood development philosophies (MVC).Change tracking which is just plain hard or almost impossible with plain javascript objects come for free with very little overhead. Tacking on uni- or bi- directional binding between model and view, client side model and server side representation, or any combination of the library's basic components is easy.Underscore its only dependency is a real a utility belt. "It's the tie to go along with jQuery's tux, and Backbone.js's suspenders."For example in this really cool feature, we implemented a kinda remote assistance system that synchronizes view elements over any number of connected authorized clients. Administrators, support staff can "type" into a remote user's screen of our application, and the changes made to the user screen from his/her browser window are streamed back to the assistance givers. Such a feature could have been built with jQuery but building a manageable, scalable and extensible solution would have simply sent one of us over the brink. This was achievable thanks to Backbone's change tracking and notifications.Another place where 2 weeks was reduced down to 4 days was in implementing an unintrusive undo/redo system for an application we are working on. We had requirements to enable users view and undo operations on entities managed by our application. Thank you Backbone.Our team loves dynamism everywhere. But make it better, give us controlled dynamism. Backbone gives us that control to implement really varying but share the same simple underlying library. Another technology that gives us such control and dynamism at superb levels is the C# language on the .NET platform but that is a topic for another topic (tautology ).Until pc_guru formally decamps to the Backbone camp, he is currently sitting on the fence with his statement " I really find Backbone.js impressive ", lets share use cases where Backbone has been really helpful in helping you and your team deliver interesting solutions.pc_guru mentioned knockoutJS. We treat HTML and JS as Zerksis and Leonidas. They can't get tangled in one another's affairs cos when they do, blood is shed. Applications get ugly and messy real quick with combos like HTML and JS using frameworks like Knockout, angular...This reply isn't meant to fuel any flame wars, but to describe 1 framework fulfills our requirements well for us.I intended pasting code on how we achieved the streaming model above, but later decided against. There seems to be little JS activity not enough to spend 30 minutes formatting code. Programming / Building Large Scale Apps With Backbone.js by kadeerna: 10:46pm On Jun 03, 2012 Of late, my team and I have been building larger scale browser based apps. With the (at its introduction) ground breaking ideas brought to the fore in Gmail & Google Maps' (and others) use of technologies priorly hidden in browsers like XMLHttpRequest, hidden frames, asynchronous loading of content into iframes coupled with John Resig's work on jQuery, and its almost immediate embracement and wide spread use off (over 55% of the 10,000 most visited websites), browser based apps have been taking off with improvements in browser technology and the general nature of interconnected-ness on systems.Further advantages include a platform independent markup, presentation, and scripting (HTML, CSS, JS) technology have further made browser based apps an attraction. Going are those days where registry issues, dll hell, missing or outdated runtimes were some of the reasons for delays and late deployments. Browsers give my team and many developers around the world independence and conformity (lets not go there) of technologies to solve user problems (the real reason why we introduce these tools in the first place).These apps my team and I are building are nontrivial apps (in our sense). They've gone by a few different names on the blogosphere most popularly Single Page Apps (SPA). These kinds of applications perform a wide range of functionality at fewer server accessible URIs. My team's library of choice are jQuery for DOM manipulation, Backbone for providing structure and persistence, and Coffeescript for improving javascripts language semantics.Backbone brings structure in applications where LOCs go over a few hundreds or functionality is less than trivial where developers have tried to structure code with jQuery abusing the libraries' original idea of simplifying "simplify the client-side scripting of HTML","document traversing, event handling, animating, and Ajax interactions for rapid web development".This topic's aim isn't to try to get you to look at backbone or similar frameworks, learn it and try to shoehorn it into implement God forbids, a form validation function in your app. It is for developers to look out to the landscape and embrace new development tools that promote existing and well researched, used, and documented philosophies (my speak) from older areas of development like desktop application development. 1 of such is MV* (Model View Variations coined I think by Addy Osmani).I won't delve into the meaning or MV*. Please read the well written articles up on the web about client side MV*.A scenario where backbone applies is an app that manages stuff (best word I could come up with) about stuff (think properties about objects).For example in designing an app to manage hotel reservation and bookings + plus integrated electronic card based room access system control, we used backbone to develop a single page application which houses all functionality in 1 non-realoaded browser accessible url at ex. http://our-hotel-suc.ks/appWe describe entities managed by the application as Models. Eg. (in javascript. we use coffee script to eliminate some in our thinking, unnecessary semantics).`var GuestInformation = Backbone.Model.extend({ defaults: { name: "", phoneNumber: "", // other properties }});var StayInformation = Backbone.Model.extend({ defaults: { checkInDate: Helper.Now() }});var Room = Backbone.Model.extend({ defaults: { number: "", clean: false, occupied: false } checkIn: function(guest) { this.set("occupied" = true; this.set("guest" = guest; }})After describing individual entities, we describe collections of entities ex.var Rooms = Backbone.Collection.extend({ model: Room, cleanRooms: function() { return this.filter(function(room) { return room.get("clean" == true; }); } availableRooms: function() { return this.filter(function(room) { return room.get("occupied" == false; }); } occupiedRooms: function() { return this.filter(function() { return room.get("occupied" == true }); }});Lastly a number of views present the information stored in the models and collectionsin host of ways. Ex. simple, detailedvar SimpleRoomView = Backbone.View.extend({ initialize: function(room) { this.model = room } render: function() { var template = "
" + "" + this.model.get("number" + "" + "" "
"; this.\$el.html(template); return this; }});var DetailRoomView = Backbone.View.extend({ initialize: function(room) { this.model = room } render: function() { var template = "
" + "" + this.model.get("number" + "" + "" // some more detail, like the // check-in date, // expected check-out date "
"; this.\$el.html(template); return this; }});var SimpleRoomViewForHouseKeeping = Backbone.View.extend({ initialize: function(room) { this.model = room } render: function() { var template = "
" + "" + this.model.get("number" + "" + "" "" "
"; this.\$el.html(template); return this; }});var SimpleRoomListView = Backbone.View.extend({ initialize: function(rooms) { this.collection = rooms; this.collection.on("add", this.add) } add: function(room) { this.el("el".append( new SimpleRoomView(room) ) } render: function() { var template = "
" + "
• " + this.collection.reduce(function(memo, room) { return memo + (new SimpleRoomView(room)).render().\$el.html() } "
• " + "