Category Archives: dev

How to create a MEAN+ stack application (MongoDB, Express, Angular, Node + Bootstrap, Jade)


      Create a Node.js with Express.js App
      Create a Git repository and clone to localhost
      Add Angular.js
      Add Bootstrap
      Add MongoDb
      Add Jade
      Add an API for GET /people
      Connect to MongoDb
      Create a sortable table with Angular

Create a Node.js with Express.js App

I will be using Bluemix to host, build and deploy my Node.js application and the MongoDb service. I am developing on my localhost for unit testing before I upload my application to Bluemix, but you can also use the online editor and online Git instead.

1. If you do not have a Bluemix account yet, sign up for a free account at,
2. Once you have an account, go to your Bluemix console at,
3. Go to your Dashboard,
4. In the ‘Cloud Foundry Apps’ box, click ‘CREATE APP’,

5. Choose ‘WEB’

Continue reading

Print Friendly, PDF & Email

Calling a Watson service in Java


Note: this API needs to be updated to v2. Identify is now a resource on the Language Translation API.

Making an HTTP REST API POST request in Java is in principle as simple this:
Request request = Request.Post(serviceURI)
.addHeader("Authorization", basicAuthorization)
.bodyString(body, ContentType.APPLICATION_FORM_URLENCODED);
Executor executor = Executor.newInstance();
String response = executor.execute(request).returnContent().asString();

This code, uses the Apache Fluent API, which exposes only the essentials of the Apache HTTPClient.

The Authorization header is required for authentication by the Watson API, and is a base64 encoded string.
String auth = username + ":" + password;
String basicAuthorization = "Basic "+ Base64.encodeBase64String(auth.getBytes());

The POST request is “x-www-form-urlencoded” and in Java consists of a List<NameValuePair>:
List<NameValuePair> params = new ArrayList<NameValuePair>();

Continue reading

Print Friendly, PDF & Email

Call IBM Watson APIs to add Machine Learning to your App

You can easily add very cool IBM Watson APIs to your application. You need to sign up for Bluemix, create an application and bind APIs or services to the app. This will create credentials (username and password) for each API or service.

Create a Bluemix acccount

First if you have not signed up for a Bluemix account yet, go to and Sign Up.

Create an App

Once you have confirmed your account, go to the Catalog and choose any Runtime. We will only use the runtime to bind services to, which will give us API credentials. For example, name the app ‘my-app1’.

Add a Service

Now, to add Services either go to Catalog > Services, and add a service to your app, or go to your app’s admin page. Bluemix is based on Cloud Foundry, so apps in Bluemix are listed under ‘CF Apps.’ Go to Dashboard > CF Apps > ‘my-app1’, and click the ‘Add a Service or API.’ I will add Personality Insights to my app in this example. Edit the required fields and click the Create button. Bluemix might ask you to restage your app. Now we’re ready to call the Personality Insights API.

Call the Watson API

To make a REST call to a Watson API, you must add an Authorization header with a Base64 encoded “Basic :” string. To generate the Basic Authorization header, use the colon as a separator for username and password and Base64 encode the Authorization string.

String username = "username from your service credentials";
String password = "password from your service credentials";
String s = username + ":" + password;
byte[] b = s.getBytes();
String enc = Base64.encodeBase64String(b);
String authorization = "Basic "+enc;

To call the API with the above credentials use the following curl statement from command line.

curl -X POST -H "Authorization: Basic BzAvEATz4UYqKfU5JA66GSIwKNgdATGiADR8YiWaOSH2Purd6tedhKUJaPa3KLshLq==" -H "Content-Type: text/plain" -H "Accept: application/json" -H "Accept-Language: en" -H "headers: true" -d 'put your text here'

For the API reference details go here!/personality-insights/profile

This curl command will return a response object that you can visualize with the Visualize Personality Insights API.!/personality-insights/visualize

Print Friendly, PDF & Email

Send a multipart/form-data request in PHP


To List your current indexes with ‘standard’ flavor use a GET request to the List Indexes API.

