How can I clone an object? - actionscript-3

I'll need to clone some objects that have several types of instances. I've searched using a search engine and found some examples however I got error after I tested them.
Example: AS3 - Clone an object
import Line;
import OtherClass;
// Set lines
var obj1:Object={
environmentLine:new EnvironmentLine(),
lineX:100,
lineY:100
};
addChild(obj1.environmentLine);
var line:Line = new Line();
line.clone(obj1);
This gives me error: Line.as, Line 12, Column 3 1170: Function does not return a value.
Example: https://gist.github.com/PrimaryFeather/6914861
import com.gamua.flox.*;
import com.gamua.flox.utils.*;
import com.gamua.flox.events.*;
// Set lines
var obj1:Object={
environmentLine:new EnvironmentLine(),
lineX:100,
lineY:100
};
addChild(obj1.environmentLine);
var clone:Object = new cloneObject(obj1);
This code is giving me warning: TypeError: Error #1064: Cannot call method global/com.gamua.flox.utils::cloneObject() as constructor.
at Untitled_07_fla::MainTimeline/frame1()
Example: https://code.google.com/p/as3-commons/source/browse/trunk/as3-commons-lang/src/main/actionscript/org/as3commons/lang/ObjectUtils.as?r=1784
import org.as3commons.lang.ObjectUtils;
var num:int = 0;
// Set lines
var obj1:Object={
environmentLine:new EnvironmentLine(),
lineX:100,
lineY:100
};
var objectUtils:ObjectUtils = new ObjectUtils();
objectUtils.clone(obj1);
This gives me error: org\as3commons\lang\ObjectUtils.as, Line 211, Column 69 1046: Type was not found or was not a compile-time constant: IIterator.
Which one is the best for cloning an object and how can I fix the errors? Or is there a good library?

Boddy you should search more on Google. This is well discussed topic on many places:
https://gist.github.com/PrimaryFeather/6914861
http://www.tomauger.com/2009/flash-actionscript/actionscript-3-gotchas-copy-by-reference-deep-copy-and-read-only-objects
AS3 - Clone an object

Related

features at "wrong" position / flipped after EPSG:31287 -> EPSG:4326 transformation

