Pass actual variable object to a function - actionscript-3

The problem is simple:
I need to pass actual variable to a function.
private var test:String = "KKK";
trace (" Before --->>> " + test);
testFunction(test);
trace (" Next --->>> " + test);
private function testFunction(d:String):void{
d = "MMM";
}
Result:
Before --->>> KKK
Next --->>> KKK
The result is correct but, What I want is, send the actual test variable to my function and change that. So I want to have output like this:
Before --->>> KKK
Next --->>> MMM
Any solution?
Thanks for your answer but if I have a code like this, I need to pass the actual variable to my function:
if ( lastPos == -1 ){// if this is first item
flagLEFT = "mid";
tempImageLEFT = new Bitmap(Bitmap(dataBANK[0]["lineimage" + 10]).bitmapData);
}else if (nextPos == -1){// if this is the last position
flagRIGHT = "mid";
tempImageRGHT = new Bitmap(Bitmap(dataBANK[0]["lineimage" + 13]).bitmapData);
}
As you see, changes are in flagLEFT and tempImageRGHT . Also I have a change on numbers (10 and 13) which can be handle in normal way. I need something like this:
private function itemFirstLast(flag:String, bmp:Bitmap, pos:int):void{
flag = "mid";
bmp = new Bitmap(Bitmap(dataBANK[0]["lineimage" + pos]).bitmapData);
}
Any solution?

One way is to return the new string and assign it to test :
private var test:String = "KKK";
trace (" Before --->>> " + test);
test = testFunction(test);
trace (" Next --->>> " + test);
private function testFunction(d:String):String{
d = "MMM";
return d;
}
This still doesn't pass the actual string object but the test string will change. Strings are passed by value in AS3, if you wan't to actually pass it in you can wrap it in an object :
var object:Object {
"test":"KKK"
};
trace (" Before --->>> " + object["test"]);
testFunction(object);
trace (" Next --->>> " + object["test"]);
private function testFunction(o:Object):void{
o["test"] = "MMM";
}

You'll need to wrap it in a class instance:
class StringValue{
function StringValue( value : String ) : void{
this.value = value;
}
public var value : String;
public function toString() : String{
return value;
}
}
private var test:StringValue = new StringValue( "KKK" );
trace (" Before --->>> " + test);//traces 'KKK'
testFunction(test);
trace (" Next --->>> " + test);//traces 'MMM'
private function testFunction(d:StringValue):void{
d.value = "MMM";
}

Please refer to the following link:
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f56.html
You need to wrap it in the Object .

Related

d3 variable equals the string "function(d)", not the value the function returns

