Google Api Calendar If else ,done with javascript - javascript

So I'm doing Google Calendar Api, that shows all the booked things for that day. I'm trying to get this code to print 'Vapaa' (means free in finnish and is shown if there's nothing booked in that time) only once but still print the rest of the appointments that come later that day. Here's the code that does the if else
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
var when = new Date(event.start.dateTime);
var hs = addZero(when.getHours());
var ms = addZero (when.getMinutes());
var end = new Date(event.end.dateTime);
var he = addZero(end.getHours());
var me = addZero (end.getMinutes());
var now = new Date();
var hn = addZero(now.getHours());
var mn = addZero (end.getMinutes());
if (!when) {
when = event.start.date;
}
if (when.getTime() <= now.getTime() && now.getTime() <= end.getTime()){
appendPre(event.summary + ' ' + hs + (':') + ms + '' + (' - ') + '' + he + (':') + me + '');
} else {
appendPre('Vapaa');
appendPre(event.summary + ' ' + hs + (':') + ms + '' + (' - ') + '' + he + (':') + me + '');
}
return;
}
} else {
appendPre('Ei varauksia');
}
Also the appendPre is printed to html with this code
function appendPre(message) {
if (message != 'Vapaa'){
var pre = document.getElementById('booked');
var textContent = document.createTextNode(message + '\n' + '\n');
} else {
var pre = document.getElementById('free');
var textContent = document.createTextNode(message + '\n' + '\n');
}
pre.appendChild(textContent);
}
I'm so lost so any help would be awesome.

return; stops right where it is and exits the function, so your for loop will only run once with the return in there. See W3C for more info.
Typically, if you want to exit only the loop, but continue in the function (if you have code after it, it doesn't look like you've shown that here), you can use break;. If you want to skip the rest of the stuff in the for loop (nothing is shown in your example), but continue iterating onto the next entry, you can use continue;. See W3C for more details.

Related

CasperJS running out of memory

I'm running the following script with CasperJS and after about 1/3rd of the way through the array it starts running out of swap space and the machine becomes extremely slow. What am i doing wrong here?
searchPages is an array of 54 numbers corresponding to a URL value for a search page.
casper.each(searchPages,function(casper,index){
loadSearch(casper,index);
});
function loadSearch(casper,index){
var currentTime = new Date();
var month = currentTime.getMonth() + 2;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var dateStart = month + "/" + day + "/" + year;
month = currentTime.getMonth() + 3;
var dateEnd = month + "/" + day + "/" + year;
casper.thenOpen(url,function(){
var myfile = "data-"+year + "-" + month + "-" + day+".html";
this.evaluate(function(j) {
document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
},index);
this.evaluate(function(start) {
$("#leaveDate").val(start);
},dateStart);
this.evaluate(function(end) {
$("#returnDate").val(end);
},dateEnd);
this.evaluate(function() {
$("#OSB_btn").click();
});
this.waitForSelector('#destinationForPackage', function() {
if (this.exists('#destinationForPackage')){
var name = casper.evaluate(function() {
return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
});
if (name != "Going To"){
if (name == null){
console.log("it's null");
}else{
name = name.replace("/","_");
casper.capture('Captures/Searches/search_' + name + '.jpg');
console.log("Capturing search_" + name);
}
}
}else{
console.log("Still doesn't exist...retry");
loadSearch(casper,index);
}
},function(){
console.log("Search page timed-out.");
},20000);
});
}
And it adds about 3GB per loop.
Well turns out this is a very well-known issue with PhantomJS. 3+ years as an open bug and apparently it has something to do with QT Webkit. Nonetheless, i was able to solve it by closing each page during the loop and re-opening a new Phantom page. It's a bit of a hacky work-around, but the memory consumption is far less. However, after about 200 pages, it still has a pretty high memory usage (1GB+). So, i break up my scripts into blocks of 200 and just start the next one upon completion. Here is the finished product that completes successfully without too much memory usage. It uses less on MacOS than Windows for some reason.
casper.start(url,function(){
this.echo('continuing captures...');
}).each(searchPages,function(casper,index){
loadSearch(this,index);
});
function loadSearch(casper,index){
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate() + 1;
var year = currentTime.getFullYear();
var dateStart = month + "/" + day + "/" + year;
var fortnightAway = new Date(+new Date + 12096e5);
var dateEnd = fortnightAway.getMonth() + 1 + "/" + fortnightAway.getDate() + "/" + fortnightAway.getFullYear();
casper.page.close();
casper.page = require('webpage').create();
casper.thenOpen(url,function(){
var myfile = "data-"+year + "-" + month + "-" + day+".html";
this.evaluate(function(j) {
document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
},index);
this.evaluate(function(start) {
$("#leaveDate").val(start);
},dateStart);
this.evaluate(function(end) {
$("#returnDate").val(end);
},dateEnd);
this.evaluate(function() {
$("#OSB_btn").click();
});
this.waitForSelector('#destinationForPackage', function() {
if (this.exists('#destinationForPackage')){
var name = casper.evaluate(function() {
return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
});
if (name != "Going To"){
if (name == null){
console.log("it's null");
}else{
name = name.replace("/","_");
name = name.replace("/","_");
casper.capture('Captures/Searches/search_' + name + '.jpg');
console.log("Capturing search_" + name);
}
}
}else{
console.log("Search failed to load. Retrying");
loadSearch(casper,index);
}
},function(){
console.log("Search page timed-out. Retrying");
loadSearch(casper,index);
},20000);
});
}
There might be a better solution to the original issue, but for a quick fix on running out of memory, try setTimeout to make the recursive call without winding up the stack...
setTimeout(() => loadSearch(casper,index), 0);
(This idea assumes that the memory issue is the result of too much recursive depth over a long wait time).

