CodeMirror is a versatile text editor implemented in JavaScript

logo
CodeMirror
is a versatile text editor implemented in JavaScript for the browser. It is specialized for editing code, and comes with a number of language modes and addonsthat implement more advanced editing functionality.

A rich programming API and a CSS theming system are available for customizing CodeMirror to fit your application, and extending it with new functionality.

Features

Original Site URL – CodeMirror

How to use jquery.cookies.js

Without jQuery

If jQuery is not available in your page, the core cookies library is available to you under the jaaulde.utils namespace:

Get a cookie

/**
 * get - get one, several, or all cookies
 *
 * @access public
 * @paramater Mixed cookieName - String:name of single cookie; Array:list of multiple cookie names; Void (no param):if you want all cookies
 * @return Mixed - Value of cookie as set; Null:if only one cookie is requested and is not found; Object:hash of multiple or all cookies (if multiple or all requested);
 */
get = function(cookieName)

Example:

  • jaaulde.utils.cookies.get('myCookie');
    • returns value of myCookie if it is present, null if not
  • jaaulde.utils.cookies.get(['myCookie', 'myOtherCookie']);
    • returns array containing value of each requested cookie if it is present, null if not
  • jaaulde.utils.cookies.get();
    • returns array of all cookies from your site

Get Filtered list of cookies

/**
 * filter - get array of cookies whose names match the provided RegExp
 *
 * @access public
 * @paramater Object RegExp - The regular expression to match against cookie names
 * @return Mixed - Object:hash of cookies whose names match the RegExp
 */
filter = function( cookieNameRegExp )

Example:

  • jaaulde.utils.cookies.filter( /^site/ );
    • returns list of cookies whose names start with “site”

Set a cookie

/**
 * set - set or delete a cookie with desired options
 *
 * @access public
 * @paramater String cookieName - name of cookie to set
 * @paramater Mixed value - Any JS value. If not a string, will be JSON encoded (http://code.google.com/p/cookies/wiki/JSON); NULL to delete
 * @paramater Object options - optional list of cookie options to specify
 * @return void
 */
set = function(cookieName, value, options)

Example:

  • jaaulde.utils.cookies.set('myCookie', 'myValue');
    • sets cookie by the name of ‘myCookie’ to value of ‘myValue’ with default options
  • jaaulde.utils.cookies.set('myCookie', 'myValue', {path: '/somedir'});
    • sets cookie by the name of ‘myCookie’ to value of ‘myValue’ with path of ‘/somedir’
  • See information on options object below

Delete a cookie

/**
 * del - delete a cookie (domain and path options must match those with which the cookie was set; this is really an alias for set() with parameters simplified for this use)
 *
 * @access public
 * @paramater MIxed cookieName - String name of cookie to delete, or Bool true to delete all
 * @paramater Object options - optional list of cookie options to specify ( path, domain )
 * @return void
 */
del = function(cookieName, options)

Example:

  • jaaulde.utils.cookies.del('myCookie');
    • deletes a cookie, ‘myCookie’, with default options
  • jaaulde.utils.cookies.del('myCookie', {path: '/somedir'});
    • deletes a cookie by the name of ‘myCookie’ which had been set with a path of ‘/somedir’
  • jaaulde.utils.cookies.del(true);
    • deletes all cookies
  • A cookie can only be deleted using the same options with which it was set
  • See information on options object below

Test if browser is accepting cookies

/**
 * test - test whether the browser is accepting cookies
 *
 * @access public
 * @return Boolean
 */
test = function()

Example:

  • jaaulde.utils.cookies.test();
    • attempts to set a cookie and returns true or false upon success or failure

Set default options to use when none are specified

/**
 * setOptions - set default options for calls to cookie methods
 *
 * @access public
 * @param Object options - list of cookie options to specify
 * @return void
 */
setOptions = function(options)

Example:

  • jaaulde.utils.cookies.setOptions({path: '/somedir'});
    • all cookies will be set or deleted with the path , ‘/somedir’, unless it is explicitly provided in a passed options object
  • See information on options object below

