Adobe After Effects: Keep "Expression-Relations" when duplicating multiple layers - duplicates

just wanted to ask, whether there is a way to keep the relations of expressions going when duplicating layers.
E.g. I have two layers, "LayerA" and "LayerB". Now I have an expression going on in "LayerB" saying, that its position always equals the position of "LayerA".
Now when I duplicate those two and get "LayerA 2" and "LayerB 2" I want the expression in "LayerB 2" to reference to "LayerA 2"'s position rather than "LayerA"'s position!
While it is no problem to simply change the expression when there is only one of them, it gets quite hard when you have multiple expressions going on ...

You might end up wanting to organize your comp differently, but, given your example (and exactly those name lengths), this position expression will work to find the appropriate 'target layer':
//base name to work from:
baseName = "Layer";
//length of that:
nameLen = baseName.length;
//this layer's name:
myName = thisLayer.name;
if (myName.length == nameLen) {
//if they are the same, then it is the original
// (non-duplicated) version
thisComp.layer("LayerA").transform.position;
} else {
//get tail string, the space and number:
tailStr = myName.substring(nameLen+1, myName.length);
//build new target layer name with "A":
targetName = myName.substring(0, (nameLen)) + "A" + tailStr
//new line pointing to target layer:
thisComp.layer(targetName).transform.position;
}

Related

Extracting color from complex function: " Cannot modify global variable 'cColor' in function."

