ActionScript - Formatting Zero With NumberFormatter? - actionscript-3

i've assigned properties to a NumberFormatter object so that formatted values contain a leading zero, trailing zeros and a 2 decimal places.
the formatting works unless the number being formatted is 0. how can i format a 0 with the set properties so that 0 becomes 0.00?
var numFormat:NumberFormatter = new NumberFormatter(LocaleID.DEFAULT);
numFormat.leadingZero = true;
numFormat.trailingZeros = true;
numFormat.fractionalDigits = 2;
trace(numFormat.formatNumber(46)); //46.00
trace(numFormat.formatNumber(0.556849)); //0.56
trace(numFormat.formatNumber(0)); //0
[EDIT]
i've remedied this problem by manually appending the locale decimal separator with the desired number of fractionalDigits if the formatted number is 0:
if (myFormattedNumber.text == "0" && numFormat.fractionalDigits)
{
myFormattedNumber.appendText(numFormat.decimalSeparator);
for (var i:uint = 0; i < numFormat.fractionalDigits; i++)
myFormattedNumber.appendText("0");
}
i'm still very interested in knowing if this is a bug or a feature, but it seems like a oversight to me.

It's not sexy, but this was similar to what I used when I ran into a similar issue:
function numberFormat(number:*, maxDecimals:int = 2, forceDecimals:Boolean = false, siStyle:Boolean = true):String
{
var i:int = 0, inc:Number = Math.pow(10, maxDecimals), str:String = String(Math.round(inc * Number(number))/inc);
var hasSep:Boolean = str.indexOf(".") == -1, sep:int = hasSep ? str.length : str.indexOf(".");
var ret:String = (hasSep && !forceDecimals ? "" : (siStyle ? "," : ".")) + str.substr(sep+1);
if (forceDecimals) for (var j:int = 0; j <= maxDecimals - (str.length - (hasSep ? sep-1 : sep)); j++) ret += "0";
while (i + 3 < (str.substr(0, 1) == "-" ? sep-1 : sep)) ret = (siStyle ? "." : ",") + str.substr(sep - (i += 3), 3) + ret;
return str.substr(0, sep - i) + ret;
}
trace("zero: " + numberFormat(0, 2, true, false))
Full article here

How about Number(value).toFixed(2) ?

Related

Private key does not satisfy the curve requirements (ie. it is invalid);

Can Anyone help me, please? It gives me the error "throw new Error('Private key does not satisfy the curve requirements (i.e., it is invalid)');" it's been 5 days of debugging the code but still no luck; please correct the code and resend it.
const Wallet = require("ethereumjs-wallet");
var possible = "abcdef1234567890";
var basePrivateKey =
"0x09e8568e418bcb88662b7d0094db85b24177ad68ae715dc871d07a5ef4c2a1";
var charsMissing = 66 - basePrivateKey.length;
var targetPublicAddress = " 0x3fFacFff9858168c4E0c34C6f88Eb9e6F8576c6B";
var missingPart = "";
for (var i = 0; i < charsMissing; i++) {
missingPart = missingPart.concat(i);
}
var maxVal = parseInt(missingPart, 16);
console.log(
` \n searching for address : ${targetPublicAddress} \n base private key : ${basePrivateKey} \n missing chars : ${charsMissing} \n it will be quiet now. if you don't see anything below me, it's working on finding your key. \n If you see something below that doesn't say 'FOUND KEY!', you have an error \n `
);
function makeHexString(numb) {
var hex = numb.toString(16);
for (var i = 0; i < charsMissing - hex.length; i++) hex = "0" + hex;
return hex;
}
for (var i = 0; i <= maxVal; i++) {
for (var j = 0; j <= basePrivateKey.length; j++) {
// console.log(" i : " + i + " : j : " + j + "\n");
var endPrivateKey = makeHexString(i);
var privateKeyGuess = [
basePrivateKey.substring(0, j) +
endPrivateKey +
basePrivateKey.substring(j, basePrivateKey.length),
];
var wallet = Wallet.fromPrivateKey(Buffer.from(privateKeyGuess, "hex"));
var publicAddress = util.bufferToHex(wallet.getAddress());
if (publicAddress.toLowerCase() == targetPublicAddress.toLowerCase()) {
console.log(
`Found Private Key: ${privateKeyGuess}\n matching address \n \n \n \n`
);
process.exit();
}
}
if (i % 100000 === 0) {
console.log("checked", i, "keys");
}
}
Length of the basePrivateKey that you shared is 62 hex characters (prepended by 0x) which is 248 bits.
However the expected length is 64 hex characters (prepended by 0x), or 256 bits. In other words, your key is invalid because it's too short.

