Convert an API KEY to string of numbers and reverse in ActionScripts3 - actionscript-3

We need to convert some API KEYs to string numbers and convert that numbers to original string.
Sample API KEY: "ZfIgG9LliwY4cDw4Rqso0m7SEQZovI"
We converted it with our algorithm
var encode_array:Array = "ZfIgG9LliwY4cDw4Rqso0m7SEQZovI".split("");
var encode_string:String;
var count1:int = encode_array.length; var i1:int;
for (i1 = 0; i1 < count1; i1++)
{
switch(encode_array[i1])
{
case "*":
encode_string += *;
break;
...
}
Converted API KEY:"364219431799224845593594391459942853555190499729152736515819"
Each 2 numbers in this string are related to 1 chracter in API KEY.(Sample: "36" > "Z")
My problem is second part to reverse this (convert each 2 number to defined character), How to possible separate every 2 numbers in this string and save them in an array?
I think it possible with Split"" or RegExp in ActionScripts, but i don't know how.

There is a straightforward method:
var s:String = '364219431799224845593594391459942853555190499729152736515819';
for (var i:int = 0; i < s.length; i += 2) {
var sub:String = s.charAt(i) + s.charAt(i + 1);
trace(sub);//convert
}

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?! :)

Prevent UrlFetchApp creating special entities

Is there any way to prevent Apps Script URlFetchApp from creating special characters? For example on a webpage there might be an apostrophe but when I look in the fetched page source that apostrophe would be written as '
Use this decode function to decode your string:
function myFunction(str) {
var str = "'<a>Content © <#>&<&#># </a>"
var decoded = decode(str);
Logger.log(decoded)
}
function decode(str) {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
}).replace(/(&#x(\d+);)/g, function(match, str1) {
var hex = match.toString().match(/(\d+)/g)[0];
var str = '';
for (var n = 0; n < hex.length; n += 2) {
str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
}
return str;
});
}
This will decode the HTML entities in JavaScript. Combined both my references. Decodes ones with x prepended and the others without.
Reference:
https://stackoverflow.com/a/23270912/16132436
https://www.codegrepper.com/code-examples/javascript/hex+to+ascii+function+javascript

How can I order my string in as3

A complex question :
I've got this code (not the complete code, but the essentials for the question, I think) :
var $pmm:String;
var $pms:String;
var $bmm:String;
var $bms:String;
function get haute1():String { return $pmm; };
function get haute2():String { return $pms; }
function get basse1():String { return $bmm; };
function get basse2():String { return $bms; };
accueil.todayHaute_txt.htmlText = haute1;
accueil.todayBasse_txt.htmlText = basse1;
accueil.todayHauteSecond_txt.htmlText = haute2;
accueil.todayBasseSecond_txt.htmlText = basse2;
"haute1" is an hour (in 24h format). Something like "13h25".
It changes everyday.
Question : How can put them in ascending order in AS3 ?
Example : If haute1 = 15h20, haute2= 6h00, basse1= 11h and basse2 = 17h, the function would put them in this order :
"haute2", then "basse1", then "haute1" and finally "basse2".
Thx
EDIT
I add this code that I have. is it helping you ?
/ Assigns hours and tidal heights
$pmm = convdateheure($tpbs[1 + $deltapm]);
$pms = convdateheure($tpbs[3 + $deltapm]);
$bmm = convdateheure($tpbs[2 - $deltapm]);
$bms = convdateheure($tpbs[4 - $deltapm]);
function convdateheure($valeur:Number):String
{
var $heure:Number = Math.floor($valeur);
var $minute:Number = Math.floor(Math.floor(($valeur - Math.floor($valeur)) * 100) * 0.6);
var hoursLabel:String = "", minsLabel:String = "";
if ($heure == 24) $heure = 0; // Check if at the 24 hour mark, change to 0
if ($heure < 10) hoursLabel += "0" + $heure.toString(); else hoursLabel = $heure.toString();
if ($minute < 10) minsLabel += "0" + $minute.toString(); else minsLabel = $minute.toString();
return hoursLabel + ":" + minsLabel;
}
If you want to order some dates written in some String format:
One way would be, depending on you date string format, just to push them into array and sort them as strings, then read them all.
Another way would be to first parse those strings into Date instances, and push their Date.time property to array, sort it, then do reverse: parse all time values from sorted array into new Date instances then use Date.toString or similar.
Assuming that $valuer is a numerical value:
var timesArray:Array = new Array();
var convertedTimesArray:Array = new Array();
function sortTimes():void{
timesArray.push($valuer);
timesArray.sort(Array.NUMERIC);
}
function convertTimes():void{
convertedTimesArray = []; // clear the array
for (var i:int = 0; i < timesArray.length; i++){
var s:String = convdateheure(timesArray[i]);
convertedTimesArray.push(s);
}
}
That should give you one array of actual times, sorted in numerical order, and one array sorted in the same numerical order, but converted to String values using your function.