Preview not display straight away

When I click on my button's at top of textarea it opens either a hyperlink modal or a image insert modal shown in codepen example below.
I can create and insert links and images fine.
How ever when I create the links or image and click save on modal the preview does not show straight away I have to press a key in textarea to see new changes in preview.
Question: When I add a new hyperlink or image from my bootstrap modal
and click save how can I make sure the changes show up in preview
straight away. Using showdown.js
CODEPEN EXAMPLE
Script
$("#message").on('keyup paste copy change', function() {
var text = document.getElementById('message').value,
target = document.getElementById('showdown'),
converter = new showdown.Converter({parseImgDimensions: true}),
html = converter.makeHtml(text);
target.innerHTML = html;
});
Full Script
$('#button-link').on('click', function() {
$('#myLink').modal('show');
});
$('#button-image').on('click', function() {
$('#myImage').modal('show');
});
$('#button-smile').on('click', function() {
$('#mySmile').modal('show');
});
$('#myLink').on('shown.bs.modal', function() {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
$('#link_title').val(selectedText);
$('#link_url').val('http://');
});
$('#myImage').on('shown.bs.modal', function() {
$("#image_url").attr("placeholder", "http://www.example.com/image.png");
});
$("#save-image").on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
var replace_word = '![enter image description here]' + '[' + counter + ']';
if (counter == 1) {
if ($('input#image_width').val().length > 0) {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#image_url').val() + ' =' + $('input#image_width').val() + 'x' + $('input#image_height').val();
} else {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#image_url').val();
}
} else {
var add_link = '\n' + ' [' + counter + ']: ' + $('#image_url').val();
}
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end,len) + add_link;
});
$("#save-link").on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
if ($('#link_title').val().length > 0) {
var replace_word = '[' + $('#link_title').val() + ']' + '[' + counter + ']';
} else {
var replace_word = '[enter link description here]' + '[' + counter + ']';
}
if (counter == 1) {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#link_url').val();
} else {
var add_link = '\n' + ' [' + counter + ']: ' + $('#link_url').val();
}
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end,len) + add_link;
});
function findAvailableNumber(textarea){
var number = 1;
var a = textarea.value;
if(a.indexOf('[1]') > -1){
//Find lines with links
var matches = a.match(/(^|\n)\s*\[\d+\]:/g);
//Find corresponding numbers
var usedNumbers = matches.map(function(match){
return parseInt(match.match(/\d+/)[0]); }
);
//Find first unused number
var number = 1;
while(true){
if(usedNumbers.indexOf(number) === -1){
//Found unused number
return number;
}
number++;
}
}
return number;
}
$("#message").on('keyup paste copy change', function() {
var text = document.getElementById('message').value,
target = document.getElementById('showdown'),
converter = new showdown.Converter({parseImgDimensions: true}),
html = converter.makeHtml(text);
target.innerHTML = html;
});
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
Just trigger the keyup event at the end of the $("#save-link").on('click', function(e) {});
I assume as jQuery setting value doesn't trigger any of the related events set on $("#message")
$("#message").trigger('keyup');
Just tested on the codepen and works fine,
$("#save-link").on('click', function(e) {
//All your code
// ....
$("#message").trigger('keyup');
});
I hope this helps !!

