Numbers not acting like numbers in AS3 - actionscript-3

Here is my code:
function castBurn()
{
var cardNumber = currentCard;// == 149 (currentCard:int)
var card1 = cardNumber - 1;// 149 - 1 = 148
var card2 = cardNumber + 1;// 149 +1 = 150
var card3 = cardNumber - row;// row = 23 and so on
var card4 = cardNumber + row;
//cardArray:Array (full of objects(Cards)
cardArray[card1].burn = true;// card1 is recognized and flips
cardArray[card2].burn = true;// throws a runtime error (term is unidentified)
cardArray[card3].burn = true;// See bottom for notes
cardArray[card4].burn = true;
for (var j = 0; j < cardArray.length; j++)
{// This works
var card = cardArray[j];
if (card.burn == true)
{
if (card.wall != true)
{
card.flip.gotoAndPlay(2);
}
}
}
}
If I substitute the card1, card2, card3, card4 vars with the numbers themselves, it works great. But I need to calculate these numbers based on the 'current card'... I have done this several times before. What am I missing?... I also tried to write var card1 = cardArray[currentCard + 1]; but that method doesn't work either. The ONLY way I get this to work is by writing card1 = 148;

AS3 is strongly typed language. Use Type declarations in your code and your compiler will tell you what is wrong.

Related

Get an array of all Numbers inside a String

How can I get an array of all Numbers (if any) inside a String?
So that this:
var txt: String = "So 1 and 22 plus33 = (56) and be4 100 is 99!";
trace(getNumAry(txt));
Output this:
1,22,33,56,4,100,99
Regular Expressions is the answer you are looking for. You need something like that (not tested, yet the idea should be correct):
var source:String = "So 1 and 22 plus33 = (56) and be4 100 is 99!"
// The pattern \d+ instructs to find one or more consequent decimal digits.
// That also means that before each match there will be a non-digit character
// or the beginning of the text, and after the match will also be a non-digit
// or the end of the text.
// The [g]lobal flag is for searching multiple matches.
var re:RegExp = /\d+/g;
// Search for all the matches.
var result:Array = source.match(re);
Without the elaborate commenting the code could be reduced to this simple one-liner:
var result:Array = "So 1 and 22 plus33 = (56) and be4 100 is 99!".match(/\d+/g);
Please keep in mind that this search will return an Array of Strings so if you want them as ints you need to take some additional steps.
This is the working solution I have come up with:
function getNumAry(txt:String):Array {
var res:Array = new Array();
var str: String = ""
//Non-Number Chars to Dot
for (var i:int = 0; i < txt.length; i++) {
if(isNum(txt.substr(i,1))){
str += txt.substr(i, 1);
} else {
str += ".";
}
}
trace(txt);
trace(str);
//Spaces to Dot
str = str.split(" ").join(".")
trace(str);
//Dots to Single Dot
while (str.indexOf("..") != -1) {
str = str.split("..").join(".");
}
trace(str);
//Remove first Dot
if (str.indexOf(".") == 0 ) {
str = str.substr(1);
}
trace(str);
//Remove last Dot
if (str.lastIndexOf(".") == str.length-1 ) {
str = str.substr(0,str.length-1);
}
trace(str);
//get Nums if any
if (str != "" && str != ".") {
res = str.split(".");
}
return res;
}
function isNum(chr: String):Boolean {
return !isNaN(Number(chr));
}
if you run this:
var txt: String = "So 1 and 22 plus33 = (56) and be4 100 is 99!";
trace(getNumAry(txt));
This is the step-by-step trace of what you get:
So 1 and 22 plus33 = (56) and be4 100 is 99!
.. 1 ... 22 ....33 . .56. ... ..4 100 .. 99.
...1.....22.....33....56........4.100....99.
.1.22.33.56.4.100.99.
1.22.33.56.4.100.99.
1.22.33.56.4.100.99
1,22,33,56,4,100,99
Wondering if there has been an easier way?! :)

Changes not having any effect out of nowhere

