URLEncode variable Parsing from String to Array as3 - regex

Ok! I have a flashVar variable that is coming into Flash, its URL encoded but I have already decoded it. My problem is I want the set of variables to be pushed into an array.
Let's say the variables are
"&text0=Enter Text...&size0=18&font0=Arial&color0=0&rotation0=0&y0=360&x0=640&text1=Enter
Text...&size1=18&font1=Arial&color1=0&rotation1=0&y1=360&x1=640"
and so on...
What I want is the variables to go into an array like
myArray[0].text = Enter Text...
myArray[0].size = 18]
myArray[0].font = Arial
myArray[0].color = 0
myArray[0].rotation = 0
myArray[0].y = 360
myArray[0].x = 640
myArray[1].text = ...........
.............................
.............................
myArray[n].text = ...........
I think there must be some way to do this. Most probably I'm thinking regular expression, but I'm pretty bad at regular expression. Please some help would be very very appreciated.
Thank You!

You don't have to decode your query string, just use the URLVariables object - it will do all the decoding for you. Then iterate over its dynamic properties to create your array. Use a RegExp to find the index numbers at the end of your variable keys:
function parseURLVariables( query:String ) : Array {
var vars:URLVariables = new URLVariables (query);
var arr:Array = [];
for (var key : String in vars) {
var splitIndex : int = key.search(/[0-9]+$/);
var name:String = key.substr (0,splitIndex);
var indexNumber:int = parseInt ( key.substr(splitIndex));
arr[indexNumber] ||= {};
arr[indexNumber][name] = vars[key];
}
return arr;
}
Since your query string starts with a an ampersand, you might have to use parseURLVariables ( myString.substr(1)), otherwise the URLVariables object will throw an error, complaining that the query string is not valid (it has to be url encoded, and start with a variable key).

you may use split method of string to something like this;
var astrKeyValue: Array = url.Split( "&" );
in this way each value in astrKeyValue is string keyvalue ( for example font1=Arial )
after than you may split each item with "=" and will get pair key and value ( for key - font1 and for value - arial)
so this code maybe will work for you
var str = "text0=Enter Text...&size0=18&font0=Arial&color0=0&rotation0=0&y0=360&x0=640&text1=Enter Text...&size1=18&font1=Arial&color1=0&rotation1=0&y1=360&x1=640"
var a : Array = str.split( "&" );
var newArr: Array = new Array()
for each ( var str1 in a )
{
var t: Array = str1.split( "=" );
newArr[ t[0] ] = t[1];
}
trace( newArr.text0 ) // -> Enter Text...

Here is a solution for you from me,
//your string data should be like this, there should be a seperate seperator (i've used pipe sign |) for each element which will be converted to an object and then pushed to the array
var strData:String = "text=Enter Text...&size=18&font=Arial&color=0&rotation=0&y=360&x=640|text=Enter Text...&size=18&font=Arial&color=0&rotation=0&y=360&x=640";
var myArray:Array = new Array();
var _tmpArr:Array = strData.split("|");
//populating the array
for(var i:int=0;i<_tmpArr.length;i++)
{
myArray.push(strToObj(_tmpArr[i]));
}
trace(myArray.length);
// coverts chunk of string to object with all key and value in it
function strToObj(str:String):Object
{
var obj:Object = new Object();
var tmpArr:Array = str.split('&');
for (var i:int = 0; i < tmpArr.length; i++)
{
var _arr:Array = String(tmpArr[i]).split('=');
var key:String = String(_arr[0]);
var val:String = String(_arr[1]);
obj[key] = val;
trace(key+" = "+val);
}
trace("----");
return obj;
}

Related

How to use regex for my List<String> in Flutter/Dart?

