Time overlap issue javascript - javascript

I am working in add task module in my project.i want to check every time task add check if existing tasks overlap or not. i am almost did but,one problem occur on time overlap condition not allow add task, example if user add tasks below times like below:
09:00 AM - 10:00 AM
10:30 AM - 11:00 AM
if i add tasks to between 10:00 AM to 10:30 AM not allowed in my condition on below:
function disabletime(start_time, end_time) {
var start_date = new Date(new Date(start_time).getTime());
var end_date = new Date(new Date(end_time).getTime());
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
if (tasks_array.length > 0) {
for (var i = 0; i < tasks_array.length; i++) {
var prev_s_date = Date.parse("1-1-2000 " + tasks_array[i].start_time);
var prev_e_date = Date.parse("1-1-2000 " + tasks_array[i].end_time);
var prev_start_date = new Date(new Date(prev_s_date).getTime());
var prev_end_date = new Date(new Date(prev_e_date).getTime());
if (i == 0) {
min_date = prev_start_date.getTime();
max_date = prev_end_date.getTime();
} else {
if (prev_end_date.getTime() > max_date) {
max_date = prev_end_date.getTime();
}
if (prev_start_date.getTime() < min_date) {
min_date = prev_start_date.getTime();
}
}
}
if ((start_date.getTime() == min_date) && (end_date.getTime() == max_date)) {
alert("Check the start and end time for this task!");
return false;
} else if ((start_date.getTime() < min_date) && (end_date.getTime() <= min_date) || (start_date.getTime() >= max_date) && (end_date.getTime() > max_date)) {
} else {
alert("Check the start and end time for this task!");
return false;
}
}
start_date = new Date(start_date.getTime() + 30 * 60000);
while (start_date < end_date) {
disable_times.push([start_date.getHours(), start_date.getMinutes()]);
start_date = new Date(start_date.getTime() + 30 * 60000);
}
return true;
}
here is my code flow, i add all tasks into json array in javascript. every time add new task check existing tasks on json array objects(inside if tasks exist) time overlap or not.
Here is a fiddle

I think it's a 'refactor if you want to debug' case.
Just breaking you problems into well isolated, small, simple problems will lead you to a solution faster than any deep debug cession.
You should break down the complexity of your code by using objects,
so you'll have a clear view on who does what, and you can test
easily each part.
I'm not sure the code below complies with all your needs, but it
should be much easier to use : i defined 2 objects : a task,
and a set of task.
For each i defined pretty simple methods, easy to read and debug.
I did not test the result, but you'll get the idea on how to do what
you want from here.
http://jsfiddle.net/gamealchemist/b68Qa/2/
// ------------------------------
// Task
function Task(startDate, endDate) {
this.start = startDate;
this.end = endDate;
}
// returns wether the time range overlaps with this task
Task.prototype.overlap = function (start, end) {
return (this.start <= end && this.end >= start);
}
// returns a string describing why the task is wrong, or null if ok
function checkTask(start, end) {
if (start > end) return "End time should exceed the start time";
if (start == end) return "End time should not same as the start time";
return null;
}
and now a set of tasks :
// ------------------------------
// Task Set
function TaskSet() {
this.tasks = [];
this.minDate = 0;
this.maxDate = 0;
}
// returns a string describing why the task cannot be added, or null if ok
TaskSet.prototype.check = function (start, end) {
var tasks = this.tasks;
// 1. Check date is valid
var dateCheck = checkTask(start, end);
if (dateCheck) return dateCheck;
// 2. overlap check
for (var i = 0; i < tasks.length; i++) {
var thisTask = tasks[i];
if (thisTask.overlap(start, end)) {
return 'time overlaps with another task';
}
}
return null;
}
// add the task.
TaskSet.prototype.add = function (start, end) {
var tasks = this.tasks;
if (task.length) {
this.minDate = start;
this.maxDate = end;
}
if (start < minDate) minDate = start;
if (end > maxDate) maxDate = end;
// you might want to check before inserting.
tasks.push(new Task(start, end));
}
// displays the current task inside the tasks div.
TaskSet.prototype.show = function () {
var tasks_array = this.tasks;
$("#tasks").html('');
$.each(tasks_array, function (index, item) {
var newRowContent = "<div>" + item.start_time + "-" + item.end_time + "</div>";
$("#tasks").append(newRowContent);
});
}
Let's use those objects :
// ---------------------------
var myTasks = new TaskSet();
$("#addtask").click(handle_AddTask_Clicked);
function handle_AddTask_Clicked(e) {
e.preventDefault();
var start = $("#task_stime").val();
var end = $("#task_etime").val();
var start_time = Date.parse("1-1-2000 " + start);
var end_time = Date.parse("1-1-2000 " + end);
var checkCanAdd = myTasks.check(start_time, end_time);
if (!checkCanAdd) {
myTasks.add(start_time, end_time);
myTasks.show(); // notice you might auto-refresh withinin add
} else {
alert(checkCanAdd);
}
}