With jQuery

If jQuery is available, then all of the above methods are available to you under the jQuery.cookies (or $.cookies ) namespace:

  • $.cookies.get()
  • $.cookies.filter()
  • $.cookies.set()
  • $.cookies.del()
  • $.cookies.test()
  • $.cookies.setOptions()

In addition, there are some jQuery function additions for helping automate some cookie tasks:

  • Set the value of a form field or the HTML of an element to a cookie named after the field’s/element’s name or id attribute
    • $('#username').cookify();
      • The value of the field, or HTML of the element, with id “username” is set to a cookie named after the name or id attribute of that field/element. If a radio or checkbox and it’s checked, the value will be set.
  • Fill a field’s value, or an element’s innerHTML with the value of a cookie
    • $('#username').cookieFill();
      • Set the value of the input, or HTML of the element, with id, ‘username’, to the value of a cookie by the same name. If a radio or checkbox and it is checked, the cookie will be set. If not checked, the cookie will be deleted.
  • Bind an input to the cookies library
    • $('#username').cookieBind();
      • Fills the field or element with id, ‘username’, with the cookie named the same and sets the field’s/element’s change event to fire cookify() to update the cookie when the input value changes

Options object

Using the options object, cookies can be set with several options such as the domain and or path for which the cookie should be available, expiration date for the cookie, and whether the cookie should be sent over HTTPS only.

The options object has four properties:

  • domain
    • STRING
    • For which domain should the cookie be available
  • path
    • STRING
    • For which path should the cookie be available
  • hoursToLive (DEPRECATED for expiresAt)
    • NUMBER
    • For how many hours should the cookie be valid? (Passing 0 means to delete the cookie at the end of the browser session–this is default. Negative values will delete the cookie, but you should use the del() method instead.)
  • expiresAt
    • Date OBJECT
    • Date object representing expiration date/time of cookie
  • secure
    • BOOL
    • Should cookie be sent to server via HTTPS only?

The structure of the object is as follows:

  var newOptions = {
    domain: '*.mydomain.com',
    path: '/somedir',
    expiresAt: new Date( 2011, 1, 1 ),
    secure: true
  }

You need only set those options which you desire to override.

The default options when not overridden are:

  • domain
    • no value – will cause current domain of current page to be used
  • path
    • /
  • expiration
    • no value–causes cookie to be deleted at end of browser session
  • secure (send over HTTPS only)
    • false

An options object can be passed with set(), del(), cookify(), and cookieBind() to override the defaults on a case by case basis. You can also pass an options object to setOptions() to override the defaults for all calls.

IMPORTANT NOTE: Cookies must be deleted using the same domain and path options with which they were set. Else the cookie will not delete. This is just how cookies work.

How to dynamically Insert Javascript And CSS

This is a short and sweet little article to show you how to dynamically insert a new Javascript (or style sheet) into your web pages, and explores how you can exploit cross-domain includes in your applications.

As JSON and DHTML start to get pushed more and more to the forefront of web-based applications, the web designer is faced with a new problem: how to dynamically insert a script element into an existing web page. It won’t take long to figure out that ajax loads and innerHTML injections won’t work.

Dynamic Cascading Style Sheets

The usefulness of being able to dynamically load a style sheet is fairly limited, but there is one very good reason to keep this tool handy: it lets you load a specific stylesheet for a specific browser. Instead of having one massive style sheet for every browser which visits your page, you can break out the stylesheets into browser specific Firefox, IE, Safari, Opera, etc styles which accommodate the eccentricities of each browser and let you serve smaller css files to your visitors to boot.

The code for this is just as simple as the javascript.

var headID = document.getElementsByTagName("head")[0];         
var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = 'FireFox.css';
cssNode.media = 'screen';
headID.appendChild(cssNode);

We get the <head> tag, then create the link and apply the attributes. When it’s all set up we insert the new cssNode into the head section of our webpage where the various styles are instantly applied.

