How to make swap(random) positions between 3 objects by AS3? - actionscript-3

//array
var boxs: Array = new Array
boxs[0] = [b1.x = 307.95 , b1.y = 202]
boxs[1] = [b2.x = 233.95 , b2.y = 202]
boxs[2] = [b3.x = 159.95 , b3.y = 202]
//varable
var oldg:Number = 0
//random number
oldg = Number(Math.floor(Math.random()*boxs.length))

Naive approach:
public function Main()
{
const array:Array = [1,2,3,4,5,6,7];
trace(array);
// 1,2,3,4,5,6,7
swapTwoRandomElements(array);
trace(array);
// 1,2,3,6,5,4,7
}
private function swapTwoRandomElements(input:Array):void
{
const indices:Array = [];
for (var i:int = 0; i < input.length; i++)
{
indices.push(i);
}
const indexFirst:int = indices[int(Math.random() * indices.length)];
indices.splice(indexFirst, 1);
const indexSecond:int = indices[int(Math.random() * indices.length)];
indices.splice(indexSecond, 1);
const tmp:* = input[indexFirst];
input[indexFirst] = input[indexSecond];
input[indexSecond] = tmp;
}

Related

Exception: The number of rows in the data does not match the number of rows in the range. The data has 1 but the range has 8. Google Script

I am having troubles in
Exception: The number of rows in the data does not match the number of rows in the range. The data has 1 but the range has 8. Google Script
function myFunction() {
var s1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Staging');
var s2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Final');
var values1 = s1.getDataRange().getValues();
var values2 = s2.getDataRange().getValues();
var Avals = s2.getRange("A1:A").getValues();
var Alast = Avals.filter(String).length;
var resultArray = [];
for(var n=0; n < values1.length ; n++)
{
var keep = false;
var counter = 0;
for(var p=0; p < values2.length ; p++)
{
if( values1[n][1] == values2[p][1])
{
keep = true;
break ;
}
}
if(keep == false)
{
resultArray.push([values1[n]]);
//s2.appendRow( values1[n] );
s2.getRange(Alast + 1, 1, values1[n].length, values1[n].length).setValues([values1[n]]);
//s2.getRange(s2.getLastRow() + 1, 1, values1.length, values1[0].length).appendRow( values1[n] );
resultArray = [];
keep = false
}
}
}
I believe you are trying to keep appending a new row to the end of the data on "Final". You should revise you script as shown below. Use resultArray to collect all new rows and save it to spreadsheet once.
function myFunction() {
var s1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Staging');
var s2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Final');
var values1 = s1.getDataRange().getValues();
var values2 = s2.getDataRange().getValues();
// s2.getDataRange() will get up to the last row of data
var Alast = values2.length;
var resultArray = [];
for(var n=0; n < values1.length ; n++)
{
var keep = false;
var counter = 0;
for(var p=0; p < values2.length ; p++)
{
if( values1[n][1] == values2[p][1])
{
keep = true;
break ;
}
}
if(keep == false)
{
resultArray.push(values1[n]);
keep = false
}
}
if( resultArray.length > 0 ) {
s2.getRange(Alast+1,1,resultArray.length,resultArray[0].length).setValues(resultArray);
}
}

How to Get (& Set) cell values from one sheet to another in Google Sheets?

