I'm trying to convert excel sheet contents and functions to my react project.
I've encountered convert FORECAST.ETS and FORECAST.LINEAR to typescript code.
Should I have to create excel file and insert my data to excel and run FORECAST.ETS and FORECAST.LINEAR then crop the value?
Is this the only way to call excel forecast function in javascript?
I was able to use the answer on a prior question to get help with using forecast. It provided a function I was able to use in order to calculate the forecast amount correctly. Maybe it will help you too.
Question/Answer
function forecast(x, ky, kx){
var i=0, nr=0, dr=0,ax=0,ay=0,a=0,b=0;
function average(ar) {
var r=0;
for (i=0;i<ar.length;i++){
r = r+ar[i];
}
return r/ar.length;
}
ax=average(kx);
ay=average(ky);
for (i=0;i<kx.length;i++){
nr = nr + ((kx[i]-ax) * (ky[i]-ay));
dr = dr + ((kx[i]-ax)*(kx[i]-ax))
}
b=nr/dr;
a=ay-b*ax;
return (a+b*x);
}
Example:
forecast(30, [6,7,9,15,21], [20,28,31,38,40] );
Related
I am newbie in javascript and i need some help please my goal is to convert a csv file to an ofx , I have found an open source and i want to understand it to modify it as my requirements,
this is the function in javascript:
// csv to ofx
function convert(csvData, filename) {
csvData = csvData.split('\n').map(row => row.trim())
csvDataInfoRow1 = csvData[0].split(';');
csvDataInfoRow2 = csvData[1].split(';');
csvDataInfoRow4 = csvData[3].split(';');
// the date at the end of the period
let dateEnd = csvDataInfoRow1[3].substr(csvDataInfoRow1[3].length - 10).split('/');
// the date at the beginning of the period
let dateBeginning = csvDataInfoRow1[2].substr(csvDataInfoRow1[2].length - 10).split('/');
My Question is why the programmer add just 3 variables:
csvDataInfoRow1 = csvData[0].split(';');
csvDataInfoRow2 = csvData[1].split(';');
csvDataInfoRow4 = csvData[3].split(';');
and not more or less varibles like that , what i mean for example why he just stopped in csvDataInfoRow4 = csvData[3].split(';') and what he want to do by this instruction !; also why for example he did'nt complete another variable like : csvDataInfoRow5 = csvData[4].split(';') and so on ...
maybe the code was only for three line CSVs
How do I get both values represented by i and j into the getSheetByName function?
Disclaimer: I am brand new at coding and am probably asking the wrong questions. My goal is to create a simple code that will delete sheets automatically by looping through the sheet names: Week 1, Week 2, etc.
Here's my code so far:
function myFunction() {
var sheet = SpreadsheetApp.getActiveSpreadsheet()
var i = "Week "
var j = 32
var mysheet = sheet.getSheetByName(i&j)
sheet.deleteSheet(mysheet)
}
In your code you have written i&j that's not the syntax to concat in Google apps script. Instead you can simply use i + j.
For looping you'll need to use any loop, like for, while, do-while.
Combining these suggestions, here is my final suggestion.
Try something like this [By using 'try' here I mean, simply don't copy-n-paste and use. Try to understand and write your own code, curated for your specific need. Maybe that way, we'll grow/learn more]
function myFunction() {
var START_WEEK = 1; //Put your starting week count here
var END_WEEK = 2; //Put your ending week count here
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet()
var pre_name = "Week"
var i;
for (i = START_WEEK; i <= END_WEEK; i++) {
try {
spreadSheet.deleteSheet(spreadSheet.getSheetByName(pre_name + " " + i))
} catch (exp) {
//Maybe sheet with that name is not found
Logger.log(exp.toString());
}
}
}
This code loop through all sheet whose name start with "Week " and then followed by week count, up till the end week count and if that's found it's deleting them.
Make sure you put in START_WEEK and END_WEEK properly.
Let me know if this doesn't work for you or if you have any query.
Thanks
i am new to Google apps script, i want to create string of random characters in the code given below in variable body2.
function myfunction() {
var files = DriveApp.getFiles();
while (files.hasNext(`enter code here`)) {
Logger.log(files.next().getName());
}
var recipient = Session.getActiveUser().getEmail();
var subject = 'A list of files in your Google Drive';
var body1 = Logger.getLog();
var body2;
for(var i=0;i<6;i++)
{
body2[i]=BigNumber.tostring("Math.floor(Math.random()*11)");
}
body=body1+body2;
MailApp.sendEmail(recipient, subject, body);
};
but when i run this function, it says "TypeError: Cannot find function tostring in object 0. (line 12, file "Code") " i can't understand how to solve this error?
Why we have to multiply random by 11 , can it be multiplied with any integer number?
what if i want that string in only capital letters.!
Some other question
1) i don't have enough knowledge of JavaScript, is it good to learn GAS directly?
2) i can't find proper written material or documentation for GAS , the material available at Google's official site is seems to be updating time by time , what to do then ? any link to material would help me .!
I guess I just figured
function randomStr(m) {
var m = m || 15; s = '', r = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i=0; i < m; i++) { s += r.charAt(Math.floor(Math.random()*r.length)); }
return s;
};
Hope someone finds it helpful.
As for a random string use this its better:
Math.random().toString(36). 36 is the base thus will use letters and numbers in the string.
As for gas documentation, the official page is pretty complete. It changes because it constantly improves and adds new services.
I have this charIdGeneration() in my GAS library
function charIdGenerator()
{
var charId ="";
for (var i = 1; i < 10 ; i++)
{
charId += String.fromCharCode(97 + Math.random()*10);
}
//Logger.log(charId)
return charId;
}
I am trying to parse a CSV file I made in Excel. I want to use it to update my Google map. This Google map is in a mobile app that I am developing with Eclipse for Android.
Honestly, I am not sure how to write the JavaScript. Any help will be greatly appreciated. I would be happy to credit your work.
I just want some JavaScript to run when the user hits a button that does the following:
Locates users current location (I have already done this part!)
Locate nearby locations as entered in the .CSV excel file by parsing the .CSV
Display a small link inside every locations notification bubble that says "Navigate" that when the user clicks it, opens google maps app and starts navigating the user to that location from the users current location (Geolocation).
This is the ONLY part I need to finish this application. So once again, any help at all will be greatly appreciated. Thanks everyone!
Honestly, I've been round and round with this problem. The CSV format is not made for easy parsing and even with complicated RegEx it is difficult to parse.
Honestly, the best thing to do is import it into an FormSite or PHPMyAdmin, then re-export the document with a custom separator that is easier to parse than ",". I often use "%%" as the field delimiter and everything works like a charm.
Dont know if this will help but see http://www.randomactsofsentience.com/2012/04/csv-handling-in-javascript.html if it helps...
Additional:
On top of the solution linked to above (my preference) I also used a shed load of stacked regular expressions to token a CSV but it's not as easy to modify for custom error states...
Looks heavy but still only takes milliseconds:
function csvSplit(csv){
csv = csv.replace(/\r\n/g,'\n')
var rows = csv.split("\n");
for (var i=0; i<rows.length; i++){
var row = rows[i];
rows[i] = new Array();
row = row.replace(/&/g, "&");
row = row.replace(/\\\\/g, "\");
row = row.replace(/\\"/g, """);
row = row.replace(/\\'/g, "'");
row = row.replace(/\\,/g, ",");
row = row.replace(/#/g, "#");
row = row.replace(/\?/g, "?");
row = row.replace(/"([^"]*)"/g, "#$1\?");
while (row.match(/#([^\?]*),([^\?]*)\?/)){
row = row.replace(/#([^\?]*),([^\?]*)\?/g, "#$1,$2?");
}
row = row.replace(/[\?#]/g, "");
row = row.replace(/\'([^\']*)\'/g, "#$1\?");
while (row.match(/#([^\?]*),([^\?]*)\?/)){
row = row.replace(/#([^\?]*),([^\?]*)\?/g, "#$1,$2?");
}
row = row.replace(/[\?#]/g, "");
row = row.split(",")
for (var j=0; j<row.length; j++){
col = row[j];
col = col.replace(/?/g, "\?");
col = col.replace(/#/g, "#");
col = col.replace(/,/g, ",");
col = col.replace(/'/g, '\'');
col = col.replace(/"/g, '\"');
col = col.replace(/\/g, '\\');
col = col.replace(/&/g, "&");
row[j]=col;
}
rows[i] = row;
}
return rows;
}
I had this problem which is why I had to come up with this answer, I found on npm a something called masala parser which is indeed a parser combinator. However it didn't run on browsers yet, which is why I am using this fork, the code remains unchanged. Please read it's documentation to understand the Parser-side of the code.
import ('https://cdn.statically.io/gh/kreijstal-contributions/masala-parser/Kreijstal-patch-1/src/lib/index.js').then(({
C,
N,
F,
Streams
}) => {
var CSV = (delimeter, eol) => {
//parses anything beween a string converts "" into "
var innerstring = F.try(C.string('""').returns("\"")).or(C.notChar("\"")).rep().map(a => a.value.join(''));
//allow a string or any token except line delimeter or tabulator delimeter
var attempth = F.try(C.char('"').drop().then(innerstring).then(C.char('"').drop())).or(C.charNotIn(eol[0] + delimeter))
//this is merely just a CSV header entry or the last value of a CSV line (newlines not allowed)
var wordh = attempth.optrep().map(a => (a.value.join('')));
//This parses the whole header
var header = wordh.then(C.char(delimeter).drop().then(wordh).optrep()).map(x => {
x.header = x.value;
return x
})
//allow a string or any token except a tabulator delimeter, the reason why we allow newlines is because we already know how many columns there is, so if there is a newline, it is part of the value.
var attempt = F.try(C.char('"').drop().then(innerstring.opt().map(a=>(a.value.__MASALA_EMPTY__?{value:""}:a))).then(C.char('"').drop())).or(C.notChar(delimeter))
//this is merely just a CSV entry
var word = attempt.optrep().map(a => (a.value[0]?.value??a.value[0]));
//This parses a CSV "line" it will skip newlines if they're enclosed with doublequotation marks
var line = i => C.string(eol).drop().then(word.then(C.char(delimeter).drop().then(word).occurrence(i - 1).then(C.char(delimeter).drop().then(wordh)))).map(a => a.value);
return header.flatMap(a => line(a.header.length - 1).rep().map(b => {
b.header = a.header;
return b
}))
};
var m = {
'tab': '\t',
"comma": ",",
"space": " ",
"semicolon": ";"
}
document.getElementById('button').addEventListener('click', function() {
var val = document.getElementById('csv').value;
var parsedCSV = CSV(m[document.getElementById('delimeter').value], '\n').parse(Streams.ofString(val)).value;
console.log(parsedCSV);
})
})
Type some csv<br>
<textarea id="csv"></textarea>
<label for="delimeter">Choose a delimeter:</label>
<select name="delimeter" id="delimeter">
<option value="comma">,</option>
<option value="tab">\t</option>
<option value="space"> </option>
<option value="semicolon">;</option>
</select>
<button id="button">parse</button>
I would suggest stripping the newlines and the end of the file. Because it might get confused.
This appears to work. You may want to translate the Japanese, but it is very straight-forward to use:
http://code.google.com/p/csvdatajs/
For statistical reasons, I want an extensive analysis from a dataset. I already have a function that exports the data to Excel, but I have raw data that way; 500 lines, 35 columns, heaps of text sometimes...
Is it possible to include a macro into a function so that the excelfile is readymade to be analyzed?
I am using ASP, Javascript, and at the moment Excel 2003.
This is the current function (written by one of my predecessors):
function exporttoexcel()
{ //export to excel
if (tableSortArray.length > 0)
{
var t, arr;
var tempArray=new Array();
for(var i=0; i, i<tableSortArray.length; i++) {
arr = tableSortArray[i].toString();
arrr = (arr.split(","));
if (i==0) { t = arrr[1]; }
else { t += ','+arrr[1]; }
}
document.excel.t.value = t;
}
// I left out some mumbojumbo about sorting here
document.excel.submit();
}
I mean macro's so that graphs are made "automatically" as well as some turntables...
Stolen from mrexcel.com (google + cut_paste = faster than typing):
' Delete any old stray copies of the module1
On Error Resume Next
Kill ("C:\MrXL1.bas")
On Error GoTo 0
' Export Module 1
ActiveWorkbook.VBProject.VBComponents("module1").Export ("c:\MrXL1.bas")
For x = 1 to 54
ThisBroker = Sheets("BrokerList").range("A" & x).value
' customization of plan omited for brevity
Sheets(Array("Menu", "Plan")).Copy
NBName = ActiveWorkbook.Name
' new book name
' Import Module 1 to this new book
Application.VBE.ActiveVBProject.VBComponents.Import ("c:\MrXL1.bas")
ActiveWorkbook.SaveAs Filename:=ThisBroker
ActiveWorkbook.Close
Next x
Kill ("C:\MrXl1.bas")
Alternatively you could also just setup a master excel file (say called "analysis.xls") that references the data in the "data" excel file, for example in a cell enter:
='Z:\excel-data[Current-data.xls]Sheet1'!$A$1
User opens up the master ("analysis.xls") and it in turn adds all the values from Z:\excel-data\Current-data.xls, just replace Current-data.xls with new data as needed.