I was working along and out of nowhere my changes stopped applying. The code functions up until the last logger instruction I wrote in.
Now any change I make to the code is acting like it isn't even there. I click save and run the code, but nothing I change actually takes effect. No instances of Logger.log("hello") do anything, but everything else runs as written.
//variables for shorthand calling of each spread sheet
var ssL = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SpecsList");
var ssR = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("RequiredSpecs");
//count the number of columns to determine the max range of the spec comparison iterator
var specIteratorMax = ssL.getLastColumn() - 2; // the -2 is to ignore column A which is text and rebase the iterator variable to 0
function runHeatMap() {
//voltage spec compare section
Logger.log("hello");
//retrieve the users preferred output voltage rating
var voltReqed = ssR.getRange("A2").getValue();
Logger.log(voltReqed);
//retrieve the output voltage ratings of all devices
var voltCompareData = ssL.getSheetValues(3, 2, 1, (ssL.getLastColumn() - 1)).flat();
Logger.log(voltCompareData);
Logger.log("hello");
Logger.log(specIteratorMax);
//store current iteration voltage spec and conduct comparison operations
for (var i = 0; i <= specIteratorMax; i++) {
var voltSpec = voltCompareData[i];
Logger.log(voltSpec);
if(voltSpec >= voltReqed) {
ssL.getRange(3,i + 2).setBackground("green");
}
else if(voltSpec < voltReqed && voltSpec >= (voltReqed * 0.95)) {
ssL.getRange(3,i + 2).setBackground("orange");
}
else {
ssL.getRange(3,i + 2).setBackground("red");
}
}
Logger.log("hello");
}
It seems to run on random data
I reduced it down to this:
function runHeatMap() {
var sh0 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet0");
var sh1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var max = sh0.getLastColumn() - 2;
var v1 = sh1.getRange("A2").getValue();
var vs = sh0.getSheetValues(3, 2, 1, sh0.getLastColumn() - 1).flat();
for (var i = 0; i <= max; i++) {
var v2 = vs[i];
if (v2 >= v1) {
sh0.getRange(3, i + 2).setBackground("green");
}
else if (v2 < v1 && v2 >= (v1 * 0.95)) {
sh0.getRange(3, i + 2).setBackground("orange");
}
else {
sh0.getRange(3, i + 2).setBackground("red");
}
}
}

Error when trying to set Google Forms quiz score