Looking to get values from several cells in the first sheet (POTemplate) of my Google Sheet file that serves as an order entry form. Line 22 is the first line in the form that collects data from our user regarding items requested for order.
The tab to which I'd like to set these values (POHistory) will serve as a running log of all order details keyed into the POTemplate tab with each order. Each entry recorded in the PO template log should include each orders' unique PO No. (found in cell N3 of the POTemplate tab) & PO Date (cell N4 of the POTemplate tab). I sincerely appreciate the help.
function submit() {
var app = SpreadsheetApp;
var tplSheet = app.getActiveSpreadsheet().getSheetByName("POTemplate");
var tplFRow = 22, tplLRow = tplSheet.getLastRow();
var tplRowsNum = tplLRow - tplFRow + 1;
var tplFCol = 1, tplLCol = 16;
var tplColsNum = tplLCol - tplFCol + 1;
var rangeData = tplSheet.getRange(22, 1, tplRowsNum, tplColsNum).getValues();
var colIndexes = [0, 3, 10, 12, 15];
var fData = filterByIndexes(rangeData, colIndexes);
var target = "POHistory";
var targetSheet = app.getActiveSpreadsheet().getSheetByName(target);
var tgtRow = targetSheet.getLastRow() + 1;
var tgtRowsNum = fData.length - tgtRow + 1;
var tgtCol = 1;
var tgtColsNum = fData[0].length - 1 + 1;
targetSheet.getRange(tgtRow, tgtCol, tgtRowsNum,
tgtColsNum).setValues(fData);
}
function filterByIndexes(twoDArr, indexArr) {
var fData = [];
twoDArr = twoDArr.transpose();
for(var i=0; i<indexArr.length; i++) {
fData.push(twoDArr[indexArr[i]]);
}
return fData.transpose();
}
Array.prototype.transpose = function() {
var a = this,
w = a.length ? a.length : 0,
h = a[0] instanceof Array ? a[0].length : 0;
if (h === 0 || w === 0) {return [];}
var i, j, t = [];
for (i = 0; i < h; i++) {
t[i] = [];
for (j = 0; j < w; j++) {
t[i][j] = a[j][i];
}
}
return t;
}
I can offer you a modification of the submit() function you have given.
function process(){
submit();
submitDate();
}
function submitDate() {
var app = SpreadsheetApp;
var tplSheet = app.getActiveSpreadsheet().getSheetByName("POTemplate");
var tplFRow = 1, tplLRow = 21;
var tplRowsNum = tplLRow - tplFRow + 1;
var tplFCol = 1, tplLCol = 16;
var tplColsNum = tplLCol - tplFCol + 1;
var rangeData = tplSheet.getRange(tplFRow, tplFCol, tplLRow, tplColsNum).getValues();
var colIndexes = [13];
var fData = filterByIndexes(rangeData, colIndexes);
var target = "POHistory";
var targetSheet = app.getActiveSpreadsheet().getSheetByName(target);
var tgtRow = targetSheet.getLastRow() + 1;
var tgtRowsNum = fData.length - tgtRow + 1;
var tgtCol = 1;
var tgtColsNum = fData[0].length - 1 + 1;
Logger.log(fData)
fData=fData.transpose();
Logger.log(fData)
targetSheet.getRange(tgtRow-1, 5, fData.length,
fData[0].length).setValues(fData);
}
function submit() {
var app = SpreadsheetApp;
var tplSheet = app.getActiveSpreadsheet().getSheetByName("POTemplate");
var tplFRow = 22, tplLRow = tplSheet.getLastRow();
var tplRowsNum = tplLRow - tplFRow + 1;
var tplFCol = 1, tplLCol = 16;
var tplColsNum = tplLCol - tplFCol + 1;
var rangeData = tplSheet.getRange(22, 1, tplRowsNum, tplColsNum).getValues();
var colIndexes = [0, 3, 10, 12, 15];
var fData = filterByIndexes(rangeData, colIndexes);
var target = "POHistory";
var targetSheet = app.getActiveSpreadsheet().getSheetByName(target);
var tgtRow = targetSheet.getLastRow() + 1;
var tgtRowsNum = fData.length - tgtRow + 1;
var tgtCol = 1;
var tgtColsNum = fData[0].length - 1 + 1;
targetSheet.getRange(tgtRow, tgtCol, tgtRowsNum,
tgtColsNum).setValues(fData);
}
function filterByIndexes(twoDArr, indexArr) {
var fData = [];
twoDArr = twoDArr.transpose();
for(var i=0; i<indexArr.length; i++) {
fData.push(twoDArr[indexArr[i]]);
}
return fData.transpose();
}
Array.prototype.transpose = function() {
var a = this,
w = a.length ? a.length : 0,
h = a[0] instanceof Array ? a[0].length : 0;
if (h === 0 || w === 0) {return [];}
var i, j, t = [];
for (i = 0; i < h; i++) {
t[i] = [];
for (j = 0; j < w; j++) {
t[i][j] = a[j][i];
}
}
return t;
}
Basically, similar code runs twice. I could be criticized for doing this, but perhaps it is convenient for you this way.

