Updating previous question with detailed example. I have a google sheet with three used columns (A: Event Title, B: Event Description, and D: Event Date). I want to create a new all day event on Google Calendar if none exists, and update the existing one if it already exists.
Here is the code I tried: I am getting the error: TypeError: Cannot read property 'setDescription' of undefined
function updatecal(){
var cal = CalendarApp.getCalendarById('c_lmsj3r1ogsaafhc68gfalstdco#group.calendar.google.com');
var data = SpreadsheetApp.getActive().getSheetByName("Data For Calendar");
const rows = data.getDataRange().getValues();
rows.forEach(function(row, index){
if (index === 0) return;
var eventdate = data.getRange(index, 4, 1, 1).getValue();
var eventtitle = data.getRange(index,1,1,1).getValue();
var eventdescription = data.getRange(index,2,1,1).getValue();
console.log(eventdate + eventtitle + eventdescription)
const eventdate1 = new Date(eventdate)
const events = cal.getEventsForDay(eventdate1);
if (events.lenght == 0){
var newevent = cal.createAllDayEvent(eventtitle,eventdate1,
{description: eventdescription});
} else {
ev = events[0];
ev.setDescription(eventdescription)
}
})
}
There is a typo in line 13 inside the if statement. You wrote lenght instead of length If you fix that the code runs just fine and the calendar events are created without any problem.
function updatecal(){
var cal = CalendarApp.getCalendarById('c_lmsj3r1ogsaafhc68gfalstdco#group.calendar.google.com');
var data = SpreadsheetApp.getActive().getSheetByName("Data For Calendar");
const rows = data.getDataRange().getValues();
rows.forEach(function(row, index){
if (index === 0) return;
var eventdate = data.getRange(index, 4, 1, 1).getValue();
var eventtitle = data.getRange(index,1,1,1).getValue();
var eventdescription = data.getRange(index,2,1,1).getValue();
console.log(eventdate + eventtitle + eventdescription)
const eventdate1 = new Date(eventdate)
const events = cal.getEventsForDay(eventdate1);
if (events.length == 0){ //The error was in this line
var newevent = cal.createAllDayEvent(eventtitle,eventdate1,
{description: eventdescription});
} else {
ev = events[0];
ev.setDescription(eventdescription)
}
})
}
References:
length()
I found out that my index page wasn't showing the updated user info for currently logged in user. So I changed the form page from:
<div class="col-xs-4">
<div class="col-md-4">
#Html.HiddenFor(model => model.SubmittedDate, new { Value = System.DateTime.Now })
#Html.HiddenFor(model => model.SubmittedBy, new { Value = Model.ADAccount })
</div>
</div>
**to:**
<div class="col-xs-4">
<div class="col-md-4">
#Html.HiddenFor(model => model.SubmittedDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.SubmittedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.UpdatedDate, new { Value = System.DateTime.Now })
#Html.HiddenFor(model => model.UpdateBy, new { htmlAttributes = new { Value = Model.ADAccount } })
</div>
</div>
I had also tried changing the form page like this but it didn't change anything:
#Html.HiddenFor(model => model.UpdateBy, new { Value = Model.ADAccount })
The submit looks like this in the form page:
#(Html.Kendo().Button()
.Name("submit")
.Content("Submit")
.HtmlAttributes(new { #class = "k-primary" })
.Events(ev => ev.Click("onClick")))
But for some reason it's still not showing the UpdateBy in the Index list. I don't see a specific reference in the Controller for UpdateBy or SubmittedBy. I see them both in the ApplicantCapturedData.cs list:
public string UpdateBy { get; set; }
public string SubmittedBy { get; set; }
I see in ApplicantController.cs, the Edit Post puts some data in the DB, but doesn't mention the updateBy or SubmittedBy variables or model specifically. However, in the old code, the SubmittedBy variable change did show on the index list. I looked in the project, and there are no specific references to SubmittedBy besides ApplicantController
When I put a watch on UpdateBy, I see it go back and forth between the old user, me, and null. Apparently it ends with the old user, because that's what is displayed in the list of applicants on the index after the form is submitted.
Any thoughts on how to fix this? I'm new to MVC, and I'm not sure why this change isn't getting back to the model/db. When the applicantController gets the applicantCapturedData, it shows the old value for UpdateBy, not the new value.
The Edit Method should return current loged-in user to the view instead of BD data, but it's not. I'm not sure why.
I looked at controller not receiving model info, but it didn't seem like the same issue to me.
Let me know if you think I'm leaving any crucial info out that you need. I obviously can't post all of the mvc files and code here for clarity and sanity.
******Update*********
This is the Edit/Post method in ApplicantController.cs. It doesn't specifically refer to the SubmittedBy or UpdateBy, but the SubmittedBy part does show up in the index, even when we updated it in the form with current AD user:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ApplicantCapturedData applicantCapturedData)
{
var eRecordSchedulinglist = applicantCapturedData.ERecordScheduling;
var eRecordScheduling = new ERecordScheduling();
// int IDs = applicantCapturedData.ID;
//updating Provider License
var providerLicenselist = applicantCapturedData.ProviderLicense;
var providerLicense = new ProviderLicense();
var eprescribelist = applicantCapturedData.EPrescribe;
var eprescribe = new EPrescribe();
//updating payor table
var payorlist = applicantCapturedData.Payor;
var payor = new Payor();
//updating tax table
var taxlist = applicantCapturedData.TaxNPITaxonomy;
var tax = new TaxNPITaxonomy();
if (ModelState.IsValid)
{
//ERecordScheduling eRecordScheduling = new ERecordScheduling();
db.Entry(applicantCapturedData).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
int getid = applicantCapturedData.ID;
//Getting values for provider license already in db
var query = from p in db.ProviderLicenses
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in query)
{
db.ProviderLicenses.Remove(i);
}
db.SaveChanges();
int c = 1;
if (providerLicenselist != null)
{
var updatePLS = providerLicenselist.ToList();
// adding only new record to db
foreach (var i in updatePLS)
{
providerLicense.LicenseNumber = i.LicenseNumber;
providerLicense.State = i.State;
providerLicense.ProviderLicenseID = i.ProviderLicenseID;
i.ApplicantCapturedData_ID = getid;
if (providerLicense.ProviderLicenseID <= c)
{
providerLicense.ProviderLicenseID = providerLicense.ProviderLicenseID++;
}
db.ProviderLicenses.Add(i);
db.SaveChanges();
}
}
//getting Values already existing in db for Erecording Schedulign
var queryERS = from p in db.ERecordSchedulings
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in queryERS)
{
db.ERecordSchedulings.Remove(i);
}
db.SaveChanges();
if (eRecordSchedulinglist != null)
{
var updateESCH = eRecordSchedulinglist.ToList();
foreach (var item in updateESCH)
{
eRecordScheduling.DepartmentName = item.DepartmentName;
eRecordScheduling.Shedules = item.Shedules;
eRecordScheduling.VisitType = item.VisitType;
eRecordScheduling.GenericProvider = item.GenericProvider;
eRecordScheduling.ERecordSchedulingID = item.ERecordSchedulingID;
// a.ApplicantCapturedData_ID = newid;
item.ApplicantCapturedData_ID = getid;
if (eRecordScheduling.ERecordSchedulingID <= c)
{
eRecordScheduling.ERecordSchedulingID = eRecordScheduling.ERecordSchedulingID++;
}
//save to db
db.ERecordSchedulings.Add(item);
db.SaveChanges();
}
}
//Getting Values that already exisit in db for Taxonomy
var querytaxo = from p in db.TaxNPITaxonomies
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in querytaxo)
{
db.TaxNPITaxonomies.Remove(i);
}
db.SaveChanges();
if (taxlist != null)
{
var UpdateTaxo = taxlist.ToList();
foreach (var t in UpdateTaxo)
{
tax.GroupNPI = t.GroupNPI;
tax.Notes = t.Notes;
tax.TaxID = t.TaxID;
tax.TaxNPITaxonomyID = t.TaxNPITaxonomyID;
tax.Taxonomy = t.TaxID;
t.ApplicantCapturedData_ID = getid;
if (tax.TaxNPITaxonomyID <= c)
{
tax.TaxNPITaxonomyID = tax.TaxNPITaxonomyID++;
}
db.TaxNPITaxonomies.Add(t);
db.SaveChanges();
}
}
var queryeprescribe = from p in db.EPrescribes
where p.ApplicantCapturedData_ID == getid
select p;
foreach (var i in queryeprescribe)
{
db.EPrescribes.Remove(i);
}
db.SaveChanges();
if (eprescribelist != null)
{
var updateeprescribe = eprescribelist.ToList();
foreach (var t in updateeprescribe)
{
eprescribe.EPrescribeOptions = t.EPrescribeOptions;
eprescribe.ID = t.ID;
t.ApplicantCapturedData_ID = getid;
if (eprescribe.ApplicantCapturedData_ID <= c)
{
eprescribe.ApplicantCapturedData_ID = eprescribe.ApplicantCapturedData_ID++;
}
db.EPrescribes.Add(t);
db.SaveChanges();
}
}
//Geting values that already exist in db for Payors
var queryPayor = from p in db.Payors
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in queryPayor)
{
db.Payors.Remove(i);
}
db.SaveChanges();
if (payorlist != null)
{
var updatepayor = payorlist.ToList();
foreach (var p in updatepayor)
{
payor.Pyor = p.Pyor;
payor.PayorID = p.PayorID;
p.ApplicantCapturedData_ID = getid;
if (payor.PayorID <= c)
{
payor.PayorID = payor.PayorID++;
}
db.Payors.Add(p);
db.SaveChanges();
}
}
return RedirectToAction("Index");
}
return View(applicantCapturedData);
}
Here's the save in ApplicantController.cs. It doesn't have a specific reference to UpdateBy or SubmittedBy either, and yet SubmittedBy used to update when I changed the AD user:
// [HttpPost]
public ActionResult Save(ApplicantCapturedData applicantCapturedData)
{
ViewBag.PostedBills = applicantCapturedData.BillingAreas;
applicantCapturedData.BillingAreas = applicantCapturedData.BillingAreas;
//updating eRecordScheduling
var list = applicantCapturedData.ERecordScheduling;
var a = new ERecordScheduling();
var OtherAddressList = applicantCapturedData.PracticeInfoOtherLocations;
var otheraddresses = new PracticeInfoOtherLocation();
//var payorlist = applicantCapturedData.Payor;
//var payor = new Payor();
// int IDs = applicantCapturedData.ID;
//updating Provider License
var providerLicenselist = applicantCapturedData.ProviderLicense;
var providerLicense = new ProviderLicense();
var Eprescribelist = applicantCapturedData.EPrescribe;
var eprescribe = new EPrescribe();
//updating payor table
var payorlist = applicantCapturedData.Payor;
var payor = new Payor();
//updating tax table
var taxlist = applicantCapturedData.TaxNPITaxonomy;
var tax = new TaxNPITaxonomy();
// var lastEnt = db.ERecordSchedulings.AsEnumerable().Where(i => i.ERecordSchedulingID.CompareTo(a.ERecordSchedulingID))
int c = 1;//lastEnter.LastOrDefault().ERecordSchedulingID;
if (ModelState.IsValid)
{
db.ApplicantCapturedDatas.Add(applicantCapturedData);
// db.ERecordSchedulings.Add(applicantCapturedData);
db.SaveChanges();
//db.ERecordSchedulings.Add(applicantCapturedData.ERecordScheduling);
//get the primary key id after adding to the Db
int newid = applicantCapturedData.ID;
if (applicantCapturedData.ERecordScheduling != null)
{
// check if we have more record on Erecord scheduling using the count
//if count is greater than zero we have record to add to db.
if (applicantCapturedData.ERecordScheduling.Count() > 0)
{
/*
* This loops thru the list and add record
*
*/
foreach (var item in list)
{
a.DepartmentName = item.DepartmentName;
a.Shedules = item.Shedules;
a.VisitType = item.VisitType;
a.GenericProvider = item.GenericProvider;
a.ERecordSchedulingID = item.ERecordSchedulingID;
// a.ApplicantCapturedData_ID = newid;
item.ApplicantCapturedData_ID = newid;
//if you put a breakpoint at the beginning of this class you will see that all id is 0 I had to increment the id so I don't override itself.
if (a.ERecordSchedulingID <= c)
{
a.ERecordSchedulingID = a.ERecordSchedulingID++;
}
//save to db
db.ERecordSchedulings.Add(item);
db.SaveChanges();
//item.LicenseNumber = a.LicenseNumber;
//item.State = a.State;
//item.ProviderLicenseID = a.ProviderLicenseID;
}
}
}
if (applicantCapturedData.ProviderLicense != null)
{
if (applicantCapturedData.ProviderLicense.Count() > 0)
{
foreach (var i in providerLicenselist)
{
providerLicense.LicenseNumber = i.LicenseNumber;
providerLicense.State = i.State;
providerLicense.ProviderLicenseID = i.ProviderLicenseID;
i.ApplicantCapturedData_ID = newid;
if (providerLicense.ProviderLicenseID <= c)
{
providerLicense.ProviderLicenseID = providerLicense.ProviderLicenseID++;
}
db.ProviderLicenses.Add(i);
db.SaveChanges();
}
}
}
if (applicantCapturedData.Payor != null)
{
if (applicantCapturedData.Payor.Count() > 0)
{
foreach (var p in payorlist)
{
payor.Pyor = p.Pyor;
payor.PayorID = p.PayorID;
p.ApplicantCapturedData_ID = newid;
if (payor.PayorID <= c)
{
payor.PayorID = payor.PayorID++;
}
db.Payors.Add(p);
db.SaveChanges();
}
}
}
if (applicantCapturedData.PracticeInfoOtherLocations != null)
{
if (applicantCapturedData.PracticeInfoOtherLocations.Count() > 0)
{
foreach (var p in OtherAddressList)
{
otheraddresses.City = p.City;
otheraddresses.Fax = p.Fax;
otheraddresses.Phone = p.Phone;
otheraddresses.State = p.State;
otheraddresses.Street = p.Street;
otheraddresses.Suite = p.Suite;
otheraddresses.ZipCode = p.ZipCode;
otheraddresses.AppID = newid;
otheraddresses.ID = p.ID;
if (otheraddresses.ID <= c)
{
otheraddresses.ID = otheraddresses.ID++;
}
db.PracticeInfoOtherLocations.Add(p);
db.SaveChanges();
}
}
}
if (applicantCapturedData.EPrescribe != null)
{
if (applicantCapturedData.EPrescribe.Count() > 0)
{
foreach (var p in Eprescribelist)
{
eprescribe.EPrescribeOptions = p.EPrescribeOptions;
eprescribe.ID = p.ID;
p.ApplicantCapturedData_ID = newid;
if (eprescribe.ID <= c)
{
eprescribe.ID = eprescribe.ID++;
}
db.EPrescribes.Add(p);
db.SaveChanges();
}
}
}
if (applicantCapturedData.TaxNPITaxonomy != null)
{
if (applicantCapturedData.TaxNPITaxonomy.Count() > 0)
{
foreach (var t in taxlist)
{
tax.GroupNPI = t.GroupNPI;
tax.Notes = t.Notes;
tax.TaxID = t.TaxID;
tax.TaxNPITaxonomyID = t.TaxNPITaxonomyID;
tax.Taxonomy = t.TaxID;
t.ApplicantCapturedData_ID = newid;
if (tax.TaxNPITaxonomyID <= c)
{
tax.TaxNPITaxonomyID = tax.TaxNPITaxonomyID++;
}
db.TaxNPITaxonomies.Add(t);
db.SaveChanges();
}
}
}
return RedirectToAction("Index");
}
return View(applicantCapturedData);
}
Plugin: eonasdan/Bootstrap 3 Datepicker
Explaination:
I want to write an application that user can select 5 different hours for each day. so i created an array and add each day (without duplicate), for example user select 31/12/2017 and 30/12/2017 , now i want to give they this ability to select only 5 different hour for each day that selected.
Tried Code:
var limit = 5;
var i = 0;
var dateArray = new Object();
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
if ($.inArray(unqdate, dateArray) == -1) {
dateArray[unqdate] = unqtime
}
}
console.log(dateArray);
});
JSFiddle
(For testing, select a date, then click on save button, then check console)
Goal:
var dateArray = {
"31-12-2017": [{
"time": "14:00"
}, {
"time": "17:15"
}],
"30-12-2017": [{
"time": "13:00"
}, {
"time": "12:15"
}]
}
Problem:
I couldn't figured out how can i add another time to each day. it's my first time i work with array and object like this.
I want to prevent duplicate entry and only five different hour per day.
Somehow I'm in learning.
There is some problem with your JS Code:
var limit = 5;
var i = 0;
var dateArray = new Object();
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
if ($.inArray(unqdate, dateArray) == -1) {
if(dateArray[unqdate] && dateArray[unqdate].length < limit) {
if(!dateArray[unqdate].find((ele) =>ele.time === unqtime)){
dateArray[unqdate].push({"time": unqtime})
}
} else {
dateArray[unqdate] = [{"time": unqtime}]
}
}
}
console.log(dateArray);
});
Note included logic for time split. You can use split by : and take the first 2 element of array.
I have created JSON response for your requirement.
Result :: JSON.stringify(parentObject)
Code is as below.
$(document).ready(function() {
$('#datetimepicker1').datetimepicker({
stepping: 30,
sideBySide: true,
showTodayButton: true,
format: 'DD-MM-YYYY HH:mm:ss',
});
// my code
var limit = 5;
var i = 0;
var parentObject = new Object();
var parentArray = [];
var dateAndTimeObject;
function isDateSelectedExists(date) {
for (var i = 0; i < parentArray.length; i++) {
var obj = parentArray[i];
if (obj["date"] === date) {
return i;
}
}
return -1;
}
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
var tempIndex = isDateSelectedExists(unqdate);
console.log("tempIndex :: " + tempIndex);
if (tempIndex == -1) {
console.log("date doesn't exists");
dateAndTimeObject = new Object();
dateAndTimeObject["date"] = unqdate;
var timeArray = [];
timeArray.push(unqtime);
dateAndTimeObject["time"] = timeArray;
parentArray.push(dateAndTimeObject);
parentObject["res"] = parentArray;
} else {
console.log("date exists");
dateAndTimeObject = parentArray[tempIndex];
var timeArray = dateAndTimeObject["time"];
if(timeArray.length<5) timeArray.push(unqtime);
dateAndTimeObject["time"] = timeArray;
}
console.log("final res :: " + JSON.stringify(parentObject));
}
});});
I am trying to get specific values from the general site that contains the annual reports of public-listed firms using Selenium Webdriver JS. Kindly help me investigate. I get the issue on clicking the Annual Report link.
The process that I'm trying to automate is listed below:
Go to site (http://edge.pse.com.ph/financialReports/form.do)
Filter by type of report (sendKeys('Annual Report') and fromDate attribute value to 4-23-2012 (year 2012 to get 4-5 annual reports of each firm)
click btnSearch
click Annual Report link per company row to view report (a tag is inside a td)
switch to the popup window
get specific values as object values and store it in the array
close popup window and get back to initial window
Repeat it on the succeeding company rows (take note that the site has pagination and a total of 22 pages (or tables) must be looped through
Kindly check my initial code for the process below. I also think that my implicitWaits are working. Does it apply on Selenium executeScript commands?
var webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
var driver = new webdriver.Builder()
.forBrowser('chrome')
.build();
driver.get('http://edge.pse.com.ph/financialReports/form.do');
driver.wait(until.titleIs('Financial Reports'), 1000)
driver.manage().timeouts().implicitlyWait(5000);
driver.findElement(By.name('tmplNm')).sendKeys('Annual Report');
driver.executeScript("document.getElementsByName('fromDate').setAttribute('value', '4-23-2012')");
driver.findElement(By.id('btnSearch')).click();
var totalPages = 22;
var num = 0;
while (num < totalPages) {
var pagingArray = driver.executeScript("document.querySelector('.paging').getElementsByTagName('span')");
for (var p = 0; p < pagingArray.length; p++) {
var page = driver.executeScript("pagingArray[p].getElementsByTagName('a')[0]");
page.click();
var table = driver.executeScript("document.querySelector('table.list')");
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++) {
if (j == 1) {
// Store the current window handle
var winHandleBefore = driver.getWindowHandle();
var reportLink = driver.executeScript("table.rows[i].cells[j].getElementsByTagName('a')[0]");
reportLink.click();
// Switch to new window opened
for (var winHandle in driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
var companyName = driver.executeScript("document.getElementById('companyName').innerHTML");
var stockTicker = driver.executeScript("document.getElementById('companyStockSymbol').innerHTML");
checkCompany(companyName, stockTicker);
var tableBS = driver.executeScript("document.getElementById('BS')");
var currentYear = driver.executeScript("tableBS.rows[1].cells[1].getElementsByTagName('span')[0]");
if (!checkBalanceSheets(companyName, currentYear)) {
bsCurrentYear = new Object();
bsCurrentYear.year = currentYear;
bsCurrentYear.currentAssets = driver.executeScript("tableBS.rows[2].cells[1].getElementsByTagName('span')[0]");
bsCurrentYear.totalAssets = driver.executeScript("tableBS.rows[3].cells[1].getElementsByTagName('span')[0]");
bsCurrentYear.currentLiabilities = driver.executeScript("tableBS.rows[4].cells[1].getElementsByTagName('span')[0]");
bsCurrentYear.totalLiabilities = driver.executeScript("tableBS.rows[5].cells[1].getElementsByTagName('span')[0]");
bsCurrentYear.company = companyName;
balanceSheets.push(bsCurrentYear);
}
var previousYear = driver.executeScript("tableBS.rows[1].cells[2].getElementsByTagName('span')[0]");
if (!checkBalanceSheets(companyName, previousYear)) {
bsPreviousYear = new Object();
bsPreviousYear.year = previousYear;
bsPreviousYear.currentAssets = driver.executeScript("tableBS.rows[2].cells[2].getElementsByTagName('span')[0]");
bsPreviousYear.totalAssets = driver.executeScript("tableBS.rows[3].cells[2].getElementsByTagName('span')[0]");
bsPreviousYear.currentLiabilities = driver.executeScript("tableBS.rows[4].cells[2].getElementsByTagName('span')[0]");
bsPreviousYear.totalLiabilities = driver.executeScript("tableBS.rows[5].cells[2].getElementsByTagName('span')[0]");
bsPreviousYear.company = companyName;
balanceSheets.push(bsPreviousYear);
}
var tableIS = driver.executeScript("document.getElementById('IS')");
if (!checkIncomeStatements(companyName, currentYear)) {
isCurrentYear = new Object();
isCurrentYear.year = currentYear;
isCurrentYear.grossrevenue = driver.executeScript("tableIS.rows[4].cells[1].getElementsByTagName('span')[0]");
isCurrentYear.grossexpense = driver.executeScript("tableIS.rows[7].cells[1].getElementsByTagName('span')[0]");
isCurrentYear.netincomeaftertax = driver.executeScript("tableIS.rows[10].cells[1].getElementsByTagName('span')[0]");
isCurrentYear.company = companyName;
isCurrentYear.eps = driver.executeScript("tableIS.rows[12].cells[1].getElementsByTagName('span')[0]");
incomeStatements.push(isCurrentYear);
}
if (!checkIncomeStatements(companyName, previousYear)) {
isPreviousYear = new Object();
isPreviousYear = previousYear;
isPreviousYear.grossrevenue = driver.executeScript("tableIS.rows[4].cells[2].getElementsByTagName('span')[0]");
isPreviousYear.grossexpense = driver.executeScript("tableIS.rows[7].cells[2].getElementsByTagName('span')[0]");
isPreviousYear.netincomeaftertax = driver.executeScript("tableIS.rows[10].cells[2].getElementsByTagName('span')[0]");
isPreviousYear.company = companyName;
isPreviousYear.eps = driver.executeScript("tableIS.rows[12].cells[2].getElementsByTagName('span')[0]");
incomeStatements.push(isPreviousYear);
}
// Close the new window, if that window no more required
driver.close();
// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
}
}
}
}
driver.executeScript("document.querySelector('.paging').getElementsByTagName('a')[2].click()");
num++;
}
PS CheckBalanceSheets and CheckIncomeStatements are for validating IF the year already exists and has been recorded before for the respective company
function checkCompany(name, ticker) {
var found = companies.some(function(el) {
return el.name === name;
});
if (!found) { companies.push({ name: name, ticker: ticker }); }
}
function checkBalanceSheets(name, year) {
var found = balanceSheets.some(function(el) {
return el.name === name && el.year === year;
});
}
function checkIncomeStatements(name, year) {
var found = incomeStatements.some(function(el) {
return el.name === name && el.year === year;
});
}
I have got a pretty complicated issue, I tried everything and its not working properly. So the conception is (i just copied the interesting part of it, otherwise it would be few hundred more lines) :
The program is a card game and 24 cards (4 different colors, one is always stronger,it is called ADU) are distributed randomly among 4 players (4 arrays). The table where you put down the cards are represented by "asztal" array. First the human player puts a card, then the computers should reach in this order:
If they have same color and higher value - pick that card
If they have same color and any value - pick that card
If they dont have matching color, any car from the special color set (for being simple, its the first card the loop would find in the array)
If they dont have matching color, nor card from special color set, than the first element of the array (player[0]).
If you run my code, you would see it is not grabbing 1/1/1 card from each array, but sometimes more. And those cards do disappear, and not getting into the asztal array. My code: (https://jsfiddle.net/daxa3pL2/)
function CardA(name,value,adu){
this.name = name;
this.value = value;
};
function CardB(name,value,adu){
this.name = name;
this.value = value;
};
function CardC(name,value,adu){
this.name = name;
this.value = value;
};
function CardD(name,value,adu){
this.name = name;
this.value = value;
};
CardA.prototype.adu = false;
CardB.prototype.adu = false;
CardC.prototype.adu = false;
CardD.prototype.adu = false;
var a9 = new CardA("Tök kilenc",0);
var a10 = new CardA("Tök tíz",10);
var aal = new CardA("Tök alsó",2);
var afel = new CardA("Tök felső",3);
var akir = new CardA("Tök király",4);
var aasz = new CardA("Tök ász",11);
var b9 = new CardB("Levél kilenc",0);
var b10 = new CardB("Levél tíz",10);
var bal = new CardB("Levél alsó",2);
var bfel = new CardB("Levél felső",3);
var bkir = new CardB("Levél király",4);
var basz = new CardB("Levél ász",11);
var c9 = new CardC("Makk kilenc",0);
var c10 = new CardC("Makk tíz",10);
var cal = new CardC("Makk alsó",2);
var cfel = new CardC("Makk felső",3);
var ckir = new CardC("Makk király",4);
var casz = new CardC("Makk ász",11);
var d9 = new CardD("Szív kilenc",0);
var d10 = new CardD("Szív tíz",10);
var dal = new CardD("Szív alsó",2);
var dfel = new CardD("Szív felső",3);
var dkir = new CardD("Szív király",4);
var dasz = new CardD("Szív ász",11);
CardC.prototype.adu = true;
var player1 = [c9,b9,b10,d9,a9,d10];
var player2 = [a10,aal,dal,c10,cal,bal];
var player3 = [bfel,bkir,basz,dfel,dkir,dasz];
var player4 = [afel,akir,aasz,cfel,ckir,casz];
var asztal = [];
asztal.push(player1.splice(0,1)[0]);
var player2card1 = function() {
for (i = 0; i < player2.length; i++) {
if (Object.getPrototypeOf(player2[i]) == Object.getPrototypeOf(asztal[0]) && player2[i].value > asztal[0].value) {
asztal.push(player2.splice(i,i+1)[0])
return
}
}
if (asztal.length == 1) {
for (i = 0; i < player2.length; i++) {
if (Object.getPrototypeOf(player2[i]) == Object.getPrototypeOf(asztal[0])) {
asztal.push(player2.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 1){
for (i = 0; i < player2.length; i++) {
if (player2[i].adu == true) {
asztal.push(player2.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 1) {
asztal.push(player2.splice(0,1)[0])
return
}
};
var player3card1 = function() {
for (i = 0; i < player3.length; i++) {
if (Object.getPrototypeOf(player3[i]) == Object.getPrototypeOf(asztal[0]) && player3[i].value > asztal[0].value) {
asztal.push(player3.splice(i,i+1)[0])
return
}
}
if (asztal.length == 2) {
for (i = 0; i < player3.length; i++) {
if (Object.getPrototypeOf(player3[i]) == Object.getPrototypeOf(asztal[0])) {
asztal.push(player3.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 2){
for (i = 0; i < player3.length; i++) {
if (player3[i].adu == true) {
asztal.push(player3.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 2) {
asztal.push(player3.splice(0,1)[0])
return
}
};
var player4card1 = function() {
for (i = 0; i < player4.length; i++) {
if (Object.getPrototypeOf(player4[i]) == Object.getPrototypeOf(asztal[0]) && player4[i].value > asztal[0].value) {
asztal.push(player4.splice(i,i+1)[0])
return
}
}
if (asztal.length == 3) {
for (i = 0; i < player4.length; i++) {
if (Object.getPrototypeOf(player4[i]) == Object.getPrototypeOf(asztal[0])) {
asztal.push(player4.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 3){
for (i = 0; i < player4.length; i++) {
if (player4[i].adu == true) {
asztal.push(player4.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 3) {
asztal.push(player4.splice(0,1)[0])
return
}
};
player2card1();
player3card1();
player4card1();
console.log(player1);
console.log(player2);
console.log(player3);
console.log(player4);
console.log(asztal);
So I debugged your code and there are two fundamental mistakes I found:
1: When you use the splice inside a loop, the indices will change. So, when you do for example
asztal.push(player2.splice(i,i+1)[0])
and put it inside a loop, the indices for player2 matching your condition will change as soon as you do the splice. So the next iteration of your loop will give incorrect results/ miss an index of an object that should be removed.
A possible solution to this is that instead of splice, inside your for-loops, just insert elements into asztal, and DON'T splice the parent. Then outside the loop, splice them from from the players using a FILTER function as follows:
var player2card1 = function() {
for (i = 0; i < player2.length; i++) {
if (Object.getPrototypeOf(player2[i]) == Object.getPrototypeOf(asztal[0]) && player2[i].value > asztal[0].value) {
asztal.push({name: player2[i].name, value: player2[i].value, prototype: player2[i].prototype});
player2[i].name = "delete";
return
}
}
player2.filter((each)=>{return each.name!== "delete"});
2: The second mistake (that I don't think is the problem here but still can cause trouble) is your use of "==". In Javascript, try to use '===' as far as possible as it also checks the type along with equality.
A little refactoring can go a long way to making this clear.
// define a card type class
function CardType(type, adu)
{
// This simply says that if ADU is undefined (not passed) then
// ADU should be set to false by default
this.adu = (typeof adu === 'undefined' ? false : adu);
this.type = type;
}
function Card(name, value, type)
{
this.name = name;
this.value = value;
this.type = type;
}
// Define our card types
var CardA = new CardType("A");
var CardB = new CardType("B");
var CardC = new CardType("C", true);// set to be ADU
var CardD = new CardType("D");
// Define our cards
var a9 = new Card("Tök kilenc",0, CardA);
var a10 = new Card("Tök tíz",10, CardA);
var aal = new Card("Tök alsó",2, CardA);
var afel = new Card("Tök felső",3, CardA);
var akir = new Card("Tök király",4, CardA);
var aasz = new Card("Tök ász",11, CardA);
var b9 = new Card("Levél kilenc",0, CardB);
var b10 = new Card("Levél tíz",10, CardB);
var bal = new Card("Levél alsó",2, CardB);
var bfel = new Card("Levél felső",3, CardB);
var bkir = new Card("Levél király",4, CardB);
var basz = new Card("Levél ász",11, CardB);
var c9 = new Card("Makk kilenc",0, CardC);
var c10 = new Card("Makk tíz",10, CardC);
var cal = new Card("Makk alsó",2, CardC);
var cfel = new Card("Makk felső",3, CardC);
var ckir = new Card("Makk király",4, CardC);
var casz = new Card("Makk ász",11, CardC);
var d9 = new Card("Szív kilenc",0, CardD);
var d10 = new Card("Szív tíz",10, CardD);
var dal = new Card("Szív alsó",2, CardD);
var dfel = new Card("Szív felső",3, CardD);
var dkir = new Card("Szív király",4, CardD);
var dasz = new Card("Szív ász",11, CardD);
var player1 = [c9,b9,b10,d9,a9,d10];
var player2 = [a10,aal,dal,c10,cal,bal];
var player3 = [bfel,bkir,basz,dfel,dkir,dasz];
var player4 = [afel,akir,aasz,cfel,ckir,casz];
var asztal = [];
// It doesn't really make sense to splice the array because
// you are changing the array.
// asztal.push(player1.splice(0,1)[0]);
// This line can be replaced with a simple:
asztal.push(player1[0]);
// This function has lots of redundant code and we can simplify it greatly
// as well as generalize it to work for each player
function getNextCard(player, card){
// By default we take the first card unless we find a better one along the way.
var matchCase2 = null, // same type, any value
matchCase3 = null, // special set
matchCase4 = player[0]; // any card
for(i = 0; i < player.length; i++)
{
// Check our first case
if(player[i].type.type == card.type.type &&
player[i].value > card.value){
return player[i];
}
if(matchCase2 === null && player[i].type.type == card.type.type){
matchCase2 = player[i];
}
if(matchCase3 === null && player[i].type.adu === true){
matchCase3 = player[i];
}
}
if(matchCase2 !== null) return matchCase2;
if(matchCase3 !== null) return matchCase3;
return matchCase4;
}
console.log(getNextCard(player2, asztal[0]));
console.log(getNextCard(player3, asztal[0]));
console.log(getNextCard(player4, asztal[0]));