Dynamic Javascript Insertion

Fortunately, dynamic insertion of CSS or Javascript is relatively painless.

var headID = document.getElementsByTagName("head")[0];         
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://www.somedomain.com/somescript.js';
headID.appendChild(newScript);

It’s really that simple. headID gets the <head> element of the page. Next we create a new ‘script’ element, assign it a text/javascript type, and then the url of the script (which can be anywhere on the net since it’s basically a javascript include). Finally we append the new element to our head section where it is automatically loaded.

If you’re loading an external javascript and you need to know when the script has loaded you can simply use .onload=yourfunction; to set up the onload handler. Here’s an example.

var headID = document.getElementsByTagName("head")[0];         
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.onload=scriptLoaded;
newScript.src = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=sunset&format=json';
headID.appendChild(newScript);

Now when this script has been loaded the .onload event will call a function named scriptLoaded().

 

 

Bootstrap 3 Examples

A whole bunch of examples demonstrating the various Bootstrap components and its features in real action.

Bootstrap Grid System

Bootstrap Typography

Bootstrap Tables

Bootstrap Lists

Bootstrap Forms

Bootstrap Icons

Bootstrap Navs

Bootstrap Navbar

Bootstrap Breadcrumbs and Pagination

Bootstrap Labels and Badges

Bootstrap Progress Bars

Bootstrap Utility Components and Classes

Bootstrap Buttons

Bootstrap Dropdowns

Bootstrap Tooltips

Bootstrap Popovers

Bootstrap Alerts Messages

Bootstrap Tabs

Bootstrap Modals

Bootstrap Accordion

Bootstrap Carousel

Bootstrap Typeahead

Bootstrap ScrollSpy

Bootstrap Affix

D3.js – JavaScript library (Charts)

Hey there,
It’s been long time, I did not post new technical things. While I was googling, I came accross Nice Data Representation library – D3.js.

D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation.

D3 allows you to bind arbitrary data to a Document Object Model (DOM), and then apply data-driven transformations to the document. For example, you can use D3 to generate an HTML table from an array of numbers. Or, use the same data to create an interactive SVG bar chart with smooth transitions and interaction.

D3 is not a monolithic framework that seeks to provide every conceivable feature. Instead, D3 solves the crux of the problem: efficient manipulation of documents based on data. This avoids proprietary representation and affords extraordinary flexibility, exposing the full capabilities of web standards such as CSS3, HTML5 and SVG. With minimal overhead, D3 is extremely fast, supporting large datasets and dynamic behaviors for interaction and animation. D3’s functional style allows code reuse through a diverse collection of components and plugins.

Reference Link – D3.js

 

Javascript Package Management – NPM – Bower – Grunt

When I was writing my previous post about Java EE and Angular, I was overwhelmed with all the javascript files that I needed to include in my application to implement the behaviour that I was looking for. OK, not that many scripts actually, four in total: Angular JS (Angular also requires jQuery), ng-grid and UI Bootstrap. Unfortunately, it was not so simple. Each script, may also need a CSS file and some of the scripts depended on different versions from each others. Finally, I also needed to include all the files in my index.html. For that particular post, I ended up doing everything manually and it was a real pain. There must be a better way!

The Problem

In Java, whether you like it or not, Maven is the number one tool to perform this kind of management, but what about Javascript? I’m far from an expert, so after asking our friend Google about it, I was a bit surprised with the amount of existent tools to do the job and for a newcomer this seemed complicated and lacking a common solution generally accepted by the community. Here are a couple of interesting posts about the problem:

Which solution?

I was not exactly sure which tool should I use, so after a few talks with a couple of colleagues that were working in Javascript applications they recommended NPM-Bower-Grunt combo:

NPM stands for Node Package Manager. Sounds weird, since we are not developing a Node.js application here, but we need NPM to use Bower and Grunt.

Bower is a package manager for the web. It will manage all your web files: javascript, css and images.

Grunt is a task-based command line build tool for JavaScript projects.

