Retrieve only the Whole Number - parseint

I want to retrieve the whole number part of 1.027863, so the code/function should give me 1 as the answer.
My requirement is to provide the number of SMSs present in a string by splitting the same into blocks of 153 characters.
So if there are 307 character 307/153 = 2.0065, I would take 2 using the ParseInt() function and add 1 to the same indicating that there are 3 parts to the SMS.
However assuming there are 306 characters which is a multiple of 153, my code is adding 1 to the answer making it wrong.
Sample of what I have done :
var String = "Hello test SMS for length and split it into sections of 153 characters for Bulk SMS system to send to respective customers and indicate the count of messages. SMS file is getting generated as per attached file. After successful campaign Launch, file can be downloaded from Documents view in Campaign screen.";
var i = 0;
var pat= new RegExp("^[a-zA-Z0-9]+$");
var flg = pat.test(String);
if (flg == true) //checking the language to be English
{
var length = String.length;
if(length > 160)
{
var msgcount = length / 153;
var sAbs = parseInt(msgcount);
var sTot = sAbs + 1;
TheApplication().RaiseErrorText("Character " + length +" / 670 ( " + sTot +" msg)" );
}
}
Where RaiseErrorText is used to Display in the format:
Characters 307 / 1530 (3 msg)
Maybe there is a better way to write this. Any suggestions experts?

Instead of your:
var msgcount = length / 153;
var sAbs = parseInt(msgcount);
var sTot = sAbs + 1;
You could just go:
var sTot = Math.ceil(length / 153);

Related

if line contains contains pattern A do smth with following lines until line cointains pattern B & nodeJS

