with Google Script i have created this html that send datas to a google sheet taking in input some data from the url (after /exec?P=tonno&Q=3&C=Cliente+1 he takes in input P,Q,C):
<!DOCTYPE html>
<html>
<head>
<title> Modulo di Ordine </title>
<script type="text/javascript">
function doGet(e){
//HtmlService.setTitle("This is MYTITLE");
var result = '<-- Riepilogo Ordine --> \n';
if (e.parameter == 'undefined') {
result += "ERRORE SCONOSCIUTO NELL'ACQUISTO! non verrà inviato l'ordine";
return ContentService.createTextOutput(result);
}
else {
var ID = '1sl0P4auOdX8i67kZ9LA8dGXm59I_fc_tSOaPaOpL1Ek'; // identificativo della cartella di foglio (Spreadsheet ID)
// var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet();
// var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var Cartella = SpreadsheetApp.openById(ID); // Cartella identificata da ID
var Foglio = Cartella.getSheets()[0]; // nella parentesi quadra il foglio ---> 0 = primo, 1 = secondo, ecc.
var Cella_R = Foglio.getRange(2,5); // riga 2, colonna 5 -> cella E2
var Inserite = Cella_R.getValue() + 1; // numero di righe inserite (letto dal foglio) incrementato di 1
Cella_R.setValue(Inserite); // scrive nel fogio il valore incrementato di «Inserite»
// var Riga = Foglio.getLastRow() + 1;
var Riga = Inserite + 2; // Riga in cui scrivere i dati
result += 'Codice Ordine: #' + Riga; // calcola la riga su cui scrivere i dati
var Cella_D = Foglio.getRange(Riga,1); // D = Data --------------> colonna 1
var Cella_O = Foglio.getRange(Riga,2); // O = Orario ------------> colonna 2
var Cella_T = Foglio.getRange(Riga,3); // T = Temperatura -------> colonna 3
var Cella_U = Foglio.getRange(Riga,4); // U = Umidità relativa --> colonna 4
var Cella_C = Foglio.getRange(Riga,5); // C = Cliente ----------->
var answer = "";
// SpreadsheetApp.setActiveSheet(sheet);
// var rowData = [];
var Giorno_Ora = new Date(); // legge data ed ora attuali
var Data = Utilities.formatDate(Giorno_Ora, "Europe/Rome", 'dd/MM/yyyy'); // estrae la data da Data_Ora
var Orario = Utilities.formatDate(Giorno_Ora, "Europe/Rome", 'HH.mm.ss' ); // estrae l'orario da Data_Ora
Cella_D.setValue(Data); //scrive la Data
Cella_O.setValue(Orario); //scrive l'orario
for (var parametro in e.parameter) {
var valore = Pulisci(e.parameter[parametro]); //estrae il valore del paramentro senza virgolette
switch (parametro) { // condizione case
case 'P':
Cella_T.setValue(valore); // Scrive il prodotto
result += '\nProdotto: ' + valore + ''; // Scrive messaggio risposta
break;
case 'C':
Cella_C.setValue(valore); // Scrive il cliente
result += '\nCliente: ' + valore + ''; // Scrive messaggio risposta
break;
case 'Q':
Cella_U.setValue(valore); // Scrive la quantità
result += '\nQuantità: ' + valore + ' pezzi'; // Scrive messaggio risposta
break;
default: //in caso di errore:
result += "\n\nParametri non validi!. L'ordine non verrà preso in considerazione";
}
} //se tutto va bene passa avanti con il successo
result += '\n\nEseguito con successo! Qualcuno provvederà a prendere in considerazione il suo ordine.';
}
return ContentService.createTextOutput(result); // Restituisce il Riepilogo dell'ordine
}
function Pulisci( value ) {
return value.replace(/^["']|['"]$/g, ""); // sostituisce cosa a cosa???
}
</script>
</head>
<body>
<p>Sicuro di voler procedere con l'ordine?</p> <br>
<input id="clickMe" type="button" value="clickme" onclick="doGet();" />
</body>
</html>
The problem is that when I press the button to call the function doGet(), this is the error and the function doesn't go on:
userCodeAppPanel:5 Uncaught TypeError: Cannot read property 'parameter' of undefined
at doGet (userCodeAppPanel:5)
at HTMLInputElement.onclick (userCodeAppPanel:1)
Can pls somebody help me?
ContentService, SpreadsheetApp, and even doGet(e) are server side functions they run on a Google Server not on your browser. You need to restructure your entire code and utilize some intermediate javascript functions and possibly google.script.run you would be well served to do a little more research in some of the examples provided here at SO.
The idea of using doGet(e) as a clientside function is rather ridculuous because the whole idea is that it's supposed to be an endpoint on the server. It's ridiculous to consider it as a clientside function.
To resolve the issue you are facing, you need to change your button HTML element to the below code -
<input id="clickMe" type="button" value="clickme" onclick="doGet(event);" />
Since you are using inline event handler, you need to pass the event as argument to onClick method. Please refer to this post in-case you have any queries.
Related
I have this program where there are a series of registered students and when they put their name, their data and the name of the teacher they have assigned.
When inserting a new student, the only thing that it does to me correctly is to print if the teacher exists or not, since the student's data does not show them to me, and finally I have a failure in the last line of the javascript code related to innerhtml , the error in question is:
Uncaught TypeError: Cannot set properties of null (setting
'innerHTML')
at mensaje.js:74
now the code:
html:
<button onclick="infoalumno()">Informacion del alumno</button>
<button onclick="insertar()">Introducir nuevo alumno</button>
<div id="info"></div>
and javascript code:
function alumno(nombre, edad, nota, profesor) {
this.nombre = nombre;
this.edad = edad;
this.nota = nota;
this.profesor = profesor;
}
function profesor(nombre, asginatura) {
this.nombre = nombre;
this.asginatura = asginatura;
}
var profesores = new Array(3);
profesores[0] = new profesor("Paco","Plastica");
profesores[1] = new profesor("Anton","Biologia");
profesores[2] = new profesor("Jacinto","Lengua");
var alumnos = new Array(2);
alumnos[0] = new alumno("Jose",24,7,profesores[0]);
alumnos[1] = new alumno("Jacobo",23,7,profesores[2]);
function infoalumno() {
var buscar = prompt("Inserta el nombre del alumno que quieres buscar");
var comprobar = false
for (let i = 0; i < alumnos.length; i++) {
if (buscar == alumnos[i].nombre) {
document.write("Nombre" + alumnos[i].nombre + "<br>Edad:" + alumnos[i].edad + "<br>Nota:" + alumnos[i].nota + "<br>Profesor:" + alumnos[i].profesor.nombre);
comprobar = true;
}
if (comprobar == false) {
document.write("Alumno " + buscar + "no existe");
}
}
}
function insertar() {
var comprobar2 = false;
var nombre = prompt("Insertar el nombre del alumno");
var edad = parseInt(prompt("Ingresa la edad"));
var nota = parseInt(prompt("Ingresa la nota"));
var profesor = prompt("¿Quien es el profesor?");
for (let i = 0; i < profesores.length; i++) {
if (profesor == profesores[i].nombre) {
var newalumno = new alumno(nombre, edad, nota, profesor[i]);
alumnos.push(newalumno);
comprobar2=true;
break;//la sentencia break permite terminar de forma abrupta un bucle y la sentencia continue permite saltarse algunas repeticiones del bucle. ... La utilidad de break es terminar la ejecución del bucle cuando una variable toma un determinado valor o cuando se cumple alguna condición.
}
}
if(comprobar2==false){
document.write("Profesor "+profesor+" no existe");
}
}
var infoprofesor ="Profesores";
for (let i = 0; i < profesores.length; i++) {
infoprofesor = infoprofesor + profesores[i].nombre+"<br>";
}
document.getElementById("info").innerHTML = infoprofesor;
1)
The teacher does not appear his name instead appears [object Object]
In this code
document.write("Nombre" + alumnos[i].nombre + "<br>Edad:" + alumnos[i].edad + "<br>Nota:" + alumnos[i].nota + "<br>Profesor:" + alumnos[i].profesor);
This alumnos[i].profesor will be a Profesor object like from calling new Profesor(...). If you wanted to show the name it would look like alumnos[i].profesor.nombre
2)
And when inserting a new student, the only thing that it does to me
correctly is to print if the teacher exists or not.
var profesor = prompt("¿Quien es el profesor?");
for (let i = 0; i < profesores.length; i++) {
if (profesor == profesores[i].nombre) {
var newalumno = new alumno(nombre, edad, nota, profesor);
alumnos.push(newalumno);
comprobar2=true;
break;
}
}
In this loop you have a related issue. The result from prompt will just be a string (your var profesor). However when you go to make your new alumno it expects a profesor object (with nombre/asignatura).
In this case you're probably want to do var newalumno = new alumno(nombre, edad, nota, profesores[i]);
I'm trying to show a graph using Google Charts.
I am able to create the chart but I'm having trouble passing an array of Arrays to the addRows method . A chart appears but without any lines charted.
If I manually write the chart's values, it works:
data.addRows([
['mai 19, 07:01', 1, 1, 1, 1]
]);
but if I try to pass the values using the array of Arrays precos_madeira, I can only see the chart, no lines...
At the end of mainFunction() you can clearly see precos_madeira is an array of Arrays.
For testing purposes, you can use
mai 19, 07:01 Mundo 73 Transferir 1 149 Troca Premium: Madeira vendido (233)
on the input box next to the Calcular custo dos PP's comprados button and then click the button
Here's the full code:
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://www.gstatic.com/charts /loader.js">
</script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['corechart','line']});
</script>
</head>
<body>
<p>1.Insere o numero de pps que queres gastar</p>
<input type="text" id="pps_a_gastar" maxlenght="100" value="pp's a gastar">
<p>2.Insere o as unidades por hora geradas em 'Aumento da produção de recursos de 20%' (para encontrar carrega em 'Bosque') </p>
<input type="text" id="unidades_hora" maxlenght="100" value="unidades/hora">
<script>
function calcula_unidades_semana(){
var un_h=document.getElementById("unidades_hora").value;
var x7_x24=parseInt(un_h)*7*24;
document.getElementById("_x7_x24").innerHTML = x7_x24;
}
function calcula_unidades_mes(){
var un_h=document.getElementById("unidades_hora").value;
var x30_x24=parseInt(un_h)*30*24;
document.getElementById("_x30_x24").innerHTML = x30_x24;
}
</script>
<p>3.Ao fim de uma semana, com o aumento de 20%, produzes mais</p>
<p id="_x7_x24"></p><p> unidades</p>
<button onclick="calcula_unidades_semana()">Calcular unidades geradas numa semana</button>
<p>3.Ao fim de um mes, com o aumento de 20%, produzes mais</p>
<p id="_x30_x24"></p><p> unidades</p>
<button onclick="calcula_unidades_mes()">Calcular unidades geradas num mes</button>
<p>---------------------------------------------------------------</p>
<p>Copia e cola TODAS as linhas do teu historico de pontos</p>
<input type="text" id="myText" maxlenght="10000" value="Some text...">
<button onclick="mainFunction()">Calcular custo dos PP's comprados</button>
<p>Teste:</p>
<p id="teste"></p>
<p>Input:</p>
<p id="input"></p>
<p>Total pp's comprados:</p>
<p id="total_pps"></p>
<p>Total pp's usados:</p>
<p id="total_pps_usados"></p>
<p>Total gasto em madeira:</p>
<p style="color:brown;" id="total_madeira"></p>
<p >Total gasto em argila:</p>
<p style="color:orange;" id="total_argila"></p>
<p>Total gasto em ferro:</p>
<p style="color:darkgrey;" id="total_ferro"></p>
<p>Precos pp:</p>
<p id="pp"></p>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
</div>
<script>
var lines = [];
var linesLength;
var text, i, bool;
var line="";
var line_counter=0;
var total_pps_comprados=0;
var total_pps_usados=0;
var total_gasto_em_madeira=0;
var total_gasto_em_argila=0;
var total_gasto_em_ferro=0;
var precos_madeira=[];
var madeira_cont=0;
function displayLines(){
linesLength = lines.length;
text = "<ul>";
for (i = 0; i < linesLength; i++) {
text += "<li>" + lines[i] + "</li>";
}
text += "</ul>";
document.getElementById("input").innerHTML = text;
}
function obterLinhas(){
var input = document.getElementById("myText").value;
for (i = 0; i < input.length; i++) {
bool=input.substr(i, 1).localeCompare(")");
if ( bool ){
line = line.concat(input.substr(i, 1));
}
else{
var pos_transf = line.indexOf("Transferir");
if (pos_transf != -1 ){
total_pps_comprados+=obter_pps_comprados();
}
var pos_ut = line.indexOf("Utilizados");
if (pos_ut != -1 ){
total_pps_usados+=obter_pps_usados();
}
lines[line_counter]=line;
line_counter+=1;
line="";
}
}
}
function obter_qtd_de_recurso_gasto(linha_sem_principio, prim_esp){
var qtd="";
if ( linha_sem_principio.search("Madeira") != -1 ){
//Obter qtd de madeira gasta a comprar os pps
qtd=linha_sem_principio.slice(linha_sem_principio.indexOf("(")+1, linha_sem_principio.length);
total_gasto_em_madeira += parseInt(qtd);
}
if ( linha_sem_principio.search("Argila") != -1 ){
//Obter qtd de argila gasta a comprar os pps
qtd=linha_sem_principio.slice(linha_sem_principio.indexOf("(")+1, linha_sem_principio.length);
total_gasto_em_argila += parseInt(qtd);
}
if ( linha_sem_principio.search("Ferro") != -1 ){
//Obter qtd de ferro gasto a comprar os pps
qtd=linha_sem_principio.slice(linha_sem_principio.indexOf("(")+1, linha_sem_principio.length);
total_gasto_em_ferro += parseInt(qtd);
}
return parseInt(qtd);
}
function obter_valor_da_data(data_str){
var mes_str;
var mes_num;
var dia_str;
var hora_str;
var min_str;
//Obter mes
mes_str = data_str.slice(0, data_str.indexOf(" "));
//Transformar mes(string) num numero
switch(mes_str){
case "jan":
mes_num=1;
break;
case "fev":
mes_num=2;
break;
case "mar":
mes_num=3;
break;
case "abr":
mes_num=4;
break;
case "mai":
mes_num=5;
break;
case "jun":
mes_num=6;
break;
case "jul":
mes_num=7;
break;
case "ago":
mes_num=8;
break;
case "set":
mes_num=9;
break;
case "out":
mes_num=10;
break;
case "nov":
mes_num=11;
break;
case "dez":
mes_num=12;
}
//Obter dia
dia_str=data_str.slice(data_str.indexOf(" "), data_str.indexOf(","));
//Obter hora
hora_str=data_str.slice(data_str.indexOf(",")+1, data_str.indexOf(":"));
//Obter min
min_str=data_str.slice(data_str.indexOf(":")+1, data_str.indexOf("M"));
return mes_num*12/(31*24*60)+parseInt(dia_str)*31/(24*60)+(parseInt(hora_str)+1)*24/60+(parseInt(min_str)+1)*60;
}
function obter_pps_comprados(){
var pos_transf = line.indexOf("Transferir");
var qtd;
var data;
var valor;
if (pos_transf != -1 ){
data = line.slice(0, line.indexOf("M"));
valor = obter_valor_da_data(data);
var line_sem_principio = line.slice(pos_transf+10);
var primeiro_espaco = line_sem_principio.lastIndexOf(" ");
qtd = obter_qtd_de_recurso_gasto(line_sem_principio, primeiro_espaco);
var pps_comprados = line_sem_principio.slice(0, line_sem_principio.length-primeiro_espaco+1);
precos_madeira[madeira_cont]=[data, parseInt(qtd)/parseInt(pps_comprados), 1, 1, 1];
madeira_cont+=1;
return parseInt(pps_comprados);
}
}
function obter_pps_usados(){
var pos_ut = line.indexOf("Utilizados");
if (pos_ut != -1 ){
var line_sem_principio = line.slice(pos_ut+10);
var primeiro_espaco = line_sem_principio.lastIndexOf(" ");
var pps_us = line_sem_principio.slice(0, line_sem_principio.length-primeiro_espaco+5); //nao deveria funcionar quando os novos pontos premium nao tem 3 digitos
return parseInt(pps_us);
}
}
function mainFunction() {
var text;
obterLinhas();
displayLines();
document.getElementById("total_pps").innerHTML = total_pps_comprados;
document.getElementById("total_pps_usados").innerHTML = total_pps_usados;
document.getElementById("total_madeira").innerHTML = total_gasto_em_madeira;
document.getElementById("total_argila").innerHTML = total_gasto_em_argila;
document.getElementById("total_ferro").innerHTML = total_gasto_em_ferro;
text = "<ul>";
for (i = 0; i < precos_madeira.length; i++) {
text += '<li>' + precos_madeira[i][0] + ":::" + precos_madeira[i][1] + "--" + precos_madeira[i][2] + "--" + precos_madeira[i][3] + "--" + precos_madeira[i][4]+"</li>";
}
text += "</ul>";
document.getElementById("pp").innerHTML = text;
}
//------CHARTS---------//
function drawChart() {
// Define the chart to be drawn.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('number', 'Madeira');
data.addColumn('number', 'Argila');
data.addColumn('number', 'Ferro');
data.addColumn('number', 'PPs na conta');
data.addRows(precos_madeira);
// Set chart options
var options = {'title' : 'Average Temperatures of Cities',
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Temperature'
},
'width':550,
'height':400,
pointsVisible: true
};
// Instantiate and draw the chart.
var chart = new google.visualization.LineChart(document.getElementById('container'));
chart.draw(data, options);
}
google.charts.setOnLoadCallback(drawChart);
</script>
</body>
</html>
I have a problem when writing a html code in chat that appears in the box, this is dangerous and ugly to see, is there any javascript or html code to block html and cone files ?
if I write on the text input a html code such as appears in the box ie the code works, how do I block there is a way or some code to paste in the text?
Here is input:
<input type="text" name="chat" id="chattbox" placeholder="Ask what you want." onfocus="placeHolder ()">
var messages = [],
lastUserMessage = "",
botMessage = "",
botName = 'Jacob', t
talking = true;
function chatbotResponse() {
talking = true;
botMessage = "non ho capito";
var hi = ['Ciao {$mybb->user['username']}','mhhh','forte','haha','Chi sei?', 'mi vuoi bene?', 'Sono un bot questo non significa che io sia scemo', 'grande', 'boh', 'bah...', 'sei forte haha', 'ti piace stertix?', 'ok','se lo dici tu.','come vuoi', 'ho fame', 'Mi sto pulendo il naso... Quello che non ho :(', 'Hai ragione', 'Sei un grande', 'aaahhhhhhh!!!', 'mlmlml', 'cavolo', 'wow', 'figo', 'come mai?', 'forse', 'Si', 'No', 'mi piace parlare con te <3', 'spacco bottilia ammazzo familia', 'ti amo', 'ti voglio bene', 'che canzone ti piace?', 'che cantante ti piace?', 'so che pensi che sia stupido ma non lo sono.', 'ma lo sarai tu.', 'va bene', 'bello', 'molto', 'molto bello', 'cosa ne pensi di stertix?', ':D', ':)', ';)', '<3', ':O', 'Che fai?', 'quale?', 'quale', 'eh', 'grave', 'eccellente', 'giusto', 'grazie', 'eccellente', 'ottimo', 'ue guaglio bell stu orolog',];
botMessage = hi[Math.floor(Math.random()*(hi.length))];
var n = lastUserMessage.search(/\b(gatto|gatti)\b/i);
if (n !== -1) {
botMessage = 'Amo i gatti!';
}
var n = lastUserMessage.search(/\b(ciao|salve|ehi|we)\b/i);
if (n !== -1) {
var vr = ['Ciao {$mybb->user['username']}!', 'Ciao fra', 'Ciao amico', 'ehi {$mybb->user['username']}!', 'We {$mybb->user['username']}!',];
botMessage = vr[Math.floor(Math.random()*(vr.length))];
}
var n = lastUserMessage.search(/\b(bene)\b/i);
if (n !== -1) {
var vr = ['Ottimo','Meglio cosi', 'Mi fa piacere',];
botMessage = vr[Math.floor(Math.random()*(vr.length))];
}
var patt = /\b(cani)\b/i;
var result = patt.exec(lastUserMessage);
if (result) {
botMessage = 'Amo i ' + result[0];
}
var n = lastUserMessage.search(/\b(animali)\b/i);
if (n !== -1) {
botMessage = 'Amo gli animali!';
}
var n = lastUserMessage.search(/\b(come va|come stai)\b/i);
if (n !== -1) {
var vir = ['Benissimo, tu?','Bene dai...', 'bene tu?', 'male, tu?', 'Malissimo, tu?', 'diciamo, tu?',];
botMessage = vir[Math.floor(Math.random()*(vir.length))];
}
var n = lastUserMessage.search(/\b(che fai|che stai facendo)\b/i);
if (n !== -1) {
var vuyr = ['Nulla, parlo con te, tu che fai?','Niente, tu?', 'Mi annoio, tu?', 'Mi vedo film zozzi, tu?', 'cerco un modo per conquistare il mondo... na scherzo sono un bot pirla, tu che fai?', ];
botMessage = vuyr[Math.floor(Math.random()*(vuyr.length))];
}
I've commented the code -- basically, if a user enters a < and then, at some point later, types a > then everything between them is stripped out by regex. From what you're describing, this seems like what you're looking for.
var filterHtmlCodes = function() {
/*****
* Here, we're going to go through and strip
* any tags -- words wrapped in <>. Thus,
* users can still enter either symbol, but
* entering both will immediately strip the
* tag value. I'm triggering on every
* keyup, but it could as easily be done on every
* change, so as to block copy/paste, for example.
*****/
myChatEl.value = myChatEl.value.replace(/<(?:.|\n)*?>/gm, '')
};
// And I prefer to add my listeners outside of my HTML.
var myChatEl = document.querySelector("#chattbox");
myChatEl.addEventListener("keyup", filterHtmlCodes)
<input type="text" name="chat" id="chattbox" placeholder="Ask what you want.">
I'm trying to parse .srt but I get an internal error and I can't figure out what is it.
Here is my code:
var subtitles;
jQuery.get('SB_LKRG-eng.srt', function(data) {
//alert(data);
function strip(s) {
return s.replace(/^\s+|\s+$/g,"");
}
srt = data.replace(/\r\n|\r|\n/g, '\n');
//alert(srt);
srt = strip(srt);
//alert(srt);
var srt_ = srt.split('\n\n');
alert(srt_);
var cont = 0;
for(s in srt_) {
st = srt_[s].split('\n');
alert(st);
if(st.length >=2) {
n = st[0];
i = strip(st[1].split(' --> ')[0]);
o = strip(st[1].split(' --> ')[1]);
t = st[2];
if(st.length > 2) {
for(j=3; j<st.length;j++)
t += '\n'+st[j];
}
subtitles[cont].number = n;
subtitles[cont].start = i;
subtitles[cont].end = o;
subtitles[cont].text = t;
//alert(subtitles[cont].start);
}
cont++;
}
});
I can extract the first 4 subtitles and then the code stops and breaks exception: TypeError, I can't understand why...
Here a sample of the subtitles file:
1
00:00:01,000 --> 00:00:04,000
Descargados de www.AllSubs.org
2
00:00:49,581 --> 00:00:52,049
Bueno, tienes que escapar, tengo que ir a jugar
3
00:00:52,084 --> 00:00:55,178
Tengo que encontrar un día que está lleno de nada más que sol
4
00:00:55,220 --> 00:00:57,552
Crucero por la calle, moviéndose al compás
5
00:00:57,589 --> 00:01:00,683
Todos los que conoces está teniendo nada más que diversión
6
00:01:00,726 --> 00:01:03,251
Deja todo detrás de ti
7
00:01:03,295 --> 00:01:06,128
Siente esas palmeras soplan
8
00:01:06,165 --> 00:01:09,157
La gente en el norte no puede encontrar
9
00:01:09,201 --> 00:01:11,829
Están fuera de palear la nieve
10
00:01:11,870 --> 00:01:14,998
El tiempo para moverse, pero no seas lento
11
00:01:15,040 --> 00:01:17,941
En sus marcas, prepárate para ir
Part of the code is from: http://v2v.cc/~j/jquery.srt/jquery.srt.js
Can anyone help me?
Thank you
var PF_SRT = function() {
//SRT format
var pattern = /(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/gm;
var _regExp;
var init = function() {
_regExp = new RegExp(pattern);
};
var parse = function(f) {
if (typeof(f) != "string")
throw "Sorry, Parser accept string only.";
var result = [];
if (f == null)
return _subtitles;
f = f.replace(/\r\n|\r|\n/g, '\n')
while ((matches = pattern.exec(f)) != null) {
result.push(toLineObj(matches));
}
return result;
}
var toLineObj = function(group) {
return {
line: group[1],
startTime: group[2],
endTime: group[3],
text: group[4]
};
}
init();
return {
parse: parse
}
}();
jQuery.get('demo.srt')
.done(function(text) {
try {
//Array with {line, startTime, endTime, text}
var result = PF_SRT.parse(text);
} catch (e) {
//handle parsing error
}
});
Demo
https://jsfiddle.net/5v7wz4bq/
Here is one problem:
o = strip(st[1].split(' --> ')[1]);
At this line, when there isn't any ' --> ' to split, the returned length of the array is 1, which errors when you ask for array item 2.
And here is another:
subtitles[cont].number = n;
....
Neither is the subtitles declared, nor its properties .number, ... etc.
Update
Here is a sample that works (switched the jQuery "read srt file" part for the data)
var data = document.getElementById("data").innerHTML;
data = data.replace(/>/g,">");
function strip(s) {
return s.replace(/^\s+|\s+$/g,"");
}
srt = data.replace(/\r\n|\r|\n/g, '\n');
srt = strip(srt);
var srt_ = srt.split('\n\n');
var cont = 0;
var subtitles = [];
for(s in srt_) {
st = srt_[s].split('\n');
if(st.length >=2) {
var st2 = st[1].split(' --> ');
var t = st[2];
if(st.length > 2) {
for(j=3; j < st.length;j++)
t += '\n'+st[j];
}
subtitles[cont] = { number : st[0],
start : st2[0],
end : st2[1],
text : t
}
console.log(subtitles[cont].number + ": " + subtitles[cont].text);
document.body.innerHTML += subtitles[cont].number + ": " + subtitles[cont].text + "<br>";
cont++;
}
}
<div id="data" style="display:none">1
00:00:01,000 --> 00:00:04,000
Descargados de www.AllSubs.org
2
00:00:49,581 --> 00:00:52,049
Bueno, tienes que escapar, tengo que ir a jugar
3
00:00:52,084 --> 00:00:55,178
Tengo que encontrar un día que está lleno de nada más que sol
4
00:00:55,220 --> 00:00:57,552
Crucero por la calle, moviéndose al compás
5
00:00:57,589 --> 00:01:00,683
Todos los que conoces está teniendo nada más que diversión
6
00:01:00,726 --> 00:01:03,251
Deja todo detrás de ti
7
00:01:03,295 --> 00:01:06,128
Siente esas palmeras soplan
8
00:01:06,165 --> 00:01:09,157
La gente en el norte no puede encontrar
9
00:01:09,201 --> 00:01:11,829
Están fuera de palear la nieve
10
00:01:11,870 --> 00:01:14,998
El tiempo para moverse, pero no seas lento
11
00:01:15,040 --> 00:01:17,941
En sus marcas, prepárate para ir
</div>
It is better to use the following regex to cover them if the number of lines of text in each section increases
/(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/g
View the output on the console
let subtitle = document.getElementById('subtitle').value;
console.log(_subtitle(subtitle));
function _subtitle(text) {
let Subtitle = text;
let Pattern = /(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/g;
let _regExp = new RegExp(Pattern);
let result = [];
if (typeof (text) != "string") throw "Sorry, Parser accept string only.";
if (Subtitle === null) return Subtitle;
let Parse = Subtitle.replace(/\r\n|\r|\n/g, '\n');
let Matches;
while ((Matches = Pattern.exec(Parse)) != null) {
result.push({
Line: Matches[1],
Start: Matches[2],
End: Matches[3],
Text: Matches[4],
})
}
return result;
}
<textarea id="subtitle">1
00:00:00,000 --> 00:00:00,600
Hi my friends
2
00:00:00,610 --> 00:00:01,050
In the first line, everything works properly
But there is a problem in the second line that I could not solve :(
3
00:00:01,080 --> 00:00:03,080
But then everything is in order and good
4
00:00:03,280 --> 00:00:05,280
You do me a great favor by helping me. Thankful</textarea>
I have a script that reads answers from a Google form when it is sent. The script is bound to a spreadsheet, that captures all answers. The script generates a PDF with some information and sends it to a user via GmailApp, and stores the PDF inside a Drive folder. But sometimes the script doesn't work. The answers are always stored in the spreadsheet, but despite this, the script doesn't run. I have checked the "Execution transcript", but it contains information about the last successful execution.
How can I guarantee that the script always runs?
Can anyone explain why this happens?
Code
//ID del template
var docTemplate = "Template ID Here";
//Nombre de la copia
var docName = "biovenCIP";
//FUnción principal para generación y envío de constancia
function onFormSubmit(e){
//Leyendo datos del formulario
var d = new Date();
var registration_date = e.values[0];
var first_name = e.values[1];
var second_name = e.values[2];
var first_lastname = e.values[3];
var second_lastname = e.values[4];
var document_type = e.values[5];
var document_number = e.values[6];
var email_address = e.values[7];
var occupation = e.values[8];
var category = e.values[9];
var payment_number = e.values[10];
var payment_date = e.values[11];
//Inicializando mensaje opcional
var occupation_message = " ";
//Generando el nombre completo
if(second_name.localeCompare("") != 0){
second_name = " " + second_name;
}
if(second_lastname.localeCompare("") != 0){
second_lastname = " " + second_lastname;
}
var full_name = first_name + second_name + " " + first_lastname + second_lastname;
full_name = full_name.replace(/\s+/g," ");
//Generando compia del template
var copyID = DocsList.getFileById(docTemplate).makeCopy(docName + '_' + document_number).getId();
var copyDoc = DocumentApp.openById(copyID);
var copyBody = copyDoc.getActiveSection();
//Reemplazando texto en el template
copyBody.replaceText('keyDate', registration_date);
copyBody.replaceText('keyFullName', full_name);
copyBody.replaceText('keyIDType', document_type);
copyBody.replaceText('keyIDNumber', document_number);
copyBody.replaceText('keyEmail', email_address);
copyBody.replaceText('keyOccupation', occupation);
switch(occupation){
case "Estudiante de pregrado":
occupation_message = "(presente carnet el primer día del evento)";
var payment_worth = 100.00;
break
case "Estudiante de postgrado":
occupation_message = "(presente carnet el primer día del evento)";
var payment_worth = 150.00;
break
case "Profesional":
var payment_worth = 200.00;
break
}
copyBody.replaceText('keyOMessage', occupation_message);
copyBody.replaceText('keyCategory', category);
copyBody.replaceText('keyPaymentNum', payment_number);
copyBody.replaceText('keyPaymentDate', payment_date);
copyBody.replaceText('keyPayment', payment_worth)
copyDoc.saveAndClose();
//Convertir temporalmente a PDF
var pdf = DocsList.getFileById(copyID).getAs("application/pdf");
//Adjuntando PDF y enviado correo electrónico
var reply_email = "info#bioven.org.ve";
var bcc_email = "congresobioven#gmail.com";
var subject = "Constancia de inscripción - BIOVEN 2015";
var body = "Estimado " + full_name + ",<br/><br/> A través de este correo electrónico le hacemos entrega de su constancia de inscripción en el V Congreso Venezolano de Bioingeniería - BIOVEN 2015, la cual deberá presentar el primer día del congreso durante la verificación de registro.<br/><br/> Agradecidos,<br/><br/> <b>Comité Organizador del BIOVEN 2015</b>";
GmailApp.sendEmail(email_address, subject, body, {name: 'Congreso BIOVEN 2015', bcc: bcc_email, htmlBody: body, replyTo: reply_email, attachments: pdf});
//Guardando PDF en Drive
var folder_id = "Folder ID Here";
DriveApp.getFolderById(folder_id).createFile(pdf);
//Borrando archivo DOC temporal
DocsList.getFileById(copyID).setTrashed(true);
}
Try defining your variable payment_worth higher up in the code:
function onFormSubmit(e){
//Leyendo datos del formulario
var d = new Date();
//Other var definitions
var payment_worth = 0;
Give it an initial value of zero. Presently, if your Case/Select ever fails, the variable payment_worth would be undefined.
Just an idea. Don't know if it's a good idea. ;)
Case Select would look like this:
switch(occupation){
case "Estudiante de pregrado":
occupation_message = "(presente carnet el primer día del evento)";
payment_worth = 100.00;
break
case "Estudiante de postgrado":
occupation_message = "(presente carnet el primer día del evento)";
payment_worth = 150.00;
break
case "Profesional":
payment_worth = 200.00;
break
}