Google script Execution failed: please try again later and consider using batch operations. The user is over quota

I have a script where I'm syncing my google contacts with google spreadsheet.
I have around 11000 contacts in my account and I've written a function getContacts which fetches all contact information from the google contacts and sends it to a function printContacts,how ever as there are too many contacts the script fails to execute to completion.
I tried using the code to create a trigger everytime the max execution time is reached but now I'm facing a new problem,as I have too many ContactsApi call the script is showing an error saying 'user quota exceeded'
If anyone can get this code to work,it'd be a great help
//Function gets the contacts from the Google Contacts and stores in an array. Calls printContacts function with that array and no. of rows as argument
function getContacts() {
var startTime= (new Date()).getTime();
Logger.log("start time set")
var scriptProperties = PropertiesService.getScriptProperties();
var num_contacts = scriptProperties.getProperty('num_contacts');
Logger.log("script property num_contacts : "+Number(num_contacts))
setHeader();
var groupName = 'System Group: My Contacts';
var group = ContactsApp.getContactGroup(groupName);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var contacts = ContactsApp.getContactsByGroup(group);
var allContacts = [];
var contactDetails = [];
var data, numData, dataArray = [], extraArray = [];
var contact_length = contacts.length;
Logger.log("contact_length : "+contact_length);
Logger.log("contacts.length : "+contacts.length);
var MAX_RUNNING_TIME = 300000;
var REASONALBLE_TIME_TO_WAIT = 60000;
var limit = contact_length;
Logger.log("limit :"+limit)
for(var i=Number(num_contacts); i <= contacts.length; i++) {
var currTime = (new Date()).getTime();
if(currTime - startTime >= MAX_RUNNING_TIME){
Logger.log("Value of i in if section : "+i)
scriptProperties.setProperty("num_contacts",i);
ScriptApp.newTrigger("getContacts")
.timeBased()
.at(new Date(currTime+REASONALBLE_TIME_TO_WAIT))
.create();
Logger.log("trigger created for i = "+i)
break;
}
else{
if(i < contacts.length)
{
allContacts[i] = [];
contactDetails[0] = contacts[i].getGivenName();
contactDetails[1] = contacts[i].getFamilyName();
data = contacts[i].getEmails();
numData = data.length;
for(var j = 0; j < numData; j++) {
dataArray[j] = data[j].getAddress();
}
contactDetails[2] = dataArray.join("\n");
dataArray = [];
data = contacts[i].getPhones(ContactsApp.Field.MOBILE_PHONE);
numData = data.length;
for(var j = 0; j < numData; j++) {
dataArray[j] = data[j].getPhoneNumber();
}
contactDetails[3] = dataArray.join("\n");
dataArray = [];
data = contacts[i].getPhones(ContactsApp.Field.WORK_PHONE);
numData = data.length;
for(var j = 0; j < numData; j++) {
dataArray[j] = data[j].getPhoneNumber();
}
contactDetails[5] = dataArray.join("\n");
dataArray = [];
// new section for home_phone ----- start
data = contacts[i].getPhones(ContactsApp.Field.HOME_PHONE);
numData = data.length;
for(var j = 0; j < numData; j++){
dataArray[j] = data[j].getPhoneNumber();
}
contactDetails[6] = dataArray.join("\n");
dataArray = [];
// new section for home_phone ----- end
data = contacts[i].getCompanies();
numData = data.length;
for(var j = 0; j < numData; j++) {
dataArray[j] = data[j].getCompanyName();
extraArray[j] = data[j].getJobTitle();
}
contactDetails[7] = dataArray.join("\n");
dataArray = [];
contactDetails[8] = extraArray.join("\n");
data = contacts[i].getAddresses();
numData = data.length;
for(var j = 0; j < numData; j++) {
dataArray[j] = data[j].getAddress();
}
contactDetails[9] = dataArray.join("\n");
dataArray = [];
contactDetails[10] = contacts[i].getNotes();
data = contacts[i].getCustomFields();
numData = data.length;
for(var j = 0; j < numData; j++) {
dataArray[j] = data[j].getValue();
}
contactDetails[11] = dataArray.join("\n");
dataArray = [];
data = [];
data = contacts[i].getContactGroups();
numData = data.length;
for(var j = 0; j < numData; j++) {
if(data[j].getName() == 'System Group: My Contacts')
{
continue;
}
else
{
dataArray[j] = data[j].getName();
}
}
contactDetails[4] = dataArray.join("\n");
dataArray = [];
contactDetails[12] = 'saved';
contactDetails[13] = contacts[i].getId();
for(var j = 0; j < 14; j++) {
allContacts[i][j] = contactDetails[j];
}
}
}
}
Logger.log("last value of i "+i);
Logger.log("num of contacts "+allContacts.length)
printContacts(allContacts, contacts.length);
setProperties_getContacts();
return;
}
//Function to print contacts to the spreadsheet.
function printContacts(contactsArray, i) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange(2, 1, i, 14);
range.setValues(contactsArray);
}