I'm trying to change the grade of a response based on its answer.
Here's the code I'm using:
function myFunction() {
var form = FormApp.openById('formID123456');
// For a question with options: "1", "2", "3", and "4",
// award points for responses that correlate with their answers.
var formResponses = FormApp.getActiveForm().getResponses();
// Go through each form response
for (var i = 0; i < formResponses.length; i++) {
var response = formResponses[i];
var items = FormApp.getActiveForm().getItems();
// Assume it's the first item
var item = items[0];
var itemResponse = response.getGradableResponseForItem(item);
// Give 4 points for "4".
if (itemResponse != null && itemResponse.getResponse() == '4') {
var points = item.asScaleItem().getPoints();
itemResponse.setScore(points == 4);
}
// Give 3 points for "3".
else if (itemResponse != null && itemResponse.getResponse() == '3') {
var points = item.asScaleItem().getPoints();
itemResponse.setScore(points == 3);
}
// Give 2 points for "2".
else if (itemResponse != null && itemResponse.getResponse() == '2') {
var points = item.asScaleItem().getPoints();
itemResponse.setScore(points == 2);
}
// Give 1 points for "1".
else if (itemResponse != null && itemResponse.getResponse() == '1') {
var points = item.asScaleItem().getPoints();
itemResponse.setScore(points == 1);
// This saves the grade, but does not submit to Forms yet.
response.withItemGrade(itemResponse);
}
}
// Grades are actually submitted to Forms here.
FormApp.getActiveForm().submitGrades(formResponses);
}
This returns the error:
We're sorry, a server error occurred. Please wait a bit and try again. (line 23, file "Code")
It seemed like it was having issues changing the score of the response, but it didn't return a specific error, so I tried to isolate the part that changes the score.
Here, the script attempts only to change the score of the response.
function myFunction() {
var form = FormApp.openById('formID123456');
var formResponses = FormApp.getActiveForm().getResponses();
// Go through each form response
for (var i = 0; i < formResponses.length; i++) {
var response = formResponses[i];
var items = FormApp.getActiveForm().getItems();
// Assume it's the first item
var item = items[0];
var itemResponse = response.getGradableResponseForItem(item);
// Set Score to 3
var points = item.asScaleItem().getPoints();
itemResponse.setScore(points == 3);
}}
Again, it returned the same error, which confirms my suspicions. Why am I having this problem and how can I fix it? Any help would be much appreciated. Thanks!
As I mentioned in comments, your posted code erroneously uses a Boolean value in the call to ItemResponse#setScore, when the method expects to receive an Integer value.
Resolving the internal server error can be done by changing your entire if-elseif chain from this:
if (itemResponse != null && itemResponse.getResponse() == '4') {
var points = item.asScaleItem().getPoints();
itemResponse.setScore(points == 4); //<--- 'points == 4' evaluates to True or False
}
// Give 3 points for "3".
else if (...
to this:
// Skip changing the score if there was no answer or the answer is "falsey"
if (!itemResponse || !itemResponse.getResponse())
continue;
var answer = itemResponse.getResponse();
var newPoints = answer *1; // Convert "2" to 2, etc.
// Assumption: newPoints <= maximum possible points.
itemResponse.setScore(newPoints);
response.withItemGrade(itemResponse);
The below code is an example of how to set all graded items in all responses to a form to their maximum possible value.
function everyonePassesForTrying() {
var form = FormApp.getActiveForm();
var responses = form.getResponses();
responses.forEach(function (fr) {
fr.getGradableItemResponses().forEach(function (gr) {
if (gr.getResponse()) {
var maxPoints = getPointValue_(gr.getItem());
if (gr.getScore() !== maxPoints) {
// Re-grade the item's response.
gr.setScore(maxPoints);
// Update the form response with the new grade.
fr.withItemGrade(gr);
}
}
else { /* They didn't even try, so no change */ }
});
});
// Submit the altered scores.
form.submitGrades(responses);
}
var itemCache = {};
function getPointValue_(item) {
var id = item.getId();
// Use a pseudo-cache of the item's point values to avoid constantly determining what
// type it is, casting to that type, and getting the max points.
if(!itemCache[id]) {
// Haven't seen it yet, so cast and cache.
item = castToType_(item);
itemCache[id] = {maxPoints: item.getPoints() *1};
}
return itemCache[id].maxPoints;
}
function castToType_(item) {
// Cast the generic item to its type.
var CHECKBOX = FormApp.ItemType.CHECKBOX,
DATE = FormApp.ItemType.DATE,
DATETIME = FormApp.ItemType.DATETIME,
DURATION = FormApp.ItemType.DURATION,
LIST = FormApp.ItemType.LIST,
MULTICHOICE = FormApp.ItemType.MULTIPLE_CHOICE,
PARAGRAPH = FormApp.ItemType.PARAGRAPH_TEXT,
SCALE = FormApp.ItemType.SCALE,
TEXT = FormApp.ItemType.TEXT,
TIME = FormApp.ItemType.TIME;
switch (item.getType()) {
case CHECKBOX: item = item.asCheckboxItem();
break;
case DATE: item = item.asDateItem();
break;
case DATETIME: item = item.asDateTimeItem();
break;
case DURATION: item = item.asDurationItem();
break;
case LIST: item = item.asListItem();
break;
case MULTICHOICE: item = item.asMultipleChoiceItem();
break;
case PARAGRAPH: item = item.asParagraphTextItem();
break;
case SCALE: item = item.asScaleItem();
break;
case TEXT: item = item.asTextItem();
break;
case TIME: item = item.asTimeItem();
break;
default:
throw new Error("Unhandled gradable item type '" + item.getType() + "'");
break;
}
return item;
}

Programming Greatest Common Divisor for HTML Webpage

EDIT: So the question is, why will my script not execute properly.
Edit 2: So this is the part that works as advertised and all items are predefined as number inputs prior too.
<script>
function Script5(){
var numeratorIn = document.getElementById("Numerator").value;
var denominatorIn = document.getElementById("Denominator").value;
var FACTOR = document.getElementById("FACTOR").value;
var Snum = document.getElementById("Snum").value;
var Sden = document.getElementById("Sden").value;
var x = document.getElementById("FinalAnswer");
x.style.display = 'none';
var x = document.getElementById("FinalDisplay");
x.style.display = 'block';
}
</script>
So I am working on a series of codes for a website I will be developing and this is a small subroutine for finding greatest common divisors. I am using Notepad++ for mobility purposes and trying to run my code in Google Chrome to start. I want to make a GCD function for variables (numeratorIn,denominatorIn). Again in HTML
This is the part I want to add into the same script
var a = Math.floor(Math.sqrt(numeratorIn));
var b = Math.floor(Math.sqrt(denominatorIn));
document.getElementById("midpage15").innerHTML = (+a);
var k = 1
if (a<b) {
while (k<a) {
if ((Snum/k == Math.floor(Snum/k)) && (Sden/k == Math.floor(Sden/k)); {
var h = k;
}
k = k++;
}
}
else if (a>b) {
while (k<b) {
if ((Snum/k == Math.floor(Snum/k)) && (Sden/k == Math.floor(Sden/k)) {
var h = k;
}
k = k++;
}
}
else (a == b) {
document.getElementById("midpage15").innerHTML = ("Final Answer 1");
}
But it breaks my button that I use to activate the script every time :(
I usually program in Python but I want to make this in HTML. So I spent about 5 hours working on it and it is just driving me nuts. I am 100% confident it has something to do with the Ifs and the while statements at the bottom.
Here Snum and Sden are string.So you need to convert it into integer first.For that you can use parseInt() function.

find the length of a string in google script

I'm trying to make a script for google sheet, who can count a letter in a text. But it seems that .length doesn't work. Anyone who can give directions on where to find the the solution.
function Tjekkode(tekst , bogstav){
var test = "";
// find the length of laengdeTekst
var laengdeTekst = tekst.length;
var t = 0;
// through the text character by character
for ( var i = 1; i<laengdeTekst ; i++) {
var test = tekst.substr(i,1);
if (test == bogstav) {
// if the letter is found, it is counted up
// REMEMBER == means compare
var t = t + 1;
}
}
// returns percent appearance of the letter
Return = t / længdeTekst * 100
}
Thanks in advance
length is ok in your code. To test it, run this script:
function test( ) {
var test = "123456";
// finder længden på teksten
var laengdeTekst = test.length;
Logger.log(laengdeTekst);
}
After you run it, check Log, press [Ctrl + Enter]
The correct code in your case:
function Tjekkode(tekst, bogstav) {
var test = "";
var laengdeTekst = tekst.length;
var t = 0;
// start looping from zero!
for ( var i = 0; i<laengdeTekst; i++) {
var test = tekst.substr(i,1);
if (test == bogstav) {
var t = t + 1;
}
}
// JavaScript is case sensitive: 'return != Return'
return t / laengdeTekst * 100;
}
Please, look at this tutorial for more info
thanks
I'll guess that I might get the one with the R instead of r at the end, but the script didn't run that line, because it kinda stopped at the .length line :/
the comments in danish is for my pupils (I'm a teacher in elementary school)
I'll see if google wants to cooperate today :|
This is the google script that worked for me. Note the 24 - that's the length of an empty message that has markup like <div>...</div>
function TrashEmptyDrafts() {
var thread = GmailApp.getDraftMessages();
for (var i = 0; i < thread.length; i++) {
b=thread[i].getBody();
if (b.length <= 24.0){
thread[i].moveToTrash();
}
}}