Javascript: Using reviver function, I seem can't get to alter all the keys, while concating the numbers

I just want to change all the keys in batchesX. But I can't seem to alter all keys, because of concat. This is what I learned from post.
Please advise how I can change all keys with numbers.
var batchesX = '[{"batch":"0010002033"},{"batch":"0010001917"},{"batch":"0000020026"},{"batch":"0000017734"},'+
'{"batch":"0000015376"},{"batch":"0000014442"},{"batch":"0000014434"},{"batch":"0000014426"},'+
'{"batch":"0000013280"},{"batch":"0000012078"},{"batch":"0000012075"},{"batch":"0000012072"},'+
'{"batch":"0000011530"},{"batch":"0000011527"},{"batch":"0000011342"},{"batch":"0000010989"},'+
'{"batch":"0000010477"},{"batch":"0000008097"},{"batch":"0000007474"},{"batch":"0000006989"},'+
'{"batch":"0000004801"},{"batch":"0000003566"},{"batch":"0000003565"},{"batch":"0000001392"},'+
'{"batch":"0000001391"},{"batch":"0000000356"},{"batch":"0000"},{"batch":"000"},{"batch":""},'+
'{"batch":null}]'; // 30 elements
//in JSON text
var batchi = "batch";
var obj_batchesY = JSON.parse(batchesX);
console.debug(obj_batchesY);
var obj_batchesYlength = obj_batchesY.length;
console.debug(obj_batchesYlength);
var obj_batchesX = JSON.parse(batchesX,
function(k,v)
{
for(var i=1; i <= obj_batchesYlength; i++ )
{
if(k=="batch")
{
this.batchi.concat(string(i)) = v;
}
else
return v;
}
}
);
console.debug(obj_batchesX);
Is the code too long winded?
Many thanks in advance.
Clement
The return value of the reviver function only replaces values. If you need to replace keys, then use stringify and replace before the parse call, like this:
JSON.parse(JSON.stringify({"alpha":"zulu"}).replace('"alpha":','"omega":'))
Here is how to replace all numeric keys:
function newkey()
{
return Number(Math.random() * 100).toPrecision(2) + RegExp.$1
}
//Stringify JSON
var foo = JSON.stringify({"123":"ashanga", "12":"bantu"});
//Replace each key with a random number without replacing the ": delimiter
var bar = foo.replace(/\d+("?:)/g, newkey)
//Parse resulting string
var baz = JSON.parse(bar);
Make sure each replaced key is unique, since duplicate keys will be removed by the parse method.

Scroll to alphabet in a List (ArrayCollection dataProvider) (Alphabet Jump)

Hopefully this is easy but that sometimes means its impossible in flex and I have searched quite a bit to no avail.
Say I have a list (LIST#1) of artists:
2Pac
Adele
Amerie
Beyonce
Jason Aldean
Shakira
The Trews
I also have a list (LIST#2) that has the values #,A-Z - how would I create an alphabet jump?
So If a user clicked on "A" in LIST#2 that would automatically scroll to "Adele" at the top of LIST#1 - not filter so he/she could scroll up to view 2Pac or down to view The Tews if they were not in the view yet.
Its a standard Flex Spark List with an ArrayCollection as the dataProvider - the artist field is called: "title" along with a unique id field that is not visible to the user.
Thanks!
Please see comments on marker answer for discussion on Dictionary that may be faster in some cases. See below for code (HAVE NOT CONFIRMED ITS FASTER! PLEASE TEST):
private function alphabet_listChange(evt:IndexChangeEvent) : void {
var letter:String;
letter = evt.currentTarget.selectedItems[0].toString();
trace(currentDictionary[letter]);
ui_lstLibraryList.ensureIndexIsVisible(currentDictionary[letter]);
}
public function createAlphabetJumpDictionary() : Dictionary {
//alphabetArray is a class level array containing, A-Z;
//alphabetDictionary is a class level dictionary that indexes A-z so alphabetDictionary["A"] = 0 and ["X"] = 25
var currentIndexDict:Dictionary = new Dictionary; //Dictionary is like an array - just indexed for quick searches - limited to key & element
var searchArray:Array = new Array;
searchArray = currentArrayCollection.source; //currentArrayCollection is the main array of objects that contains the titles.
var currentIndex:Number; //Current index of interation
var currentAlphabetIndex:Number = 0; //Current index of alphabet
for (currentIndex = 0; currentIndex < searchArray.length; currentIndex++) {
var titleFirstLetter:String = searchArray[currentIndex].title.toString().toUpperCase().charAt(0);
if (titleFirstLetter == alphabetArray[currentAlphabetIndex]) {
currentIndexDict[titleFirstLetter] = currentIndex;
trace(titleFirstLetter + " - " + currentIndex);
currentAlphabetIndex++;
} else if (alphabetDictionary[titleFirstLetter] > alphabetDictionary[alphabetArray[currentAlphabetIndex]]) {
trace(titleFirstLetter + " - " + currentIndex);
currentIndexDict[titleFirstLetter] = currentIndex;
currentAlphabetIndex = Number(alphabetDictionary[titleFirstLetter] + 1);
}
}
return currentIndexDict;
}
private function build_alphabeticalArray() : Array {
var alphabetList:String;
alphabetList = "A.B.C.D.E.F.G.H.I.J.K.L.M.N.O.P.Q.R.S.T.U.V.W.X.Y.Z";
alphabetArray = new Array;
alphabetArray = alphabetList.split(".");
return alphabetArray;
}
private function build_alphabetDictionary() : Dictionary {
var tmpAlphabetDictionary:Dictionary = new Dictionary;
for (var i:int=0; i < alphabetArray.length; i++) {
tmpAlphabetDictionary[alphabetArray[i]] = i;
trace(alphabetArray[i] + " - " + i);
}
return tmpAlphabetDictionary;
}
private function buildCurrentDictionary() : void {
trace("Collection Changed");
currentDictionary = new Dictionary;
currentDictionary = createAlphabetJumpDictionary();
}
The Flex Spark list has a very convenient method called ensureIndexIsVisible(index). Check the Flex reference documentation. All you have to do is to find the index of the first artist for the corresponding selected alphabet letter:
public function findAlphabetJumpIndex():Number
{
var jumpToIndex:Number;
var selectedLetter:String = alphabethList.selectedItem;
for (var i:int=0; i < artists.length; i++)
{
var artistName:String = artists.getItemAt(i);
var artistFirstLetter:String = artistName.toUpperCase().charAt(0);
if (artistFirstLetter == selectedLetter)
{
jumpToIndex = i;
break;
}
}
return jumpToIndex;
}
You can iterate your artist list data provider and check if artist name starts with selected alphabet from list two. When corresponding artist is found, set artist list selected index a value what you get from iterating data.