class Article{
final String id;
final List<ArticleArray> arrays;
}
class ArticleArray {
final String id;
final String array;
}
TextFormField(
onChanged: (_searchinput) {
List<String> searcharray = _searchinput.split(',');
),
_articlesForDisplay = _articles.where((article){
for(int i = 0; i < article.arrays.length; i++)
{
searchinit = article.arrays[i].arrays.toLowerCase();
}
return searchinit.contains(
RegExp(//necessary code here, caseSensitive: false),
);})
basically what i am trying to do is i am trying to search
array by array like:
-Textformfields follows the user input and every time "," is entered,i
put that word into "searcharray".
-Then i initiate a search in my function(total code is not needed to write here,
i included necessary functions),i try to use "regexp" function to search for the arrays
in my article archives.
Example:
articles[0].arrays[0].array = 'a1'
articles[0].arrays[1].array = 'a2'
articles[1].arrays[0].array = 'a1'
articles[1].arrays[1].array = 'b2'
searcharray = ['a1','b2']
Here,basically what i try to do is i try to search my article arrays by every list of arrays as possible so it matches the right one. Thats what i want.
Not sure I understand your specific requirements.
Here, I define a RegExp that I try to match to at least one item of my data.
void main() {
List<String> data = ['a1','b2', 'c3', 'a4', 'a5', 'd6'];
RegExp exp = new RegExp(r"(a\d+)");
print(data.any((item) => exp.hasMatch(item)));
}

Google Script - Removing Else statement properly so it skips/ignores

I have a checklist, column C indicates which test is automated by "enabled" or "disabled" written in the cells.
Further down the row is a column for the the Pass / Empty column for each test.
I have code that looks for if Enabled in column C, in X column on that row, mark as Pass automatically (or 'P' in my case).
The problem: If C column contains "Disabled" but also a Pass, when I run the script it replaces that Pass with an empty cell. How can I change the else statement to just ignore that cell and leave whatever is in it for anything but Enabled condition is met
function autoPassPC() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Aug 2020');
// What to put in the test result
var values1 = "P";
// Where to look for Auto:
var values2 = sheet.getRange("C10:C15" + sheet.getLastRow()).getValues();
// Keyword to look for in Auto: column
var putValues = [];
for (var i = 0; i < values2.length; i++) {
if (values2[i][0] === "Enabled") {
putValues.push([values1]);
} else {
putValues.push([""]);
}
}
// Put value1 inside row, column# for test result
sheet.getRange(10, 25, putValues.length, 1).setValues(putValues);
}
Basically how do I get rid of
} else {
putValues.push([""]);
}
properly? Just deleting this causes the script to put 'P' on every single row. Just want it to ignore the cells instead.
Thanks!
Removing the else statement will actually skip the row, but as soon as you skip a row, all following values in putValues will be on the wrong row. Instead of "skipping", try pushing the already existing value into putValues.
function autoPassPC() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Aug 2020');
// What to put in the test result
var values1 = "P";
// Where to look for Auto:
var enabledDisabled = sheet.getRange("C10:C15" + sheet.getLastRow()).getValues();
var testResultsRange = sheet.getRange("X10:X15" + sheet.getLastRow());
var testResults = testResultsRange.getValues();
// Keyword to look for in Auto: column
var putValues = [];
for (var i = 0; i < enabledDisabled.length; i++) {
if (enabledDisabled[i][0] === "Enabled") {
putValues.push([values1]);
} else {
putValues.push([testResults[i][0]]); // Push the existing cell value
}
}
// Put value1 inside row, column# for test result
testResultsRange.setValues(putValues);
}
You could also try getting the entire table at once thus having only one getValues() call.

define, initialize and use types in js-ctypes

