JavaScript: Executing synchronously

I am being ask this question often; therefore, I am posting the answer here.

Commonly there are those who wish to do a process that normally is asynchronously, such as performing AJAX operations in a synchronous fashion. There are a few ways to do this.

If you are coding in JS for NodeJS, then you can use the package async-waterfall, example:

  function readFile(callback) {
        fs.readFile('your_file.json', function (error, file) {
            if (error) {
                callback(error);
            } else {
                callback(null, file);
            }
        });
    }
    ...
    function processFile(file, callback){
        // Some code here
    }
    ...
    async.waterfall([
        readFile,
        processFile
    ], function (error) {
        if (error) {
            // handle error made in readFile or processFile method 
        }
    });

Else, you can use promise chains which is part of Javascript, example:

    new Promise(function(resolve, reject) {
      try{
          resolve(readfile());
      }catch(e){
          reject("error message");
      }
    }).then(function(result) {
      return processFile(result)    
    });

Or, you can use async/await: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Share

Great Idea, I wish I could Help You.

In the middle of the night, while sleeping, you got a great idea for a new app. You are excited and cannot wait to share it with your friend, the Amazing Developer. In the morning, you call your pal and arrange to meet for lunch. You met and shared your vision with great expectation that your companion becomes your partner; however, you find yourself being turned down. You should not be surprised. It was meant to happen. While your idea was great, you were not prepared to present it.

Developing an app is not just sitting down and coding until it happens. Many other aspects must be taken into account such as:

  • The user interface: how does the application look?
  • The user experience: how does the application behave when interacting with the user?
  • The application flow: How does it flow from the main page where the user can go inside the application?
  • The name: Does the name already exist?
  • The market research: Are there other applications like it already existing? What differentiates your application from them? What it is unique or enhanced?
  • The website: No application will be taken seriously if there is not a website for it.
  • Publishing your application: Is your application a website? Then, what hosting do you need? Is your application a mobile app? Then, what are the requirements to publish such an application? Is your application for a desktop? Which OS will it support? How are you going to sell it?
  • Social Network: Do you need a presence on social networks to promote your app?
  • The maintenance: Who is going to take care of it? How will customers reach you when trouble shows up?
  • Do I need to add an End User License Agreement? How about a Disclosure Agreement?

The list goes on, but do not despair. There is a way that you can increase your chances of success and it is by doing your homework prior to presenting your idea.

So… You got your idea. You have it in your mind. You know how it should work and why it is so great. However, let’s face it, you do not know how to do programming nor you have the intention to learn about it, then what can you do? Well, let us tackle down the things that you can do that do not require any programming skills to accomplish it.

Draw a storyboard. You only need a pencil, a ruler, an eraser, and paper. Lots of paper. The idea is to draw how the program would look and how the program should behave when interacting with the user. What will happen when the user presses the arrow button? What text will show up in the text area? Check out how other applications do it and pick what you like about them. No technical skill required for that!
Draw the website. You should use four colors. Black and white, plus two colors of your choice. Keep it simple. Browse through the internet and use other websites as inspiration to build yours. What sections will the website have? What text and pictures will those sections hold? What can the users do on your website?

Do some market research. Are there already applications out there that do the same? What will your application provide that they do not have? Does the name you wish to use already exist?

Do you require funds? Can you obtain them if you have to? How much funds do you think you will need?

Do you need to create a corporation? What kind of corporation it is?

What else can you do that does not require programming?

In short, you need to do more than just present your inspiration. Before you present your idea to your Friendly Neighborhood Developer, you should already have a lot of work done. Then, your friend can worry about making time to do the coding because you are already on top of things. Your associate does not have to spend time designing, researching and doing extra work. He or she will be more than willing to join you on your enterprise.

 

Share

Express Gateway: Tips

Configuration: Order of Policies Matter

When working on Auth0, make sure that the order in which you set the pipelines’ policies matches the order in which the policies are listed:
(gateway.config.yaml)
Order of policies matter

Metrics: Use epimetheus or prom-client Package

You can use either prom-client or epimetheus.
Personally, I found easier to use the epimetheus package in Gateway Express:

'use strict';

const epimetheus = require('epimetheus');

module.exports = function (gatewayExpressApp) {
  epimetheus.instrument(gatewayExpressApp, {url: '/metrics'});
};

Something to considered is that some of the metrics display by epimetheus and prom-client differ.
For example, with epimetheus the http request duration are in milliseconds:

http_request_duration_milliseconds{quantile="0.01",method="get",path="/api/",cardinality="one",status="200"} 1

while in prom-client, the http request duration are in seconds:

http_request_duration_seconds_bucket{service="api",instance="api-3432dc43c4-h3eeg",le="0.005",path="/metrics",method="GET",apiVersion="1.0.0",status="200"} 466081

Swagger

Express Gateway use express. I tried different swagger packages; however, the closest results was to display all the endpoints from the admin side of Express Gateway.
Then, I decided to check the code implemented in the restify-swagger-jsdoc and it did the trick. Here is the modified code:

'use strict';

const swaggerJSDoc = require("swagger-jsdoc");
const path = require("path");
const fs = require("fs");
const mime = require("mime-types");
const swaggerUiPath = path.dirname(require.resolve('swagger-ui'));
const publicPath = '/api'.replace(/\/+$/, '');

const swaggerSpec = swaggerJSDoc({
	swaggerDefinition: {
		info: {
			title: 'API documentation',
			version: '0.0.1',
			description: 'API documentation'
		},
		host: undefined,
		basePath: '/',
		schemes: undefined,
		tags: []
	},
	apis: [
		'../**/routes/*.js'
	]
});

module.exports = function (gatewayExpressApp) {

	gatewayExpressApp.get(`${publicPath}/swagger.json`, (req, res) => {
		res.setHeader('Content-type', 'application/json');
		res.send(swaggerSpec);
	});

	gatewayExpressApp.get(new RegExp(publicPath + '\/?$'), (req, res) => {
		res.setHeader('Location', `${publicPath}/index.html`);
		res.sendStatus(302);
	});

	gatewayExpressApp.get(new RegExp(publicPath + '\/(.*)$'), (req, res) => {
		fs.readFile(path.resolve(swaggerUiPath, req.params[0]), (err, content) => {
			if (err) {
				res.sendStatus(500);
				res.send(`File ${req.params[0]} does not exist`);
				res.end;
				return;
			}
			if (req.params[0] === 'index.html') {
				let jsonFileUrl =  `${req.secure ? 'https' : 'http'}`.concat('://').concat(`${req.headers.host}${publicPath}/swagger.json`); 
				content = new Buffer(content.toString().replace('url = "http://petstore.swagger.io/v2/swagger.json"', `url = "${jsonFileUrl}"`)); 
			} 
			const contentType = mime.lookup(req.params[0]); 
			if (contentType !== false) { 
				res.setHeader('Content-Type', contentType); 
			} 
			res.write(content); 
			res.end(); 
		}); 
	}); 
};

 

Share

Using Acoustic Levitation to “Fake Gravity” in Space Stations

Last night, I got an idea while sleeping. How about using Acoustic Levitation to fake gravity in Space Stations.
Acoustic levitation is also known as ultrasonic levitation, acoustic tractors, and ultrasonic tractors.

The reason I said “fake” is that we are not really creating a gravity field but instead we are using the principle of acoustic levitation to  push the astronaut towards one direction (which would be considered the floor).

Note: I don’t know if this is a good idea since I don’t have the budget, the knowledge, the time or the way to experiment this concept; however, if this is actually plausible, then I think it would be interesting to experiment and find out.

I am not going to over over the details of Acoustic Levitation in this post since there are many places where its explained such as HowStuffWorks (check link here).

I leave you with some videos below showing how acoustic levitation works.

 

 

 

 

 

 

 

 

 

This is a video made by Argonne National Laboratory:

And here is a video of BristoLIG showing how to make one at home:
 

Share

Amazon’s Alexa Dev Conference (Denver, CO)

On April 12 of 2018, I went to Amazon’s Alexa Dev Conference at the Denver Marriott Tech Center in 4900 S Syracuse St., Denver, Colorado.

I meet with my friend and co-worker Matt Reddick.

The conference was nice. After doing the checking and obtained our badges, we got greeted by substantial breakfast which consisted of cooked ham, sausage, scramble eggs, and french toasts made with raising bread (I think).

We went over:

  • Introduction, a future projection and a general overview of Alexa’s related product and services.
  • Skill building basics such as Intent, Slots, handling request, AWS Lambda, and NodeJS.
  • AMAZON.LITERAL vs. AMAZON.SearchQuery Slot
  • Voice Design, conversation flow diagrams vs. frame diagrams, and Session Attributes.
  • New Alexa Skills Kit features, APIs, calling public APIs and Calling cloud services
  • Using AWS DynamoDB (vs. Session Attributes) and AWS IOT.

Part of the presentation required the participation of the audience which I found interesting.

At the end, there was a competition based on the Skill all participant created. The participation was optional.

ASK CLI

ask new --template
ask deploy
ask simulate -l "EN-US" -t "start quiz game"

Skill Code Generator for Skill Builder Language Models

GitHub Links

Other Links

 

Share