Trouble with nested Json data

I'm having a ton of trouble trying to access the nested json data (pasted at the bottom). I'm able write:
var dataResults = jsonResult["data"] as NSDictionary
In order to create a dictionary containing the data within "data", however, Xcode will not allow me to call on anything within "data" such as the information within "current_condition". I've tried to make current_condition it's own dictionary like so:
var results = dataResults["current_condition"] as NSDictionary
But it would seem that this is turning up as nil
I have also attempted accessing using the standard method for calling nested loops:
var dataResults = jsonResult["data"]["current_condition"] as NSDictionary
But this results in a compiler error.
Any help? Much appreciated!
Json data:
{
data = {
"current_condition" = (
{
cloudcover = 0;
humidity = 68;
"observation_time" = "01:39 AM";
precipMM = "0.0";
pressure = 1017;
"temp_C" = 20;
"temp_F" = 68;
visibility = 10;
weatherCode = 143;
weatherDesc = (
{
value = Mist;
}
);
weatherIconUrl = (
{
value = "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0006_mist.png";
}
);
winddir16Point = NE;
winddirDegree = 50;
windspeedKmph = 7;
windspeedMiles = 4;
}
);
request = (
{
query = "London, United Kingdom";
type = City;
}
);
weather = (
{
date = "2014-07-25";
precipMM = "1.5";
tempMaxC = 27;
tempMaxF = 81;
tempMinC = 14;
tempMinF = 57;
weatherCode = 353;
weatherDesc = (
{
value = "Light rain shower";
}
);
weatherIconUrl = (
{
value = "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0009_light_rain_showers.png";
}
);
winddir16Point = NE;
winddirDegree = 54;
winddirection = NE;
windspeedKmph = 15;
windspeedMiles = 10;
},
{
date = "2014-07-26";
precipMM = "5.8";
tempMaxC = 28;
tempMaxF = 83;
tempMinC = 16;
tempMinF = 61;
weatherCode = 176;
weatherDesc = (
{
value = "Patchy rain nearby";
}
);
weatherIconUrl = (
{
value = "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0009_light_rain_showers.png";
}
);
winddir16Point = NNE;
winddirDegree = 12;
winddirection = NNE;
windspeedKmph = 11;
windspeedMiles = 7;
},
{
date = "2014-07-27";
precipMM = "0.2";
tempMaxC = 26;
tempMaxF = 80;
tempMinC = 13;
tempMinF = 55;
weatherCode = 116;
weatherDesc = (
{
value = "Partly Cloudy";
}
);
weatherIconUrl = (
{
value = "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png";
}
);
winddir16Point = NW;
winddirDegree = 321;
winddirection = NW;
windspeedKmph = 14;
windspeedMiles = 9;
},
{
date = "2014-07-28";
precipMM = "1.9";
tempMaxC = 26;
tempMaxF = 78;
tempMinC = 12;
tempMinF = 54;
weatherCode = 116;
weatherDesc = (
{
value = "Partly Cloudy";
}
);
weatherIconUrl = (
{
value = "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png";
}
);
winddir16Point = N;
winddirDegree = 351;
winddirection = N;
windspeedKmph = 13;
windspeedMiles = 8;
},
{
date = "2014-07-29";
precipMM = "0.0";
tempMaxC = 28;
tempMaxF = 82;
tempMinC = 16;
tempMinF = 60;
weatherCode = 113;
weatherDesc = (
{
value = Sunny;
}
);
weatherIconUrl = (
{
value = "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0001_sunny.png";
}
);
winddir16Point = NNW;
winddirDegree = 329;
winddirection = NNW;
windspeedKmph = 13;
windspeedMiles = 8;
}
);
};
}
Oddly enough, I have a sample weather app that I converted to Swift. I get my data elsewhere, but I found this library to be a great way to deal with JSON in Swift: https://github.com/dankogai/swift-json/. Much cleaner and easier.
It's because the subscript in Dictionary returns an optional:
subscript (key: KeyType) -> ValueType?
Meaning you have to unwrap the optional before you can downcast:
let dataResults = jsonResult["data"]! as NSDictionary
let results = dataResults["current_condition"]! as NSDictionary
As of Beta 3 you can access the value directly without downcasting, like this:
let dataResults = jsonResult["data"]!
let results = dataResults["current_condition"]
However I would suggest you wrap it around an if-let to make sure you don't unwrap nil values.