SCardTransmit function is defined in https://msdn.microsoft.com/en-us/library/windows/desktop/aa379804%28v=vs.85%29.aspx
I want to declare and use this function, I have problems with the definition of some arguments in js-ctypes (especially in type casting):
LPCSCARD_IO_REQUEST: A pointer to the protocol header structure
LPCBYTE: A pointer to the actual data to be written to the card
LPBYTE: Pointer to a 32-byte buffer that receives the ATR string from the currently inserted card, if available. (this arg is in the status function)
How Can define, initialize and use them?
Here my code:
//-----------------define types----------------------
Cu.import('resource://gre/modules/ctypes.jsm');
var TYPES = {
ABI: is64bit ? ctypes.default_abi : ctypes.winapi_abi,
DWORD: ctypes.uint32_t,
LONG: ctypes.long,
BYTE: ctypes.unsigned_char //ctypes.uint8_t
};
TYPES.LPDWORD = TYPES.DWORD.ptr;
TYPES.SCARDCONTEXT = TYPES.ULONG_PTR;
TYPES.SCARDHANDLE = TYPES.ULONG_PTR;
TYPES.LPBYTE = TYPES.BYTE.ptr;
var CONST = {
SCARD_PROTOCOL_T0: 0x00000000,
SCARD_PROTOCOL_T1: 0x00000001
}
const SCARD_IO_REQUEST = new ctypes.StructType("myStruct" ,
[{"dwProtocol": TYPES.DWORD},
{"cbPciLength": TYPES.DWORD}]);
//------------------declaration-------------------------
var SCardTransmit = cardLib.declare('SCardTransmit', TYPES.ABI, TYPES.LONG, TYPES.SCARDHANDLE, SCARD_IO_REQUEST.ptr, TYPES.LPBYTE, TYPES.DWORD, SCARD_IO_REQUEST.ptr, TYPES.LPBYTE, TYPES.LPDWORD);
//------------------initializing---------------------
var _SCARD_IO_REQUEST = new SCARD_IO_REQUEST;
_SCARD_IO_REQUEST.dwProtocol = CONST.SCARD_PROTOCOL_T0|CONST.SCARD_PROTOCOL_T1;
_SCARD_IO_REQUEST.cbPciLength = _SCARD_IO_REQUEST.dwProtocol.toString().length;
var command = ctypes.char.array(42)("00a4040010a0000000183003010000000000000000");
var commandLength = command.toString().length;
var response = TYPES.LPBYTE;
var responseLength = TYPES.LPDWORD;
//----------------using-------------------------
var rez_SCT = SCardTransmit(cardHandle, _SCARD_IO_REQUEST, command, commandLength, null, response, responseLength.address());
if(rez_SCT.toString() != CONST.SCARD_S_SUCCESS.toString())
{
console.error('cannot begin transaction, error code was: ' + rez_SCT + ' in other terms it is: 0x' + rez_SCT.toString(16) + ' you can look up this error value here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa374738%28v=vs.85%29.aspx#smart_card_return_values');
throw new Error('failed to begin transactio!');
}

google-apps-script multiple criteria writing over headers