Last array element keeps returning false

I have a time/date converter. When the user enters "130" for example it returns "06/07/2016 01:30:00" when they enter "6 7 16" for example it returns "06/07/2016 00:00:00" but when the user enters "6 7 16 130" for example it returns "06/07/2016 false:00"
Here is my relevant code (can show more if need be):
function checkDateTime(val) {
var nowDate = new Date();
var month, day, year, time;
var ar;
if (eval(val)) {
var tval = val.value;
ar = tval.split(' ');
if (ar.length === 3) { // i.e. if it's supposed to be a date
ar[0] = month;
ar[1] = day;
ar[2] = year;
document.getElementById("FromDate").value = CheckDate(val) + ' ' + '00:00:00';
//checkDate(ar[0] + ' ' + ar[1] + ' ' + ar[2]);
}
//alert(LeftPadZero(ar[0]) + ' ' + LeftPadZero(ar[1]) + ' ' + LeftPadZero(ar[2]));
//alert(CheckDate(ar[0] + ' ' + ar[1] + ' ' + ar[2]));
if (ar.length === 1) { // if it's a time
ar[0] = time;
var MM = nowDate.getMonth() + 1;
var DD = nowDate.getDate();
var Y = nowDate.getFullYear();
var nowDateFormat = LeftPadZero(MM) + '/' + LeftPadZero(DD) + '/' + Y;
alert(ar[0]);
document.getElementById("FromDate").value = nowDateFormat + ' ' + checktime(val) + ':00';
}
if (ar.length === 4) { // if date and time
ar[0] = month;
// alert(ar[0]);
ar[1] = day;
// alert(ar[1]);
ar[2] = year;
// alert(ar[2]);
ar[3] = time;
// alert(ar[3]);
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(val) + ':00';
// alert(ar[0] + ' ' + ar[1] + ' ' + ar[2] + ' ' + ar[3]);
}
}
}
function CheckDate(theobj) {
var isInvalid = 0;
var themonth, theday, theyear;
var arr;
if (eval(theobj)) {
var thevalue = theobj.value;
arr = thevalue.split(" ");
if (arr.length < 2) {
arr = thevalue.split("/");
if (arr.length < 2) {
arr = thevalue.split("-");
if (arr.length < 2) {
isInvalid = 1;
}
}
}
if (isInvalid == 0) {
themonth = arr[0];
theday = arr[1];
if (arr.length == 3) {
theyear = arr[2];
} else {
theyear = new Date().getFullYear();
}
if (isNaN(themonth)) {
themonth = themonth.toUpperCase();
//month name abbreviation array
var montharr = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
for (i = 0; i < montharr.length; i++) {
//if the first 3 characters of month name matches
if (themonth.substring(0, 3) == montharr[i]) {
themonth = i + 1;
break;
}
}
} else {
if (themonth < 1 || themonth > 12) {
isInvalid = 1;
}
}
}
if (isNaN(themonth) || isNaN(theday) || isNaN(theyear)) {
isInvalid = 1;
}
if (isInvalid == 0) {
var thedate = LeftPadZero(themonth) + "/" + LeftPadZero(theday) + "/" + LeftPadZero(theyear);
return thedate;
} else {
return false;
}
}
}
function checktime(x) {
var tempchar = new String;
tempchar = MakeNum(x);
if (tempchar != '' && tempchar.length < 4) {
//e.g., if they enter '030' make it '0030'
if (tempchar.length == 3) {
tempchar='0' + tempchar;
}
//e.g, if they enter '11' make it '1100'
if (tempchar.length == 2) {
tempchar=tempchar + '00';
}
//e.g, if they enter '6' make it '0600'
if (tempchar.length == 1) {
tempchar='0' + tempchar + '00';
}
}
if (tempchar==null || tempchar == '') {
return false;
}
else {
if (tempchar=='2400') {
return false;
}else{
var tempnum= new Number(tempchar);
var swmin = new Number(tempnum % 100);
var swhour = new Number((tempnum-swmin)/100);
if (swhour < 25 && swmin < 60) {
x = LeftPadZero(swhour) + ":" + LeftPadZero(swmin);
return x;
}
else {
return false;
}
}
}
return false;
/*
if(eval(changecount)!=null){
changecount+=1;
}
*/
}
function MakeNum(x) {
var tstring = new String(x.value);
var tempchar = new String;
var f = 0;
for (var i = 0; i < tstring.length; i++) {
// walk through the string and remove all non-digits
chr = tstring.charAt(i);
if (isNaN(chr)) {
f=f;
}
else {
tempchar += chr;
f++;
}
}
return tempchar;
}
I have tried numerous things to figure out why the time element returns false in an array of length 4, but not an array length 1 for some reason, including setting various alerts and checking the console. I have googled this problem several times and came up empty.
To reiterate, my problem is that the time element returns false in an array of 4, and what I am trying to accomplish is for the user to input a date and time and have them both formatted and displayed correctly.
Can anybody help and/or offer any advice and/or suggestions? Thanks!
Edit: user enters '130' should convert to '06/07/2016(today's date) 01:30:00'
6 7 16 should convert to '06/07/2016 00:00:00'
6 7 16 130 should convert to '06/07/2016 01:30:00'
There seems to be some missing parts here... various functions and whatever input type these ones need are excluded from your post... However, taking a guess, I'm going to say that when you are making your final "checktime" call, rather than passing the full "val" variable, you should just be passing the last chunk of your split input, "ar[3]" in this case. That way, only that piece is evaluated by the function.
IE:
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(val) + ':00';
should be
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(ar[3]) + ':00';
Again, this is just a guess due to the missing pieces.
Edit:
After getting some additional details, the issue DOES seem to be in the data being sent to the checktime function, however, due to the current code setup, the fix is actually just making sure that the data being processed by the checktime function is only the last item in the array... see below for the correction within the checktime function:
tempchar = MakeNum(x);
becomes
tempchar = MakeNum(x).split(' ').pop();

