Stop Podio calculation after certain event - podio

We currently have a counter that calculates from "Enrollment date" to "today" by weeks.
We'd like the weeks to stop being counted once a separate field ("Offer sent") is updated.
Is this possible?

There are couple of ways of handling this. Here is one of examples. So, Podio app has 2 fields, Date with date and time set, and Category with multiple options to show how you can handle date and time.
var category = #Category;
var now = new Date;
var today = new Date;
today.setHours(0, 0, 0, 0);
var durationTillNow = (now - #Date)/1000/60/60/24;
var fromDate = #Date;
fromDate.setHours(0, 0, 0, 0);
var durationTillNowWithoutTime = (today - fromDate)/1000/60/60/24;
if (category == 'round to nearest number') {
"Rounded to: " + Math.round(durationTillNow).toString() + " day(s)";
} else if (category == 'round up') {
"Round up: " + Math.ceil(durationTillNow).toString() + " day(s)";
} else if (category == 'round down') {
"Round down: " + Math.floor(durationTillNow).toString() + " day(s)";
} else if (category == 'show full diff') {
"Full diff: " + durationTillNow.toString() + " day(s)";
} else if (category == 'just ignore time') {
"Ignoring time part: " + durationTillNowWithoutTime.toString() + " day(s)";
} else if (category == 'something else') {
"it's something else selected";
} else {
"yet another else option selected";
}

Related

Python selenium close modal window after reading its content

I have the HTML as following:
function showModal(msg) {
var content = document.getElementById("modal-content");
content.innerHTML = msg;
modal.style.display = "block";
}
showModal(msg + "<br>Job started, check status on the project jobs page.");
After all is said and done, I get the following window:
How do I read the content of the box and if there is "Success" I can click the close on top right to go back to the previous page.
I don't have a clue how to approach this.
Edit: Extended HTML looks as following:
function makeInputScenario(ids,params,has_extra = false) {
var sd = gete("sdate").value;
var ed = gete("edate").value;
var sdt = new Date(sd);
var edt = new Date(ed);
if (sdt > edt) {
showModal("Start date is after end date, please fix!");
return;
}
var p = gete("pool").value;
var dzr = gete("dzr").value;
var pfd = gete("pfd").value;
var udb = gete("udb").value;
var uds = gete("uds").value;
if (uds == "None") uds = "";
var rop = gete("rop-text").value;
var fuds = gete("fuds").value;
if (fuds == "None") fuds = "";
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function() {
hideProgress();
if (!params) setInteraction(false);
if (xhr.status == 200) {
var msg = "<strong>SUCCESS:</strong><br><pre>" + xhr.responseText + "</pre>"
showModal(msg);
if (params) {
if (has_extra) {
showProgress("Processing, please wait...");
doAction("run-params","POST","/scenario/run","user=PJMRTO LONG RUN AUCTION" + params + "&cir=" + getCir(),function (ret) {
setInteraction(false);
clearTimeout(updProgrs);
showModal(msg + "<p>" + ret + "</p>");
});
} else {
var ods = gete("ods").value;
showProgress("Adding new job, please wait...");
doAction("run-params","POST","/job","user=PJMRTO LONG RUN AUCTION&sdate=" + sd + "&edate=" + ed + "&ids=" + ids + "&ods=" + ods + "&rops=" + encode(rop) + "&post=" + encode("") + "&std=" + encode("") + "&cir=" + getCir(),function (job) {
showProgress("Starting job " + job + ", please wait...");
doAction("run-params","POST","/run","id=" + job + params,function (x) {
setInteraction(false);
clearTimeout(updProgrs);
showModal(msg + "<br>Job started, check status on the project jobs page.");
});
});
}
}
} else if (xhr.status == 500) {
setInteraction(false);
clearTimeout(updProgrs);
var logurl = "/idblog?q=host&name=" + encode(ids) + "&pool=" + encode(p) + "&sd=" + encode(sd) + "&ed=" + encode(ed);
showModal(wrapError("<pre>" + xhr.responseText + "</pre><br><button onclick=\"getIDBlog('" + logurl + "');\" class=\"btn btn-primary\">Download Log</button>"));
}
},false);
setInteraction(true);
if (params) {
gete("start-job").style.display = "none";
gete("host-status").style.display = "none";
}
var sparams = "user=PJMRTO LONG RUN AUCTION&pool=" + p + "&dzr=" + dzr + "&pfd=" + pfd + "&ids=" + ids + "&sdate=" + sd + "&edate=" + ed + "&udb=" + udb + "&uds=" + uds + "&rop=" + encode(rop);
if (fuds != "") {
sparams += "&fuds=" + fuds + "&ius=" + gete("ods").value;
showProgress("Creating base and fixed UC input scenarios, please wait...");
} else {
showProgress("Creating input scenario, please wait...");
}
updProgrs = setTimeout(updateProgress, 300000);
xhr.open("POST","/scenario",true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("x-csrf-token","NhISQUB1eCANGh46HwsgTnsAISkCAAAATeFn4B0myInXzZc7+8QJMA==");
xhr.send(sparams);
}
So here variable "msg" is storing the value "SUCCESS". It would be better to get the variable "msg" usin javascript.
So that would be :-
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://Reachyourpage")
message = driver.execute_script("return msg")
print ("SUCCESS" in message)
It should return true in case of success. I am no expert in Python but just a beginner so mind my coding.. !!
C# equivalant here would be :-
IJavaScriptExecutor js = (IJavaScriptExecutor)_driver;
string title = js.ExecuteScript("return msg");
Here, title will have the complete message.
The algorithm is to get the value of "msg" var using javascript.
For Closing the message, have u tried using SendKeys(Keys.Esc) ??
Hope it Helps!!

Handle multiple dropdown lists with VueJS

I am new at VueJs and I want to create a form. It contains questions with category and rate. My target is to take the rate of each question and his category, and all questions from category 'F' will have scoreF (which will occur from the sum of rates) and all questions from category 'H' will have a scoreH. Here is my job till now. Thank you in advance for your help!
https://codepen.io/dparanou/pen/zYGPexa
<select v-bind:id="question.id" #change="onChange($event, question.id, question.category)">
<option disabled selected>--</option>
<option v-for="n in question.answers" :value="n">{{n}}</option>
</select>
<span>Score F: {{fScore}}</span>
<span>Score H: {{hScore}}</span>
And here is my JS file
data: {
fScore: 0,
hScore: 0,
},
methods: {
onChange(event, id, cat) {
num = event.target.value;
console.log("id: "+ id + ", category: " + cat + ", score: " + num);
if(cat == "F") {
this.fScore += num;
console.log(this.fScore);
} else {
this.hScore += num;
}
}
}
It had only to convert the event into Integer!
onChange(event, id, cat) {
var num = parseInt(event.target.value);
if(cat == "F") {
this.fScore += num;
} else {
this.hScore += num;
}
}

web3 - event.watch spits out events in random order

I am watching an event:
var events = EthProj.Message({}, { fromBlock: 0, toBlock: 'latest'});
events.watch((error, results) => {
Inside the event I do this tempString = ((messages.split(":")[1].split(",")[0] + " (From: " + messages.split(":")[2].split("}")[0]) + ")").replace(/"/g, ''); Which, long story short, makes a string from the event giving the event from the block (i.e. It gives the event made at block 173).
I then set a <h2> element's text from each event. When this happens it sets them in a seemingly random order. What can be going on, it sets them from block 0 to the latest block, so how can this happen.
Here is the full code: https://pastebin.com/wGt5kL1Y
var events = EthProj.Message({}, { fromBlock: 0, toBlock: 'latest'});
events.watch((error, results) => {
i++;
messages = "";
messages = JSON.stringify(results.args);
if(i === messageToGet) {
if(messages.split(":")[1].split(",")[0] != '""') {
console.log(messages.split(":")[1].split(",")[0] + " (From: " + messages.split(":")[2].split(",")[0].split("}")[0].split("}")[0] + ")");
tempString = ((messages.split(":")[1].split(",")[0] + " (From: " + messages.split(":")[2].split("}")[0]) + ")").replace(/"/g, '');
} else {
console.log("(No included text)" + "(From: " + messages.split(":")[2].split(",")[0].split("}")[0] + ")");
tempString = (("(no included text) " + " (From: " + messages.split(":")[2].split("}")[0]) + ")").replace(/"/g, '');
}
if((messages.split(":")[1].split(",")[0] === undefined) || (messages.split(":")[2].split(")")[0] === undefined)) {
return;
}
if(document.getElementById("Message" + placeToSet) != null) {
document.getElementById("Message" + placeToSet).remove();
if(document.getElementById("hr" + placeToSet) != null) {
document.getElementById("hr" + placeToSet).remove();
}
}
if(document.getElementById("Message" + placeToSet) === null) {
var newh2 = document.createElement('h2');
newh2.setAttribute("id", ("Message" + placeToSet));
var text = document.createTextNode(tempString);
newh2.appendChild(text);
document.body.appendChild(newh2);
var newHR = document.createElement('hr');
newHR.setAttribute("id", ("hr" + placeToSet));
}
}
});

SQL Error 42S22 when updating multiple records using query from server script in Azure Mobile Services

I'm currently running into problems while trying to customize the update script for a table of User Stories on Azure Mobile Services. My intention is to have the update script receive an item that contains an array of UserStory objects, construct a SQL string using that array, and then use mssql.query with that string against the UserStory table to update the individual records.
The following SQL achieves what I'm looking to do and works correctly when executed in Visual Studio:
UPDATE
masterstorylist.UserStory
SET
UserStory.relativepriority =
CASE UserStory.id
WHEN 'C36DC45B-170B-49F4-A747-6F4D989C1859' THEN '24'
WHEN '7EC413C3-17A8-410A-A394-ABF334364226' THEN '25'
WHEN '99890AFE-13C2-4E1A-8376-B501CB07080D' THEN '26'
END
Here's the server script that I have created in an attempt to achieve the same result:
function update(item, user, request) {
if(item.stories.length > 0){
var sql = "UPDATE masterstorylist.UserStory SET UserStory.relativepriority = CASE UserStory.id ";
for(var i = 0; i < item.stories.length; ++i){
sql+= ("WHEN '" + item.stories[i].id + "' THEN " + item.stories[i].relativepriority + " ");
}
sql+="END";
mssql.query(sql, {
success: function(results) {
request.respond();
},
error: function(err) {
request.respond(err);
}
});
}
else{
request.respond(statusCodes.NO_CONTENT, 'No records specified for update in request.');
}
}
The error I get back is
"sqlstate":"42S22","code:207"
which I think means that SQL can't find the relativepriority or id column. I've tried different syntax, such as qualifying the column names more or less or using [] around the columns, but the result is always the same.
I'm not sure what else to try, and details around creating and executing queries with the mssql object are hard to come by. I've been working off the examples here and here.
What am I missing?
EDIT: In case it helps, I reworked the code to see if using mssql.open would help. I modeled after the examples from the "MS Drivers for Node.js for SQL Server guide" (which I can't link to because I have low rep). The net result is the exact same error :/ Here's the new code in case it gives folks any ideas:
function update(item, user, request) {
if(item.stories.length > 0){
var sql = "UPDATE UserStory SET relativepriority = CASE id ";
for(var i = 0; i < item.stories.length; ++i){
sql+= ("WHEN '" + item.stories[i].id + "' THEN " + item.stories[i].relativepriority + " ");
}
sql+="END ";
console.log("opening connection...");
mssql.open({
success: function(connection){
console.log("mssql.open success");
console.log("executing query...");
connection.query(sql, function(err,results){
if(err){
console.log("query failed");
request.respond(err)
}
console.log("query successful");
request.respond();
});
},
error: function(err) {
console.log("fail on open: " + err);
request.respond(err);
}
});
}
else{
request.respond(statusCodes.OK, 'No records specified for update in request.');
}
}
P.S. This is my first post on Stack Overflow! :)
Ok, I figured out the answer to my own question. It turns out that the JSON object that the Mobile Service SDK was passing up wasn't formatted to the liking of Node.js. The item object coming into the script had an array of objects in it item.stories, which looked ok to me when it was logged to the console with console.log(item.stories); but apparently wasn't formatted well enough for me to access the individual objects in the 'item.stories' array using array notation.
I was able to fix both of the scripts above by adding the line var storiesToUpdate = JSON.parse(item.stories); and then using storiesToUpdate[i] instead of item.stories[i]. That seems to have done the trick. Ideally I'll find a way to fix the JSON generated on my clients so that I don't need this extra JSON.parse.
Here are three now working examples on how to update multiple records at once.
Simplest way to do what I wanted:
var storiesToUpdate;
var returnItem;
function update(item, user, request) {
storiesToUpdate = JSON.parse(item.stories);
returnItem = item;
if(storiesToUpdate.length > 0){
var sql = "UPDATE UserStory SET relativepriority = CASE id ";
for(var i = 0; i < storiesToUpdate.length; ++i){
sql+= ("WHEN '" + storiesToUpdate[i].id + "' THEN " + storiesToUpdate[i].relativepriority + " ");
}
sql+="END ";
mssql.query(sql,{
success: function(connection){
request.respond(statusCodes.OK, returnItem);
},
error: function(err) {
console.log("fail on open: " + err);
request.respond(err);
}
});
}
else{
request.respond(statusCodes.OK, returnItem);
}
}
Another way using mssql.open as well (not sure why you'd ever want to do this...):
var storiesToUpdate;
var returnItem;
function update(item, user, request) {
storiesToUpdate = JSON.parse(item.stories);
returnItem = item;
if(storiesToUpdate.length > 0){
var sql = "UPDATE UserStory SET relativepriority = CASE id ";
for(var i = 0; i < storiesToUpdate.length; ++i){
sql+= ("WHEN '" + storiesToUpdate[i].id + "' THEN " + storiesToUpdate[i].relativepriority + " ");
}
sql+="END ";
console.log("opening connection...");
mssql.open({
success: function(connection){
console.log("mssql.open success");
console.log("executing query...");
connection.query(sql, function(err,results){
if(err){
console.log("query failed");
request.respond(err)
}
console.log("query successful");
request.respond(statusCodes.OK, returnItem);
//request.respond(statusCodes.OK);
});
},
error: function(err) {
console.log("fail on open: " + err);
request.respond(err);
}
});
}
else{
request.respond(statusCodes.OK, returnItem);
}
}
And lastly, here's how to update multiple records without using mssql using the recommended batching techniques (this is rough and probably needs to be cleaned up):
var UserStoryTable = tables.getTable('UserStory');
var batchSize = 10;
var startIndex = 0;
var endIndex = 0;
var totalCount = 0;
var errorCount = 0;
var g_item;
var g_request;
var storiesToUpdate;
function update(item, user, request) {
//the json array has to be parsed first
storiesToUpdate = JSON.parse(item.stories);
g_item = item;
g_request = request;
if(item.stories.length > 0){
updateItems();
}
else{
console.log("empy update request");
request.respond(statusCodes.OK);
}
}
function updateItems(){
var batchCompletedCount = 0;
var updateComplete = function() {
batchCompletedCount++;
totalCount++;
if(batchCompletedCount === batchSize || totalCount === storiesToUpdate.length) {
if(totalCount < storiesToUpdate.length) {
// kick off the next batch
updateItems();
} else {
// or we are done, report the status of the job
// to the log and don't do any more processing
console.log("Update complete. %d Records processed. There were %d errors.", totalCount, errorCount);
g_request.respond(statusCodes.OK);
}
}
};
var errorHandler = function(err) {
errorCount++;
console.warn("Ignoring insert failure as part of batch.", err);
updateComplete();
};
var startIndex = totalCount;
var endIndex = totalCount + batchSize - 1;
if(endIndex >= storiesToUpdate.length) endIndex = storiesToUpdate.length - 1;
for(var i = startIndex; i <= endIndex; i++) {
console.log("Updating: " + storiesToUpdate[totalCount]);
UserStoryTable.update(storiesToUpdate[i],{
success: updateComplete,
error: errorHandler
});
}
}

PhoneGap jquerymobile SQL dynamic link

I am building a PhoneGap iOS App with the help of the jquery-mobile framework. I have a primary jquery-mobile autodivided list, populated by an SQL database. This autodivided list work as expected. When clicking on one link of this dynamic list, a dynamic page is supposed to fire up, containing some extra details included in the same SQL database. However, when the database doesn't load the page details.
I successfully made this work outside jquerymobile framework, with a few script changes. But I really need the autodividers function coming from jquerymobile.
First I assumed that this dynamic page was outside the DOM, but adding the following function at mobileinit() doesn't solve my SQL loading issue:
$( 'fooddetails.html?id' ).live( 'pagebeforecreate',function(event, ui){
alert( 'This page was just inserted into the dom!' );
});
Below is a complete script for my database & the dynamic URL to fire the extra details page:
var db;
var dbCreated = false;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
db = window.openDatabase("FoodDirectoryDB", "1.0", "PhoneGap", 200000);
if (dbCreated)
db.transaction(getAlimentaries, transaction_error);
else
db.transaction(populateDB, transaction_error, populateDB_success);
}
function transaction_error(tx, error) {
$('#busy').hide();
alert("Database Error: " + error);
}
function populateDB_success() {
dbCreated = true;
db.transaction(getAlimentaries, transaction_error);
}
function getAlimentaries(tx) {
var sql = "select e.id, e.foodName, e.groupfoodName, e.quantity, e.picture, count(r.id) reportCount " +
"from food e left join food r on r.managerId = e.id " +
"group by e.id order by e.foodName ";
tx.executeSql(sql, [], getAlimentaries_success);
}
function getAlimentaries_success(tx, results) {
$('#busy').hide();
$('#foodList li').remove();
var len = results.rows.length;
for (var i=0; i<len; i++) {
var food = results.rows.item(i);
console.log(food.foodName);
$('#foodList').append('<li><a href="fooddetails.html?id=' + food.id + '">' +
'<img src="pics/' + food.picture + '" class="arrow-r"/>' +
'<p class="line1">' + food.foodName + '</p>' +
'</a></li>');
$( 'employeedetails.html?id' ).live( 'pageshow',function(event, ui){
alert( 'This page was just inserted into the dom!' );
});
}
$('#foodList').listview('refresh');
db = null;
}
function populateDB(tx) {
$('#busy').show();
tx.executeSql('DROP TABLE IF EXISTS food');
var sql =
"CREATE TABLE IF NOT EXISTS food ( "+
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"foodName VARCHAR(50), " +
"groupfoodName VARCHAR(50), " +
"quantity VARCHAR(50), " +
"portion VARCHAR(50), " +
"managerId INTEGER, " +
"glucides VARCHAR(30), " +
"picture VARCHAR(200))";
tx.executeSql(sql);
tx.executeSql("INSERT INTO food (id,foodName,groupfoodName,managerId,quantity,portion,glucides,picture) VALUES (1,'Abricot','Fruits frais et fruits secs',1,'1 abricot','65g','5','fruits_legumes.png')");
tx.executeSql("INSERT INTO food (id,foodName,groupfoodName,managerId,quantity,portion,glucides,picture) VALUES (2,'Abricots secs','Fruits frais et fruits secs',1,'4 abricots secs','80g','30','fruits_legumes.png')");
I was also trying to add data-ajax="false" rel"external" to this dynamic link, but this doesn't change unfortunately and I read that these attributes in a dynamic link are not authorized:
$('#foodList').append('<li><a href="fooddetails.html?id=' + food.id + '">' +
Below is the script of the details dynamic page that doesn't load correctly:
var id = getUrlVars()["id"];
var db;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("opening database");
db = window.openDatabase("FoodDirectoryDB", "1.0", "PhoneGap", 200000);
console.log("database opened");
db.transaction(getAlimentary, transaction_error);
}
function transaction_error(tx, error) {
$('#busy').hide();
alert("Database Error: " + error);
}
function getAlimentary(tx) {
$('#busy').show();
var sql = "select e.id, e.foodName, e.groupfoodName, e.managerId, e.quantity, e.portion, e.glucides, " +
"e.picture, m.foodName managerFirstName, m.groupfoodName managerLastName, count(r.id) reportCount " +
"from food e left join food r on r.managerId = e.id left join food m on e.managerId = m.id " +
"where e.id=:id group by e.groupfoodName order by e.groupfoodName, e.foodName";
tx.executeSql(sql, [id], getAlimentary_success);
}
function getAlimentary_success(tx, results) {
$('#busy').hide();
$('#foodList li').remove();
var food = results.rows.item(0);
$('#foodPic').attr('src', 'pics/' + food.picture);
$('#foodName').text(food.foodName);
$('#foodgroupName').text(food.groupfoodName);
$('#foodQuantity').text(food.quantity);
$('#foodPortion').text(food.portion);
console.log(food.glucides);
if (food.glucides) {
$('#actionList').append('<li><a href="tel:' + food.glucides + '"><p class="line1">Teneur en Glucides</p>' +
'<p class="line2">' + food.glucides + '</p><img src="img/food.png" class="action-icon"/></a></li>');
}
$('#foodList').listview('refresh');
db = null;
}
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}