$url_listindexes = '';
$params1 = 'flavor=standard&apikey='.$apikey;
$response = file_get_contents($url_listindexes .'?'.$params1);
if($response) { $json = json_decode($response); if($json){ $indexes = $json->index; } return $indexes; }


POST multipart/form-data with native PHP

function send_multipart_post_message($sync_or_async, $json1){
$url = "".$sync_or_async."/addtotextindex/v1";
// using WordPress custom functions to retrieve index and apikey
$index1 = wp_idolondemand_get_setting('index');
$apikey = wp_idolondemand_get_setting('apikey');
$eol = "\r\n";
$data = '';
$data .= '--' . $mime_boundary . $eol;
$data .= 'Content-Disposition: form-data; name="apikey"' . $eol . $eol;
$data .= $apikey . $eol;
$data .= '--' . $mime_boundary . $eol;
$data .= 'Content-Disposition: form-data; name="index"' . $eol . $eol;
$data .= $index1 . $eol;
$data .= '--' . $mime_boundary . $eol;
$data .= 'Content-Disposition: form-data; name="json"; filename="allposts.json"' . $eol;
$data .= 'Content-Type: application/json' . $eol;
$data .= 'Content-Transfer-Encoding: base64' . $eol . $eol;
$data .= base64_encode($json1) . $eol;
// alternatively use 8bit encoding
//$data .= 'Content-Transfer-Encoding: 8bit' . $eol . $eol;
//$data .= $json1 . $eol;
$data .= "--" . $mime_boundary . "--" . $eol . $eol;
$params = array('http' => array(
'method' => 'POST',
'header' => 'Content-Type: multipart/form-data; boundary=' . $mime_boundary,
'content' => $data
//'proxy' => 'tcp://localhost:8888' //use with Charles to catch http traffic
$ctx = stream_context_create($params);
$response = file_get_contents($url, FILE_TEXT, $ctx);
return $response;

Continue reading

Print Friendly, PDF & Email

[JavaScript] Find Related Concepts as D3js Bubble Chart

The Find Related Concepts API from IDOL OnDemand returns the most relevant terms and concepts from related documents. Here’s represented as a D3 Bubble Chart. Thanks to incredibly good work by Mike Bostock. For a description of the API go here
For D3 Data-Driven Documents go here:

Print Friendly, PDF & Email

[JavaScript] POST upload file with XHR FormData

This example uses the Optical Character Recognition (OCR) API from IDOL OnDemand. For details see here:

Print Friendly, PDF & Email

HTML5 and JavaScript: Flip an Image using HTML5 Canvas

See the working code example on jsfiddle.

<!DOCTYPE html>
<title>Flipping an Image Horizontally and Vertically</title>
<script src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
var imageurl = null;
$(document).ready( function() {
$('#loadimage').click(function() {
$('#mirrorh').click(function() {
$('#mirrorv').click(function() {
function urlProvided() {
var userinput = document.getElementById('imageurl');
imageurl = userinput.value;
function loadImage(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = imageurl;
img.onload = function(){
var w = img.width;
var h = img.height;
canvas.width = w;
canvas.height = h;
function mirror(mirrorh,mirrorv){
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
var img = new Image();
img.src = imageurl;
var w = img.width;
var h = img.height;
ctx.scale(1, -1);
ctx.translate(0, -h);
ctx.scale(-1, 1);
Your image URL: <input type="text" id="imageurl"></input><button id="loadimage">load image</button>
<button id="mirrorh">mirrorh</button>
<button id="mirrorv">mirrorv</button>
<canvas id="canvas"></canvas>

Print Friendly, PDF & Email

CSharp: POST Request to Query API and JSON Parsing

Use the System.Net.WebClient object to make a POST request in C#. For parsing JSON, you can use Json.NET by James Newton-King. Install both packages using the NuGet Package Manager. This code example posts a search for the text ‘Dog’ to the Query API. This example uses the text parameter, if you want to use the file parameter to upload a document as a search parameter you will need to use multipart/form content type, with for instance RestSharp client for .NET.

string apiKey = "your-apikey";
string iodURL = "";
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["apikey"] = apiKey;
formData["text"] = "Dog";
byte[] responseBytes = webClient.UploadValues(iodURL, "POST", formData);
UTF8Encoding enc = new UTF8Encoding();
string json = enc.GetString(responseBytes);

The JSON response is serialized using Json.NET into .NET Objects representing the JSON response as a DocumentList of Document type.

DocumentList documentList = JsonConvert.DeserializeObject(json);
List docs = documentList.Documents;
public class DocumentList
public List Documents { get; set; }
public class Document
public string Reference { get; set; }
public double Weight { get; set; }
public List Links { get; set; }
public string Index { get; set; }
public string Title { get; set; }
public Object Content { get; set; }

The above code will parse the JSON response from IDOL OnDemand.

"documents" : [{
"content" : { },
"index" : "news_eng",
"links" : [ "DOG" ],
"reference" : "",
"title" : "Stick Dog Wants a Hot Dog by Tom Watson - review",
"weight" : 89.5
"content" : { },
"index" : "news_eng",
"links" : [ "DOG" ],
"reference" : "",
"title" : "Dog attacks on children are tragic – but we can try to understand the triggers | Deborah Orr",
"weight" : 88.010000000000005

Access the properties as normal:

foreach (Document doc in docs)
Debug.WriteLine("doc.reference: " + doc.Reference);

To do a multipart/form-data POST request, the simplest way is to use a client like RestSharp, which you can install via NuGet:

string apiKey = @"your-apikey";
string iodURL = @"";
string file = @"C:\Users\user1\Documents\iod\TheSecretSpiritualHistoryOfCalculus_ScientificAmerican.pdf";
var client = new RestClient(iodURL);
var request = new RestRequest("", Method.POST);
request.AddParameter("apikey", apiKey);
request.AddFile("file", file);
RestResponse response = (RestResponse) client.Execute(request);
string content = response.Content;
Debug.WriteLine("status: "+ response.StatusCode + ", content: " + content);

Brian Grinstead wrote a great article on a Multipart form post in C# implementation, for those who are interested.

Print Friendly, PDF & Email

Arduino: TMP36 temperature sensor

The TMP36 temperature sensor is an easy to use temperature sensor. With a few lines of code you can measure the temperature with reasonable accuracy.

int sensorPin = A0;
float celsius;
float kelvin;
float fahrenheit;
void getTemperature()
float val = analogRead(sensorPin);
// analogRead returns a 0 to 5 volts measure on a scale from 0 to 1023,
// i.e. 2*10 bits or 1024 units
val = (val * 5.0) / 1024;
// convert Volts to milliVolts
// the TMP36's linear scale is 10 mV / degree Celsius
// i.e. (* 1000 / 10) = * 100
val = (val) * 100;
celsius = val;
kelvin = val + 273.15;
fahrenheit = ((val * 9)/5.0) + 32;


Print Friendly, PDF & Email

Cordova: Install or Update Cordova on Windows with Visual Studio

To install Apache Cordova on Windows and to use it with Visual Studio 2010 Express for Windows Phone, follow these steps:

  1. Get the source code for the latest version from the Cordova project page or for older versions go to the Cordova distribution archive.
  2. Unzip the source archive
  3. Locate the file in the extracted directory, and unzip the archive.
    C:/>cd cordova-3.4.0
  4. Change directory to cordova-wp8 and run the createTemplates.bat script.
    C:/cordova-3.4.0>cd cordova-wp8
  5. Copy the generated template files and to the Visual Studio Templates directory in the users My Documents folder ~/Document
    s\Visual Studio 2010\Templates\ProjectTemplates.
    C:\cordova-3.4.0\cordova-wp8>copy "C:\Users\user1\Document
    s\Visual Studio 2010\Templates\ProjectTemplates"

Now, start Visual Studio 2010 Express for Windows Phone, and in the File menu, select New Project…. In the Installed Templates select the Cordova template you just copied.

To add Cordova plugins on Windows with Visual Studio, go here.

Print Friendly, PDF & Email