adding two variables together

I have been trying for... about 4 hours now lmao.
currentCalc returns 50
currentSum returns 0 when i alert them. Yet I cannot add them together with parseInt????
what am i doing wrong :'(
var identRow = $('tr.identRow');
identRow.each(function () {
var getIdentClass = $(this).attr('class').split(' ').slice(1);
$('tr.ohp' + getIdentClass + ' td.EURm').each(function (index) {
var currentCalc = parseInt($(this).text().replace('.', ''), 10);
var currentSum = $('tr.' + getIdentClass + ' td.totalEURm', this).text().replace('.', '');
total = parseInt(currentCalc, 10) + parseInt(currentSum, 10);
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
if (index == 6) {
alert(total);
}
});
});
EDIT:
Oh goodness. Im completely confused now. I putr the break there. It says total = 50.
I want each iteration to add itself to the total. That is why I add currentCalc to the text of the field im plopping the currentCalc into.
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
with my code now like this:
var identRow = $('tr.identRow');
identRow.each(function () {
var getIdentClass = $(this).attr('class').split(' ').slice(1);
$('tr.ohp' + getIdentClass + ' td.EURm').each(
function (index) {
var currentCalc = parseInt($(this).text().replace('.', ''), 10) || 0;
var currentSum = parseInt($('tr.' + getIdentClass + ' td.totalEURm', this).text().replace('.', ''), 10) || 0;
var total = currentCalc + currentSum;
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
if (index === 6) {
alert(total);
}
});
});
it alerts: 50, then 0, then 50, then 0.
EDIT:
How do I add currentCalc to its last value?
So first iteration its 10, seconds its 20. How do i make it so on the 2nd iteration it equals 30. currentCalc++ is just adding 1 to it.
Now you understand how crap i am :)
I am no expert in JS, but I saw that currentCalc is already an int:
var currentCalc = parseInt($(this).text().replace('.',''), 10);
//...
total = parseInt(currentCalc, 10) + parseInt(currentSum, 10);
so probably the parseInt on an int instead that on a string fails (?)
If you get two alerts, that likely means either your outer or inner .each statements is matching two entries.
If you're using firebug, use console.debug(total); instead of alert(). I recommend using console.debug(this) at some point to make sure it has what you think it has, too. Put it above the alert(). That information would be useful to see.
I do some code formatting and cleanup, try this:
var identRow = $('tr.identRow');
identRow.each(function () {
var getIdentClass = $(this).attr('class').split(' ').slice(1);
$('tr.ohp' + getIdentClass + ' td.EURm').each(
function (index) {
var currentCalc = parseInt($(this).text().replace('.', ''), 10) || 0;
var currentSum = parseInt($('tr.' + getIdentClass + ' td.totalEURm', this).text().replace('.', ''), 10) || 0;
var total = currentCalc + currentSum;
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
if (index === 6) {
alert(total);
}
});
});
I added condition if parseInt fails the vars currentCalc and currentSum will be 0.
Also, like in answer above i'm avoiding double parseInt
Can you give an example html page to try out?
//SUM OF COLUMNS
var total = 0;
var identRow = $('tr.identRow');
identRow.each(function () {
var getIdentClass = $(this).attr('class').split(' ').slice(1);
$('tr.ohp' + getIdentClass + ' td.EURm').each(
function (index) {
var currentCalc = $(this).text().replace('.', '');
total = parseInt(currentCalc)+total;
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
});
});
did the trick.
Now i just gotta set the total to 0 when it gets to the second category because at the moment it keeps adding from where it left off. Progress though. Thanks for everything