finally i got solution from my friends on below code:
function disabletime(start_time, end_time) {
var start_date = start_time;
var end_date = end_time;
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
var startTimeOverlapIndex = -1;
var endTimeOverlapIndex = -1;
var sameDateIndex = -1;
if (tasks_array.length > 0) {
for (var i = 0; i < tasks_array.length; i++) {
var prev_s_date = new Date("January 1, 1111 " + tasks_array[i].start_time);
var prev_e_date = new Date("January 1, 1111 " + tasks_array[i].end_time);
if(end_date<=prev_e_date) {
if(end_date>prev_s_date) {
endTimeOverlapIndex = i+1;
break;
}
}
if(start_date<prev_e_date) {
if(start_date>=prev_s_date) {
startTimeOverlapIndex = i+1;
break;
} else {
if(end_date>prev_s_date) {
endTimeOverlapIndex = i+1;
break;
}
}
}
if(start_date.toString()===prev_s_date.toString() && end_date.toString()===prev_e_date.toString()) {
sameDateIndex = i+1;
break;
}
}
if(sameDateIndex>0) {
alert("Sorry! your time cannot be same as task ("+startTimeOverlapIndex+"), please check again!");
return false;
} else if(startTimeOverlapIndex>0) {
alert("Sorry! your START time is overlaping with task ("+startTimeOverlapIndex+"), please check again!");
return false;
} else if(endTimeOverlapIndex>0) {
alert("Sorry! your END time is overlaping with task ("+endTimeOverlapIndex+"), please check again!");
return false;
} else {
//do whatever you do
return true;
}
}
return true;
}
Live link on fiddle find here
http://jsfiddle.net/mur7H/

It is 100% working. Please find below the correct answer with date and time overlapping.
function isBetween(ST, ET, PST, PET) {
var res = false;
if (((ST - PST) * (ST - PET) <= 0) || ((ET - PST) * (ET - PET) <= 0) || ((PST - ST) * (PST - ET) <= 0) || ((PET - ST) * (PET - ET) <= 0)) res = true;
return res;
}
function disabletime(start_time, end_time) {
debugger;
var start_date = new Date(start_time);
var end_date = new Date(end_time);
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
var startTimeOverlapIndex = -1;
var endTimeOverlapIndex = -1;
var sameDateIndex = -1;
var resultA = true;
if (KitchenHourList.length > 0) {
for (var i = 0; i < KitchenHourList.length; i++) {
var prev_s_date = new Date(KitchenHourList[i].KitchenFromDate + " " + KitchenHourList[i].KitchenFromTime);
var prev_e_date = new Date(KitchenHourList[i].KitchenToDate + " " + KitchenHourList[i].KitchenToTime);
var STMinut = (start_date.getHours() * 60) + start_date.getMinutes();
var ETMinut = (end_date.getHours() * 60) + end_date.getMinutes();
var PSTMinut = (prev_s_date.getHours() * 60) + prev_s_date.getMinutes();
var PETMinut = (prev_e_date.getHours() * 60) + prev_e_date.getMinutes();
if (end_date <= prev_e_date) {
if (end_date > prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
endTimeOverlapIndex = i + 1;
break;
}
}
}
if (start_date < prev_e_date) {
if (start_date >= prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
startTimeOverlapIndex = i + 1;
break;
}
} else {
if (end_date > prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
{
endTimeOverlapIndex = i + 1;
break;
}
}
}
}
}
if (start_date.toString() === prev_s_date.toString() && end_date.toString() === prev_e_date.toString()) {
sameDateIndex = i + 1;
break;
}
}
if (sameDateIndex > 0) {
alert("Sorry! your time cannot be same as row (" + startTimeOverlapIndex + "), please check again!");
return false;
} else if (startTimeOverlapIndex > 0) {
alert("Sorry! your START time is overlaping with row (" + startTimeOverlapIndex + "), please check again!");
return false;
} else if (endTimeOverlapIndex > 0) {
alert("Sorry! your END time is overlaping with row (" + endTimeOverlapIndex + "), please check again!");
return false;
} else {
return true;
}
}
return true;
}

Related

mutliple set timeouts running at once