Execute Code as Fast as Possible

I am using node.js with my WebStorm IDE to parse a large JSON file (~500 megabytes). Here is my code:
fs = require("fs");
fs.readFile('C:/Users/.../Documents/AAPL.json', 'utf8', function (err,data) {
for (i = 0; i < 1000; i++) {
var hex = JSON.parse(data)[i]._source.layers.data["data.data"];
var askPrice = parseInt(hex.substring(215, 239).split(":").reverse().join(""),16);
var bidPrice = parseInt(hex.substring(192, 215).split(":").reverse().join(""),16);
var symbol = hex.substring(156, 179);
var timestamp = hex.substring(132, 155);
var askSize = hex.substring(240, 251);
var bidSize = hex.substring(180, 191);
var price = String((+bidPrice+askPrice)/2);
var realprice = price.slice(0, price.length - 4) + "." + price.slice(price.length - 4);
function hex2a(hexx) {
var hex = hexx.toString();
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
if(JSON.parse(data)[i]._source.layers.data["data.len"] == 84 && realprice.length == 8 && +realprice <154 && +realprice >145) {
console.log(i + " " + hex2a(symbol.replace(/:/g, "")) + " sold for " + realprice + " at " + parseInt(timestamp.split(":").reverse().join(""), 16));
}
}
});
The problem I am running into however is that my IDE is parsing this file at an extremely slow speed, roughly 1 iteration a second. I do not think this is because I have a slow computer, for I have a high end rig with a core i7 7700k and a gtx 1070. I tried executing the code in the console with the same result. I tried trimming down the code and again I achieved the same speed:
fs = require("fs");
fs.readFile('C:/Users/Brandt Winkler Prins/Documents/AAPL.json', 'utf8', function (err,data) {
for (i = 0; i < 12000; i++) {
var hex = JSON.parse(data)[i]._source.layers.data["data.data"];
var askPrice = parseInt(hex.substring(215, 239).split(":").reverse().join(""),16);
var bidPrice = parseInt(hex.substring(192, 215).split(":").reverse().join(""),16);
var price = String((+bidPrice+askPrice)/2);
var realprice = price.slice(0, price.length - 4) + "." + price.slice(price.length - 4);
if(+realprice <154 && +realprice >145) {
console.log(realprice);
}
}
});
How should I execute my code to get my data as fast as possible?
You're running JSON.parse(data) every iteration, that might take quite some time for a 500MB json file.
The solution would be to move it out of the loop and reuse the parsed object:
var obj = JSON.parse(data);
for (...

Get total rows filtered by if() statement in google apps scripts

I've got this fn().
Is there any simple way to return the number of filtered rows by this conditional statement in Google app scripts?
function getGlobers(globers, project){
var body = "";
var data = globers.getValues();
for( i = 0; i < data.length; i++ ){
if( data[i][2] == project ){
body += "<tr><td style=" + STYLE.TD + ">" + data[i].join("</td><td style=" + STYLE.TD + ">") + "</td></tr>";
}
}
return body;
}
Thanks.
for example (see comments in code)
function getGlobers(globers, project){
var body = "";
var n = 0; // use a variable to count
var data = globers.getValues();
for( i = 0; i < data.length; i++ ){
if( data[i][2] == project ){
n++;// increment each time condition is true
body += "<tr><td style=" + STYLE.TD + ">" + data[i].join("</td><td style=" + STYLE.TD + ">") + "</td></tr>";
}
}
return [body,n];// return an array of 2 values
}
Usage :
var result = getGlobers(range,project);
Logger.log('array result = '+result);
Logger.log('body (string) = '+result[0]);
Logger.log('length (integer) = '+result[1]);
note : instead of an array you could also return an object with 2 properties... a matter of choice.
EDIT : an example using object properties :
function getGlobers(globers, project){
var body = "";
var n = 0;
var result = {};
var data = globers.getValues();
for( i = 0; i < data.length; i++ ){
if( data[i][2] == project ){
n++;
body += "<tr><td style=" + STYLE.TD + ">" + data[i].join("</td><td style=" + STYLE.TD + ">") + "</td></tr>";
}
}
result['body'] = body;
result['length'] = n;
return result;
}
Usage :
var result = getGlobers(range,project);
Logger.log('body = '+result.body);
Logger.log('length = '+result.length);

Get rowIndex = -1 in Chrome. In IE, FF works fine

I would like for first row and column of cells to be assigned a letter and a digit (like an excel table), with rows (cell.cellIndex == 0), no problems it's working fine, but for every column (row.rowIndex == 0 && cell.cellIndex != 0) it works only in browsers IE and FF, in Chrome it's not working. It gets a rowIndex = -1
for (var i = 0; i <= inpRow.value; i++) {
array[i] = new Array();
arrayFunc[i] = new Array();
row = document.createElement('tr')
table.appendChild(row);
for (var j = 0; j <= inpCol.value; j++) {
cell = document.createElement('td');
row.appendChild(cell);
cell.setAttribute('id', (i) + "." + (j));
if (row.rowIndex == 0 && cell.cellIndex != 0) { // row.rowIndex in chrome gets -1
if ((j-1) >= 26) { // j-1 to asign letter from the second cell
var tmp = (j-1) / 26;
for (var f = 0; f < parseInt(tmp, 10) ; f++) {
for (var k = 0; k <= (j-1) - (26 * parseInt(tmp, 10)) ; k++) {
cell.innerHTML = '<b>' + String.fromCharCode(f + 65) + String.fromCharCode(k + 65) + '</b>';
}
}
} else {
cell.innerHTML = '<b>' + String.fromCharCode(j + 64) + '</b>';
}
cell.style.backgroundColor = 'gray';
} else if (cell.cellIndex == 0) {
cell.innerHTML = '<b>' + i + '</b>';
cell.style.backgroundColor = 'gray';
}
}
I have alternative variant using not row and cell Index, but using id:
cell.id.substr(0, 1) == '0' && cell.id != '0.0'
and it works fine in all browsers, but i would like to use cell and row Index:
row.rowIndex == 0 && cell.cellIndex != 0
Full code
It seems like both Chrome and Safari assign a row index of -1 to each row you append to a table using the "document.createElement('tr');" approach. Then there is no point searching for or comparing rows by index since each row is simply -1.
Instead of the following 2 lines just before the start of you 2nd for loop:
row = document.createElement('tr')
table.appendChild(row);
use:
row = table.insertRow(-1);
This should do exactly the same job, but Chrome and Safari will now insert correct indexes for each row.
It was a bug in the Webkit layout engine, (that moved to the forked Blink engine as well). This is why it works well in Firefox but not in Chrome (Blink) or Safari (Webkit).
The bug is reported here.

Nine-patch images for web development [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I'm wondering if there is something like 9-patch in Android, but for web development?
Disclosure: I have no idea about web development at all, but I was curious to know if it exists. And a simple web search with the term 9-patch didn't bring up any related results, so I figured it has either another term or it doesn't exist or is not used widely enough.
Anyone knows?
Yes. It is used for border-image in CSS 3:
http://www.css3.info/preview/border-image/
http://www.w3.org/TR/css3-background/#border-images
If you're still interested I created a Javascript file that uses canvas to create real nine patch image support for the web. The open source project can be found here:
https://github.com/chrislondon/9-Patch-Image-for-Websites
Well, I took the trouble to correct deserts errors I found in the link above.
Knowing NinePath android is a useful tool adding dynamic painting and recognition of padding (which was missing in the previous pluying). I could add one few scripts for complete functionality.
Replace the following code in the library path9.js!
function NinePatchGetStyle(element, style)
{
if (window.getComputedStyle)
{
var computedStyle = window.getComputedStyle(element, "");
if (computedStyle === null)
return "";
return computedStyle.getPropertyValue(style);
}
else if (element.currentStyle)
{
return element.currentStyle[style];
}
else
{
return "";
}
}
// Cross browser function to find valid property
function NinePatchGetSupportedProp(propArray)
{
var root = document.documentElement; //reference root element of document
for (var i = 0; i < propArray.length; i++)
{
// loop through possible properties
if (typeof root.style[propArray[i]] === "string")
{
//if the property value is a string (versus undefined)
return propArray[i]; // return that string
}
}
return false;
}
/**
* 9patch constructer. Sets up cached data and runs initial draw.
* #param {Dom Element} div El Elemento dom en donde se pinta el ninepath
* #param {function} callback La funcion que se llamara cuando se termina
* la carga de la imagen y el pintado del elemento div.
* #returns {NinePatch} Un objeto nine path
*/
function NinePatch(div,callback)
{
this.div = div;
this.callback =callback;
this.padding = {top:0,left:0,right:0,bottom:0};
// Load 9patch from background-image
this.bgImage = new Image();
this.bgImage.src = NinePatchGetStyle(this.div, 'background-image').replace(/"/g, "").replace(/url\(|\)$/ig, "");
var este = this;
this.bgImage.onload = function()
{
este.originalBgColor = NinePatchGetStyle(este.div, 'background-color');
este.div.style.background = 'none';
// Create a temporary canvas to get the 9Patch index data.
var tempCtx, tempCanvas;
tempCanvas = document.createElement('canvas');
tempCanvas.width = este.bgImage.width;
tempCanvas.height = este.bgImage.height;
tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(este.bgImage, 0, 0);
// Obteniendo el padding lateral derecho
var dataPad = tempCtx.getImageData(este.bgImage.width-1,0,1,este.bgImage.height).data;
var padRight = este.getPadBorder(dataPad,este.bgImage.width,este.bgImage.height);
este.padding.top = padRight.top;
este.padding.bottom = padRight.bottom;
dataPad = tempCtx.getImageData(0,este.bgImage.height-1,este.bgImage.width,1).data;
var padBottom = este.getPadBorder(dataPad,este.bgImage.width,este.bgImage.height);
este.padding.left = padBottom.top;
este.padding.right = padBottom.bottom;
// Loop over each horizontal pixel and get piece
var data = tempCtx.getImageData(0, 0, este.bgImage.width, 1).data;
// Use the upper-left corner to get staticColor, use the upper-right corner
// to get the repeatColor.
var tempLength = data.length - 4;
var staticColor = data[0] + ',' + data[1] + ',' + data[2] + ',' + data[3];
var repeatColor = data[tempLength] + ',' + data[tempLength + 1] + ',' +
data[tempLength + 2] + ',' + data[tempLength + 3];
este.horizontalPieces = este.getPieces(data, staticColor, repeatColor);
// Loop over each horizontal pixel and get piece
data = tempCtx.getImageData(0, 0, 1, este.bgImage.height).data;
este.verticalPieces = este.getPieces(data, staticColor, repeatColor);
// use this.horizontalPieces and this.verticalPieces to generate image
este.draw();
este.div.onresize = function()
{
este.draw();
};
if(callback !== undefined)
{
if (typeof(callback) === "function")
callback();
}
};
}
// Stores the HTMLDivElement that's using the 9patch image
NinePatch.prototype.div = null;
// Padding
NinePatch.prototype.padding = null;
// Get padding
NinePatch.prototype.callback = null;
// Stores the original background css color to use later
NinePatch.prototype.originalBG = null;
// Stores the pieces used to generate the horizontal layout
NinePatch.prototype.horizontalPieces = null;
// Stores the pieces used to generate the vertical layout
NinePatch.prototype.verticalPieces = null;
// Stores the 9patch image
NinePatch.prototype.bgImage = null;
// Gets the horizontal|vertical pieces based on image data
NinePatch.prototype.getPieces = function(data, staticColor, repeatColor)
{
var tempDS, tempPosition, tempWidth, tempColor, tempType;
var tempArray = new Array();
tempColor = data[4] + ',' + data[5] + ',' + data[6] + ',' + data[7];
tempDS = (tempColor === staticColor ? 's' : (tempColor === repeatColor ? 'r' : 'd'));
tempPosition = 1;
for (var i = 4, n = data.length - 4; i < n; i += 4)
{
tempColor = data[i] + ',' + data[i + 1] + ',' + data[i + 2] + ',' + data[i + 3];
tempType = (tempColor === staticColor ? 's' : (tempColor === repeatColor ? 'r' : 'd'));
if (tempDS !== tempType)
{
// box changed colors
tempWidth = (i / 4) - tempPosition;
tempArray.push(new Array(tempDS, tempPosition, tempWidth));
tempDS = tempType;
tempPosition = i / 4;
tempWidth = 1;
}
}
// push end
tempWidth = (i / 4) - tempPosition;
tempArray.push(new Array(tempDS, tempPosition, tempWidth));
return tempArray;
};
NinePatch.prototype.getPadBorder = function(dataPad,width,height)
{
var staticRight = dataPad[0] + ',' + dataPad[1] + ',' + dataPad[2] + ',' + dataPad[3];
var pad={top:0,bottom:0};
// Padding para la parte superior
for (var i=0;i<dataPad.length;i+=4)
{
var tempColor = dataPad[i] + ',' + dataPad[i + 1] + ',' + dataPad[i + 2] + ',' + dataPad[i + 3];
if(tempColor !==staticRight)
break;
pad.top++;
}
// padding inferior
for (var i=dataPad.length-4;i>=0;i-=4)
{
var tempColor = dataPad[i] + ',' + dataPad[i + 1] + ',' + dataPad[i + 2] + ',' + dataPad[i + 3];
if(tempColor !==staticRight)
break;
pad.bottom++;
}
return pad;
};
// Function to draw the background for the given element size.
NinePatch.prototype.draw = function()
{
var dCtx, dCanvas, dWidth, dHeight;
if(this.horizontalPieces === null)
return;
dWidth = this.div.offsetWidth;
dHeight = this.div.offsetHeight;
dCanvas = document.createElement('canvas');
dCtx = dCanvas.getContext('2d');
dCanvas.width = dWidth;
dCanvas.height = dHeight;
var fillWidth, fillHeight;
// Determine the width for the static and dynamic pieces
var tempStaticWidth = 0;
var tempDynamicCount = 0;
for (var i = 0, n = this.horizontalPieces.length; i < n; i++)
{
if (this.horizontalPieces[i][0] === 's')
tempStaticWidth += this.horizontalPieces[i][2];
else
tempDynamicCount++;
}
fillWidth = (dWidth - tempStaticWidth) / tempDynamicCount;
// Determine the height for the static and dynamic pieces
var tempStaticHeight = 0;
tempDynamicCount = 0;
for (var i = 0, n = this.verticalPieces.length; i < n; i++)
{
if (this.verticalPieces[i][0] === 's')
tempStaticHeight += this.verticalPieces[i][2];
else
tempDynamicCount++;
}
fillHeight = (dHeight - tempStaticHeight) / tempDynamicCount;
// Loop through each of the vertical/horizontal pieces and draw on
// the canvas
for (var i = 0, m = this.verticalPieces.length; i < m; i++)
{
for (var j = 0, n = this.horizontalPieces.length; j < n; j++)
{
var tempFillWidth, tempFillHeight;
tempFillWidth = (this.horizontalPieces[j][0] === 'd') ?
fillWidth : this.horizontalPieces[j][2];
tempFillHeight = (this.verticalPieces[i][0] === 'd') ?
fillHeight : this.verticalPieces[i][2];
// Stretching :
if (this.verticalPieces[i][0] !== 'r') {
// Stretching is the same function for the static squares
// the only difference is the widths/heights are the same.
dCtx.drawImage(
this.bgImage,
this.horizontalPieces[j][1], this.verticalPieces[i][1],
this.horizontalPieces[j][2], this.verticalPieces[i][2],
0, 0,
tempFillWidth, tempFillHeight);
} else {
var tempCanvas = document.createElement('canvas');
tempCanvas.width = this.horizontalPieces[j][2];
tempCanvas.height = this.verticalPieces[i][2];
var tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(this.bgImage,
this.horizontalPieces[j][1], this.verticalPieces[i][1],
this.horizontalPieces[j][2], this.verticalPieces[i][2],
0, 0,
this.horizontalPieces[j][2], this.verticalPieces[i][2]);
var tempPattern = dCtx.createPattern(tempCanvas, 'repeat');
dCtx.fillStyle = tempPattern;
dCtx.fillRect(
0, 0,
tempFillWidth, tempFillHeight);
}
// Shift to next x position
dCtx.translate(tempFillWidth, 0);
}
// shift back to 0 x and down to the next line
dCtx.translate(-dWidth, (this.verticalPieces[i][0] === 's' ? this.verticalPieces[i][2] : fillHeight));
}
// store the canvas as the div's background
var url = dCanvas.toDataURL("image/png");
var tempIMG = new Image();
var _this = this;
tempIMG.onload = function(event)
{
_this.div.style.background = _this.originalBgColor + " url(" + url + ") no-repeat";
};
tempIMG.src = url;
};
The usage is the following:
var elemDom = document.getElementById("idDiv");
var background = "border.9.png";
if (background.match(/\.9\.(png|gif)/i)) // Es nine path?
{
elemDom.style.backgroundRepeat = "no-repeat";
elemDom.style.backgroundPosition = "-1000px -1000px";
elemDom.style.backgroundImage = "url('"+background+"')";
var ninePatch = new NinePatch(elemDom,function()
{
elemDom.style.paddingLeft = ninePatch.padding.left;
elemDom.style.paddingTop = ninePatch.padding.top;
elemDom.style.paddingRight = ninePatch.padding.right;
elemDom.style.paddingBottom = ninePatch.padding.bottom;
});
}
I forked https://github.com/chrislondon/9-Patch-Image-for-Websites and fixed the bugs based on the above comments. Now the 9-Patch javascript works well. Please check out https://github.com/blackmonkey/jQuery-9-Patch