Animate CC AS3 how to manage data when writing to a file - actionscript-3

I am building a program on Animate CC 2019 which needs to access a text file where it can read from and write to.
I want to store strings and numbers, from Input Texts, then write them in the file, in addition to the already existent contents.
I also need to be able to manage how the data is written in the file. So, for example, I want to have 2 arrays: Array1 stores names and Array2 stores numbers. So when the program writes to the file, it needs to write on each line the corresponding values of a specific index in the arrays. So if Array1(0) = name1 & Array2(0) = 52, in the file it should be written:
name1 52
If not exactly like this, a way which data can be written in a manageable way.
I am trying this on Windows 10/AIR.
My questions:
How can I manage how data are written in a file?
Which code should I use? I find info on two ways to approach this:
a. Code using “File” and “FileStream” which does NOT work! I get error messages: “Type was not found or was not a compile-time constant” for both, like the system does not recognize the commands. Are these commands still usable on the current version of Animate CC?
b. The code snipets/AIR code which does work, however, I cannot find a way to manage how data are written in the file, as explained above. Everytime something is written in the file, the previous data are overwritten.
Below the codesnipets code which works.
/* Click to Write to a Text File
Clicking on the specified object will prompt the user to select a location and file name and save a text string to it.
Instructions:
To set what data is saved to the file change "Text to save to file." to the data you wish to save.
*/
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
movieClip_1.addEventListener(MouseEvent.CLICK, fl_SaveFile);
var fl_FileDataToSave:String = "Text to save to file.";
var fl_SaveFileStream:FileStream = new FileStream(); // FileStream used to write to the file
var fl_SaveFileChooser:File = File.documentsDirectory; // Default to the documents directory
fl_SaveFileChooser.addEventListener(Event.SELECT, fl_WriteFileHandler);
// Opens a Save As dialog box for user to specify a file name
function fl_SaveFile(event:MouseEvent):void
{
fl_SaveFileChooser.browseForSave("Save As:");
}
// Write data in fl_FileDataToSave variable
function fl_WriteFileHandler(event:Event):void
{
fl_SaveFileChooser = event.target as File;
fl_SaveFileStream = new FileStream();
fl_SaveFileStream.openAsync(fl_SaveFileChooser, FileMode.WRITE);
fl_SaveFileStream.writeMultiByte(fl_FileDataToSave, File.systemCharset);
fl_SaveFileStream.close();
}

Related

Palantir foundry code workbook, export individual xmls from dataset