I have taken a bit of script from Serge which is great (original link here. I have added in a second criteria to exclude certain rows and it works great except, if there is not header in the sheet being copied to, it will not work (error: "The coordinates or dimensions of the range are invalid.") and if I enter a header or some other data, it overwrites it. Can anyone assist please? I have also found that is there is no match to the criteria I get following message "TypeError: Cannot read property "length" from undefined."
Also, what change would I need to make to change the cell 'dataSheetLog[i][12]' to the status variable, i.e. "COPIED" after I have copied it across. I have tried writing a setValue line but it is obviously the wrong instruction for that syntax.
Code is:
{
var Spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheetLog = Spreadsheet.getSheetByName("LOG");
var sheetMaint = Spreadsheet.getSheetByName("MAINTENANCE");
var Alast = sheetLog.getLastRow();
var criteria = "08 - Maintenance"
var status = "COPIED"
var dataSheetLog = sheetLog.getRange(2,1,Alast,sheetLog.getLastColumn()).getValues();
var outData = [];
for (var i in dataSheetLog) {
if (dataSheetLog[i][2]==criteria && dataSheetLog[i][12]!=status){
outData.push(dataSheetLog[i]);
}
}
sheetMaint.getRange(sheetMaint.getLastRow(),1,outData.length,outData[0].length).setValues(outData);
}
In:
sheetMaint.getRange(sheetMaint.getLastRow(),1,outData.length,outData[0].length).setValues(outData);
getLastRow() refers to the last occupied row and should be ,getLastRow() + 1,to keep from overwriting your headers and other problems.
Edited:
{
var Spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheetLog = Spreadsheet.getSheetByName("LOG");
var sheetMaint = Spreadsheet.getSheetByName("MAINTENANCE");
var Alast = sheetLog.getLastRow(); // Log
var criteria = "08 - Maintenance"
var status = "COPIED"
var dataSheetLog = sheetLog.getRange(2,1,Alast,sheetLog.getLastColumn()).getValues(); //Log
var dataSheetLogStatusRange = sheetLog.getRange(2,13,Alast,1); //Log
var dataSheetLogStatus = dataSheetLogStatusRange.getValues(); //Log
var outData = [];
for (var i =0; i < dataSheetLog.length; i++) {
if (dataSheetLog[i][2]==criteria && dataSheetLog[i][12]!=status){
outData.push(dataSheetLog[i]);
dataSheetLogStatus[i][0] = "COPIED";
}
}
if(outData.length > 0) {
sheetMaint.getRange(sheetMaint.getLastRow() + 1,1,outData.length,outData[0].length).setValues(outData);
dataSheetLogStatusRange.setValues(dataSheetLogStatus);
}
}
}
what change would I need to make to change the cell
'dataSheetLog[i][12]' to the status variable, i.e. "COPIED" after I
have copied it across.
You were trying to update the value in the array that was extracted from the sheet and not the sheet itself. As arrays are zero based and spreadsheets are not, to translate, +1 must be added to array row and column indices. I am assuming status is in column M of your sheet.

AS3/Regular Expressions - Replacing segments of a string

I have absolutely no knowledge in Regex whatsoever. Basically what I'm trying to do is have an error class that I can use to call errors (obviously) which looks like this:
package avian.framework.errors
{
public class AvError extends Object
{
// errors
public static const LAYER_WARNING:String = "Warning: {0} is not a valid layer - the default layer _fallback_ has been used as the container for {1}.";
/**
* Constructor
* Places a warning or error into the output console to assist with misuse of the framework
* #param err The error to display
* #param params A list of Objects to use throughout the error message
*/
public function AvError(err:String, ...params)
{
trace(err);
}
}
}
What I want to be able to do is use the LAYER_WARNING like this:
new AvError(AvError.LAYER_WARNING, targetLayer, this);
And have the output be something along the lines of:
Warning: randomLayer is not a valid layer - the default layer _fallback_ has been used as the container for [object AvChild].
The idea is to replace {0} with the first parameter parsed in ...params, {1} with the second, etc.
I've done a bit of research and I think I've worked out that I need to search using this pattern:
var pattern:RegExp = /{\d}/;
You can use StringUtil
var original:String = "Here is my {0} and my {1}!";
var myStr:String = StringUtil.substitute(original, ['first', 'second']);
Using the g flag in RegExp you can create an array containing all of your {x} matches, then loop through this array and replace each of the matches with the appropriate parameter.
Code:
var mystring:String = "{0} went to {1} on {2}";
function replace(str:String, ...params):String
{
var pattern:RegExp = /{\d}/g;
var ar:Array = str.match(pattern);
var i:uint = 0;
for(i; i<ar.length; i++)
{
str = str.split(ar[i]).join(params[i]);
}
return str;
}
trace(replace(mystring, "marty", "work", "friday")); // marty went to work on friday
i'm assuming you want to have several static constants with varying replacement instances ({0}, {1}, {2}, etc.) in each string constant.
something like this should work - sorry, it's untested:
public function AvError(err:String, ...params)
{
var replacementArray:Array = err.match(new RegExp("{\\d}", "g"));
for (var i:int = 0, i < replacementArray.length, i++)
err = err.replace(new RegExp(replacementArray[i], "g"), params[i]);
trace(err);
}
if you do have several static constants with varying replacement instances, you'll want to check for an appropriate matching amount of …params that are passed.