Both Bower and Grunt are Node.js packaged modules and we only need NPM to download them. Bower is going to be responsible to download and manage all the javascript dependencies for our web application. Finally, Grunt will automate the task for adding the correct tags to the html files. Actually, Grunt also have tasks to concatenate and minify multiple files in a single one. This is useful to improve the performance of your application in production environments, but it was not may main focus.

The Setup

Paulo Grácio, a very good friend of mine that I work with, was kind enough to pick up my Java EE Angular sample on Github and setup everything needed to provide the application with Javascript Package Management. Thank you so much Paulo!

Maybe it’s a stupid comparison, but I’ll try to establish parallels with Java Maven build, to help people like me that are used to Maven to better understand what’s going on.

Install NPM

The pre-built installer of Node.js is all you need to have NPM up and running on your machine, but I actually followed this post to install NPM using Homebrew on OS X.

Now we need a package.json file in the root project folder. We are using this one:

In this file, you can find the node settings for your project. The most interesting stuff here is the devDependencies definition. Here you can find the Grunt task to download the project dependencies (grunt-bower-install-simple) and the task to inject the scripts and css in the index.html (grunt-wiredep). This is similar to the plugins definitions in a Maven pom.xml file. Running npm install should download everything you need to start using Grunt and the project tasks.

Managing Web Packages with Bower

Now we need to tell Bower which packages we want to include in the project. Add a file named bower.json in the root project folder:

Remember the original problem? Manage Angular, jQuery, ng-grid and UI Bootstrap dependencies? Here we have the definitions. I can compare it again like being a bit similar to the dependencies section in a Maven pom file for a Java project. Just a small detail, Bower uses Convention-over-Configuration to define project paths. This is important because the default location to download the javascript packages does not follow the Maven folder layout, so we should change Bower path to match Maven web app layout. To fix this, we need to add a file named .bowerrc to the project root folder:

Defining Grunt Tasks

To glue everything together, we use Grunt to run the different tasks, but first we need to add another file to the project root folder, Gruntfile.js:

For this file, we are just adding configurations to each Grunt task. We can also assemble all the tasks together to run in our own defined task named build or default. This is like defining our own Maven build lifecycle (which is not possible in Maven) and configuring the plugins settings. So, we actually have plugins (tasks) definitions in one file (package.json) and plugins (tasks) settings in a separate file (Gruntfile.js).

There is one more thing to do: we need to add a few special placeholders into our HTML files so that the Grunt tasks can add Javascript and CSS files automatically, based on Bower dependencies. For this project we have an unique index.html file and the head section should look like this:

The <!-- bower:css --> marks the location in the html file where the css files dependencies must be inserted and <!-- build:css css/third-party.css --> is used to indicate the merged file with all the css code. For <!-- bower:js --> and <!-- build:js lib/third-party.js --> it works the some way. Note that we have separated the external files from the own application files.

Final Structure

The project structure result is the following:

NPM-Bower-Grunt Structure

Executing Grunt Tasks

After all this setup, we are finally ready to execute Grunt tasks and have our web files managed! So, going from the start, we execute from the command line in the project folder root:

npm install

followed by

grunt

You will notice the following:

  • A node_modules folder is created with all of the Bower and Grunt dependencies.
  • A src/main/webapp/lib/bower folder is created with all of the web application dependencies (Angular, jQuery, ng-grid and UI Bootstrap).
  • The src/main/webapp/index.html file is injected with the needed Javascript and CSS files.
  • A build folder is generated with an optimised version of the web application (files concatenated and minified).

The end result:

NMP-Bower-Grunt Result

You can also execute individual Grunt tasks:

grunt bower – Downloads the web application dependencies.
grunt bowerInstall – Modifies and inject the required files in your index.html.

Resources

You can find the updated Java EE 7 – Angular JS example with Javascript Package Management in Github, here. For the moment it’s in a branch but we intend to merge it with the original example.

