How do I resolve the error of duplicate variable definitions? There has to be
separate namespaces and use for each definition, but I'm just not seeing it.
CODE
I didn't write this, but I've been trying to unpackage it and change the classes and seem to have broken it. I want to use this for time-scaling the playback of my movies.There's cool math in here for time-scaling.
//time-scaling script
import flash.display.*;
import flash.events.Event.*;
var _time_scale:Number = .25;
var _frames_elapsed:int = 0;
var _clip:MovieClip;
function Main():void {
_clip = new SomeClip;
addEventListener(Event.ENTER_FRAME, handleEnterFrame);
//integer??
function handleEnterFrame(e:Event):void {
_frames_elapsed ++;
}
// we multiply the "real" time with our timescale to get the scaled time
// we also need to make sure we give an integer as a parameter, so we use Math.round() to round the value off
_clip.gotoAndStop(Math.round(_clip.totalFrames * _frames_elapsed * _time_scale ));
}
var myTimer:Timer = new Timer(10);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener (e:TimerEvent):void{
ball1.rotationY += 5;/////////replace function///////////
}
myTimer.start();
ERRORS
**3596**
Warning: Duplicate variable definition.
**1151**
A conflict exists with definition _clip in namespace internal
NOTES
integers, non nested loop
It's because you are missing the ending "}" of the constructor, after this line:
addEventListener(Event.ENTER_FRAME, handleEnterFrame);
And the two following lines should probably be in your constructor, not just in the class declaration:
var myTimer:Timer = new Timer(10);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
If you are using the Timer and TimerEvent classes, you should import them:
import flash.utils.Timer;
import flash.events.TimerEvent;
Also, you don't need the .* at the end of the Event import.
Another "also". You should have access modifiers on your members ie. vars, and functions. So you should really say:
private var _clip:MovieClip;
It sounds to me like you need to look into the basics of AS3. Here is a really good starting point: http://www.actionscript.org/resources/articles/611/1/Getting-started-with-Actionscript-3/Page1.html
_clip is a reserved key word, you'll have to use something else.
Related
I begin with Java 8 and i have a migration project. I have read a lot of documentation and tutorial to use foreach or streams but i have a little last problem. I don't find the answer, just tutorial easy example.
I'm trying to transform this loop :
for ( Map.Entry<Neuron, Double> entry: this.entries.entrySet() ) {
value += entry.getKey().getExitValue() * entry.getValue();
}
This solution doesn't match and i know why (anonymous class => final/local var)
this.entries.forEach( (neuron, weight) -> {
value += neuron.getExitValue() * weight;
});
But only with a foreach i don't know how do this simple operation.
I think it's very easy but...
I have try with stream but i have similar problems.
Double sum = entries.entrySet()
.stream()
.forEach( entry-> { ? } );
Thanks you in advance.
As #Holger said in the comments above - in this case it is better to use mapToDoble. However there is still a way to do it using forEach loop. Please note that it is an ugly, dirty trick and it is just for demonstration purposes and it shouldn't be used in production code. As we know only final or effectively final variables can be used with lambda expressions, that's why value += is an illegal expression. Java-8 added a few new classes to java.util.concurrent.atomic one of them is DoubleAdder. You can use it with lambda:
DoubleAdder adder = new DoubleAdder();
stream.forEach(e -> adder.add(e.getKey().getExitValue() * e.getValue()));
System.out.println(adder.sum());
I don't see any cases when this should be used instead of mapToDouble
I introduced a list to stall the values and then do calculation with list.
final List<BigDecimal> valuesList = new ArrayList<>();
otherList.stream().forEach(val-> valuesList.add(map.get(val)));
final BigDecimal lastValue = valuesList.stream().filter(Objects::nonNull).reduce(BigDecimal.ZERO,BigDecimal::add);
I have an ArrayCollection(neList) of Objects(neObj). Each neObj has several fields like ipAddress,TID,etc.. In most cases neObj will be have values of both TID and ipAddress, rarely it will not have TID but have ipAddress... After adding Objects(neObj), I need to sort the ArrayCollection whose behaviour must be similar to array.sort() which has got strings only..(i.e nos first followed by strings in alphabetical order)
Things I have tried:
1)Using neList.source.sort() and neList.refresh.. but it did not work as neList.source has objects not straight forward things like strings
2)I think i cannot use sortOn function of ArrayCollection as it can be done on only 1 field
My Requirement:
Use Case1:- Objects in ArrayCollection have both TID and IP
neObj1.TID="RAPC" neObj1.ipAddress="121.1.1.2"; neObj2.TID="RAPA" neObj2.ipAddress="121.1.1.1"
O/P after sorting should be
neObj2 neObj1
Use Case2:- 1 of the objects does not have TID
neObj1.ipAddress="121.1.1.2"; neObj2.TID="RAPA" neObj2.ipAddress="121.1.1.1"
O/P after sorting should be
neObj1 neObj2
As hinted in the comments, you'll need to use a sort compareFunction to decide how the items will be sorted.
I do like to point out that sorting a combination of letters and numbers is tricky in the sense that there is no natural order by default. e.g. when sorting, 1, 2 and 11, the order will be 1, 11, 2. You can however solve this using the naturalCompare method in the AS3Commons Lang project.
Here's a code sample for your case. The sort is implemented as a subclass of the Sort class so that you can easily reuse it in other collections:
package {
import mx.collections.Sort;
import org.as3commons.lang.StringUtils;
public class NaturalSort extends Sort {
public function NaturalSort() {
compareFunction = function (a:Object, b:Object, fields:Array = null):int {
var stringA:String = (("TID" in a) ? a.TID : "AAAA") + a.ipAddress;
var stringB:String = (("TID" in b) ? b.TID : "AAAA") + b.ipAddress;
return StringUtils.naturalCompare(stringA, stringB);
};
}
}
}
To apply this:
var collection:ArrayCollection;
collection.sort = new NaturalSort();
collection.refresh();
I want to get a list of all Locales that have a different language, where the ISO3 code is used to identify the language of a Locale. I thought the following should work
class ISO3LangComparator implements Comparator<Locale> {
int compare(Locale locale1, Locale locale2) {
locale1.ISO3Language <=> locale2.ISO3Language
}
}
def allLocales = Locale.getAvailableLocales().toList()
def uniqueLocales = allLocales.unique {new ISO3LangComparator()}
// Test how many locales there are with iso3 code 'ara'
def arabicLocaleCount = uniqueLocales.findAll {it.ISO3Language == 'ara'}.size()
// This assertion fails
assert arabicLocaleCount <= 1
You are using the wrong syntax: you are using Collection.unique(Closure closure):
allLocales.unique {new ISO3LangComparator()}
You should use Collection.unique(Comparator comparator)
allLocales.unique (new ISO3LangComparator())
So simply use () instead of {}, and your problem is solved.
what Adam said.
or...
allLocales.unique{it.ISO3Language}
and you forget about the comparator
Does Scala support something like dynamic properties? Example:
val dog = new Dynamic // Dynamic does not define 'name' nor 'speak'.
dog.name = "Rex" // New property.
dog.speak = { "woof" } // New method.
val cat = new Dynamic
cat.name = "Fluffy"
cat.speak = { "meow" }
val rock = new Dynamic
rock.name = "Topaz"
// rock doesn't speak.
def test(val animal: Any) = {
animal.name + " is telling " + animal.speak()
}
test(dog) // "Rex is telling woof"
test(cat) // "Fluffy is telling meow"
test(rock) // "Topaz is telling null"
What is the closest thing from it we can get in Scala? If there's something like "addProperty" which allows using the added property like an ordinary field, it would be sufficient.
I'm not interested in structural type declarations ("type safe duck typing"). What I really need is to add new properties and methods at runtime, so that the object can be used by a method/code that expects the added elements to exist.
Scala 2.9 will have a specially handled Dynamic trait that may be what you are looking for.
This blog has a big about it: http://squirrelsewer.blogspot.com/2011/02/scalas-upcoming-dynamic-capabilities.html
I would guess that in the invokeDynamic method you will need to check for "name_=", "speak_=", "name" and "speak", and you could store values in a private map.
I can not think of a reason to really need to add/create methods/properties dynamically at run-time unless dynamic identifiers are also allowed -and/or- a magical binding to an external dynamic source (JRuby or JSON are two good examples).
Otherwise the example posted can be implemented entirely using the existing static typing in Scala via "anonymous" types and structural typing. Anyway, not saying that "dynamic" wouldn't be convenient (and as 0__ pointed out, is coming -- feel free to "go edge" ;-).
Consider:
val dog = new {
val name = "Rex"
def speak = { "woof" }
}
val cat = new {
val name = "Fluffy"
def speak = { "meow" }
}
// Rock not shown here -- because it doesn't speak it won't compile
// with the following unless it stubs in. In both cases it's an error:
// the issue is when/where the error occurs.
def test(animal: { val name: String; def speak: String }) = {
animal.name + " is telling " + animal.speak
}
// However, we can take in the more general type { val name: String } and try to
// invoke the possibly non-existent property, albeit in a hackish sort of way.
// Unfortunately pattern matching does not work with structural types AFAIK :(
val rock = new {
val name = "Topaz"
}
def test2(animal: { val name: String }) = {
animal.name + " is telling " + (try {
animal.asInstanceOf[{ def speak: String }).speak
} catch { case _ => "{very silently}" })
}
test(dog)
test(cat)
// test(rock) -- no! will not compile (a good thing)
test2(dog)
test2(cat)
test2(rock)
However, this method can quickly get cumbersome (to "add" a new attribute one would need to create a new type and copy over the current data into it) and is partially exploiting the simplicity of the example code. That is, it's not practically possible to create true "open" objects this way; in the case for "open" data a Map of sorts is likely a better/feasible approach in the current Scala (2.8) implementation.
Happy coding.
First off, as #pst pointed out, your example can be entirely implemented using static typing, it doesn't require dynamic typing.
Secondly, if you want to program in a dynamically typed language, program in a dynamically typed language.
That being said, you can actually do something like that in Scala. Here is a simplistic example:
class Dict[V](args: (String, V)*) extends Dynamic {
import scala.collection.mutable.Map
private val backingStore = Map[String, V](args:_*)
def typed[T] = throw new UnsupportedOperationException()
def applyDynamic(name: String)(args: Any*) = {
val k = if (name.endsWith("_=")) name.dropRight(2) else name
if (name.endsWith("_=")) backingStore(k) = args.first.asInstanceOf[V]
backingStore.get(k)
}
override def toString() = "Dict(" + backingStore.mkString(", ") + ")"
}
object Dict {
def apply[V](args: (String, V)*) = new Dict(args:_*)
}
val t1 = Dict[Any]()
t1.bar_=("quux")
val t2 = new Dict("foo" -> "bar", "baz" -> "quux")
val t3 = Dict("foo" -> "bar", "baz" -> "quux")
t1.bar // => Some(quux)
t2.baz // => Some(quux)
t3.baz // => Some(quux)
As you can see, you were pretty close, actually. Your main mistake was that Dynamic is a trait, not a class, so you can't instantiate it, you have to mix it in. And you obviously have to actually define what you want it to do, i.e. implement typed and applyDynamic.
If you want your example to work, there are a couple of complications. In particular, you need something like a type-safe heterogenous map as a backing store. Also, there are some syntactic considerations. For example, foo.bar = baz is only translated into foo.bar_=(baz) if foo.bar_= exists, which it doesn't, because foo is a Dynamic object.
In the big picture I want to create a frame based application in Bada that has a single UI control - a label. So far so good, but I want it to display a number of my choosing and decrement it repeatedly every X seconds. The threading is fine (I think), but I can't pass the label pointer as a class variable.
//MyTask.h
//...
result Construct(Label* pLabel, int seconds);
//...
Label* pLabel;
//MyTask.cpp
//...
result
MyTask::Construct(Label* pLabel, int seconds) {
result r = E_SUCCESS;
r = Thread::Construct(THREAD_TYPE_EVENT_DRIVEN);
AppLog("I'm in da constructor");
this->pLabel = pLabel;
this->seconds = seconds;
return r;
}
//...
bool
Threading::OnAppInitializing(AppRegistry& appRegistry)
{
// ...
Label* pLabel = new Label();
pLabel = static_cast<Label*>(pForm->GetControl(L"IDC_LABEL1"));
MyTask* task = new MyTask();
task->Construct(&pLabel); // HERE IS THE ERROR no matching for Label**
task->Start();
// ...
}
The problem is that I have tried every possible combination of *, &, and just plain pLabel, known in Combinatorics...
It is not extremely important that I get this (it is just for training) but I am dying to understand how to solve the problem.
Have you tried:
task->Construct(pLabel, 0);
And by that I want to point out that you are missing the second parameter for MyTask::Construct.
No, I haven't. I don't know of a second parameter. But this problem is solved. If I declare a variable Object* __pVar, then the constructor should be Init(Object* pVar), and if I want to initialize an instance variable I should write
Object* pVar = new Object();
MyClass* mClass = new MyClass();
mClass->Construct(pVar);