I am currently trying to convert WFS2/GML3.2 data in EPSG:31287 to geojson using openlayers 6.15.1. For geojson I am trying to convert it to EPSG:4326/WGS84 using the following Typescript snippit:
import { WFS } from 'ol/format'
import { GeoJSON } from 'ol/format'
import { register } from 'ol/proj/proj4';
import * as proj4x from "proj4";
const proj4 = (proj4x as any).default;
// define EPSG:31287
proj4.defs('EPSG:31287', '+proj=lcc +lat_0=47.5 +lon_0=13.3333333333333 +lat_1=49 +lat_2=46 +x_0=400000 +y_0=400000 +ellps=bessel +towgs84=577.326,90.129,463.919,5.137,1.474,5.297,2.42319999999019 +units=m +no_defs +type=crs');
register(proj4);
// initialize WFS parser
const parser = new WFS({featureNS: 'http://mapserver.gis.umn.edu/mapserver', version: '2.0.0'
const data = '...some wfs 2.0.0 response containing GML3.2 data...';
// read the features
const wfsFeatures = parser.readFeatures(data);
// and immediatly write it as geojson, transforming it from EPSG:31287->EPSG:4326
const geoJsonString = new GeoJSON().writeFeatures(wfsFeatures, {
featureProjection: 'EPSG:31287',
dataProjection: 'EPSG:4326'
});
However it seems something is going wrong during the re-projection. Not only is the geometry at the wrong location, it also seems rotated/flipped:
[1]: https://i.stack.imgur.com/7GV1o.png
Interestingly, no matter which output-transformation I choose (when exporting to GML3.2 instead of GeoJSON, tried 4326 and 3857), the result always looks the same in QGIS. Only when specifying EPSG:31287 everywhere the result is correct (but of course in the wrong projection), most likely because openlayers detects it actually can avoid re-projection between equal projections.
Any idea what is going on here? Some pointers would really help.

cocos2d-js: Error: Invalid Native Object using setPhysicsBody

I'm trying to implement chipmunk physics engine for a cocos2d-js game. I'm getting the following error when i run it.
jsb: ERROR: File Y:\Documents\cocos\PrebuiltRuntimeJs\frameworks\js-bindings\bindings\auto\jsb_cocos2dx_auto.cpp: Line: 2143, Function: js_cocos2dx_Node_setPhysicsBody
Invalid Native Object
JS: D:/PROJECTS/cocos/Sliderule/runtime/win32/../../src/app.js:32:Error: Invalid Native Object
Here is the code i'm working with
`init:function () {
this._super();
var size = cc.winSize;
this.rect1 = new cc.Sprite(res.null_png,cc.rect(0,0, 200, 25));
this.rect1.setColor(cc.color(255,50,50,1));
this.rect1.setPosition(size.width/2, size.height-12.5);
this.rect1._setAnchorX(0.5);
this.rect1._setAnchorY(0.5);
this.rectbody1 = new cp.Body(1,cp.momentForBox(1,this.rect1.getContentSize().width, this.rect1.getContentSize().height));
this.rectbody1.p = cc.p(size.width/2, size.height-12.5);
this.space.addBody(this.rectbody1);
this.rectshape1 = new cp.BoxShape(this.rectbody1, this.rect1.getContentSize().width - 14, this.rect1.getContentSize().height);
this.space.addShape(this.rectshape1);
this.rect1.setPhysicsBody(this.rectbody1);
this.addChild(this.rect1,1);
`
I get the problem when setting the body to the sprite. Thanks in Advance.
This error message usually appears because of a missing retain(). You have to explicitly set sprites to be kept by the native system (Android, iOS) otherwise it's not valid after some time. And then, if you don't need it anymore: release it.
Try:
this.rect1.retain()
after you created the sprite. And then
this.rect1.release()
when you don't need it anymore.

as3 selecting a file dynamically

i need to select a video file and convert it to a byte array. the file i am trying to select has been recorded by the cameraUi interface. i can get the path to the file using
fileName = media.file.url;
readFileIntoByteArray(filePath, inBytes);
when i am passing it into the byte array i need to select directory first and then pass in the the rest of the path.
private function readFileIntoByteArray(fileName:String, data:ByteArray):void
{
var inFile:File = File.userDirectory;
inFile = inFile.resolvePath(fileName);
trace (inFile.url);
inStream.open(inFile , FileMode.READ);
inStream.readBytes(data);
}
this leads to duplication of the first part of the path.
i want to keep this dynamic as it will be run on different devices. i hard coded the file into the the variables section of flash debugger and it worked also i get an error if i leave out file.userDirectory
thanks in advance any help would be appreciated
You should always use File.applicationStorageDirectory instead of File.userDirectory. Due to security risk will vary to vary different device. File.applicationStorageDirectory will work any device.
Robust way of working with filepath
var firstPartPath:String = File.applicationStorageDirectory.nativePath;
var fullPath:String = File.applicationStorageDirectory.resolvePath("fileName.jpg").nativePath;
var expectedPath:String = fullPath.replace(firstPartPath,""); // "/fileName.jpg"
Here expectedPath value you should pass around your project instead of hard code value like c:\users\XXXX\ and save into database also use expectedPath value.
For latter access file just pass only expectedPath.
var inFile:File = File.applicationStorageDirectory.resolvePath(expectedPath);
Needn't worry about forward and backword slashes. File resolvePath() take care for you.
private function readFileIntoByteArray(fileName:String, data:ByteArray):void
{
var inFile:File = File.applicationStorageDirectory.resolvePath(fileName);
trace (inFile.url);
trace (inFile.nativePath);
trace (inFile.exists); //if file present true else false.
inStream.open(inFile , FileMode.READ);
inStream.readBytes(data);
}

JSON.parse(dt) doesn't work at all, give all the errors it can imagine

I have this code at server side (nodejs):
socket.on('data', function(dt){
var rdata = dt;
var msg = JSON.parse(rdata);
broadcast(msg);
});
Also I tried this way: var msg = JSON.parse(dt);
dt gets either:
{"chat":"hey","nickname":"nick_name"} OR
'{"chat":"hey","nickname":"nick_name"}'
Also I have this at the client side (AS3), tried both:
var msg = JSON.stringify({nickname: nname.text, chat: input_txt.text}); OR
var msg = "'" + JSON.stringify({nickname: nname.text, chat: input_txt.text}) + "'";
That is what console gives:
undefined:1
{"chat":"hey","nickname":"nick_name"}
^
SyntaxError: Unexpected token
DEBUG: Program node app exited with code 8
Also in some other situations, it gives all kinds of messages.
Just have no idea what is going on.
BTW, also tried JSONStream, still doesn't work.
What kind of socket exactly are you using? If you are using a websocket you might have already received an object as a response (I think most frameworks do so). If you are using plain net.socket you might be receiving a buffer or the data in chunks and not all at once. This seems like an appropriate fix for that situation:
var buffer;
socket.setEncoding('utf8');
socket.on('data', function(data) {
buffer += data;
});
socket.on('end', function() {
var object = JSON.parse(buffer);
});
Unexpected token at the end of data string, is some ghost symbol that is not a white space. trim() doesn't work, so to substring the last symbor works. This is AS3 symbol, so we have to keep it. First you save this symbol in the new variable. the you erase this symbol from the line. After that you can parse the string. work with it.
undefined:1
{"chat":"hey","nickname":"nick_name"}
^
SyntaxError: Unexpected token
DEBUG: Program node app exited with code 8
When you finish working with it, stringify the object, then add ghost symbol to the end and send over the socket. Without this symbol AS3 will not parse the data.
I don't know why is that, but that works for me.

Outputting an uint / Number value as a String in ActionScript3

Let me preface this by stating that I am not terribly familiar with ActionScript, so forgive any seemingly obvious things that I may be missing.
I current have a very simple function with an AS3 application that will output a file when a button is clicked using a FileReference object as seen below :
//Example download event
public function download(event:MouseEvent):void
{
//Build a simple file to store the current file
var outputFile:FileReference = new FileReference();
//Perform a function to build a .wav file from the existing file
//this returns a ByteArray (buffer)
downloadBuffer = PrepareAudioFile();
//Attempt to build the filename (using the length of bytes as the file name)
var fileName:String = downloadBuffer.length.toString() + ".wav";
//Save the file
audioFile.save(downloadBuffer, fileName);
}
There appears to be an error occurring somewhere within here that is resulting in the File not being outputted at all when I attempt to concatenate the file name as seen above. However, if I replace the fileName variable with a hard-coded option similar to the following, it works just fine :
audioFile.save(downloadBuffer, "Audio.wav");
Ideally, I would love to derive the duration of the file based on the length of the byteArray using the following :
//Get the duration (in seconds) as it is an audio file encoded in 44.1k
var durationInSeconds:Number = downloadBuffer.length / 44100;
//Grab the minutes and seconds
var m:Number = Math.floor(durationInSeconds / 60);
var s:Number = Math.floor(durationInSeconds % 60);
//Create the file name using those values
audioFile.save(downloadBuffer, m.toString() + "_" + s.toString() + ".wav");
Any ideas would be greatly appreciated.
Where is the problem other than missing the parentheses in m.toString()?
Aren't you missing a .lenght before the division of downloadBuffer as well?
I was finally able to come up with a viable solution that required explicit typing of all of the variables (including using a separate variable for the .toString() operations) as seen below :
public function download(event:MouseEvent):void
{
//Build a simple file to store the current file
var outputFile:FileReference = new FileReference();
//Perform a function to build a .wav file from the existing file
//this returns a ByteArray (buffer)
downloadBuffer = PrepareAudioFile();
//When accessing the actual length, this needed to be performed separately (and strongly typed)
var bufferLength:uint = downloadBuffer.length;
//The string process also needed to be stored in a separate variable
var stringLength:String = bufferLength.toString();
//Use the variables to properly concatenate a file name
var fileName:String = dstringLength + ".wav";
//Save the file
audioFile.save(downloadBuffer, fileName);
}
It's bizarre that these had to explicitly be stored within separate values and couldn't simply be used in-line as demonstrated in the other examples.