Update
In the meanwhile I have merged this code with the original example. Please, download the original source of this post from the release 2.0. You can also clone the repo, and checkout the tag from release 2.0 with the following command: git checkout 2.0.

Final Thoughts

Uff! It was not easy to do this. A lot of files to add and to configure and a lot of tools to study. Maybe there is an easier way to accomplish the same using other existent setups and tools in the Javascript landscape. I cannot tell you this is the best, since I would have to setup all the other solutions around the Javascript landscape, but this is a possible approach and it works. Just a couple of weeks after working on this, I found the following:

And just like that Grunt and RequireJS are out, it’s all about Gulp and Browserify now

Don’t get me wrong, but I feel that the Javascript landscape is popping build tools like mushrooms. In my opinion it would be better to have a single standardised tool that everyone could use. Let’s see what is going to happen in the future.

Probably it could also be easier to use Yeoman to generate the structure, but we also wanted to learn more about the individuals tools, and I think you learn a bit more by doing things manually the first couple of times.

Originally Written by  – Roberto Cortez

Understanding JavaScript Promises

A promise represents the eventual result of an asynchronous operation. It is a placeholder into which the successful result value or reason for failure will materialize.

Why Use Promises?

Promises provide a simpler alternative for executing, composing, and managing asynchronous operations when compared to traditional callback-based approaches. They also allow you to handle asynchronous errors using approaches that are similar to synchronous try/catch.

Promise States

A promise can be in one of 3 states:

  • Pending – the promise’s outcome hasn’t yet been determined, because the asynchronous operation that will produce its result hasn’t completed yet.
  • Fulfilled – the asynchronous operation has completed, and the promise has a value.
  • Rejected – the asynchronous operation failed, and the promise will never be fulfilled. In the rejected state, a promise has a reason that indicates why the operation failed.

When a promise is pending, it can transition to the fulfilled or rejected state. Once a promise is fulfilled or rejected, however, it will never transition to any other state, and its value or failure reason will not change.

Promises have been implemented in many languages, and while promise APIs differ from language to language, JavaScript promises have converged to the Promises/A+ proposed standard. EcmaScript 6 is slated to provide promises as a first-class language feature, and they will be based on the Promises/A+ proposal.

Using Promises

The primary API for a promise is its then method, which registers callbacks to receive either the eventual value or the reason why the promise cannot be fulfilled. Here is a simple “hello world” program that synchronously obtains and logs a greeting.

var greeting = sayHello();
console.log(greeting);    // 'hello world’

However, if sayHello is asynchronous and needs to look up the current greeting from a web service, it may return a promise:

var greetingPromise = sayHello();
greetingPromise.then(function (greeting) {
    console.log(greeting);    // 'hello world’
});

The same message is printed to the console, but now other code can continue while the greeting is being fetched.

As mentioned above, a promise can also represent a failure. If the network goes down and the greeting can’t be fetched from the web service, you can register to handle the failure using the second argument to the promise’s then method:

var greetingPromise = sayHello();
greetingPromise.then(function (greeting) {
    console.log(greeting);    // 'hello world’
}, function (error) {
    console.error('uh oh: ', error);   // 'uh oh: something bad happened’
});

If sayHello succeeds, the greeting will be logged, but if it fails, then the reason, i.e. error, will be logged using console.error.

Transforming Future Values

One powerful aspect of promises is allowing you to transform future values by returning a new value from callback function passed to then. For example:

var greetingPromise = sayHello();
greetingPromise.then(function (greeting) {
    return greeting + '!!!!';
}).then(function (greeting) {
    console.log(greeting);    // 'hello world!!!!’
});

Sequencing Asynchronous Operations

A function passed to then can also return another promise. This allows asynchronous operations to be chained together, so that they are guaranteed to happen in the correct order. For example, if addExclamation is asynchronous (possibly needing to access another web service) and returns a promise for the new greeting:

var greetingPromise = sayHello();
greetingPromise.then(function (greeting) {
    return addExclamation(greeting); // addExclamation returns a promise
}).then(function (greeting) {
    console.log(greeting);    // 'hello world!!!!’
});