I'm processing through Telegram history (txt file) reading it line by line when I when there is a pattern
Free_Trade_Calls__AltSignals:* / * (*)
example
Free_Trade_Calls__AltSignals:GAS / BTC (binance)
then store "following lines" in a separate variables each (and also store that that traiding pair RDN/ BTC and exchange bittrex) in separate variables) until it hits timestamp (today's date), then search for the pattern again
but when I see pattern
Free_Trade_Calls__AltSignals:TARGET
proceed to next line
whole example
Free_Trade_Calls__AltSignals:IOC/ BTC (bittrex)
BUY : 0.00164
SELL :
TARGET 1 : 0.00180
TARGET 2 : 0.00205
TARGET 3 : 0.00240
STOP LOS : 0.000120
2018-04-19 15:46:57 Free_Trade_Calls__AltSignals:TARGET
I've got some incomplete pseudocode but it is mostly BS anyway - quite new to parsing text aynway here is
let now = new Date();
// var diff = (now.getTime() - date.getTime()) / 60000; // diff in min
const fs = require('fs'),
path = require('path'),
filePath = path.join(__dirname, 'chats.txt'),
// myString = "Free_Trade_Calls__AltSignals";
buy,
sell = [3],
sl;
let lines = [];
const buf = fs.readFileSync(filePath)
lines [] = buf.toString().split('\n'){
for (line < lines.length){
if (!err) {
if(line.indexOf("Trade_Calls__AltSignals: * / * (*)") > -1) {
currency = line.indexOf(2);
exchange = line.indexOf(4);
nextline();
while (line.indexOf($new.Date) < - 1){ // no containing Date
if (line.indexOf(buy) > -1 ){
line = buy
}
if (line.indexOf(buy) > -1 ){
}
}else{
nextline();
}
}
}
}
}

XPages typeahead takes too long

When we try typeahead with ftSearch , it takes too long to complete (to be shown on the screen). ftsearch finishes at the same time
[0D88:000B-0B44] 30.12.2015 10:03:06 HTTP JVM: Start= 30.12.2015 10:03
[0D88:000B-0B44] 30.12.2015 10:03:06 HTTP JVM: Finish= 30.12.2015 10:03
But in the inputbox which has typeahead properties results return more then 5 seconds. I mean It takes too long.
is there any suggestion how to decrease the time
'fldDefName = inthe inputbox there is a option for ftSearch named "Var" colNumber = Column Number for results. I generally user [0]
function getTypeAheadList(vName,frmName,fldName,fldDefName,colNumber)
{
var searchView:NotesView = database.getView(vName);'
var query = "(FIELD Form CONTAINS "+ frmName + " AND FIELD " + fldName + " CONTAINS *" + fldDefName +"*)";
print("Query= "+query);
var searchOutput:Array = ["å","åå"];
var hits = searchView.FTSearch(query);
var entries = searchView.getAllEntries();
var entry = entries.getFirstEntry();
for (i=0; i<hits; i++)
{
searchOutput.push(entry.getColumnValues()[colNumber]);
entry = entries.getNextEntry();
}
searchOutput.sort();
var result ="<ul><li><span class='informal'></span></li>";
var limit = Math.min(hits,50);
for (j=0; j<limit; j++)
{
var name = searchOutput[j].toString();
var start = name.indexOfIgnoreCase(lupkey)
var stop = start + lupkey.length;
name = name.insert("</b>",stop).insert("<b>",start);
result += "<li>" + name + "</li>";
}
result += "</ul>";
return result;
Reduce the number of docs that will be returned by FTSearch to 50 with
var hits = searchView.FTSearch(query, 50);
Right now the search result might contain e.g. 5000 docs and it takes time to push them into searchOutput and to sort. You reduce the hints afterwards to 50 anyway...

Error parsing string to int in Podio

Anyone knows why the calculation field returns an error when converting a string into an integer?
var $prix = Max of Prix de vente; //Value is 2000.00
var $titre = All of Nom du produit;
var $nbr_heure = $titre[0].substring(0, 3).trim(); //Value is "25"
parseInt($nbr_heure)
parseInt($prix) returns 2000
I have tried parseFloat() and Number(). It seems like as soon as it tried to convert a string, it doesn't process.
My static workaround
var $prix = Max of Prix de vente;
var $titre = All of Nom du produit;
var $nbr_heure = $titre[0].substring(0, 3).trim();
var $taux_horaire = 0;
//Conversion stupide manuelle
if($nbr_heure == "25")
$taux_horaire = $prix / 25;
else if($nbr_heure == "50")
$taux_horaire = $prix / 50;
else if($nbr_heure == "100")
$taux_horaire = $prix / 100;
else
$taux_horaire = 89;
$taux_horaire;
More info, if you do this:
$prix + parseInt($nbr_heure); //Same error
and
$prix + $nbr_heure; //Gives 200025 (String concatenation)
Thank you for any feedback!
You are getting the error because parseInt() is returning NaN instead of an actual number. Or because your substring call is failing.
If your $titre field doesn't contain a value your substring call will fail. So make sure to check in your calculation that it is working with a value and not undefined.
In a similar vein parseInt will return NaN if you call it with an empty string.

Grabbing text from webpage and storing as variable

On the webpage
http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463
It lists prices for a particular item in a game, I wanted to grab the "Current guide price:" of said item, and store it as a variable so I could output it in a google spreadsheet. I only want the number, currently it is "643.8k", but I am not sure how to grab specific text like that.
Since the number is in "k" form, that means I can't graph it, It would have to be something like 643,800 to make it graphable. I have a formula for it, and my second question would be to know if it's possible to use a formula on the number pulled, then store that as the final output?
-EDIT-
This is what I have so far and it's not working not sure why.
function pullRuneScape() {
var page = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var number = page.match(/Current guide price:<\/th>\n(\d*)/)[1];
SpreadsheetApp.getActive().getSheetByName('RuneScape').appendRow([new Date(), number]);
}
Your regex is wrong. I tested this one successfully:
var number = page.match(/Current guide price:<\/th>\s*<td>([^<]*)<\/td>/m)[1];
What it does:
Current guide price:<\/th> find Current guide price: and closing td tag
\s*<td> allow whitespace between tags, find opening td tag
([^<]*) build a group and match everything except this char <
<\/td> match the closing td tag
/m match multiline
Use UrlFetch to get the page [1]. That'll return an HTTPResponse that you can read with GetBlob [2]. Once you have the text you can use regular expressions. In this case just search for 'Current guide price:' and then read the next row. As to remove the 'k' you can just replace with reg ex like this:
'123k'.replace(/k/g,'')
Will return just '123'.
https://developers.google.com/apps-script/reference/url-fetch/
https://developers.google.com/apps-script/reference/url-fetch/http-response
Obviously, you are not getting anything because the regexp is wrong. I'm no regexp expert but I was able to extract the number using basic string manipulation
var page = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var TD = "<td>";
var start = page.indexOf('Current guide price');
start = page.indexOf(TD, start);
var end = page.indexOf('</td>',start);
var number = page.substring (start + TD.length , end);
Logger.log(number);
Then, I wrote a function to convert k,m etc. to the corresponding multiplying factors.
function getMultiplyingFactor(symbol){
switch(symbol){
case 'k':
case 'K':
return 1000;
case 'm':
case 'M':
return 1000 * 1000;
case 'g':
case 'G':
return 1000 * 1000 * 1000;
default:
return 1;
}
}
Finally, tie the two together
function pullRuneScape() {
var page = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var TD = "<td>";
var start = page.indexOf('Current guide price');
start = page.indexOf(TD, start);
var end = page.indexOf('</td>',start);
var number = page.substring (start + TD.length , end);
Logger.log(number);
var numericPart = number.substring(0, number.length -1);
var multiplierSymbol = number.substring(number.length -1 , number.length);
var multiplier = getMultiplyingFactor(multiplierSymbol);
var fullNumber = multiplier == 1 ? number : numericPart * multiplier;
Logger.log(fullNumber);
}
Certainly, not the optimal way of doing things but it works.
Basically I parse the html page as you did (with corrected regex) and split the string into number part and multiplicator (k = 1000). Finally I return the extracted number. This function can be used in Google Docs.
function pullRuneScape() {
var pageContent = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var matched = pageContent.match(/Current guide price:<.th>\n<td>(\d+\.*\d*)([k]{0,1})/);
var numberAsString = matched[1];
var multiplier = "";
if (matched.length == 3) {
multiplier = matched[2];
}
number = convertNumber(numberAsString, multiplier);
return number;
}
function convertNumber(numberAsString, multiplier) {
var number = Number(numberAsString);
if (multiplier == 'k') {
number *= 1000;
}
return number;
}

Comparing #Now to a Date/Time field?

How do I compare #Now to a data / time value in a document? This is what I have
var ProjectActiveTo:NotesDateTime = doc.getItemValueDateTimeArray("ProjectActiveTo")[0];
var ProjectExpired;
var d1:Date = #Now();
if (d1 > ProjectActiveTo.toJavaDate())
{
dBar.info("Today: " + d1 + " > " + ProjectActiveTo.toJavaDate());
ProjectExpired = true;
}
else
{
dBar.info("Today: " + d1 + " < " + ProjectActiveTo.toJavaDate());
ProjectExpired = false;
}
But this always seems to return false. I printed out some diagnostic messages.
Today: 1/18/13 6:02 PM < 1/20/01 5:00 PM
Obviously today is greater than 1/20/01 but this is the result of my test. Why?
I have done some searching and saw that the compare member function might be used but it returns an error for me and compare is not in the intelisense (or whatever Lotus calls it) in the design editor.
Found this little snippet on line - it should point you in the right direction
var doc:NotesDocument = varRowView.getDocument();
var d:NotesDateTime = doc.getItemValue("BidDueDate")[0];
var t:NotesDateTime = session.createDateTime("Today");
if (d.timeDifference(t) > 0 ) {
return "Overdue";
}else{
return "";
}

Resources