I have a dataset which have an xml column and i am trying to export individual xmls as files with filename being in another column using codeworkbook
I filtered the rows i want using below code
def prepare_input(xml_with_debug):
from pyspark.sql import functions as F
filter_column = "key"
filter_value = "test_key"
df_filtered = xml_with_debug.filter(filter_value == F.col(filter_column))
approx_number_of_rows = 1
sample_percent = float(approx_number_of_rows) / df_filtered.count()
df_sampled = df_filtered.sample(False, sample_percent, seed=0)
important_columns = ["key", "xml"]
return df_sampled.select([F.col(c).cast(F.StringType()).alias(c) for c in important_columns])
It works till here. Now for the last part i tried this in a python task, but was complaining about the parameters (i should have set it up wrongly). But even if it works it will be as a single file i think.
from transforms.api import transform, Input, Output
#transform(
output=Output("/path/to/python_csv"),
my_input=Input("/path/to/input")
)
def my_compute_function(output, my_input):
output.write_dataframe(my_input.dataframe().coalesce(1), output_format="csv", options={"header": "true"})
I am trying to set it up in GUI like below
My question i guess is, what will be the code in the last Python task (write_file) after the prepare input so that i extract individual xmls (And if possible zip them into single file for download)
You can access the output dataset filesystem and write files into it in whatever format you want.
The documentation for that can be found here: https://www.palantir.com/docs/foundry/code-workbook/transforms-unstructured/#writing-files
(If you want to do it from a code repository it's very similar https://www.palantir.com/docs/foundry/transforms-python/unstructured-files/#writing-files)
By doing that you can create multiple different files or you can create a single zip file and write it into a dataset.

Psychopy: how to avoid to store variables in the csv file?

When I run my PsychoPy experiment, PsychoPy saves a CSV file that contains my trials and the values of my variables.
Among these, there are some variables I would like to NOT be included. There are some variables which I decided to include in the CSV, but many others which automatically felt in it.
is there a way to manually force (from the code block) the exclusion of some variables in the CSV?
is there a way to decide the order of the saved columns/variables in the CSV?
It is not really important and I know I could just create myself an output file without using the one of PsychoPy, or I can easily clean it afterwards but I was just curious.
PsychoPy spits out all the variables it thinks you could need. If you want to drop some of them, that is a task for the analysis stage, and is easily done in any processing pipeline. Unless you are analysing data in a spreadsheet (which you really shouldn't), the number of columns in the output file shouldn't really be an issue. The philosophy is that you shouldn't back yourself into a corner by discarding data at the recording stage - what about the reviewer who asks about the influence of a variable that you didn't think was important?
If you are using the Builder interface, the saving of onset & offset times for each component is optional, and is controlled in the "data" tab of each component dialog.
The order of variables is also not under direct control of the user, but again, can be easily manipulated at the analysis stage.
As you note, you can of course write code to save custom output files of your own design.
there is a special block called session_variable_order: [var1, var2, var3] in experiment_config.yaml file, which you probably should be using; also, you should consider these methods:
from psychopy import data
data.ExperimentHandler.saveAsWideText(fileName = 'exp_handler.csv', delim='\t', sortColumns = False, encoding = 'utf-8')
data.TrialHandler.saveAsText(fileName = 'trial_handler.txt', delim=',', encoding = 'utf-8', dataOut = ('n', 'all_mean', 'all_raw'), summarised = False)
notice the sortColumns and dataOut params

Append string to a Flash AS3 shared object: For science

So I have a little flash app I made for an experiment where users interact with the app in a lab, and the lab logs the interactions.
The app currently traces a timestamp and a string when the user interacts, it's a useful little data log in the console:
trace(Object(root).my_date + ": User selected the cupcake.");
But I need to move away from using traces that show up in the debug console, because it won't work outside of the developer environment of Flash CS6.
I want to make a log, instead, in a SO ("Shared Object", the little locally saved Flash cookies.) Ya' know, one of these deals:
submit.addEventListener("mouseDown", sendData)
function sendData(evt:Event){
{
so = SharedObject.getLocal("experimentalflashcookieWOWCOOL")
so.data.Title = Title.text
so.data.Comments = Comments.text
so.data.Image = Image.text
so.flush()
}
I don't want to create any kind of architecture or server interaction, just append my timestamps and strings to an SO. Screw complexity! I intend to use all 100kb of the SO allocation with pride!
But I have absolutely no clue how to append data to the shared object. (Cough)
Any ideas how I could create a log file out of a shared object? I'll be logging about 200 lines per so it'd be awkward to generate new variable names for each line then save the variable after 4 hours of use. Appending to a single variable would be awesome.
You could just replace your so.data.Title line with this:
so.data.Title = (so.data.Title is String) ? so.data.Title + Title.text : Title.text; //check whether so.data.Title is a String, if it is append to it, if not, overwrite it/set it
Please consider not using capitalized first letter for instance names (as in Title). In Actionscript (and most C based languages) instance names / variables are usually written with lowercase first letter.

How can I reference a Flash file's own filename from actionscript?

In our pipeline, we ultimately publish HTML5 using Toolkit for CreateJS. However one of the steps to get us to that HTML5 includes publishing an SWF that outputs some Javascript code. I've mostly managed to automate this using JSFL. However, at present there is one line of AS3 that our artists have to find on the timeline and change manually, but it interrupts their workflow, and if they miss it or mess it up it is hard to catch, so I would like to automate it too:
Object(root).log.text += " root.skillAnime189 = factory();\n";
From the above, "skillAnime189.fla" is the name of the .fla file which contains this code. This is the case if the artist is working on Skill Animation #189, but if he is doing #304 or #6 or #1022 (no padding) the number changes accordingly, and he has to update that line accordingly.
So, I would like to change that line to something like:
var flaName:String = getThisFlashFileName().split(".")[0];
Object(root).log.text += " root." + flaName + " = factory();\n";
but I am at a loss as to how to access the name of the .fla file containing the code.
The common way to get the swf name is to parse stage.loaderInfo.url parameter:
var url:String = stage.loaderInfo.url;
url = url.split("?")[0]; //remove query string after "?"
var swfname:String = url.substring(url.lastIndexOf("/")+1);
trace(swfname);
output:
astest.swf
But this code gives swf but, rather than fla, so you need to maintain the same names for flas and published swfs (any case usually they are the same, so it shouldn't be the problem)

Actionscript 3 saving currentframe location to local hard drive?

I asked similar question sometime ago, but I am making new one to be much more specific with my question with some example!
I´ve found this code snippet/tutorial from googling, but I cant seem to figure out how to modify it for my needs:
// open a local shared object called "myStuff", if there is no such object - create a new one
var savedstuff:SharedObject = SharedObject.getLocal("myStuff");
// manage buttons
btnSave.addEventListener(MouseEvent.CLICK, SaveData);
btnLoad.addEventListener(MouseEvent.CLICK, LoadData);
function SaveData(MouseEvent){
savedstuff.data.username = nameField.text // changes var username in sharedobject
savedstuff.flush(); // saves data on hard drive
}
function LoadData(MouseEvent){
if(savedstuff.size>0){ // checks if there is something saved
nameField.text = savedstuff.data.username} // change field text to username variable
}
// if something was saved before, show it on start
if(savedstuff.size>0){
nameField.text = savedstuff.data.username}
So what I am trying to figure out how to do, is to save users current frame to local hard drive, as my flash progress is based on frame location. yeah, so how do I modify it so that it stores data of current frame? and how about current frame inside movieclip, if that is makes things different?
help MUUUCH appreciated! thanks!
In your example it looks like it is already saving something to the shared object:
savedstuff.data.username = nameField.text;
Just replace it with the movie clip frame value instead (and probably under a different property name other then "username").
Then on load, there is another line where it loads the data:
nameField.text = savedstuff.data.username;
It would be the same way, except replace "username" with whatever property name you choose. Then you may have to parse into an int again and use it to restore progress however way you have it set up.