This can be written more simply as:

var greetingPromise = sayHello();
greetingPromise
    .then(addExclamation)
    .then(function (greeting) {
        console.log(greeting);    // 'hello world!!!!’
    });

Handling Errors

What if an error occurs while performing an asynchronous operation? For example, what if sayHello, or addExclamation fails? In synchronous code, you can use try/catch, and rely on exception propagation to handle errors in one spot. Here is a synchronous version of the previous example that includes try/catch error handling. If an error occurs in either sayHello or addExclamation (or console.log for that matter), the catch block will be executed:

var greeting;
try {
    greeting = sayHello();
    greeting = addExclamation(greeting);
    console.log(greeting);    // 'hello world!!!!’
} catch(error) {
    console.error('uh oh: ', error);   // 'uh oh: something bad happened’
}

When dealing with asynchronous operations, synchronous try/catch can no longer be used. However, promises allow handling asynchronous errors in a very similar way. This allows you not only to write asynchronous code that is similar in style to synchronous code, but also to reason about asynchronous control flow and error handling similarly to synchronous code.

Here is an asynchronous version that handles errors in the same way:

var greetingPromise = sayHello();
greetingPromise
    .then(addExclamation)
    .then(function (greeting) {
        console.log(greeting);    // 'hello world!!!!’
    }, function(error) {
        console.error('uh oh: ', error);   // 'uh oh: something bad happened’
    });

Notice that just like the synchronous example, you can use a single error handling block, in this case passed as the second parameter to the final call to then.

Jing, Free Screenshot and Screencast Software

Features

Jing sun graphic

The always-ready program that allows you to instantly capture images and record video on your computer—then share them with anyone. Jing is a great tool for adding basic visual elements to all of your online conversations

Jing for Screenshots

Capture What You See

The Jing sun sits nicely on your desktop, ready to capture your screen at a moment’s notice. Jing will capture a window, pane, or region with just one click.

Jing Loves to Share

Send your screenshots all over the web. With Jing, you can add an image to your blog, or instantly share your captures through IM, email and more. Share your Jing screenshots on:

Sharing Locations

Annotate Captures

Make a point

Make a Point

Need to emphasize a point or explain a tricky concept? Mark up your screenshot with a text box, arrow, highlight, or picture caption.

No need to wait

No Need to Wait

Simply paste the link into an IM, email, forum post, anywhere…and when the person clicks it they see your freshly–uploaded screenshot.

Share Instantly

Share Images Instantly

Jing will place a hyperlink on your clipboard when you send your screenshots to a destination like Screencast.com or Flickr.

 


Jing for Screencasts

Record What You See (and Do)

Select any window or region that you would like to record, and Jing will capture everything that happens in that area. From simple mouse movements to a fully narrated tutorial, Jing records everything you see, and do. And then lets you share your SWF videos with anyone.

Jing videos are limited to 5 minutes for instant, focused communication.

Instantly share Jing video on:

sharing options, facebook, screencast, youtube

 

Record what you see

Narrate with a Microphone

Narrate on the Fly

If your computer has a microphone, Jing can record your commentary at the same time as your movements.

Sharing Options

Want Options?

Jing can also be configured to return html embed code so you can insert your image or video directly into a blog, website, wiki and more.

 Share to Screencast.com

Share Video at the Speed of Conversation

As soon as you’re done recording, your screencast video is ready to upload and share over the web, IM, and email.


Jing for Sharing

Jing icon

Snagit and Camtasia Studio

Jing is a great basic tool for adding visuals to your conversations, but sometimes you need more. Record videos longer than 5-minutes. And upload your creations directly to your YouTube channel with Snagit and Camtasia Studio.

Sharing folders

Get More with Screencast.com

Screencast.com is where that handy little URL comes from after you capture an image or video. Screencast.com lets you share your videos and images with anyone, organize your creations, and allows viewers to comment on your content.