so, i have a for loop that I want to run multiple set timeouts at once so it can continually check if it is a certain time for multiple times. i can't just check for all multiple times all at once, the check needs to repeat after different amounts of time. it only continues to repeat the last iteration of the loop, the last dict in lat.
my approach simplified a bit:
lat = list of dictionaries with some values that differentiate them + times
for(i = 0; i< lat.length; i++){
if(lat[i][differentiate value]) = {
function checktime(){
if(currenttime != lat[i]){
setTimeout(checktime,30000)
}
else{
console.log("yay the time is right!")
}
}
else if(lat[i][differentiate value]) = {
function checktime(){
if(currenttime != lat[i]){
setTimeout(checktime,50000)
}
else{
console.log("yay the time is right!")
}
}
}
How would I go about making this (its for a notification app)
original code:
(each value in later looks like [[75,null,[7,28,2021]], null,[[9,52,"p"]],"e&r"] with the amount of notifications, a preset date, the date for these reminders to be on, by time, which would be the first if, and the array of at times. for testing I had 2 laters with 2 different at times):
chrome.storage.sync.get('later', function(data){
if (data.later !== null){
var lat = data.later;
for(i = 0; i< lat.length; i++){
var currentDict = lat[i];
if(currentDict['notis'][1] !== null){
console.log("cheese")
var by = currentDict['notis'][1];
console.log(by)
const d = new Date();
var hr = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
var da = currentDict['notis'][0][2][1];
var mo = currentDict['notis'][0][2][0];
var ye = currentDict['notis'][0][2][2]
var h = by[0];
var m = by[1];
var ampm = by[2];
if(ampm == "p"){
h = h + 12;
}
var byMS = h*3600000 + m*60000;
var currentMS = hr*3600000 + min*60000 + sec*1000;
//check if right date then check if time is lesss than
function checkdate(){
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if(da == day && mo == month && ye == year){
var amt = 0;
function checktime(){
if(byMS >= currentMS){
//noti and delete
var int = setInterval(function(){
chrome.notifications.create({
title: currentDict['name'],
message: "do da " + currentDict['name'],
iconUrl: "logo.png",
type: "basic"
})
amt++
console.log(amt)
const dddd = new Date();
console.log(dddd.getMinutes() + " / " + dddd.getSeconds())
if(amt >= currentDict['notis'][0][0]){
clearInterval(int)
console.log("done")
//ju finish taht
console.log(lat)
lat.splice(lat.indexOf(currentDict),1)
console.log(lat)
chrome.storage.sync.set({'later': lat})
}
}, (byMS-currentMS)/currentDict['notis'][0][0])
}
else{
setTimeout(checktime,30000)
}
}
checktime();
}
else{
setTimeout(checkdate,66400000)
}
}
checkdate();
}
else if(currentDict['notis'][2] !== null){
console.log("cheese")
var at = currentDict['notis'][2];
console.log(at)
var arrayat = [];
for(j = 0; j<= at.length-1; j++){
var atcycle = at[j];
console.log(atcycle)
const ddd = new Date();
var hr = ddd.getHours();
var min = ddd.getMinutes();
var da = currentDict['notis'][0][2][1];
var mo = currentDict['notis'][0][2][0];
var ye = currentDict['notis'][0][2][2]
var hrat = atcycle[0];
var minat = atcycle[1];
var ampm = atcycle[2];
if(ampm == "p"){
hrat = hrat + 12;
}
console.log(hrat + "/" + minat + "/" + ampm)
if(hr <= hrat){
var temparray = [];
temparray.push(hrat)
temparray.push(minat)
arrayat.push(temparray);
console.log(arrayat)
}
else if(hr == hrat){
if(min<minat){
var temparray = [];
temparray.push(hrat)
temparray.push(minat)
arrayat.push(temparray);
console.log(arrayat)}
}
}
console.log(arrayat.length)
function checkdate(){
console.log(arrayat.length)
console.log("date")
const d = new Date();
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if(da == day && mo == month && ye == year){
function check(){
console.log(arrayat.length)
console.log("check")
for(l=0; l<arrayat.length; l++){
console.log(arrayat.length)
const dd = new Date();
var hr = dd.getHours();
var min = dd.getMinutes();
console.log(arrayat[l][1])
console.log(min)
if(arrayat[l][0] == hr && arrayat[l][1] == min ){ //at one of the times
console.log(arrayat)
arrayat.splice(l,1)
console.log(arrayat)
if(arrayat.length == 0){
lat.splice(lat.indexOf(currentDict),1)
chrome.storage.sync.set({'later': lat})
console.log(lat)
}
chrome.notifications.create({
title: currentDict['name'],
message: "do da " + currentDict['name'],
iconUrl: "logo.png",
type: "basic"
})
//add noti with name and delete it
console.log(arrayat)
check();
}
}
console.log(arrayat.length)
if(arrayat.length !== 0){
console.log("and repeat")
setTimeout(check,15000);//SETINTERVAL INSTEAD? ANDCLEAR
}
}
check();
}
else{
setTimeout(checkdate,66400000)
}
}
checkdate();
}
}
}
})
}
This is the wrong approach. You know the times, so you know how far off they are in time. You don't need to check over and over again if the time has arrived. Instead work out how many milliseconds until the time in question, then set a timeout for that time.
You basically need to pass different functions to each setTimeout():
function checktime1(){
if(currenttime != lat[i]){
setTimeout(checktime1,30000)
}
else{
console.log("yay the time is right!")
}
}
function checktime2(){
if(currenttime != lat[i]){
setTimeout(checktime2,50000)
}
else{
console.log("yay the time is right!")
}
}
However, this is obviously not scalable. If you have lots of timeouts you will be writing lots of duplicate functions. Worse, if you have a dynamic number of timeouts this won't solve your problem.
Fortunately, javascript lets us declare functions inside another function:
function checktime(timeout){
function loop () {
if(currenttime != lat[i]){
setTimeout(loop,timeout)
}
else{
console.log("yay the time is right!")
}
}
loop();
}
This allows you to dynamically create functions as needed:
checktime(30000);
checktime(50000);
If you need to pass arguments to each timeouts (eg. if you need to display custom alerts) you can just pass it to your outer function and it will be captured in a closure:
function checktime(timeout, message){
function loop () {
if(currenttime != lat[i]){
setTimeout(loop,timeout)
}
else{
console.log(message)
}
}
loop();
}
Then you can do:
checktime(30000, "Yay, the time is right for timer 1");
checktime(50000, "Yay, the time is right for timer 2");
Similarly, if you need to execute custom logic for each timer you can also pass it as an argument (callback):
function checktime(timeout, callback){
function loop () {
if(currenttime != lat[i]){
setTimeout(loop,timeout);
}
else{
console.log("yay the time is right!");
callback(); // <----------------- execute custom logic
}
}
loop();
}
Which you can use like:
checktime(30000, () -> console.log("TIMER 1"));
checktime(50000, () -> alert("TIMER 2"));

Date range for cash flows

I am trying to create a cash flow with dates.
I have 2 dates: Start and End
If payments are monthly and suppose the rent payment day is on 15th. Then the cashflow would :
10/15/2018
11/15/2018
12/15/2018
1/15/2019..... and so forth until the end date.
Similarly if rent is paid every 3 months then cashflow would look like:
10/15/2018 1/15/2018 4/15/2018... and so forth.
I have the following code which works every time except when the rent is on 1st day of the month or last day of the month.
function createLedger(stDate, etDate){
if (stDate && etDate) {
var d2 = new Date(etDate);
var sDay = d2.getUTCDate();
var sMonth = d2.getUTCMonth() + 1;
var sYear = d2.getUTCFullYear();
var endOfLeaseDate = sYear + "-" + sMonth + "-" + sDay;
var d3 = new Date(stDate);
var s1Day = d3.getUTCDate();
var s1Month = d3.getUTCMonth() + 1;
var s1Year = d3.getUTCFullYear();
var startOfLeaseDate = s1Year + "-" + s1Month + "-" + s1Day;
var ddlFrequency = document.getElementById("ddFrequency");
var selectedFrequency = ddlFrequency.options[ddlFrequency.selectedIndex].value;
if (selectedFrequency) {
if (selectedFrequency == "D") {
dates = dateRange(startOfLeaseDate, endOfLeaseDate);
}
Here is where the issue is:
else if (selectedFrequency == "Q") {
dates = getQuartersDateRange(d3, d2)
dates = SortedQuarter(d3,dates);
}
else {
dates = [];
}
}
else {
dates = [];
}
createFormElement();
}
}
And i have the following codes to get the date range and quarter range.
function getQuartersDateRange(startOfLeaseDate, endOfLeaseDate) {
var dates = [];
var qlist = listQuarters(startOfLeaseDate, endOfLeaseDate);
for (var i = 0; i < qlist.length; i++) {
var yearquarter = qlist[i].split('-');
var dateQ = new Date(yearquarter[0], (yearquarter[1] * 3 - 3) + 1, startOfLeaseDate.getUTCDate());
qDay = dateQ.getUTCDate();
qMonth = dateQ.getUTCMonth();
qYear = dateQ.getUTCFullYear();
var qDate = qYear + "-" + qMonth + "-" + qDay;
dates.push(qDate);
}
return dates;
}
function SortedQuarter(startOfLeaseDate, dates) {
var qdatesSorted = [];
for (var j = 0; j < dates.length; j++) {
var month;
var splitDate = dates[j].split('-');
if (j == 0)
month = startOfLeaseDate.getUTCMonth() + 1;
else {
startOfLeaseDate.setMonth(startOfLeaseDate.getUTCMonth() + 3)
month = startOfLeaseDate.getUTCMonth() + 1;
}
var qDate = splitDate[0] + "-" + month + "-" + splitDate[2];
qdatesSorted.push(qDate);
}
return qdatesSorted;
}
function listQuarters(sDate, eDate) {
if (sDate > eDate) {
var t = eDate;
eDate = sDate;
sDate = t;
}
sDate = new Date(sDate);
sDate.setDate(2);
var startQ = getQuarter(sDate);
var endQ = getQuarter(eDate);
var result = [startQ];
while (startQ != endQ) {
sDate.setMonth(sDate.getUTCMonth() + 3);
startQ = getQuarter(sDate);
result.push(startQ);
}
return result;
}
The issue here is that when the start date = 11/1/2018 and end date = 01/31/2020
the cashflow prints as follows
11/1/2018 3/1/2019 6/1/2019 9/1/2019 12/1/2019...and so forth. So instead of going from 11/1/2018 to 2/1/2018, it skips the month and goes to the next one. I am not sure why it does that only towards the end of the month or the beginning of the month.
Any help is appreciated. Thank you.
Using moment library worked for me. aLSO, I rewrote the date range as follows:
function createLedger(stDate, etDate) {
if (stDate && etDate) {
var endOfLeaseDate = moment(etDate, "MM/DD/YYYY");
var startOfLeaseDate = moment(stDate, "MM/DD/YYYY");
dateRange(startOfLeaseDate, endOfLeaseDate);
}
}
function dateRange(stDate, etDate) {
var dates = [];
var now = etDate.clone();
var day = etDate.date();
while(now.isAfter(stDate)) {
var month = now.clone().endOf("month");
if (now.date() < day && day <= month.date()) {
now.date(day);
}
dates.push(now.format("MM/DD/YYYY"));
//dates._reverse();
now = now.clone().subtract({"months": 1});
}
console.log(dates);
}
function RunLedgerAndPV() {
var stDate = "11/26/2018";
var etDate = "09/25/2019";
createLedger(stDate, etDate);
}
RunLedgerAndPV();

Exceeded maximum execution time in Google Adwords

This is an extension of the following question. I can't use it because PropertiesService and ScriptApp is not supported in Adwords and I didn't find anything relevant so far on the question adapted to Adwords.
I have an Adwords script that constantly gets the error Exceeded maximum execution time. For an MCC accounts, I think the maximum time execution is 30 minutes. Does anyone know if there is a way to extend this time limit? Or perhaps is there a way to call the Adwords script again and it picks up from where it left off? Queuing? Could I use an MCCScript with Google-Apps-Script?
Here is what I have done so far ...
function timeDrivenTrigger(myFunct) {
var REASONABLE_TIME_TO_WAIT = 4*6000;
var MAX_RUNNING_TIME = 1*6000;
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1sYQ__CM33oL2OLzbScQEdcQ6LvDxJCohP024vdSGfSI/edit#gid=0');
var sheet = ss.getSheets()[0];
var cell = sheet.getRange('A1');
var startTime= (new Date()).getTime();
myFunct;
var startRow= cell.getValue() || 1;
for(var ii = startRow; ii <= 10000; ii++) {
var currTime = (new Date()).getTime();
if(currTime - startTime >= MAX_RUNNING_TIME) {
cell.setValue(ii);
ScriptApp.newTrigger("runMe")
.timeBased()
.at(new Date(currTime+REASONABLE_TIME_TO_WAIT))
.create();
break;
}
}
}
UPDATE WITH PARALLEL EXECUTION
Here is my whole code ...
//Your build Google-Spreadsheet
var SPREADSHEET_URL = "https://docs.google.com/spreadsheets/d/1k4o_8O_11OvhZRergefWKgXQ8_XxIs7D31-NV9Ove-o/edit#gid=749396300";
//Fetch and convert data in a JSON structure
var spreadsheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = spreadsheet.getSheetByName('Campaigns');
var data = sheet.getRange("A:C").getValues();
var accountList = accountsListing(data);
accountList= accountList.map(function (el) {
return el.trim();
});
function main() {
accountIdList = [];
accountItr = MccApp.accounts().get();
while(accountItr.hasNext()) {
account = accountItr.next();
if (accountList.indexOf(account.getName()) > -1) {
accountIdList.push(account.getCustomerId())
}
}
if(accountList.length > 0) {
var accountSelector = MccApp.accounts()
.withIds(accountIdList)
.withLimit(40);
accountSelector.executeInParallel('adjustCPCmax');
}
}
String.prototype.format = function () {
var i = 0, args = arguments;
return this.replace(/{}/g, function () {
return typeof args[i] != 'undefined' ? args[i++] : '';
});
};
function isBlank(line) {
return line[0].trim() === '' && line[1].trim() === '';
}
function parseData(data) {
const output = {};
var currentGroupName = '';
data.forEach(function(line, index){
if (isBlank(line) || index === 0){
return;
}
if (line[0].trim().length > 1) {
currentGroupName = line[0].trim();
}
output[currentGroupName] = output[currentGroupName] || {};
output[currentGroupName][line[1]] = line[2];
});
return output;
}
function accountsListing(data) {
function isBlank(line){
return line[0].trim() === '';
}
const output = [];
data.forEach(function(line, index) {
if (isBlank(line) || index === 0) {
return;
}
output.push(line[0])
});
return output
}
function parseKeyword(keyword, keywordId, maxCPC) {
Logger.log('THE NAME OF THE KEYWORDID IS ' + keywordId + '\n')
var report = AdWordsApp.report(
'SELECT Id, Criteria, CampaignName, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
'FROM KEYWORDS_PERFORMANCE_REPORT ' +
'WHERE ' +
'Id = ' + keywordId);
var rows = report.rows();
while(rows.hasNext()) {
var row = rows.next();
var keywordIdReport = row['Id'];
var keywordNameReport = row['Criteria'];
var campaignName = row['CampaignName'];
var cpcBid = row['CpcBid'];
var firstPageCpc = row['FirstPageCpc'];
var firstPositionCpc = row['FirstPositionCpc'];
var topOfPageCpc = row['TopOfPageCpc'];
Logger.log('INFO')
Logger.log(keyword.getText())
Logger.log(keywordId)
Logger.log(keywordNameReport)
Logger.log(keywordIdReport + '\n')
if (keywordId === keywordIdReport) {
if (firstPositionCpc && (firstPositionCpc > 0 && firstPositionCpc <= maxCPC)) {
var newCPC = firstPositionCpc;
} else if (topOfPageCpc && (topOfPageCpc > 0 && topOfPageCpc <= maxCPC)) {
var newCPC = topOfPageCpc;
} else if (firstPageCpc && (firstPageCpc > 0 && firstPageCpc <= maxCPC )) {
var newCPC = firstPageCpc;
} else {
var newCPC = minCPC;
}
Logger.log('KeywordIdReport :' + keywordIdReport)
Logger.log('campaignName :' + campaignName)
Logger.log('CPCbid :' + cpcBid)
Logger.log('firstPositionCpc : ' + firstPositionCpc)
Logger.log('topOfPageCpc : ' + topOfPageCpc)
Logger.log('firstPageCpc : ' + firstPageCpc)
Logger.log('NewCPC : ' + newCPC + '\n')
keyword.bidding().setCpc(newCPC)
break;
}
}
}
function getMaxCPC(account, campaign) {
var cleanData= parseData(data);
//Formatting account and campaign
var account = '{}'.format(account.getName())
var campaign = '{}'.format(campaign.getName())
Logger.log('Account :' + account)
Logger.log('Campaign :' + campaign + '\n')
return cleanData[account][campaign];
}
function adjustCPCmax() {
//min CPC
var minCPC = 0.50;
var account = AdWordsApp.currentAccount();
Logger.log('=================================' + account.getName() + "=======================================")
var campaignIterator = AdWordsApp.campaigns().get();
while (campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
try {
var maxCPC = getMaxCPC(account, campaign)
}
catch(e) {
}
if (maxCPC) {
Logger.log('The entrence worked with max CPC : ' + maxCPC + '\n')
keywordIterator = campaign.keywords().get();
var startTime= (new Date()).getTime();
while (keywordIterator.hasNext()) {
var keyword= keywordIterator.next()
var keywordId = Number(keyword.getId()).toPrecision()
parseKeyword(keyword, keywordId, maxCPC);
}
}
}
}
Be aware that this code will work in the MCC script environment. It could work for any account from a Google spreadsheet.
P.S. This following question gave me a good idea how to process, but I want to know your suggestions.

Keep Overlapping Events On Top

I am using full calendar.
Here is a sample of the problem:
The problem being that non-working days should stay on top no matter what. Default Task should be sliding between nwd and super cool project.
Would anyone know what I could either do on serverside, which currently does:
var sortedList = eventList
.OrderBy(p => p.resource).
ThenBy(p => new
DateTime(ConvertFromUnixTimestamp(p.start).Year,
ConvertFromUnixTimestamp(p.start).Month,
ConvertFromUnixTimestamp(p.start).Day)
).ThenBy(p => !p.isDate)
.ThenBy(p => p.title).ToList();
List<dynamic> finalList = new List<object>();
for (int i = 0; i < sortedList.Count(); ++i)
{
var e = sortedList.ElementAt(i);
finalList.Add(
new
{
id = i.ToString(),
realid = e.realid,
isDate = e.isDate,
title = e.title,
start = ResolveStartDate(StartDate(ConvertFromUnixTimestamp(e.start).AddSeconds(i))),
end = e.end,
description = e.description,
allDay = e.allDay,
resource = e.resource,
editable = e.editable,
color = e.color
}
);
}
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(finalList);
Or client side, which fullcalendar seems to have:
function segCmp(a, b) {
//return (b.msLength - a.msLength) * 100 + (a.event.start - b.event.start);
return (a.event.start - b.event.start);
}
function segsCollide(seg1, seg2) {
//return seg1.end > seg2.start && seg1.start < seg2.end;
return false;
}
/* Event Sorting
-----------------------------------------------------------------------------*/
// event rendering utilities
function sliceSegs(events, visEventEnds, start, end) {
var segs = [],
i, len=events.length, event,
eventStart, eventEnd,
segStart, segEnd,
isStart, isEnd;
for (i=0; i<len; i++) {
event = events[i];
eventStart = event.start;
eventEnd = visEventEnds[i];
if (eventEnd > start && eventStart < end) {
if (eventStart < start) {
segStart = cloneDate(start);
isStart = false;
}else{
segStart = eventStart;
isStart = true;
}
if (eventEnd > end) {
segEnd = cloneDate(end);
isEnd = false;
}else{
segEnd = eventEnd;
isEnd = true;
}
segs.push({
event: event,
start: segStart,
end: segEnd,
isStart: isStart,
isEnd: isEnd,
msLength: segEnd - segStart
});
}
}
return segs.sort(segCmp);
}
// event rendering calculation utilities
function stackSegs(segs) {
var levels = [],
i, len = segs.length, seg,
j, collide, k;
for (i=0; i<len; i++) {
seg = segs[i];
j = 0; // the level index where seg should belong
while (true) {
collide = false;
if (levels[j]) {
for (k=0; k<levels[j].length; k++) {
if (segsCollide(levels[j][k], seg)) {
collide = true;
break;
}
}
}
if (collide) {
j++;
}else{
break;
}
}
if (levels[j]) {
levels[j].push(seg);
}else{
levels[j] = [seg];
}
}
return levels;
}
That could allow an event spanning multiple days to always stay below a non-working day? a non-working day is defined in the event as isDate. So if event.isDate then it is a non working segment.
Thanks

How to delete and object from and array

Thanks for your help in advance. I have been trying for two days how to delete an object which is stored in an array and I dont get it. Just reading a lot on forums and trying, but nothing works.
<head>
<style>
</style>
<script type="text/javascript">
//Global Array to saved more than one object without having to declare all of them
var car = {};
var i;
var numRecords2 = 0;
var doors;
var outOfDateInsurance;
var contRecords = -1;
// Class Cars
function Cars(record, brand, color, doors, insurance, outOfDateInsurance)
{
this.record = record;
this.brand = brand;
this.color = color;
this.doors = doors;
this.insurance = insurance;
this.outOfDateInsurance = outOfDateInsurance;
}
//To validate number of the doors. It has to be 3 or 5
function validateDoors()
{
doors = prompt("Number of doors");
doors = parseInt(doors);
if (isNaN(doors) === false && (doors == 3 || doors == 5))
{
return;
}
else
{
alert("Wrong character. Please, set 3 or 5");
validateDoors();
}
}
//To validate date's format
function validateFormatDate(outOfDateInsurance)
{
var RegExPattern = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/;
if ((outOfDateInsurance.match(RegExPattern)) && (outOfDateInsurance!=''))
{
return true;
}
else
{
return false;
}
}
//To check if the date is in the calendar
function realDate(outOfDateInsurance)
{
var fechaf = outOfDateInsurance.split("/");
var d = fechaf[0];
var m = fechaf[1];
var y = fechaf[2];
return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0)).getDate();
}
//To validate the date is over today
function validateAboveDate(outOfDateInsurance)
{
var datef = outOfDateInsurance.split("/");
var d = datef[0];
var m = datef[1];
var y = datef[2];
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10)
{
dd='0'+dd
}
if(mm<10)
{
mm='0'+mm
}
var today = dd+'/'+mm+'/'+yyyy;
var todayf = today.split("/");
var dt = todayf[0];
var mt = todayf[1];
var yt = todayf[2];
if ((d > dt) && (m >= mt) && (y >= yt))
{
return true;
}
else
{
if ((d = dt) && (m > mt) && (y >= yt))
{
return true;
}
else
{
if ((d < dt) && (m > mt) && (y >= yt))
{
return true;
}
else
{
return false;
}
}
}
}
//To validate the date's is right
function checkingDate()
{
outOfDateInsurance = prompt("Insurance's End date (dd/mm/yyyy)");
if(validateFormatDate(outOfDateInsurance))
{
if(realDate(outOfDateInsurance))
{
if (validateAboveDate(outOfDateInsurance))
{
alert("Record has been introduced into the system");
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
//To create objects
function addCar()
{
var numRecords = prompt("How many records do you want to introduce to the system?");
numRecords = parseInt(numRecords);
if (isNaN(numRecords) === false)
{
var istart = contRecords + 1;
var iend = numRecords2 + numRecords;
//problema aƱadiendo cars porque reemplaza si no lo hago todo de una vez
for (i = istart; i < iend; i++)
{
contRecords++;
var record = contRecords;
var brand = prompt("Car's Brand");
var color = prompt("Car's Color");
validateDoors();
var insurance = confirm("Does have the car insurance? Press OK for YES and CANCEL for NO");
if (insurance === true)
{
insurance = "Yes";
checkingDate();
}
else
{
insurance = "No";
alert("Record has been introduced into the system");
}
//CONSTRUCTOR We are creating the object car in the Class Cars
car[i] = new Cars(record, brand, color, doors, insurance, outOfDateInsurance);
}
numRecords2 = numRecords2 + numRecords;
}
else
{
alert("Please, introduce the number of the records you want to introduce");
addCar();
}
}
//To display the objects created
function displayCar()
{
document.getElementById("container").innerHTML = "";
for (i = 0; i < numRecords2; i++)
{
//we are creating an element <p>
var parag = document.createElement('p');
parag.id = "paragraph" + i;
//we are creating an element <br>
var br = document.createElement('br');
//we are creating a text node
var textRecord = document.createTextNode("Record: " + car[i].record);
var textBrand = document.createTextNode("Brand: " + car[i].brand);
var textColor = document.createTextNode("Color: " + car[i].color);
var textDoors = document.createTextNode("Number of doors: " + car[i].doors);
var textInsurance = document.createTextNode("Insurance: " + car[i].insurance);
if (car[i].insurance === "Yes")
{
var textOutOfDateInsurance = document.createTextNode("Date Insurance: " + car[i].outOfDateInsurance);
}
else
{
var textOutOfDateInsurance = document.createTextNode("Date Insurance: ");
}
//we are adding the text nodes created to the <p>
parag.appendChild(textRecord);
//We are creating a clone from a node to have multiple break lines
parag.appendChild(br.cloneNode());
parag.appendChild(textBrand);
parag.appendChild(br.cloneNode());
parag.appendChild(textColor);
parag.appendChild(br.cloneNode());
parag.appendChild(textDoors);
parag.appendChild(br.cloneNode());
parag.appendChild(textInsurance);
parag.appendChild(br.cloneNode());
parag.appendChild(textOutOfDateInsurance);
//we are adding the whole <p> with the text nodes into the div created in the html
document.getElementById("container").appendChild(parag);
}
}
function deleteCar()
{
car[0] = null;
car.splice(0);
for (i = 0; i <= contRecords; i++)
{
alert(car[i]);
}
//if (contRecords >=0)
//{
// var numRecordToDelete = prompt("Introduce the record's number you want to delete");
// numRecordToDelete = parseInt(numRecordToDelete);
// if (isNaN(numRecordToDelete) === false)
// {
// //var i = numRecordToDelete;
// //
// // alert('Record: ' + i);
// //if(car[i].record === 'Record: ' + i)
// //{
// // alert('Record: ' + i);
// // car.splice(i,1);
// // return false;
// //}
// car.shift();
// document.getElementById("container").innerHTML = car;
// }
// else
// {
// alert("The character you have introduce is not a number");
// deleteCar();
// }
//}
//else
//{
// alert("There are no any record to delete");
// return;
//}
}
</script>
</head>
<body>
<h1 style="text-align: center;">WELLCOME TO THE AMAZING SOFTWARE TO ADD CARS TO YOUR SYSTEM</h1>
<br><br>
<!-- Button to create the object car -->
<input type="button" value="Add Car" onclick="addCar()">
<!-- Button to display the objects created -->
<input type="button" value="See Cars" onclick="displayCar()">
<input type="button" value="Delete Cars" onclick="deleteCar()">
<BR>
<hr>
<BR>
<!-- Div which information's objects is going to be displayed -->
<div id="container"></div>
</body>
So the thing is, I am adding objects to the array like a BBDD and i dont know how to do it to delete one object from the array and re-organize the other objects in the array's positions like, if I delete the element's array number 2, then, the number 3 will be the second one and the fodth one would be the third, etc...
Thanks a lot, any doubt, please, let me know. I really appreciate your help.
//Global Array to saved more than one object without having to declare all of them
var car = [],
doors,
outOfDateInsurance;
// Class Cars
function Cars(record, brand, color, doors, insurance, outOfDateInsurance)
{
this.record = record;
this.brand = brand;
this.color = color;
this.doors = doors;
this.insurance = insurance;
this.outOfDateInsurance = outOfDateInsurance;
}
//To validate number of the doors. It has to be 3 or 5
function validateDoors()
{
doors = prompt("Number of doors");
doors = parseInt(doors);
if (isNaN(doors) === false && (doors == 3 || doors == 5))
{
return;
}
else
{
alert("Wrong character. Please, set 3 or 5");
validateDoors();
}
}
//To validate date's format
function validateFormatDate(outOfDateInsurance)
{
var RegExPattern = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/;
if ((outOfDateInsurance.match(RegExPattern)) && (outOfDateInsurance!=''))
{
return true;
}
else
{
return false;
}
}
//To check if the date is in the calendar
function realDate(outOfDateInsurance)
{
var fechaf = outOfDateInsurance.split("/");
var d = fechaf[0];
var m = fechaf[1];
var y = fechaf[2];
return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0)).getDate();
}
//To validate the date is over today
function validateAboveDate(outOfDateInsurance)
{
var datef = outOfDateInsurance.split("/");
var d = datef[0];
var m = datef[1];
var y = datef[2];
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10)
{
dd='0'+dd
}
if(mm<10)
{
mm='0'+mm
}
var today = dd+'/'+mm+'/'+yyyy;
var todayf = today.split("/");
var dt = todayf[0];
var mt = todayf[1];
var yt = todayf[2];
if ((d > dt) && (m >= mt) && (y >= yt))
{
return true;
}
else
{
if ((d = dt) && (m > mt) && (y >= yt))
{
return true;
}
else
{
if ((d < dt) && (m > mt) && (y >= yt))
{
return true;
}
else
{
return false;
}
}
}
}
//To validate the date's is right
function checkingDate()
{
outOfDateInsurance = prompt("Insurance's End date (dd/mm/yyyy)");
if(validateFormatDate(outOfDateInsurance))
{
if(realDate(outOfDateInsurance))
{
if (validateAboveDate(outOfDateInsurance))
{
alert("Record has been introduced into the system");
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
//To create objects
function addCar()
{
var numRecords = prompt("How many records do you want to introduce to the system?");
numRecords = parseInt(numRecords);
if (isNaN(numRecords) === false)
{
var iend = numRecords;
//problema aƱadiendo cars porque reemplaza si no lo hago todo de una vez
for (var i = 0; i < iend; i++)
{
var brand = prompt("Car's Brand");
var color = prompt("Car's Color");
validateDoors();
var insurance = confirm("Does have the car insurance? Press OK for YES and CANCEL for NO");
if (insurance === true)
{
insurance = "Yes";
checkingDate();
}
else
{
insurance = "No";
alert("Record has been introduced into the system");
}
//CONSTRUCTOR We are creating the ARRAY car in the Class Cars
car.push(new Cars(car.length + 1, brand, color, doors, insurance, outOfDateInsurance));
}
}
else
{
alert("Please, introduce the number of the records you want to introduce");
addCar();
}
displayCar();
}
//To display the objects created
function displayCar()
{
document.getElementById("container").innerHTML = "";
for (var i = 0; i < car.length; i++)
{
//we are creating an element <p>
var parag = document.createElement('p');
parag.id = "paragraph" + i;
//we are creating an element <br>
var br = document.createElement('br');
//we are creating a text node
var textRecord = document.createTextNode("Record: " + car[i].record);
var textBrand = document.createTextNode("Brand: " + car[i].brand);
var textColor = document.createTextNode("Color: " + car[i].color);
var textDoors = document.createTextNode("Number of doors: " + car[i].doors);
var textInsurance = document.createTextNode("Insurance: " + car[i].insurance);
if (car[i].insurance === "Yes")
{
var textOutOfDateInsurance = document.createTextNode("Date Insurance: " + car[i].outOfDateInsurance);
}
else
{
var textOutOfDateInsurance = document.createTextNode("Date Insurance: ");
}
//we are adding the text nodes created to the <p>
parag.appendChild(textRecord);
//We are creating a clone from a node to have multiple break lines
parag.appendChild(br.cloneNode());
parag.appendChild(textBrand);
parag.appendChild(br.cloneNode());
parag.appendChild(textColor);
parag.appendChild(br.cloneNode());
parag.appendChild(textDoors);
parag.appendChild(br.cloneNode());
parag.appendChild(textInsurance);
parag.appendChild(br.cloneNode());
parag.appendChild(textOutOfDateInsurance);
//we are adding the whole <p> with the text nodes into the div created in the html
document.getElementById("container").appendChild(parag);
}
}
function deleteCar()
{
if (car.length >0)
{
var numRecordToDelete = prompt("Introduce the record's number you want to delete");
numRecordToDelete = parseInt(numRecordToDelete);
if (isNaN(numRecordToDelete) === false)
{
alert('Record: ' + numRecordToDelete);
if(numRecordToDelete >= car.length)
{
alert('Record: ' + numRecordToDelete);
car.splice(numRecordToDelete - 1,1);
displayCar();
return false;
}
else {
alert("Record not exist");
deleteCar();
}
}
else
{
alert("The character you have introduce is not a number");
deleteCar();
}
}
else
{
alert("There are no any record to delete");
return;
}
}
<h1 style="text-align: center;">WELCOME TO THE AMAZING SOFTWARE TO ADD CARS TO YOUR SYSTEM</h1>
<br><br>
<!-- Button to create the object car -->
<input type="button" value="Add Car" onclick="addCar()">
<!-- Button to display the objects created -->
<input type="button" value="See Cars" onclick="displayCar()">
<input type="button" value="Delete Cars" onclick="deleteCar()">
<BR>
<hr>
<BR>
<!-- Div which information's objects is going to be displayed -->
<div id="container"></div>
You can use Array.splice() to delete entries from an array.
Link
car.splice(0,1);
I should you work with an array of objects. Actually you work with an object how array where re many objects. With this is more easy foreach actual cars to add, see and delete.
car = [];
when add:
car.push(new Cars(record, brand, color, doors, insurance, outOfDateInsurance));
Other than that, I suggest you when you add or delete car, refresh data for the client can see changes and refreshing records number for deletes.
When your splice a element of array, the other elements after will move -1. For this reason must call displayCar() at the end.
var numRecordToDelete = prompt("Introduce the record's number you want to delete");
car.splice(numRecordToDelete,1);
I believe I understand what you are looking for and the example provided should address that, if not let me know.
<script>
var collectionOfObjects = [];
collectionOfObjects.push({name: "anObject1"});
collectionOfObjects.push({name: "anObject2"});
collectionOfObjects.push({name: "anObject3"});
collectionOfObjects.push({name: "anObject4"});
console.log("collectionOfObjects initial state");
console.log(collectionOfObjects);
console.log("deleteing 2nd member - this will delete the object even if other things have reference to it and not just remove it from the collection");
console.log("deleteing 2nd member - it will croupt the length of the array but we can fix that");
delete collectionOfObjects[2];
collectionOfObjects = collectionOfObjects.sort();
collectionOfObjects.length = collectionOfObjects.length - 1
console.log("collectionOfObjects after delete");
</script>
On a side note I just noticed you could do this also:
//To validate date's format
function validateFormatDate(outOfDateInsurance)
{
var RegExPattern = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/;
return outOfDateInsurance.match(RegExPattern) && (outOfDateInsurance!='')
}

Categories

Resources