In some d3js code, I am using an anonymous function(d) to return the value of -importance from a JSON file. I use the returned value, stored in kwdAssbly object, to decide whether or not to render part of a diagram.
where I break on:
kwdAssbly.opt = (function(d){
return d["-importance"];
});
With a watch set on the object kwdAssbly, the debugger shows numerical values for kwdAssbly.width & kwdAssbly.height but shows kwdAssbly.opt = kwdAssbly.opt(d). I'm expecting a string value of either required or optional! If I put a watch on d in the function, it shows -importance:"optional", but this isn't assigned to my kwdAssbly.opt object attribute
Why is the function declaration being returned as the value?
Here's a code snippet of the context:
.attr("nullAttrib", function(d, i) { // calculate the text width and store it
var kwdAssbly = {}; //the keyword group's height and width object
kwdAssbly.width = this.getBoundingClientRect().width + padding;
kwdAssbly.height = this.getBoundingClientRect().height;
kwdAssbly.opt = (function(d){
return d["-importance"];
});
kwdProps[i] = kwdAssbly;
if (i>0){
kwdX += kwdProps[i-1].width;
if (kwdProps[i].opt == "optional"){
OptOffset = 40;
var Lsiding = kwdgrp.append(function(){return sidingL})
.attr("transform","translate(" + kwdX + ", " + (kwdProps[i].height*2/3 + line1y + OptOffset) + ")");
var Rsiding = kwdgrp.append(function(){return sidingR})
.attr("transform","translate(" + kwdX+50 + ", " + (kwdProps[i].height*2/3 + line1y + OptOffset) + ")");
}
else {
OptOffset = 0;
}
}
Working/correct answer by Altocumulus:
You won't need an anonymous function to get the string value.
Just use kwdAssbly.opt = d["-importance"];

How to take a specific info from a string in json format?

I've got this AS3 code :
var myString:String;
var request:URLRequest = new URLRequest("http://www.swellmap.co.nz/ajr.php?r=plugin&a=Surfing&s=Anse%20Vata&country=nz&swellmap=1&country=ncd&swellmap=1&_=1460963404274");
var loader:URLLoader = new URLLoader();
loader.load(request);
loader.addEventListener(Event.COMPLETE,weatherLoaded);
function weatherLoaded(e:Event):void{
myString = e.target.data;
trace(myString); //output is {"tides":"High: 05:40 am (1.32 m); Low: 12:10 pm (0.57 m); High: 06:10 pm (1.19 m); ","seatemp":"27°C","forecastdate":"17h","rating":"<img src='http:\/\/www.swellmap.co.nz\/style\/img\/weathericons\/1r.png' alt='Poor conditions' title='Poor conditions' \/>","rating_class":"<span class='badge badge-important' alt='Poor conditions' title='Poor conditions'>1<\/span>","summary":"<img class='wx-summary' src='http:\/\/www.swellmap.co.nz\/style\/img\/weathericons\/suncloud.png' title='Sunny with some cloud' \/>","title":"Anse Vata","smaplink":"http:\/\/www.swellmap.co.nz\/surfing\/new-caledonia\/anse-vata","vars":{"hs_sw":{"value":"0.4","title":"Swell","unit":"m"},"hs":{"value":"0.6","title":"Wave","unit":"m"},"wface":{"value":"0.8","title":"Set face","unit":"m"},"tp":{"value":"13","title":"Period","unit":"s"},"dpm":{"value":"S","title":"Swell dir","unit":"°"},"windma":{"value":"E 12","title":"Wind","unit":"kts"},"gstma":{"value":"16","title":"Gusts","unit":"kts"}}}
var myData : Object = JSON.parse(e.target.data);
for each (var s:* in myData) { trace("key:",s,"value:",myData[s]); }
trace(myData); }
My String is containing lots of infos.
How could I take specifics informations ?
Exemple:
If I want to take the swell (in this example, the swell is : "0.4 m # 13 s"). How could I do that? (the purpose is to displays it in a text box like that :
function(searchTheSwell){
var swell_AnseVata;
swell_AnseVata =.... ?
info_txt.text = swell_AnseVata;
}
Thx
Just set a breakpoint after you parse the data and examine the myData in the debugger - you will see the object structure. Or just trace the whole object structure out:
import mx.utils.ObjectUtil;
trace(ObjectUtil.toString(myData));
In your case you'd need to put your string together out of the vars in your object:
var hs_sw:Object = myData.vars.hs_sw;
var tp:Object = myData.vars.tp;
trace(hs_sw.value + " " + hs_sw.unit + " # " + tp.value + " " + tp.unit);

How to get dynamic object properties

I'm receiving a Json object from a request and I would like to Iterate over its properties and do something like:
if property is equals to "EN" than get it's value.
The solutions That I saw in the web are all related with GetProperties/GetProperty methods but I tried both and none of them worked.
This should be something "simple" but I think that I'm missing something here.
//Deserializing the object
ExpandoObject deserializedContent = JsonConvert.DeserializeObject<ExpandoObject>(obj.ToString(), new ExpandoObjectConverter());
dynamic deserializedDynamicContent = deserializedContent;
//Tries
var value = deserializedDynamicContent.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
var value = deserializedDynamicContent.GetType().GetProperty("ES").GetValue();
in both cases I get zero properties.
I can only get the values if I do the code below, but this will obly me to code if a new language is added.
deserializedDynamicContent.EN,
deserializedDynamicContent.ES or
deserializedDynamicContent.PT
What Am I doing wrong here?
{
"EN":[{"Id":1,"Name":"One"},{"Id":2,"Name":"Two"},{"Id":3,"Name":"Tree"}],
"ES":[{"Id":1,"Name":"Uno"},{"Id":2,"Name":"Dos"},{"Id":3,"Name":"Tres"}],
"PT":[{"Id":1,"Name":"Um"},{"Id":2,"Name":"Dois"},{"Id":3,"Name":"Três"}]
}
I'm not sure exactly what you're trying to achieve, but since ExpandoObject implements IDictionary<string,object> you should be able to do something like this:
var expando = JsonConvert.DeserializeObject<ExpandoObject>(yourJson);
var dict = (IDictionary<string, object>)expando;
// look for a particular key...
object value;
if (dict.TryGetValue("EN", out value))
{
Console.WriteLine("Key exists!");
var list = (List<dynamic>)value;
Console.WriteLine(string.Join(",", list.Select(x => "{" + x.Id + "," + x.Name + "}")));
}
// or enumerate the entire dictionary...
foreach (var kvp in dict)
{
var list = (List<dynamic>)kvp.Value;
Console.WriteLine(
kvp.Key + ":" + string.Join(",", list.Select(x => "{" + x.Id + "," + x.Name + "}")));
}

civic address in wp8

I am working on a wp8 project and need to find the location . I've used windows.device.geoloaction name space to find the lattitude and longitude now I need to find the address(country state and zip). I found this example but I am confused how to pass the coordinates that I obtained . Here is my code.
public async void FindTADeviceLocation()
{
////Declare Geolocator object
Geolocator geolocator = new Geolocator();
// Set user's accuracy
geolocator.DesiredAccuracy = PositionAccuracy.High;
//get the position of the user.
try
{
//The await guarantee the calls to be returned on the thread from which they were called
Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromMinutes(1),
timeout: TimeSpan.FromSeconds(10)
);
var geoQ = new ReverseGeocodeQuery();
geoQ.QueryCompleted += geoQ_QueryCompleted;
if (geoQ.IsBusy == true)
{
geoQ.CancelAsync();
}
// Set the geo coordinate for the query
geoQ.GeoCoordinate = geoposition.Coordinate;
geoQ.QueryAsync();
}
catch (Exception ex)
{
if ((uint)ex.HResult == 0x80004004)
{
MessageBox.Show("position is unknown");
}
}
}
void geoQ_QueryCompleted(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Result.Count() > 0)
{
string showString = e.Result[0].Information.Name;
showString = showString + "\nAddress: ";
showString = showString + "\n" + e.Result[0].Information.Address.PostalCode + " " + e.Result[0].Information.Address.City;
showString = showString + "\n" + e.Result[0].Information.Address.Country + " " + e.Result[0].Information.Address.CountryCode;
showString = showString + "\nDescription: ";
showString = showString + "\n" + e.Result[0].Information.Description.ToString();
MessageBox.Show(showString);
}
}
I know the problem is in the line geoQ.GeoCoordinate = geoposition.Coordinate;
But how can I pass the coordinates to geoQ.GeoCoordinate?
Thanks in adwance
This is done. The geocordinate takes arguments of the type double. so all we've to do is to convert the cordiantes into double and pass it.
var currentLocationLatitude = Convert.ToDouble(geoposition.Coordinate.Latitude.ToString("0.0000000000000"));
var currentLocationLongitude = Convert.ToDouble(geoposition.Coordinate.Longitude.ToString("0.0000000000000"));
var geoQ = new ReverseGeocodeQuery();
geoQ.QueryCompleted += geoQ_QueryCompleted;
if (geoQ.IsBusy == true)
{
geoQ.CancelAsync();
}
// Set the geo coordinate for the query
geoQ.GeoCoordinate = new GeoCoordinate(currentLocationLatitude, currentLocationLongitude);
geoQ.QueryAsync();
Thanks

Error: Expecting rightparen before colon

I'm working on an actionscript and I can'f seem to find the problem on this code block.
Please help.
Partial code:
private function constructCommunicatorAndConnect() : void
{
var cHost:* = ExternalData.splashServerHosts[this.m_nSplashServerIndex];
var nPort:* = int(ExternalData.splashServerPorts[this.m_nSplashServerIndex]);
var cSocket:* = new ReconnectingStringSocket(cHost, nPort, new RandomXORScrambler(68, 47));
cSocket.addEventListener(ReconnectingStringSocket.RECONNECTING, function (event:Event) : void
{
MultiplayerContainer.addTextToConsole("Lost splash connection, trying to reconnect...");
return;
}// end function
);
cSocket.addEventListener(ReconnectingStringSocket.RECONNECTING_SUCCESSFUL, function (event:Event) : void
{
MultiplayerContainer.addTextToConsole("Splash connection succesfully reestablished");
return;
}// end function
);
this.m_cSplashCommunicator = new SplashCommunicator(cSocket, MultiplayerContainer.player.com.miniclip.multiplayer.container.player:ILocalPlayer::sessionID, MultiplayerContainer.player.userID, ExternalData.gameID, this);
this.m_cSplashCommunicator.connect();
MultiplayerContainer.addTextToConsole("Connecting to splash server #" + this.m_nSplashServerIndex + " (" + cHost + ":" + nPort + ") with session \"" + MultiplayerContainer.player.sessionID + "\"");
dispatchEvent(new Event(COMMUNICATOR_CONSTRUCTED));
return;
}// end function
The error is at
this.m_cSplashCommunicator = new SplashCommunicator(cSocket, MultiplayerContainer.player.com.miniclip.multiplayer.container.player:ILocalPlayer::sessionID, MultiplayerContainer.player.userID, ExternalData.gameID, this);
Some relevant functions:
public function SplashCommunicator(param1:StringSocket_i, param2:String, param3:String, param4:String, param5:ISplashListener)
{
super(param1, param5);
param1.setSocketEventHandler(this.handleSocketEvent);
param1.addEventListener(Event.CONNECT, this.socketConnected);
this.m_cSessionID = param2 != null ? (param2) : ("");
this.m_cUserID = param3 != null ? (param3) : ("");
this.m_cGameID = param4;
this.m_cListener = param5;
return;
}// end function
heres your problem, Check your code
.player:ILocalPlayer::sessionID, Multiplaye // check these ::
whatever = new whatever(somemorestuff,hi{in here is where you have ::::::::::},outside);
See the above pattern the colon is inside the parentheses (MC{x:200,y:200});
Im hoping your following me