I try to reduce the size of my Fontawesome icon fonts.
First I parse my css file for retrieving all the unicode codes
with
const numericValue = parseInt(unicodeHex, 16)
const character = String.fromCharCode(numericValue)
glyphList.push(character)
Next I generate a string with
const glyphListStr = glyphlist.join(' ')
console.log(glyphListStr)
It gives (tested it contains \uF5EC \uE00F \uF4CD \uE022 \uE2CE \uF3CA ) it is OK
My strange behavior.
Working code
const fontmin = new Fontmin()
.use(Fontmin.glyph({
text: ' ' ,//glyphListStr
hinting: false
}))
But when I use the variable it fails:
What I make wrong?
const fontmin = new Fontmin()
.use(Fontmin.glyph({
text: glyphListStr, //' '
hinting: false
}))
After many hours I decided to upgrade my typescript to 4.8.2
and I cannot understand why but now it is working !
It was probably a wrong type somewhere.
Related
I am working on a project where I require to format incoming numbers in the following way:
###.###
However I noticed some results I didn't expect.
The following works in the sense that I don't get an error:
console.log(07);
// or in my case:
console.log(007);
Of course, it will not retain the '00' in the value itself, since that value is effectively 7.
The same goes for the following:
console.log(7.0);
// or in my case:
console.log(7.000);
JavaScript understands what I am doing, but in the end the actual value will be 7, which can be proven with the following:
const leadingValue = 007;
const trailingValue = 7.00;
console.log(leadingValue, trailingValue); // both are exactly 7
But what I find curious is the following: the moment I combine these two I get a syntax error:
// but not this:
console.log(007.000);
1) Can someone explain why this isn't working?
I'm trying to find a solution to store numbers/floats with the exact precision without using string.
2) Is there any way in JS/NodeJS or even TypeScript to do this without using strings?
What I currently want to do is to receive the input, scan for the format and store that as a separate property and then parse the incoming value since parseInt('007.000') does work. And when the user wants to get this value return it back to the user... in a string.. unfortunately.
1) 007.000 is a syntax error because 007 is an octal integer literal, to which you're then appending a floating point part. (Try console.log(010). This prints 8.)
2) Here's how you can achieve your formatting using Intl.NumberFormat...
var myformat = new Intl.NumberFormat('en-US', {
minimumIntegerDigits: 3,
minimumFractionDigits: 3
});
console.log(myformat.format(7)); // prints 007.000
Hi
You can use an aproach that uses string funtions .split .padStart and .padEnd
Search on MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
Here you have an example:
const x = 12.1;
function formatNumber( unformatedNumber) {
const desiredDecimalPad = 3;
const desiredNonDecimalPad = 3;
const unformatedNumberString = unformatedNumber.toString();
const unformatedNumberArr = unformatedNumberString.split('.');
const decimalStartPadded = unformatedNumberArr[0].padStart(desiredDecimalPad, '0');
const nonDecimalEndPadded = unformatedNumberArr[1].padEnd(desiredNonDecimalPad, '0');
const formatedNumberString = decimalStartPadded + '.' + nonDecimalEndPadded;
return formatedNumberString;
}
console.log(formatNumber(x))
To generate dynamic PDF files, I'm using PDFKit.
The generation works fine, but I'm having trouble displaying arabic characters, even after installing an arabic font.
Also, Arabic text is generated correctly, but I believe the word order is incorrect.
As an example,
I'm currently using pdfkit: "0.11.0"
Text: مرحبا كيف حالك ( Hello how are you )
Font: Amiri-Regular.ttf
const PDFDocument = require("pdfkit");
var doc = new PDFDocument({
size: [595.28, 841.89],
margins: {
top: 0,
bottom: 0,
left: 0,
right: 0,
},
});
const customFont = fs.readFileSync(`${_tmp}/pdf/Amiri-Regular.ttf`);
doc.registerFont(`Amiri-Regular`, customFont);
doc.fontSize(15);
doc.font(`Amiri-Regular`).fillColor("black").text("مرحبا كيف حالك");
doc.pipe(fs.createWriteStream(`${_tmp}/pdf/arabic.pdf`));
doc.end();
OUTPUT:
PDF with arabic text
this problem allowed me to go through here, but unfortunately I am not convinced by the answers posted and even add a library to change the direction of the text with pdfkit.
after several minutes on the pdfkit guide docs, here is the solution:
doc.text("مرحبا كيف حالك", {features: ['rtla']})
You are right the order of the Arabic words are wrong and you habe to set-up the direction of the sentence
try to use this
doc.rtl(true);
or This as a configuration for single line or text
doc.font(`Amiri-Regular`).fillColor("black").text("مرحبا كيف حالك", {rtl: true});
Answer adapted from the info here:
install the package: npm install twitter_cldr
Run this function to generate the text:
const TwitterCldr = TwitterCldrLoader.load("en");
private maybeRtlize(text: string) {
if (this.isHebrew(text)) {
var bidiText = TwitterCldr.Bidi.from_string(text, { direction: "RTL" });
bidiText.reorder_visually();
return bidiText.toString();
} else {
return text;
}
}
Value = maybeRtlize("مرحبا كيف حالك")
doc.font(`Amiri-Regular`).fillColor("black").text(Value);
Another method that's also possible is to reverse the text (using something such as text.split(' ').reverse().join(' ');, however while this will work for simple arabic text, it will start having issues the moment you introduce English-numericals for example. so the first method is recommended.
I would suggest you do one of the following depending on your needs
1 ) if you have a low number of doc.text functions used to generate the document you can add {features: ['rtla']} as second parameter to the function as follows:
doc.text('تحية طيبة وبعد', { features: ['rtla'] });
2 ) if you have many calls to doc.text instead of adding {features: ['rtla']} as a parameter to each call, you can reverse all you text before hand by iterating on your data object and reversing the word order as follows:
let str = "السلام عليكم ورحمة الله وبركاته";
str = str.split(' ').reverse().join(' ');
doc.text(str);
I am trying to parse the xref stream from PDF in JavaScript. I managed to succesfully isolate the stream itself (I checked that it's ok by comparing it in debugging mode with the value between steram. and endstream tags in PDF.
However, when I try to inflate it using pako lib, I get an error saying: ERROR incorrect header check.
The compression method is FlateDecode, which can be seen from the dictionary.
Here is the code in question:
const dict = pdfStr.slice(pdf.startXRef);
const xrefStreamStart = this.getSubstringIndex(dict, 'stream', 1) + 'stream'.length + 2;
const xrefStreamEnd = this.getSubstringIndex(dict, 'endstream', 1) + 1;
const xrefStream = dict.slice(xrefStreamStart, xrefStreamEnd);
const inflatedXrefStream = pako.inflate(this.str2ab(xrefStream), { to: 'string' });
pdfStr is the whole PDF read as a string, while *pdf.startXRef* holds the value of the position of the xref stream object.
Here's the whole PDF if someone wants to have a look: https://easyupload.io/lzf9he
EDIT: As mcernak has suggested I had a problem that I included /r and /n in the stream. However, now that I corrected the code I got a different error: invalid distance too far back
The stream content is located between stream\r\n and \r\nendstream.
You need to take into account those two additional characters (\r\n) at the beginning and at the end to read the correct data:
const dict = pdfStr.slice(pdf.startXRef);
const xrefStreamStart = this.getSubstringIndex(dict, 'stream', 1) + 'stream'.length + 2;
const xrefStreamEnd = this.getSubstringIndex(dict, 'endstream', 1) - 2;
const xrefStream = dict.slice(xrefStreamStart, xrefStreamEnd);
const inflatedXrefStream = pako.inflate(this.str2ab(xrefStream), { to: 'string' });
I want to carry out variable substitutions on a string (I've already ruled out template literals because the string has to be stored and evaluated later).
Mustache or something like it would seem like a contender, but I want to know if the substitution was incomplete. In this case, it's to produce urls, so missing parts mean invalid urls:
Testing this out in node:
var Mustache = require('mustache');
var result = Mustache.render("/someurl/{{path1}}/{{path2}}/", {path1:"my-path-to-1"})
console.log(`result:${result}:`)
This happens without a problem, but the resulting url is useless because Mustache silently replaced the missing path2 with an empty string. What I would like to see is an exception getting thrown (best) or failing that an easy way to recognize that not everything was substituted.
Note: the template string is arbitrary and so are the substitution object's contents.
output:
result:/someurl/my-path-to-1//:
This is the Python equivalent that I am looking for:
res = "/someurl/%(path1)s/%(path2)s/" % {"path1":"my-path-to-1"}
output:
KeyError: 'path2'
I ended up using sprintf, which has the benefit of having a different format than Mustache (or Django) so that you can embed it in data-url or the like:
const sprintf = require("sprintf-js").sprintf;
var o_substit = {
path1 : "mypath1"
};
var T_URL = "/someurl/%(path1)s/%(path2)s/";
console.log(`\nT_URL:${T_URL}, substitutions:`);
try {
console.dir(o_substit);
console.log("expecting a failure...")
var url = sprintf(T_URL, o_substit);
console.log(` url:${url}:`);
}
catch (e){
console.log(` exception:${e}`);
};
var o_substit = {
path1 : "mypath1"
,path2 : "mypath2"
};
console.log(`\nT_URL:${T_URL}, substitutions:`);
try{
console.dir(o_substit);
console.log("\nexpecting a success:")
var url = sprintf(T_URL, o_substit);
console.log(` url:${url}:`);
}
catch (e){
console.log(` exception:${e}`);
};
output:
T_URL:/someurl/%(path1)s/%(path2)s/, substitutions:
{ path1: 'mypath1' }
expecting a failure...
exception:Error: [sprintf] property 'path2' does not exist
T_URL:/someurl/%(path1)s/%(path2)s/, substitutions:
{ path1: 'mypath1', path2: 'mypath2' }
expecting a success:
url:/someurl/mypath1/mypath2/:
Hey all im not every good with regexp i was hoping someone could help.
ok so this is the sting "KEY FOUND! [ 57:09:91:40:32:11:00:77:16:80:34:40:91 ]"
And i need to pull "57:09:91:40:32:11:00:77:16:80:34:40:91", now this key can be meany length not just as written here and with or with out the ":"
now the second sting i would like to test and extract is: "[00:00:09] Tested 853 keys (got 179387 IVs)", i would like to pull "00:00:09" and "853" and "179387".
this would be the raw string http://regexr.com?31pcu or http://pastebin.com/eRbnwqn7
this is what im doing now.
var pass = new RegExp('KEY FOUND\!')
var tested = new RegExp('Tested')
var fail = new RegExp('\Failed. Next try with ([0-9]+) IVs')
var data="Look at the link i added"
if (tested.test(data)) {
self.emit('update', mac, {
'keys' : data.split('Tested ')[1].split(' keys ')[0],
'ivs' : data.split('got ')[1].split(' IVs')[0]
});
} else if (pass.test(data)) {
var key = data.split('KEY FOUND! [')[1].split(' ]')[0].split(':').join('');
} else if (fail.test(data)) {
console.log(data);
}
thanks all
Edit:
I have added more the the question to help with the answer
If it is always surrounded by [] then it is simple:
\[([\s\S]*)\]
This will match any characters enclosed by [].
See it in action here.