xls String to Array in JavaScript - arrays

String.prototype.splitCSV = function(sep) {
for (var foo = this.split(sep = sep || ","), x = foo.length - 1, tl; x >= 0; x--) {
if (foo[x].replace(/"\s+$/, '"').charAt(foo[x].length - 1) == '"') {
if ((tl = foo[x].replace(/^\s+"/, '"')).length > 1 && tl.charAt(0) == '"') {
foo[x] = foo[x].replace(/^\s*"|"\s*$/g, '').replace(/""/g, '"');
} else if (x) {
foo.splice(x - 1, 2, [foo[x - 1], foo[x]].join(sep));
} else foo = foo.shift().split(sep).concat(foo);
} else foo[x].replace(/""/g, '"');
} return foo;
};
this code is convert csv string to array. my question is that how to convert xls and tsv string to array?

You can look at Alasql's CSV parser, which can convert CSV and TSV strings to array:
CSV and TSV parsers code (sorry, I cannot put all code her because of size)
Or you can use Alasql to load data from CSV, TSV, XLS, or XLSX files directly to JavaScript:
alasql('SELECT * FROM XLSX("mydata.xlsx")',[], function(res){
// do something
});
alasql('SELECT * FROM TSV("mydata.tsv", {headers:true})',[], function(res){
// do something
});

Related

if the command used does not contain a valid hex code

if (command === "hex")
{ let hex = args[0]
if(!hex) return message.reply("Please specify a hex code!")
function hexToRgb(hex) {
if (hex.charAt(0) === '#') hex = hex.substring(1)
if(!hexToRgb(hex)) return message.reply("Not a valid hex.")
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + "," + g + "," + b;
}
let embed = new Discord.MessageEmbed()
.setTitle("Hex Code")
.setColor(hex)
.addFields(
{
name: `RGB`,
value: hexToRgb(hex) + ``
}
)
message.channel.send({embeds: [embed]})
}
Here is my above code for the hex command. I would like the bot to send a message that it's unable to convert hex to color if the user is using an invalid hex code (e.g. #GGGGGG) or a non-hex code (e.g. "Hello"). How could I achieve that?
You can use regex. This simple function will return whether or not it is a valid hex code
String.prototype.isHex = function() {
return ( this.match(/#?[a-f0-9]+/i)?.[0] || false )
}
And run it like this
'#ffffff'.isHex() //'#ffffff'
'Hello'.isHex() //false
'#gggggg'.isHex() //false
You can use a RegExp (#[A-Za-z0-9_]{6}) to validate the string as a hexadecimal value preceded by a #
function isHex(str) {
return !!str.match(/#[A-Za-z0-9_]{6}/).length;
}
if (!isHex('some value')) return message.reply("Not a valid hex.")

Read content from PDF using React Native

I am trying to read text from PDF file using expo and React Native. I used the below code to read but it's not working. On click of a button i use the DocumentPicker to select the PDF file and then i wanted to extract the text from the document alone. I am trying to create a app to read out the text for me.
But i am not able to do that. Thanks in advance.
loadText = async()=>{
//Alert.alert("load text triggered");
let result = await DocumentPicker.getDocumentAsync({});
if(result.type == 'success') {
// alert(result.uri);
let contents = await FileSystem.readAsStringAsync(result.uri);
//console.warn('content', contents);
if(contents.length > 0){
//let res = base64.fromByteArray(this.stringToUint8Array(contents));
//alert("t" + res);
this.setState({textToBeRead : this.atob(contents)});
alert("test" + this.state.textToBeRead);
}
}
};
atob = (input) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let str = input.replace(/=+$/, '');
let output = '';
if (str.length % 4 == 1) {
throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (let bc = 0, bs = 0, buffer, i = 0;
buffer = str.charAt(i++);
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
buffer = chars.indexOf(buffer);
}
return output;
}

How to get and manipulate text between two special charters?

Hi *John* We wish you* Happy Birthday * and blah blah blah..
Ho can I get text between each pair of * and return like
Hi <b>john</b> We wish you <b> Happy Birthday </b> and blah blah blah..
You can use this regexp /\*([^\*]+)\*/g
const regex = /\*([^\*]+)\*/g;
const str = `Hi *John* We wish you* Happy Birthday * and blah blah blah..`;
const subst = `<b>$1</b>`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
As a function
const str = `Hi *John* We wish you* Happy Birthday * and blah blah blah..`;
function bold(str) {
const regex = /\*([^\*]+)\*/g;
const subst = `<b>$1</b>`;
// The substituted value will be contained in the returned variable
return str.replace(regex, subst);
}
const result = bold(str);
console.log('Substitution result: ', result);
I think this will solve your problem.
str = "Hi *John* We wish you* Happy Birthday * and blah blah blah..";
replaceInStr(str, "<b>");
function replaceInStr(str, replace) {
str = str.replace(/\*/, replace);
if(replace === "<b>") {
replace = "</b>";
} else {
replace = "<b>";
}
if(str.search(/\*/) !== -1) {
replaceInStr(str, replace);
} else {
console.log(str);
}
}
you can use like this
var stringArray = str.split("*");
var stringOut = "";
for (var i = 0 ; i < stringArray.length; i++) {
stringOut += stringArray[i];
if (i % 2 !== 0) {
stringOut += "</br>";
}
else
{
stringOut += "<br>";
}
}
Try this :
var txt = "Hi *John* We wish you* Happy Birthday * and blah blah blah..";
txt = txt.replace(/\*(.*?)\*/g, "<b>$1</b>");
console.log(txt);

Write list of files into a js file using npm

I'd like to have a script for npm that did the following:
Gets a list of files inside a folder (and subfolders)
Write it into a JS file, with the following format:
module.exports = [
"folder/filename.png",
"folder/subfolder/filename.png"
];
I'm currently doing it like this using the cli in Linux:
echo 'module.exports = [' | tee files.js && find . -name "*png" | sed s:"./":" '": | sed s:".png":".png',": | tee files.js --append && echo '];' | tee files.js --append
Which is a bit contrived and not really cross platform. Are there any npm packages that provide similar functionality? I'm kinda lost on it.
Well don't I feel silly. Had never used node directly but it was trivial to write a script to do this.
#!/usr/bin/env node
var fs = require('fs');
var list = [];
function traverse(folder) {
var files = fs.readdirSync(folder);
for (var i = 0; i < files.length; i++) {
if (files[i].indexOf('.png') > -1 || files[i].indexOf('.jpg') > -1) {
list.push(folder + "/" + files[i]);
console.log(i + folder + "/" + files[i]);
} else {
var path = folder + "/" + files[i];
if (fs.lstatSync(path).isDirectory()) {
traverse(path);
}
}
}
}
function start() {
traverse('./images');
var string = "module.exports = [\n";
for (var i = 0; i < list.length; i++) {
string += " '" + list[i];
if (list[i] !== list[list.length - 1]) {
string += "',\n";
} else {
string += "'\n];"
}
}
fs.writeFile("./src/assets.js", string, function (err) {
if (err) {
return console.log(err);
}
console.log("Assets file was updated!");
});
}
start();

how to check if a JSONArray is empty in java?

I am working on an android app that get json content of a webservice called "WebUntis". The Json content i am getting looks like:
{"jsonrpc":"2.0","id":"req-002",
"result":[
{"id":125043,"date":20110117,"startTime":800,"endTime":850,
"kl":[{"id":71}],
"te":[{"id":23}],
"su":[{"id":13}],
"ro":[{"id":1}]},
{"id":125127,"date":20110117,"startTime":1055,"endTime":1145,
"kl":[{"id":71}],
"te":[{"id":41}],
"su":[{"id":19}],
"ro":[{"id":31}]},
...]}
As you can see in the result-array there are also other arrays like "kl", "su" and "ro"
I am getting the content of these array and then i store them in an arraylist.
But when one of these array is empty, like;
{"jsonrpc":"2.0","id":"req-002",
"result":[
{"id":125043,"date":20110117,"startTime":800,"endTime":850,
"**kl":[]**,
"te":[{"id":23}],
"su":[{"id":13}],
"ro":[{"id":1}]},
{"id":125127,"date":20110117,"startTime":1055,"endTime":1145,
"kl":[{"id":71}],
"te":[{"id":41}],
"su":[{"id":19}],
"ro":[{"id":31}]},
...]}
I am always getting the error IndexOutOfRangeException,
but I am always telling it that it should not take the empty arrays, this is what I have tried:
JSONObject jsonResult = new JSONObject(s);
// Get the result object
JSONArray arr = jsonResult.getJSONArray("result");
for (int i = 0; i < arr.length(); i++) {
JSONObject c = arr.getJSONObject(i);
anfangStunde[i] = c.getString("startTime");
endeStunde[i] = c.getString("endTime");
// get the jsonarrays (kl, su, ro)
kl = c.getJSONArray("kl");
su = c.getJSONArray("su");
ro = c.getJSONArray("ro");
// check if kl is not null
if(kl != null){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
if (klassenID[i] != null) {
klasse = webuntis.klassenMap.get(klassenID[i]);
Log.d("ID und Klasse=", "" + klassenID[i] + ";" + klasse);
}
// get th ids
fachID[i] = su.getJSONObject(0).getString("id");
if (fachID[i] != null) {
fach = webuntis.faecherMap.get(fachID[i]);
Log.d("ID und Fach=", "" + fachID[i] + ";" + fach);
}
// "Start;Ende;Klasse;Fach;Raum" store in arraylist
webuntis.stundenPlan.add(anfangStunde[i] + ";" + endeStunde[i] + ";" + klasse + ";" + fach);
// Write Data into a file for offline use:
}
Can anyone help me ?
If the array is defined in the file but is empty, like:
...
"kl":[]
...
Then getJSONArray("kl") will return an empty array, but the object is not null. Then, if you do this:
kl = c.getJSONArray("kl");
if(kl != null){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
kl is not null and kl.getJSONObject(0) will throw an exception - there is no first element in the array.
Instead you can check the length(), e.g.:
kl = c.getJSONArray("kl");
if(kl != null && kl.length() > 0 ){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
You can also use isEmpty() method, this is the method we use to check whether the list is empty or not. This method returns a Boolean value. It returns true if the list is empty otherwise it gives false. For example:
if (!k1.isEmpty()) {
klassenID[i] = kl.getJSONObject(0).getString("id");
}
You can use the regular length() method. It returns the size of JSONArray. If the array is empty, it will return 0. So, You can check whether it has elements or not. This also keeps you in track of total elements in the Array, You wont go out of Index.
if(k1 != null && k1.length != 0){
//Do something.
}
This is another way to do it...
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call,
Response<JsonObject> response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(new Gson().toJson(response.body()));
JSONArray returnArray = jsonObject.getJSONArray("my_array");
// Do Work Only If Not Null
if (!returnArray.isNull(0)) {
for (int l = 0; l < returnArray.length(); l++) {
if (returnArray.length() > 0) {
// Get The Json Object
JSONObject returnJSONObject = returnArray.getJSONObject(l);
// Get Details
String imageUrl = returnJSONObject.optString("image");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<JsonObject> call,
Throwable t) {
}
});

Resources