Redis how to store a number instead of string - javascript

I am trying to store a number as a value in Redis key. For example, I want to store a value of 4. and I don't want it to be stored as "4". Why I need this? Because when I retrieve this value back, I will be doing some bitwise op on it. If it stores as "4" (instead of 4), the value actually stored in Redis seems to be 52 (that is... 00110100 instead of 00000100).
You might wonder, why I don't use Redis bitops. The reason is I have to store an array of many bits. I don't want to be doing redis bitops in a loop. I just want to locally create an equivalent array and upload it by calling set command.
In Javascript, I tried doing
redis.set(key, 4)
obviously it didn't work. Then I tried
redis.set(key, "\x04")
This works. But how do I store an array of bytes by converting to this format? What am I missing here?

Internally, if all of the values of a data type are numeric, then the data is stored by its numeric representation. Otherwise, the data is stored as a string. You cannot force Redis to use a specific representation method for a single data point, as far as I know, and anyways - you'll always get the value as a string. You'll need to parse the value yourself and convert it into an integer, float, etc.

Related

What will passing an array with a single integer to Uint8Array do to the content passed to it?

I am experimenting with the Web Serial API (https://codelabs.developers.google.com/codelabs/web-serial/#3) to read and write data to an Arduino processor (atmega 328p). I couldn't figure out why the message being sent to the board goes through an Uint8Array in an example I found:
const sendToBoard(command) {
let message = new Uint8Array([command])
const writer = outputStream.getWriter();
writer.write(message);
writer.releaseLock();
}
What will passing an array do to the integer passed to Uint8Array and what is its relevance when sending it through a serial port to a board? Could it be done without it?
If you mean the example with the led matrix its explained why they use an array they store the values of the individual led in the matrix that way
arr.push(cb.checked === true ? 1 : 0);
and this is probably the reason why. So you can of course send single values over serial but its more efficient to do bursts of data instead of single values in that scenario (MatrixLED)
EDIT
The Uint8Array() constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax.
Read more here and in-depth readingWhy the dev choose to use exactly this method - you have to write an email to the author of the program.

How do you deal with decimal (,) and javascript?

I've an ASP.NET MVC application, C#, and some numbers into my Model in decimal type, which treat the fractional part as comma (i.e. 12,5).
I serialize them and send to the client using JSON, which correctly convert the comma to point:
var result = Json(new { Value = myModel.myValue }); // become Value = 12.5
Than I process the data client side, with some math function, getting the number value always with point (i.e. 12.5 * 3 = 37.5).
But, when I need to post back to the server the processed value, if I keep the point and I store the value into my Model (which is decimal, as said), it truncate the values after the point.
Do I really need to do result.replace('.', ',') before sending back data client side? Damn not so good. Best practices?
The paradox is that for mvc's jquery validator (being decimal required) I need to print the value into the input box with comma. The round-trip is crazy...
You can use stringify - This converts a JavaScript object into a string,
var myJSON = JSON.stringify(Yourvalue);
This may be helpful, rather than burdening the server with the client's wild choice of encoding, get the javascript to do it.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
It nicely turns 98.76 into 98,76 when passing it through 'it-IT'

MD5 hash is Different

On sql server : Out put : 0x5C8C8AAFE7AE37EA4EBDF8BFA01F82B8
SELECT HASHBYTES('MD5', convert(varchar,getdate(),112)+'mytest#+')
On JavaScript : Out put : 5c8c8aafe7ae37ea4ebdf8bfa01f82b8
//to get Md5 Hash bytes
vm.getMd5Hashbytes = function () {
var currentDate = moment().format('YYYYMMDD');
var md5Hash = md5.createHash(currentDate + 'mytest#+');
return md5Hash;
}
angular-md5 module
Q : Can you tell me why this difference ? SQL server shows 0x as prefix.Why ?
This is purely a formatting issue. Both versions are producing an identical sequence of bytes. SQL Server and node just have different conventions when it comes to presenting these bytes in a human readable format.
You can get similar formatting by specifically telling SQL Server how to format your binary data
declare #hashAsBinary varbinary(max)
declare #hashAsText char(32)
set #hashAsBinary = HASHBYTES('MD5', '20160818mytest#+')
set #hashAsText = LOWER(CONVERT(varchar(max), #hashAsBinary, 2))
select #hashAsText
Which outputs:
5c8c8aafe7ae37ea4ebdf8bfa01f82b8
See SQL Server converting varbinary to string
I am not sure how else to explain it but it will take more space than a comment allows for so I will post it as an answer.
Look at the source code that you are referencing. At the end (lines 210 and 212) you will see it converts the binary value to a hex string (and then to lower case which does not matter unless you opt for a string comparison at the end). End result = your JavaScript library returns a representation using the type string formatted as hex.
Your Sql function HASHBYTES on the other hand produces a varbinary typed result (which is a different type than string (varchar)).
So you have 2 different data types (each living on their own space as you have not pulled one to the other). You never mention where you are doing the comparison, ie: on the database or are you pulling from the database to script. Either way to do a comparison you need to convert one type so you are either comparing 2 strings types OR comparing two binary types. If you do not compare similar types you will get unexpected results or run time exceptions.
If you are comparing using strings AND in JavaScript then look at your library that you are referencing, it already has a call named wordToHex, copy and paste it and reuse it to convert your Sql result to a string and then do a string comparison (do not forget to compare case insensitive or also make it lower case).
Edit
WebApi is black box for me.It is a 3rd party service.I just need to send the security token as mentioned above.
Assuming that the type accepted by that web api is byt[] appending 0x to your string in javascript and then sending it to the web api should work as in the web api will then translate the incoming parameter as a byte array and execute the comparison using the correct types. As this is a black box there is no way to know for certain unless you either ask them if the accepted type is indeed a byte array or to test it.

how to filter out non-numeric values

I have a table (in a RethinkDB database) that has a bunch of documents with the field VIN0. This field almost always stores numbers, as intended.
I had some data corruption recently where there are some strings in place of numbers for the field VIN0. Queries I was using to manipulate this data now return the error: "e: Expected type NUMBER but found STRING in:"
I'd like to filter for the strings, but I can't seem to find them. Is there a way to use something like Number.isInteger() to filter out these items within RethinkDB?
Thanks!
You can use typeOf to find type of a field, or a element. Let's say you want to filter document with VIN0 is a number
r.db('db').table('table').filter(r.row('VIN0').typeOf().eq('NUMBER'))
You can also try to correct problem by using coereTo to convert string to number.
r.db('db').table('table')
.filter(r.row('VIN0').typeOf().eq('STRING'))
.update({VIN0: r.row('VIN0').coerceTo('NUMBER')})
Hope this helps.

Convert UUID to/from binary in Node

The project I work on switched to MySQL. The keys we use are UUID strings (like 43d597d7-2323-325a-90fc-21fa5947b9f3), but the database field, rather than be a string, is defined as binary(16) - 16-byte unsigned binary.
I understand that a UUID is basically a 16-byte binary, but I have no idea how to convert from/to a binary number.
I'm using node-mysql to access the database, and I tried using node-uuid to parse the UUID, but that yields an array of integers. I also tried using Node's Buffer, but that just yields a buffer object.
How do I convert a UUID string to fit into that field? And how do I turn a value I read from that field into a UUID?
Due to lack of time, I'll paste the comment that provided valid result(s) and modify the answer later so it's clearer.
Right, if you have a UUID 43d597d7-2323-325a-90fc-21fa5947b9f3 in that string format already in your JS app, you'd send the following query to MySQL:
SELECT col FROM table WHERE uuid_col = UNHEX(REPLACE('43d597d7-2323-325a-90fc-21fa5947b9f3', '-', ''));
If you want to pull data out and have UUID in readable format, you have to convert it to hexadecimal notation.
SELECT HEX(uuid_col) FROM table;
That one will give you the UUID without dashes. It appears that the node-uuid.parse method works if you give it hex string without dashes.
While N.B.'s answer works I stumbled upon another solution.
UUID v1 starts with character segments that are time based; however, the smallest units come first making distribution rather scattered in an index.
If you aren't stuck on the precise UUID v1 format than there is a NodeJS module that can generate unique IDs based on UUID v1 that also monotonically increase and scale about as well as auto incremented IDs. It also works with node-mysql.
Checkout: monotonic-id
An example with node-mysql:
var MID = require('monotonic-id');
var mid = new MID();
client.query('INSERT INTO `...` SET `mid`=?', mid.toBuffer(), function(err, res) {
...
})

Categories