RSS

Category Archives: dev

POST a file, read a JSON response

Here’s a trick to send a file to a server AND read a response from it, in the same context.
I used it with a Node.js server (Express + busboy) and it worked like a charm.

When using HTML forms, you can submit stuff to a server but you can’t read a response from it.
If you need some kind of “send data” → (do something server side) → “read response” it can be painful.

I wrote a workaround to manage this kind of situation. It is pretty simple:
– prepare a form as usual
– block the original event
– build an ajax request as a POST method

Here’s the code

 
Leave a comment

Posted by on 2017/07/14 in dev, Uncategorized

 

Tags: , ,

Promises rejection (..but with style)

I find handy define this kind of function in my code:

function if_error(reject, err) {
  if (err) {
    console.error(err);
    reject(err);
  }
}

Now when I’ll need to handle a rejection, my code will be

something.can('go-wrong', (err) => {
  if_error(reject, err);
  ...

It’s something between pure functional programming and very readable code.

 
Leave a comment

Posted by on 2017/05/16 in dev

 

Tags: ,

Arduino colors!

Last night I was playing with a Neopixel Ring controlled by a Wemos Mini, when I decided to attach a potentiometer to manually handle the colors.
Now, when you read from an analog source you’ll get a value in an interval, like [0, 1024]. The problem with this kind of value is that it is a single number that needs to be mapped in three r,g,b values (ring.setPixelColor(n, red, green, blue);)!

After trying a good way to map [0,1024] => {[0,255], [0,255], [0,255]}, I remembered there are MANY ways to define colors: RGB, CMYC, HSV, …Wait! HSV? It’s perfect!
It’s like handling polar coordinates where you have an angle that describes the Hue and it is a number between 0 and 360. The other parameters are two vectors and describe the Saturation and the Brightness. These values can be set constant to 1, in my case.

First let’s map the analog value to a Hue value:

int val = analogRead(A0); // 0 - 1024
float h = 360.0 * ((float)val / (float)1024); // 0 - 360

then use this function to convert. Note that r,g and b are by ref.

/**
* HSV to RGB color conversion
* The hue value H runs from 0 to 360 degrees.
* The saturation S is the degree of strength or purity and is from 0 to 1. Purity is how much white is added to the color, so S=1 makes the purest color (no white).
* Brightness V also ranges from 0 to 1, where 0 is the black.
* R,G,B are between 0 and 255.
* http://www.cs.rit.edu/~ncs/color/t_convert.html
*/
void HSVtoRGB(float h, float s, float v, float *r, float *g, float *b)
{
    int i;
    float f, p, q, t;

    if (s == 0) {
        // achromatic (grey)
        *r = *g = *b = v;
    }
    else {
        h /= 60;      // sector 0 to 5
        i = floor(h);
        f = h - i;      // factorial part of h
        p = v * ( 1 - s );
        q = v * ( 1 - s * f );
        t = v * ( 1 - s * ( 1 - f ) );

        switch( i ) {
            case 0:
                *r = v;
                *g = t;
                *b = p;
                break;
            case 1:
                *r = q;
                *g = v;
                *b = p;
                break;
            case 2:
                *r = p;
                *g = v;
                *b = t;
                break;
            case 3:
                *r = p;
                *g = q;
                *b = v;
                break;
            case 4:
                *r = t;
                *g = p;
                *b = v;
                break;
            default:    // case 5:
                *r = v;
                *g = p;
                *b = q;
                break;
        }
        
        *r *= 255;
        *g *= 255;
        *b *= 255;
    }
}
 
Leave a comment

Posted by on 2017/03/24 in dev

 

Tags: ,

Extract the XPath of every node from an XML. Uh, in SQL Server

Disclaimer: this is SQL Server 2005 compliant! =O

Ok, we’re on a database and we want tables:

EXEC sp_xml_preparedocument @idoc OUTPUT, @xml
SELECT 
    ISNULL(id,'') AS id
    , parentid
    , ROW_NUMBER() OVER (
	PARTITION BY parentid,localname
	ORDER BY id
    ) AS idx
    , ROW_NUMBER() OVER (
	PARTITION BY parentid
	ORDER BY id
    ) AS position
    , nodetype
    , CASE
	WHEN (nodetype = 3) THEN 'text()'
	WHEN (nodetype = 2) THEN '@' + localname
	ELSE localname
    END as localname
    , text
  INTO #nodetree
  FROM OPENXML(@idoc, '/', 3)
EXEC sp_xml_removedocument @idoc

ALTER TABLE #nodetree ADD PRIMARY KEY (id)
SELECT * FROM #nodetree

Now let’s use a recursive CTE to build the XPath of every text node

;WITH cte AS (
  SELECT
    parentid
    , id
    , N'/' + localname + '[' + cast(idx as nvarchar(100)) + ']' AS xpath
    , text
  FROM #nodetree WHERE nodetype = 3
  UNION ALL
  SELECT
    parent.parentid
    , node.id
    , N'/' + localname + '[' + cast(idx as nvarchar(100)) + ']' + xpath
    , node.text
  FROM cte AS node
  INNER JOIN #nodetree parent on parent.id = node.parentid
)
SELECT
  REPLACE(xpath, '/text()[1]', '') as xpath, text
  FROM cte
  WHERE parentid IS NULL

Finally check the XPath built:

select 
  node.value(N'insert here one xpath row from the CTE', nvarchar(1000))
  from @xml.nodes(N'.') as T(node)
 
Leave a comment

Posted by on 2016/12/23 in dev

 

Tags: , , ,

js timestamp

Sometimes while logging js I need to have a timestamp in the beggining of the row. There are libraries to manage timestamps and to print wonderful logs, but sometimes the needs are only to make some console.log while debugging.

This is my one-line way to handle it:

function timestamp() {
  return (new Date).toISOString().match(/([0-9]{2}:[0-9]{2}:[0-9]?[0-9].[0-9]{3})/g)[0];
}

or “keep only the time part of an ISO formatted timestamp”.

 
Leave a comment

Posted by on 2016/12/16 in dev

 

Tags: , ,

youtubing

I was studying (rev-eng) how does YouTube works when I’ve found this post about the get_video_info call.

After some digging and some trying I’ve made a node.js module to make the request and parse the response, without the need for the official API.

Here’s the link:
https://github.com/pste/youtube.get-video-info

 
Leave a comment

Posted by on 2016/07/29 in dev

 

Tags: , , , ,

How-to handle app parameters in Node.js

Let say you have to handle one or more custom parameters in your Node.js app. There are many ways to do that, here are my fab 4.
In these examples I’ll read a debug (on/off) and a port (number) parameters.

UPDATED:
keep an eye on these two modules:

 

Passing them to the interpreter

node app.js --debug --port 8080
var dbg = (process.argv.indexOf('--debug') >= 0);
var port = 0;
if (process.argv.indexOf('--port') >= 0 && (process.argv.indexOf('--port')  +1 < process.argv.length))
  port = process.argv.indexOf('--port') + 1;

 

Adding them to the package.json

 ...
 "config": {
   "port": 8080,
   "debug": "true"
 },
 ...
var dbg = (process.env.npm_package_config_debug == 'true');
var port = process.env.npm_package_config_port || 0;

If you’re using PM2, you also need to create an ecosystem.json file (https://keymetrics.io/2014/06/25/ecosystem-json-deploy-and-iterate-faster/) to correctly handle the package.json stuff.

Using a local json file (params.json)

{
  "debug": "true",
  "port": 8080
}
var pars = require('./params.json');
console.log(pars.port, pars.debug);

 

Using an environment variable (not my preferred …)

export debug=true
export port=8080
var dbg = (process.env.debug == 'true');
var port = process.env.port || 0;
 
Leave a comment

Posted by on 2016/07/07 in dev

 

Tags: , ,