Get the Exact Position and Size of a Window in Windows

Problem

You would like to know the exact pixel position and size of a window in Microsoft Windows.

Solution

Use the very useful utility Sizer. You can download it for free from the page below:

http://www.brianapps.net/sizer/

I downloaded the portable version (download the Zip Package).

Launch sizer.exe from the extracted zip package.

Then right click the title bar of the window of which you would like to know the position and size.

Select the option Resize/reposition from the context menu. Select ‘New entry …’

Now, you can see the width and height as well as the top and left offset for your window:

Remove Duplicates from Array in CoffeeScript

Problem

You have an array in CoffeeScript, which contains equal elements multiple times such as:

[1,1,2,3,3]

You would like to have only unique values in the array. Thus, transform it into:

[1,2,3]

Solution

You can use the following method to accomplish such:

removeDuplicates = (ar) ->
  if ar.length == 0
    return []  
  res = {}
  res[ar[key]] = ar[key] for key in [0..ar.length-1]
  value for key, value of res

alert(removeDuplicates([1,2,3,3,4,4,5]));

References

This solution is based on this approach (with a few minor issues fixed).

Cross-Domain Requests in GWT with JSONP

GWT RPC is built upon AJAX requests and thus is subject to the Same-Origin Policy. However, it is really easy in GWT (as well as in other JavaScript applications) to circumvent this policy using a method called JSON-with-padding (JSONP).

Unfortunately, there are a couple of issues one needs to consider before utilizing JSON-P:

Amount of Data Send from Client to Server

The biggest limitation of JSONP is that it uses GET and not POST requests. Thus, all data send from the client to the server needs to be encoded as URL query parameters such as:

http://myserver.com/myrpctarget?data_from_client=lotsofdatafromclient

These URL parameters can only hold a limited amount of data. I couldn’t find a conclusive upper limit on this, but most sensible suggestions seem to indicate that parameters should be limited to between 2,000 or 4,000 bytes. Please note that many sources here discuss the limit of characters which can be put into a browsers address bar. This limit is not the same as the limit for GET requests triggered from within JS code.

Reliance on GWT RPC

It is a non-trivial (but not impossible – I’ve done it!) endeavor to channel GWT RPC requests through JSONP. Thus, if your application is deeply dependent on GWT RPC, it will probably involve a lot of work to make it JSONP ready. Good news is that if you use the Request Builder API things will be far easier.

Other than these two issues there is really nothing stopping you from writing GWT client applications, which can communicate with multiple servers. I believe that this decoupling from client and server is far more valuable than the added security derived from restricting requests to one domain. After all, the browser is a client application which is by design meant to communicate with many different servers. If you have a choice, consider the two factors above and architect your GWT applications from the very beginning in a way which enables JSONP requests.

Resources

GWT JavaDoc – JsonpRequestBuilder

Wikipedia – JSONP

GWT 2, JSONP and Javascript Overlays with JsonpRequestBuilder

Insert Text at Caret Position in Summernote Editor for Bootstrap

Problem

Using the very useful Summernote Editor component for Bootstrap, you would like to insert some text at the current caret position programmatically.

Solution

The Summernote API does not provide any dedicated methods for inserting text. However, that’s not a problem since we can use the JQuery/native DOM API to insert text into the editor. Thankfully, the content of the Summernote editor is nothing but vanilla HTML/DOM elements. Thus, we can insert text at the current cursor position as follows (if the Summernote editor is focused):

To Insert at the End of the Current Paragraph

$(document.getSelection().anchorNode.parentNode).append(“appended!”);

To Insert at the Current Cursor Position

var selection = document.getSelection();

var cursorPos = selection.anchorOffset;

var oldContent = selection.anchorNode.nodeValue;

var toInsert = “InsertMe!”;

var newContent = oldContent.substring(0, cursorPos) + toInsert + this.substring(cursorPos);

selection.anchorNode.nodeValue = newContent;

Note: You probably will have to work some magic with the document.getSelection() call. The problem is that once you would click a button or trigger the action in some other way, the selection would change. Thus, I save a reference to the document.getSelection() upon every focus and key press event on the editor.

References

MDN – Selection.anchorNode

Stackoverflow – Get caret position in contentEditable div

Stackoverflow – Inserting Text at Cursor Position using JS/JQuery

Stackoverflow – JQuery Plugin for Inserting Text at Caret

 

 

 

CoffeeScript Fat Arrow (=>) explained

