Is there a way I can check to see if the "go to page based on answer" is checked in Google Forms - google-apps-script

When using .setChoices() It looks for an array of created choices. If it is a multiple choice question it can be formatted either createChoice(value) or createChoice(value, navigationType).
When looking at a choice you put in something like: var cPage = chkItem.getChoices()[j].getGotoPage();
This will produce either the page object or a Null value.
The problem is when a question is set to "go to page based on answer" and they have not set a page for every entry, and left the default to continue it also reads it (in my case cPage), as null. This means if I want to go through each choice to capture it, modify it, then push it back out to the question, it my ending Array that I push out consists of both Null and Objects, which produces an error.
My workaround for questions without pages is for the script to forcibly change the question to handle page navigation but set everyone to CONTINUE.
I would like to find a way to check if the question has "go to page based on answer" checked and if not then be able to create choices using just the value.

Figured it out: I need to check the first choice if it has a PageNavigationType(). If it does then the box is checked. If null then it is not checked. I have not written the code to fully test this but the theory should work. (I was checking against just the goToPage type which is why it didn't work before. )
var choicecount = chkItem.getChoices().length-1;
var hasNavType = chkItem.getChoices()[0].getPageNavigationType(); //if null
for (var j = 0; j <= choicecount; ++j) {
var cValue = chkItem.getChoices()[j].getValue();
var cPage = chkItem.getChoices()[j].getGotoPage();
var cNav = chkItem.getChoices()[j].getPageNavigationType();
// Logger.log(j+" "+cPage);
if (cValue != reValues[0]){
if (hasNavType == null){
newChoices.push(chkItem.createChoice(cValue));
} else {
if (cPage == null){
newChoices.push(chkItem.createChoice(cValue,cNav));
} else {
newChoices.push(chkItem.createChoice(cValue,cPage));
}
}
}
}

Related

Can I include conditional logic in VS Code snippets?

I would like to write a snippet in VS Code that writes a "switch" expression (in Javascript), but one where I can define the number of cases.
Currently there is a snippet that produces the outline of a switch expression with 1 case, and allows you to tab into the condition, case name, and the code contained within.
I want to be able to type "switch5" ("5" being any number) and a switch with 5 cases to be created, where I can tab through the relevant code within.
I know the snippets are written in a JSON file, can I include such conditional logic in this, or is it not possible?
Thanks!
The short answer is that you cannot do that kind of thing in a standard vscode snippet because it cannot dynamically evaluate any input outside of its designated variables with some limited workarounds like I'll mention next.
You might - I and others have written answers on SO about his - type your various case values first and then trigger a snippet tat would transform them into a switch statement. It is sort of doing it backwords but it might be possible.
There are extensions, however, that do allow you to evaluate javascript right in a snippet or setting and output the result. macro-commander is one such extension. I'll show another simpler extension doing what you want: HyperSnips.
In your javascript.hsnips:
snippet `switch(\d)` "add number of cases to a switch statement" A
``
let numCases = Number(m[1]) // 'm' is an array of regex capture groups
let caseString = ''
if (numCases) { // if not 'switch0'
let tabStopNum = 1
caseString = `switch (\${${tabStopNum++}:key}) {\n`
for (let index = 0; index < m[1]; index++) {
caseString += `\tcase \${${tabStopNum++}:value}:\n\t\t\$${tabStopNum++}\n`
caseString += '\t\tbreak;\n\n'
}
caseString += '\tdefault:\n'
caseString += '\t\tbreak;\n}\n'
}
rv = `${caseString}` // return value
``
endsnippet
The trickiest part was getting the unknown number of tabstops to work correctly. This is how I did it:
\${${tabStopNum++}:key}
which will resolve to ${n:defaultValue} where n gets incremented every time a tabstop is inserted. And :defaultValue is an optional default value to that tabstop. If you don't need a defaultValue just use \$${tabStopNum++} there.
See https://stackoverflow.com/a/62562886/836330 for more info on how to set up HyperSnips.

Avoiding data corruption if column state is saved, new column is defined in server and data is saved in edit

Answer in
How to replace remapColums with remapColumnsByName in free jqgrid
contains code to save and restore jqgrid column order.
It contains method to restore columns state:
var restoreColumnState = function (colModel) {
var colItem, i, l = colModel.length, colStates, cmName,
columnsState = getObjectFromLocalStorage(myColumnStateName);
if (columnsState) {
colStates = columnsState.colStates;
for (i = 0; i < l; i++) {
colItem = colModel[i];
cmName = colItem.name;
if (cmName !== "rn" && cmName !== "cb" && cmName !== "subgrid") {
colModel[i] = $.extend(true, {}, colModel[i], colStates[cmName]);
}
}
}
return columnsState;
};
This method causes invalid data posting from inline edit if new column is defined in server side.
jqgrid is populated from remote json data array. In this array columns must be the same as in column state.
If columns state is saved and new column is added to jqgrid in server code,
colStates[cmName] value is undefined.
This code causes new column to be added to end of jqgrid columns. However, in json data array it appears in the column as defined in server.
On inline edit, if row is saved, wrong values are assigned to form fields and invalid values are passed to server.
I tried to fix it adding colStates[cmName] !== undefined check:
if (cmName !== "rn" && cmName !== "cb" && cmName !== "subgrid" && colStates[cmName] !== undefined) {
but problem persists.
How to fix this that if new column is added to jqgrid colmodel in server, restoring column state allows to save correct data?
New column which is not found in saved columns list should appear in the same relative position as it is defined in colmodel. Column order shoudl corrspond to remote data from server.
Update
ColModel is defined in Razor view in variable cm
<script>
var
$grid,
myColumnsState,
isColState,
myColumnStateName;
$(function () {
var cm= #Html.Raw(Model.GetColModel());
$grid = $("#grid");
myColumnStateName = #Model.ColumnStateName();
myColumnsState = restoreColumnState(cm, myColumnStateName);
isColState = typeof (myColumnsState) !== 'undefined' && myColumnsState !== null;
$grid.jqGrid({
page: isColState ? myColumnsState.page : 1,
sortname: isColState ? myColumnsState.sortname : "",
sortorder: isColState ? myColumnsState.sortorder : "",
....
</script>
I know the problem very good! One need to implement some kind of validating checks of the previously saved state of the grid before the usage. The deepness of checks could depend on the exact requirements of your application and from the information which one knows exactly. The most opened and unclear thing: should one make some correction/fixing of the previously saved state or should one discard the state on the first small error? The answer on the question depends on the project where jqGrid are used. Deep fixing could include fixing of sorting parameter and modifying previously saved filter. Another example: the state could include ids of selected rows, but the fixing of the part of the state could be bad idea in the common case. One loading of the data could imply one setting of selected rows, but loading of another data (unfiltered for example) could do have the rows and the rows should be do selected. There are no best choice in the case, all depends on the exact project requirements. In any way the implementation of the state validation/fixing isn't a simple code.
Only because of the complexity of the problems of validation of previously saved state and the existence of different scenarios of validation I didn't implemented such feature in free jqGrid. Any good implementation needs time and the resulting code will be not simple. It will have some options for some typical scenarios. I would like to implement the feature in the future, but I just didn't found the time for the implementation, because I have to do my main job to earn money for my family and I still try to help other people in the community who have small, but important, for the person, problems with jqGrid of free jqGrid.

How to merge the contents of two variables

I have many string variables that start with "Question" and then end with a number. ("Question1")
Each variable has a question in it ("How many times does it say E?")
There is an editable textbox on the stage that the user types in which question number he want to be displayed in a different textbox. ("1")
When the user clicks a button, I want that the text of Question1 should be displayed in the textbox.
My code looks like this:
var Question1:String = "How many times does it say E?" ;
var Question2:String = "How many times does it say B?" ;
var Question3:String = "How many times does it say A?" ;
myButton.addEventListener(MouseEvent.CLICK, displayQuestion);
function displayQuestion(event:MouseEvent):void
{
var QuestionNumber:Number = Number(userInputQuestionNumber.text);
textBoxDisplayQuestion.text= Question(QuestionNumber);
}
How can I get the textBoxDisplayQuestion to display the actual text of the Question??
(the code i have now obviously is not working!!)
But this example doesnt seem to work: I created a class called Question and here is the code:
import Question;
var QuNoLoad:Number;
var Qu1:Question = new Question(1,"how","yes","no","maybe","so","AnsB","AnsA");
trace(Qu1.QuNo, Qu1.Qu, Qu1.AnsA,Qu1.AnsB, Qu1.AnsC, Qu1.AnsD, Qu1.CorAns, Qu1.FaCorAns);
//the following is the code for the button
loadQu.addEventListener(MouseEvent.CLICK, loadQuClick);
function loadQuClick(event:MouseEvent):void
{
//this sets the variable "QuNoLoad" with the contents of the "textBoxQuLoad"
//imagine the user inputed "1"
QuNoLoad=Number(textBoxQuLoad.text);
//this SHOULD!! display the contents of "Qu1.Qu"
textQu.text= this["Qu"+QuNoLoad.toString()+".Qu"]
//and when i traced this statment the value was "undefined"
}
Why???
You can reference a variable by name using square brackets [] operator, such as:
this["Question" + QuestionNumber.toString()]
You may use this operator to dynamically set and retrieve values for a property of an object.
Keeping the question number as an integer, your function would be:
var Question1:String = "How many times does it say E?" ;
var Question2:String = "How many times does it say B?" ;
var Question3:String = "How many times does it say A?" ;
function displayQuestion(event:MouseEvent):void
{
var QuestionNumber:uint = uint(userInputQuestionNumber.text);
textBoxDisplayQuestion.text = this["Question" + QuestionNumber.toString()];
}
This is a pretty fundamental concept in programming that will make a lot of things harder to do until you understand it well, and it's pretty hard to explain without starting with some groundwork:
What's happening here is easiest to talk about with plain old Object rather than classes, so lets start with a very simple example:
var question1:Object = new Object();
question1.number = 1;
Note that with Object you didn't have to say that number existed ahead of time, it gets created when you set it. Now, when you say either question1.number you get 1, obviously. What is happening, however is that first question1 gets the value you stored in the variable question1 (which is { number: 1 }), then the .number gets the value stored in the property number stored in that value: 1.
To save some typing, you can use a shorthand called "object literals":
var question1 = {
number: 1
};
Now lets try a more complex object:
var question1 = {
number: 1,
text: "How many times does it say A?",
answers: {
a: 1,
b: 2,
c: 3,
d: 4,
correct: "b"
}
};
Now question1 is an object that has 3 properties, one of which, answers, is an object with 5 properties: a, b, c, d, and correct. This could also be written as:
var question1 = new Object();
question1.number = 1;
question1.text = "How many times does it say A?";
question1.answers = new Object();
question1.answers.a = 1;
question1.answers.b = 2;
question1.answers.c = 3;
question1.answers.d = 4;
question1.answers.correct = "b";
It should be pretty clear why the literal syntax exists now!
This time, if you say question1.answers.correct you get "b": first question1 gets you the { number: 1,...} value, then the .answers gets the { a: 1, b: 2,...} value, then finally the .correct gets the "b" value.
You should also know that this is a special variable that has a particular meaning in ActionScript (and JavaScript, on which it is based): it broadly refers to the object in when the code you are writing is inside: for "global" code (not inside a function), var adds properties to this object: var number = 2; and this.number = 2 are this same here. (This is not true when you're in function, this behaves differently there, sometimes in very strange ways, so be careful!)
Now you might start seeing what's happening: when you use [], for example, question1["number"], rather than question1.number, you are passing the property name you want to get as a String value, which means you can change what property you get while you are running, rather than when you compile ("runtime" vs. "compiletime"), but it also lets you get properties with names you can't refer to with the . syntax!
var strange = {
"a strange name? That's OK!": 1
};
trace(strange["a strange name? That's OK!"]);
So when you write this["Qu" + QuNoLoad.toString() + ".QuNo"], you create a name like "Qu2.QuNo", for example, you are trying to get a property with that exact name, . included, which doesn't exist! What you were trying to do the equivalent of: Qu2.QuNo could be written as this["Qu" + QuNoLoad].QuNo.
I shouldn't leave this without saying, though, that for something like this, I would use arrays, which exist so that you can use a single name to store a list of values:
var questions:Array = [ // set questions to an array with multiple questions
new Question(...),
new Question(...),
...
];
for each (var question:Question in questions) { // Look at each question in the array
if (question.QuNo == textBoxQuLoad.text) { // If this is the right question
loadQuestion(question);
break; // Found it, stop looking at each question by "breaking out" of the for each
}
}
There's lots more you can do with arrays, so read up on them when you get time.

How to find specific value in a large object in node.js?

Actually I've parsed a website using htmlparser and I would like to find a specific value inside the parsed object, for example, a string "$199", and keep tracking that element(by periodic parsing) to see the value is still "$199" or has changed.
And after some painful stupid searching using my eyes, I found the that string is located at somewhere like this:
price = handler.dom[3].children[3].children[3].children[5].children[1].
children[3].children[3].children[5].children[0].children[0].raw;
So I'd like to know whether there are methods which are less painful? Thanks!
A tree based recursive search would probably be easiest to get the node you're interested in.
I've not used htmlparser and the documentation seems a little thin, so this is just an example to get you started and is not tested:
function getElement(el,val) {
if (el.children && el.children.length > 0) {
for (var i = 0, l = el.children.length; i<l; i++) {
var r = getElement(el.children[i],val);
if (r) return r;
}
} else {
if (el.raw == val) {
return el;
}
}
return null;
}
Call getElement(handler.dom[3],'$199') and it'll go through all the children recursively until it finds an element without an children and then compares it's raw value with '$199'. Note this is a straight comparison, you might want to swap this for a regexp or similar?

Select statement selection through URL parameters

I'm attempting to alter the contents of certain parts of a HTML form through usage of the URL. For a text field, I'm aware that this will suffice,
http://<domain>?fieldname=ping&anotherfield=pong
On the form there are multiple select braces (drop down boxes); Is it possible to pick an int or string value through the url for this?
There seems to be little documentation on this (or even people trying to do the same)...
You haven't specified how you want to do this, but I'll assume that you want to use JavaScript:
To get a value from QueryString:
getQueryStringArgument = function(key) {
var hu = window.location.search.substring(1);
var gy = hu.split("&");
for (i = 0; i < gy.length; i++) {
var ft = gy[i].split("=");
if (ft[0] == key)
return ft[1];
}
}
To set the selected value of the select list:
document.getElementById("sel").value = getQueryStringArgument("id");
For a text field, I'm aware that this will suffice
No, it won't (at least, not in a generic way).
For a text field, the default value is specified by the value attribute. There might be a server side script that populates it based on query string data, but there doesn't have to be.
On the form there are multiple select braces (drop down boxes); Is it possible to pick an int or string value through the url for this?
Again, this requires an attribute to be set (selected on <option>), and that could (again) be set by a server side script based on the query string data.