Cannot see the content inside of a MovieClip

I don't know why this is happening. What I want to do is easy: Create a container and then add a grid of squares in order to build a trivia:
private var square:MovieClip = new MovieClip();
square.width = 308;
square.height = 400;
square.x = 48;
square.y = 223;
square.name = "square";
addChild(square);
private function generarGrilla():void {
var cant = 36;
var col:Number = 5;
var yCounter:Number = -4;
var xCounter:Number = 4;
var sY:Number = 10;
var sX:Number = 10;
for (var j = 1; j < cant; j++) {
var caja:clip = new clip();
caja.name = "opcion" + j;
caja.x = 20 + caja.width * j * 1.2;
caja.y = 20 + caja.height * j * 1.2;;
// caja.x = (sX + caja.width) * xCounter ;
// caja.y = (sY + caja.height) * yCounter;
caja.addEventListener(MouseEvent.CLICK, seleccionarOpcion);
caja.buttonMode = true;
caja.mouseChildren = false;
var contentText = new TextField();
var formato = new TextFormat();
formato.size = 14;
contentText.defaultTextFormat = formato;
contentText.width = 36;
contentText.height = 34;
contentText.x = -10;
contentText.y = -10;
for(var u:uint = 0; u < cant; u++){
contentText.text = "" + u;
}
square.addChild(caja);
caja.addChild(contentText);
}
var barra:score = new score();
barra.x = 80;
barra.y = -200;
barra.puntajeTXT.text = "hola";
addChild(barra);
barra.botonSalir.buttonMode = true;
barra.botonSalir.addEventListener(MouseEvent.CLICK, salirJuego);
}
The square movieclip is placed on the stage without any problem, but I cannot see the grid...