Anyone who has worked with JavaScript for anything but a very short time will have come across the problem that the meaning of ‘this’ is often ambiguous at best. CoffeeScript attempts to mitigate this problem somewhat by introducing the Fat Arrow operator (=>). This operator can be used as a replacement for the thin arrow operator (->) used extensively in CoffeeScript for defining functions.

Unfortunately, it is not easy to understand what the fat arrow operator does.I hope the following rules provide some guidance on how to use this operator in CoffeeScript:

Rule 1: You Don’t Need the Fat Arrow If You Don’t Use: class, this, and @

If you are a beginner in JavaScript and/or CoffeeScript, I would recommend keeping your hands of the language constructs ‘this’, ‘class’ and ‘@’. You can implement any application you like without having to use these constructs and it will make your applications more robust and bug free.

Rule 2: Use the Fat Arrow when You Use @ in a Callback Definition in a Method

If you use classes in your code and you want to create a new anonymous function to be passed as a callback (such as to listen to an onclick event or to defined setTimeout function), define this function with the fat arrow operator. This will assure that you still have access to the methods and properties of the class you are working with.

The fat arrow will ‘override’ the default meaning of the @ operator as follows, to assure that ‘this’ refers to what we would expect it:

CoffeeScript

delayedAction = =>  
  alert(@messsage)

setTimeout(delayedAction, 100);

JavaScript

delayedAction = (function(_this) {
  return function() {
    return alert(_this.messsage);
  };
})(this);

setTimeout(delayedAction, 100);

Rule 3: Don’t Use Methods as Callbacks and Avoid the Fat Arrow Operator in All Other Circumstances

There is one more use case for the Fat Arrow operator, which is that it has a special meaning when used for the definition of class methods. This is useful when the methods of a class are to be passed as a callback. I personally don’t think that’s a very useful feature and it’s better to define an anonymous function to handle a callback and then call a method of your class/object from within this callback. Following this rule enables us not having to worry about whether to define a method with a thin or fat arrow – which is otherwise tricky since the right choice here is external to the class we are writing.

More Reading

Karl Seguin – Ten Features I Like About CoffeeScript

Michael Kramer - The Simplified Fat Arrow Guide for CoffeeScript

Azat Mardanov - Understanding Fat Arrows (=>) in CoffeeScript

Giang Nguyen - Coffeescript: Fat arrow vs thin arrow

Embed HTML Code in JavaScript File

Problem

You would like to include HTML code as a String in a JavaScript file.

Solution

Firstly, load the HTML code into a JavaScript variable (e.g. by using jQuery.ajax()).

$.ajax({url: 'http://mydomain.com/htmlfile.html'})