I'd like to extract the "col" color value from this function to be used to paint plots or candle colors. But everything I try creates one error or another. I checked the Script Reference. Shouldn't there be some way to "return" a value, as is usually the case with most functions?
lset(l,x1,y1,x2,y2,col)=>
line.set_xy1(l,x1,y1)
line.set_xy2(l,x2,y2)
line.set_width(l,5)
line.set_style(l, line.style_solid)
line.set_color(l,y2 > y1 ? #ff1100 : #39ff14) //red : green
temp = line.get_price(l,bar_index) // another value to extract
The documentation is showing it like this:
line.new(x1, y1, x2, y2, xloc, extend, color, style, width) → series line
So in your code it's looking differently and also the "new" is missing.
Scrolling a bit up on the linked page shows that there exist indeed methods to retrieve some properties of the line object:
Lines are managed using built-in functions in the line namespace. They include:
line.new() to create them.
line.set_*() functions to modify the properties of an line.
line.get_*() functions to read the properties of an existing line.
line.copy() to clone them.
line.delete() to delete them.
The line.all array which always contains the IDs of all
the visible lines on the chart. The array’s size will depend on
the maximum line count for your script and how many of those you
have drawn. aray.size(line.all) will return the array’s size.
The most simple usage is to instantiate a line object with the correct values directly, like shown here:
//#version=5
indicator("Price path projection", "PPP", true, max_lines_count = 100)
qtyOfLinesInput = input.int(10, minval = 1)
y2Increment = (close - open) / qtyOfLinesInput
// Starting point of the fan in y.
lineY1 = math.avg(close[1], open[1])
// Loop creating the fan of lines on each bar.
for i = 0 to qtyOfLinesInput
// End point in y if line stopped at current bar.
lineY2 = open + (y2Increment * i)
// Extrapolate necessary y position to the next bar because we extend lines one bar in the future.
lineY2 := lineY2 + (lineY2 - lineY1)
lineColor = lineY2 > lineY1 ? color.lime : color.fuchsia
line.new(bar_index - 1, lineY1, bar_index + 1, lineY2, color = lineColor)
Getting the line color from outside is difficult or impossible though as there never exists a method to retrieve it while for other properties those methods exist.
So the most simple way is to create the same funcionality, to get the color that exists inside the line-object, outside too, or only outside.
currentLineColor = y2 > y1 ? #ff1100 : #39ff14
You could try to extend the line-object somehow like this:
line.prototype.get_color = function() {
return this.color;
};
console.log(line.get_color())
I'm not sure if the approach with the prototype is working but it's worth it to try if you need it.

Search Array of Strings with Non-sensitivity and Non-exact Match

Notice: I have made a few changes to the original question as my problem was not with commas within string.
I have a function I've been working on to exclude a cell value from a new array that contains a string I am searching for. I am doing this in order to put together a list for .setHiddenValues, since .setVisibleValues is not supported/implemented yet.
Here are my requirements for the sake of clarity:
Currently working:
Able to handle numbers as well as strings
Can search for lowercase and uppercase. visibleValueStr is user inputted so it can't be so sensitive.
colValueArr may have strings with commas within.
Still working on:
visibleValueStr can be a single value or array.
Case sensitivity("apple" to match "Apple")
Not exact matches("apple" to match "apple and banana")
Here is the function I currently have with the above met/unmet conditions:
function getHiddenValueArray(colValueArr,visibleValueArr){
var flatUniqArr = colValueArr.map(function(e){return e[0].toString();})
.filter(function(e,i,a){
return (a.indexOf(e.toString())==i && visibleValueArr.indexOf(e.toString()) == -1);
})
return flatUniqArr;
}
Please let me know what other info I need. I will update this question as I continue to do my research in the meanwhile.
Clarification from comments:
User inputs input(s) on HTML form and the variable is passed on as visibleValueArr.
When using Logger.log(visibleValueArr).
[apple, banana]
When using Logger.log(colValueArr).
[[Apple],[apple][apple][apple and banana],[apple],[banana, and apple],
[apple, and banana],[orange],[orange, and banana],[kiwi],[kiwi, and orange],
[strawberry]]
So when I use:
SpreadsheetApp.newFilterCriteria().setHiddenValues(newArray).build();
newArray should be the hidden values. In this case it should be:
orange
kiwi
kiwi, and orange
strawberry
Basically anything that does not contain what visibleValueArr is.
Instead, it returns all values back, hiding them all.
When I use [Apple, Banana] the "Apple" and "Banana" values are left out of newArray as they should be, but "Apple and Banana" and "Apple, and Banana" are not"
In addition, I would also like to understand what the e,i,a in function(e,i,a) represent. I'm trying to apply .toLowerCase() in different places to see if that resolves part of my issue but I'm not sure where to do it.
Issues:
Case sensitivity("apple" to match "Apple")
Not exact matches("apple" to match "apple and banana")
Solution:
Use regex-search with case insensitivity
Modified Script:
function getHiddenValueArray(colValueArr,visibleValueArr){
/*colValueArr = [["Apple"],["apple"],["orange"],["Apple, and Banana"]];
visibleValueArr = ['apple','banana'];*/
var flatUniqArr = colValueArr.map(function(e){return e[0].toString();})
.filter(function(e,i,a){
return (a.indexOf(e)==i && !(visibleValueArr.some(function(f){
return e.search(new RegExp(f,'i'))+1;
})));
});
//Logger.log(flatUniqArr); will log orange
return flatUniqArr;
}
References:
String#search
Array#some
Array#filter
Array#map

getting a random element from an array of movieclips(or labels in a timeline) in Flash CC . Actionscript 3

I am making a pretty neat quiz-game in flashCC right now and I definitely need your help.
My skills are more on the design then the programming side. So to many of you this might seem a baby question (and asked many times before) but from all the answers I saw so far, I couldn't get any results for my project.
So here is the thing :
I need the EXACT script for creating an array (with movieclips inside? or instance names of mcs? How does this even work?)
and a method, to pick a random element of this array without repeats until the "game is over".
Paul
The easiest way to pick a random element from an array without repeating is to first sort the array with a "random" function, then pop or shift items out of it until the array is empty.
Let's say you have an array of items which can be filled with either instances or instance names, you've chosen instance names: :
var FirstArray:Array = ["blau", "orange", "green"];
Now, you'll need a random sort function:
// you do not need to modify this function in any way.
// the Array.sort method accepts a function that takes in 2 objects and returns an int
// this function has been written to comply with that
function randomSort(a:Object, b:Object):int
{
return Math.random() > .5 ? -1 : 1;
}
The way a sort function normally works is it compares two objects and returns -1 if the first item precedes the second item, 1 if the opposite is true, and 0 if they are the same.
So what we're doing in the function above is returning -1 or 1 randomly. This should get the array all jumbled up when you call:
FirstArray.sort(randomSort);
Now that the array is randomly sorted, you can begin pulling items from it like so:
if(FirstArray.length) // make sure there's at least one item in there
{
// since you are using instance names, you'll need to use that to grab a reference to the actual instance:
var currentQuizItem:MovieClip = this[FirstArray.pop()];
// if you had filled your array with the actual instances instead, you would just be assigning FirstArray.pop() to currentQuizItem
// every time you call pop on an array, you're removing the last item
// this will ensure that you won't repeat any items
// do what you need to do with your MovieClip here
}
else
{
// if there aren't any items left, the game is over
}
When strung together, the above code should be enough to get you up and running.
You could try something like:
var array:Array = [1, 2, 3, 4, 5];
var shuffledArray:Array = [];
while (array.length > 0)
{
shuffledArray.push(array.splice(Math.round(Math.random() * (array.length - 1)), 1)[0]);
}
trace('shuffledArray: ', shuffledArray, '\nrandom item: ', shuffledArray[0]);

How to merge the contents of two variables

I have many string variables that start with "Question" and then end with a number. ("Question1")
Each variable has a question in it ("How many times does it say E?")
There is an editable textbox on the stage that the user types in which question number he want to be displayed in a different textbox. ("1")
When the user clicks a button, I want that the text of Question1 should be displayed in the textbox.
My code looks like this:
var Question1:String = "How many times does it say E?" ;
var Question2:String = "How many times does it say B?" ;
var Question3:String = "How many times does it say A?" ;
myButton.addEventListener(MouseEvent.CLICK, displayQuestion);
function displayQuestion(event:MouseEvent):void
{
var QuestionNumber:Number = Number(userInputQuestionNumber.text);
textBoxDisplayQuestion.text= Question(QuestionNumber);
}
How can I get the textBoxDisplayQuestion to display the actual text of the Question??
(the code i have now obviously is not working!!)
But this example doesnt seem to work: I created a class called Question and here is the code:
import Question;
var QuNoLoad:Number;
var Qu1:Question = new Question(1,"how","yes","no","maybe","so","AnsB","AnsA");
trace(Qu1.QuNo, Qu1.Qu, Qu1.AnsA,Qu1.AnsB, Qu1.AnsC, Qu1.AnsD, Qu1.CorAns, Qu1.FaCorAns);
//the following is the code for the button
loadQu.addEventListener(MouseEvent.CLICK, loadQuClick);
function loadQuClick(event:MouseEvent):void
{
//this sets the variable "QuNoLoad" with the contents of the "textBoxQuLoad"
//imagine the user inputed "1"
QuNoLoad=Number(textBoxQuLoad.text);
//this SHOULD!! display the contents of "Qu1.Qu"
textQu.text= this["Qu"+QuNoLoad.toString()+".Qu"]
//and when i traced this statment the value was "undefined"
}
Why???
You can reference a variable by name using square brackets [] operator, such as:
this["Question" + QuestionNumber.toString()]
You may use this operator to dynamically set and retrieve values for a property of an object.
Keeping the question number as an integer, your function would be:
var Question1:String = "How many times does it say E?" ;
var Question2:String = "How many times does it say B?" ;
var Question3:String = "How many times does it say A?" ;
function displayQuestion(event:MouseEvent):void
{
var QuestionNumber:uint = uint(userInputQuestionNumber.text);
textBoxDisplayQuestion.text = this["Question" + QuestionNumber.toString()];
}
This is a pretty fundamental concept in programming that will make a lot of things harder to do until you understand it well, and it's pretty hard to explain without starting with some groundwork:
What's happening here is easiest to talk about with plain old Object rather than classes, so lets start with a very simple example:
var question1:Object = new Object();
question1.number = 1;
Note that with Object you didn't have to say that number existed ahead of time, it gets created when you set it. Now, when you say either question1.number you get 1, obviously. What is happening, however is that first question1 gets the value you stored in the variable question1 (which is { number: 1 }), then the .number gets the value stored in the property number stored in that value: 1.
To save some typing, you can use a shorthand called "object literals":
var question1 = {
number: 1
};
Now lets try a more complex object:
var question1 = {
number: 1,
text: "How many times does it say A?",
answers: {
a: 1,
b: 2,
c: 3,
d: 4,
correct: "b"
}
};
Now question1 is an object that has 3 properties, one of which, answers, is an object with 5 properties: a, b, c, d, and correct. This could also be written as:
var question1 = new Object();
question1.number = 1;
question1.text = "How many times does it say A?";
question1.answers = new Object();
question1.answers.a = 1;
question1.answers.b = 2;
question1.answers.c = 3;
question1.answers.d = 4;
question1.answers.correct = "b";
It should be pretty clear why the literal syntax exists now!
This time, if you say question1.answers.correct you get "b": first question1 gets you the { number: 1,...} value, then the .answers gets the { a: 1, b: 2,...} value, then finally the .correct gets the "b" value.
You should also know that this is a special variable that has a particular meaning in ActionScript (and JavaScript, on which it is based): it broadly refers to the object in when the code you are writing is inside: for "global" code (not inside a function), var adds properties to this object: var number = 2; and this.number = 2 are this same here. (This is not true when you're in function, this behaves differently there, sometimes in very strange ways, so be careful!)
Now you might start seeing what's happening: when you use [], for example, question1["number"], rather than question1.number, you are passing the property name you want to get as a String value, which means you can change what property you get while you are running, rather than when you compile ("runtime" vs. "compiletime"), but it also lets you get properties with names you can't refer to with the . syntax!
var strange = {
"a strange name? That's OK!": 1
};
trace(strange["a strange name? That's OK!"]);
So when you write this["Qu" + QuNoLoad.toString() + ".QuNo"], you create a name like "Qu2.QuNo", for example, you are trying to get a property with that exact name, . included, which doesn't exist! What you were trying to do the equivalent of: Qu2.QuNo could be written as this["Qu" + QuNoLoad].QuNo.
I shouldn't leave this without saying, though, that for something like this, I would use arrays, which exist so that you can use a single name to store a list of values:
var questions:Array = [ // set questions to an array with multiple questions
new Question(...),
new Question(...),
...
];
for each (var question:Question in questions) { // Look at each question in the array
if (question.QuNo == textBoxQuLoad.text) { // If this is the right question
loadQuestion(question);
break; // Found it, stop looking at each question by "breaking out" of the for each
}
}
There's lots more you can do with arrays, so read up on them when you get time.

Randomly selecting an object property

I guess a step back is in order. My original question is at the bottom of this post for reference.
I am writing a word guessing game and wanted a way to:
1. Given a word length of 2 - 10 characters, randomly generate a valid english word to guess
2.given a 2 - 10 character guess, ensure that it is a valid english word.
I created a vector of 9 objects, one for each word length and dynamically created 172000
property/ value pairs using the words from a word list to name the properties and setting their value to true. The inner loop is:
for (i = 0; i < _WordCount[wordLength] - 2; i)
{
_WordsList[wordLength]["" + _WordsVector[wordLength][i++]] = true;
}
To validate a word , the following lookup returns true if valid:
function Validate(key:String):Boolean
{
return _WordsList[key.length - 2][key]
}
I transferred them from a vector to objects to take advantage of the hash take lookup of the properties. Haven't looked at how much memory this all takes but it's been a useful learning exercise.
I just wasn't sure how best to randomly choose a property from one of the objects. I was thinking of validating whatever method I chose by generating 1000 000 words and analyzing the statistics of the distribution.
So I suppose my question should really first be am I better off using some other approach such as keeping the lists in vectors and doing a search each time ?
Original question
Newbie first question:
I read a thread that said that traversal order in a for.. in is determined by a hash table and appears random.
I'm looking for a good way to randomly select a property in an object. Would the first element in a for .. in traversing the properties, or perhaps the random nth element in the iteration be truly random. I'd like to ensure that there is approximately an equal probability of accessing a given property. The Objects have between approximately 100 and 20000 properties. Other approaches ?
thanks.
Looking at the scenario you described in your edited question, I'd suggest using a Vector.<String> and your map object.
You can store all your keys in the vector and map them in the object, then you can select a random numeric key in the vector and use the result as a key in the map object.
To make it clear, take a look at this simple example:
var keys:Vector.<String> = new Vector.<String>();
var map:Object = { };
function add(key:String, value:*):void
{
keys.push(key);
map[key] = value;
}
function getRandom():*
{
var randomKey = keys[int(Math.random() * keys.length)];
return map[randomKey];
}
And you can use it like this:
add("a", "x");
add("b", "y");
add("c", "z");
var radomValue:* = getRandom();
Using Object instead of String
Instead of storing the strings you can store objects that have the string inside of them,
something like:
public class Word
{
public var value:String;
public var length:int;
public function Word(value:String)
{
this.value = value;
this.length = value.length;
}
}
Use this object as value instead of the string, but you need to change your map object to be a Dictionary:
var map:Dictionary = new Dictionary();
function add(key:Word, value:*):void
{
keys.push(key);
map[key] = value;
}
This way you won't duplicate every word (but will have a little class overhead).