Cannot collect alle results of asynchronous call with geo.getLocations (Google Maps)

Below is my code. The problem is that recordsOut[0] is always undefined, whatever I try.
I know it has to do with the callback result. I tried to add some delays to give it more time to give a result back, but that did not help.
Any idea (with example please)? Very much appreciated.
function getAddress(id, searchValue) {
geo.getLocations(searchValue, function(result) {
if (result.Status.code == G_GEO_SUCCESS) {
var recordsOutStr = id + ';' + searchValue + ';';
for (var j = 0; j < result.Placemark.length; j++)
recordsOutStr += result.Placemark[j].address + ';' + result.Placemark[j].Point.coordinates[0] + ';' + result.Placemark[j].Point.coordinates[1];
recordsOut.push(recordsOutStr);
alert(recordsOutStr);
}
else {
var reason = "Code " + result.Status.code;
if (reasons[result.Status.code])
reason = reasons[result.Status.code]
alert('Could not find "' + searchValue + '" ' + reason);
}
});
}
function delay(ms)
{
var date = new Date();
var curDate = null;
do
{
curDate = new Date();
}
while (curDate - date < ms);
}
function processData()
{
objDataIn = document.getElementById("dataIn");
objDataOut = document.getElementById("dataOut");
if (objDataIn != null)
{
//alert(objDataIn.value);
if (objDataOut != null) {
recordsIn = explode(objDataIn.value, ';', true);
//for (i = 0; i < recordsIn.length; i++)
for (i = 0; i <= 5; i++)
{
addressStr = recordsIn[i]['address'] + ', ' +
recordsIn[i]['postalcode'] + ' ' +
recordsIn[i]['city'] + ', ' +
recordsIn[i]['country'];
getAddress(recordsIn[i]['id'], addressStr); //This will set resultStr
delay(200);
}
delay(5000);
alert('***' + recordsOut[0] + '***');
alert('***' + recordsOut[1] + '***');
alert('***' + recordsOut[2] + '***');
alert('***' + recordsOut[3] + '***');
alert('***' + recordsOut[4] + '***');
}
}
document.frmGeoCoder.submit();
}
Make sure that you have already defined recordsOut like this:
var recordsOut = [];
If you do it like this - var recordsOut; - it will be undefined.
If that doesn't work for you, please post the rest of the code, so we can see exactly what's going on.

Categories