.done(function(html) {

Then apply the following two simple regular expressions on the html code to generate valid JavaScript code.

var safeHtml = html

.replace(/\n/g, "\\n")

.replace(/\"/g, "\\\"")

You can use this String now to build a JavaScript file:

var myScript = 'var html="'+safeHtml+'";';

 

The Dangers of the OK Plateau and How to Overcome Them

I found the following wonderful quote in Daniel Goleman’s Focus: The Hidden Driver of Excellence via Brain Pickings:

Amateurs are content at some point to let their efforts become bottom-up operations. After about fifty hours of training — whether in skiing or driving — people get to that “good-enough” performance level, where they can go through the motions more or less effortlessly. They no longer feel the need for concentrated practice, but are content to coast on what they’ve learned. No matter how much more they practice in this bottom-up mode, their improvement will be negligible.

The experts, in contrast, keep paying attention top-down, intentionally counteracting the brain’s urge to automatize routines. They concentrate actively on those moves they have yet to perfect, on correcting what’s not working in their game, and on refining their mental models of how to play the game, or focusing on the particulars of feedback from a seasoned coach. Those at the top never stop learning: if at any point they start coasting and stop such smart practice, too much of their game becomes bottom-up and their skills plateau.

While this excerpt is centred on sports, it of course applies to many areas in which we might want to develop expertise.

I read another book some time ago, The Little Book of Talent by Daniel Coyle, in which there were some similar ideas. However, in The Little Book of Talent it was added that there are two types of skills: hard skills and soft skills. The former being skills that can easily be advanced through deliberate practice, such as hitting a perfect forehand in tennis, and the latter being skills which are more difficult to practice deliberately, such as developing a strategy to win a tennis match. I think this is a distinction worthy of consideration in the context of the above quote.

 

GWT Exclude Package From Source Path

Problem

The Google Web Toolkit Java to JavaScript transpiler is a powerful tool to convert Java source code into JavaScript files. Unfortunately, not all Java code can be transpiled into JavaScript code by GWT.

Sometimes, a project contains a mix of Java code that can be converted into JavaScript and Java code that doesn’t. In that case, the GWT compiler issues errors such as ‘No source code is available for type …‘.

Solution

GWT module definitions (.gwt.xml) files allow to specify fine-grained rules which files in a project are to be converted and which files should not. The rules are based on Ant patterns, which can be difficult to wrap one’s head around. Below are a few handy examples.

Exclude all files in packages with the name ‘/jre/’

<source path='' >

    <exclude name="**/jre/**" />
</source>

Exclude the file ‘ForJre.java’:

<source path='' >
   <exclude name="**/ForJre.java" />
</source>

JavaScript and JSON Essentials (Packt) Review

JavaScript and JSON Essentials‘ by Packt publishing is a hands-on guide to developing JavaScript/PHP based web applications while using the JSON data format. This review of the book contains a quick summary of the contents as well as points to consider if you think of purchasing the book.

Overall, this as an easy to read book suited for novices in web development, packed with examples and easy to follow step-by-step instructions. However, advanced JavaScript developers will be familiar with most of the concepts covered in the book.

Contents

Chapter 1: JavaScript Basics

Explains the very basics of JavaScript, such as how to embed a script in a webpage, simple expressions (3+4), arrays and objects.

Chapter 2: Getting Started with JSON

Goes through the fundamental rules of JSON documents and how to access the data they contain in JavaScript applications.

Chapter 3: Working with Real-time JSON

Goes through an example of processing a complex JSON document, a collection of employees with their personal and employment details. Specifically, to query data from the document such as retrieving the positions of employees and to modify data.

Chapter 4: AJAX Calls with JSON Data

Shows how to set up a simple web server under a Linux (LAMP) and Windows (ASP.NET) environment. Then, how to host a simple PHP script dynamically rendering JSON data and using XMLHttpRequest to access the data from this script from a JavaScript application.

Chapter 5: Cross-domain Asynchronous Requests

This chapter firstly expands the PHP script and JavaScript application developed in the previous chapter. Specifically, by allowing to pass query parameters to the PHP script. Then, an example is shown how to load a JSON document through JSONP from the site reddit.

Chapter 6: Building the Carousel Application

Shows how to develop a small example application in which student records are retrieved from a server and displayed in a web browser.

Chapter 7: Alternate Implementations of JSON

Portrays numerous ways in which JSON data is used such as in PHP Composer and for Node.js package manager NPM. Briefly compares JSON with the data definition format YAML.

Chapter 8: Debugging JSON

Introduces numerous tools that can aid in developing JavaScript applications such as Firebug and tools to validate (only syntax) and format JSON documents.

The Good

  • Provides a good introduction to developing simple applications with JavaScript and PHP which utilize JSON data.
  • The book is overall well organized and it is easily understandable what is covered in the chapters.
  • There are plenty of examples and step-by-step instructions
  • The PDF version of the book is easy to navigate, with helpful bookmarks, which allow to browse the table of contents and hyperlinks throughout the document.

Caveat Emptor

  • Don’t expect to become a grandmaster of JavaScript after reading the JavaScript intro of the book. It’s around 14 pages and only meant to give a brief idea of JavaScript. If you are new to JavaScript, consider a complementary book such as Object-Oriented JavaScript or JavaScript The Good Parts.
  • This book, as its title specifies covers the ‘Essentials’ of JavaScript and JSON. Thus it’s a good starting point to become familiar with these technologies but does not contain more advanced or nuanced discussions, such as good design practices for JSON documents, performance issues or tradeoffs in using JSON.

Disclaimer: Thanks to Packt Publishing for providing a free review copy of this book!

Render HTML from Object with CoffeeKup

CoffeeKup allows to render HTML from multiple sources:

  • A String containing valid CoffeeScript code
  • A JavaScript/CoffeeScript object arranged according to CoffeeKup rules

To render HTML from a String is quite straightforward and documented on the CoffeeeScript reference: you can use the methods .compile and .render as documented there.

However, to render HTML from a JavaScript/CoffeeScript object can also come in handy, to create a tight link between your logic and markup. The .render method is not only able to process a String but is also able to process a certain kind of Object as well.

Here find two examples of how to render JavaScript and CoffeeScript objects into HTML:

JavaScript Object

CoffeeKup.render(function() {

  return div({ class: 'mydiv' }, 'Hello World');

});

which results in:

"<div class='mydiv'>Hello World</div>"

CoffeeScript Object

CoffeeKup.render(div 'mydiv', ->'Hello World'<span style="line-height: 1.5em;">);

resulting in the same HTML as above.