Closure Compiler issues warning with namespaced enum - google-closure-compiler

The following sample code generates a compiler warning on advanced optimization: "JSC_UNSAFE_NAMESPACE: incomplete alias created for namespace NS". If I remove the #enum comment, it doesn't give the warning.
var NS = {};
/**
* #enum {string}
*/
NS.type = {
FOO : 'bar'
};
NS.foobar = function(){ alert(NS.type.FOO); };
window['NS'] = NS;
window['NS']['foobar'] = NS.foobar;
Exporting only the function and not the namespace also seems to work:
window['NS_foobar'] = NS.foobar;
What am I doing wrong? Is there a way around this? I'd rather not include the Closure library if possible.

The compiler expects to collapse the enum value into single variables:
NS.type.FOO becomes NS$type$FOO. The "NS" that you exported would not contain what you expect.
I suspect you want something like this:
window['NS'] = {}; // an external namespace object.
window['NS']['foobar'] = NS.foobar; // add 'foobar' to the external namespace.

Related

How to rewrite a c++ function from an R package

I am using the compute_iterative_ratings function from the R package "comperank":
https://github.com/cran/comperank/blob/master/src/RcppExports.cpp
I would like to modify this function so that it accepts one more argument (an integer variable called amateur), so that the function becomes:
compute_iterative_ratings(rate_fun, player1_id, score1, player2_id, score2, initial_ratings, amateur)
I'd like to just copy the cpp file, modify it to accept the extra argument, and then save it into my working directory so that I can then call sourceCpp for when I need it. This is all new territory for me so I'm not sure what I'm supposed to edit. I also do not know what the final 2 blocks of code mean.
static const R_CallMethodDef CallEntries[] = {
{"_comperank_compute_iterative_ratings", (DL_FUNC) &_comperank_compute_iterative_ratings, 6},
{NULL, NULL, 0}
};
RcppExport void R_init_comperank(DllInfo *dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
The code you are looking at is autogenerated. This code will be updated when you adjust the corresponding C++ function and call Rcpp::compileAttributes within the package. So instead of RcppExports.cpp you should edit iterative-ratings.cpp. This is also true when using Rcpp::sourceCpp.
The only part there you'll need to change is the number 6 to 7, as it informs R about the number of parameters in the function _comperank_compute_iterative_ratings.
static const R_CallMethodDef CallEntries[] = {
{"_comperank_compute_iterative_ratings", (DL_FUNC) &_comperank_compute_iterative_ratings, 7},
{NULL, NULL, 0}
};
For more information see
https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Registering-native-routines

Closure Compiler warning - HTMLCanvasElement and Element types mismatch

I am not sure how to clear this warning:
WARNING - actual parameter 1 of
CanvasRenderingContext2D.prototype.drawImage does not match formal parameter
found : Element
required: (HTMLCanvasElement|HTMLImageElement|HTMLVideoElement|null)
ctx.drawImage( poolCanvas, rect.x, rect.y );
Here is the relevant code:
var /** #type {HTMLCanvasElement|Element} */ poolCanvas = document.createElement('canvas');
var /** #type {CanvasRenderingContext2D} */ ctx;
...
ctx.drawImage( poolCanvas, rect.x, rect.y );
I have tried a various combination of type declarations and I can't get rid of this warning.
What am I doing wrong here?
You need to type cast the call to document.createElement:
var poolCanvas =
/** #type {!HTMLCanvasElement} */ (document.createElement('canvas'));
Note the extra parens - they are required for a type cast

Flex 3: Using array item value as an objects name

If I have a list of items in an array that represent the names of modules:
var phaseNames:Array = new Array("directorsPrep", "checkIO", "pickupPhoto", "pickupPhoto", "syncing", "dailies", "pictureEdit", "soundEdit", "soundMix", "colorCorrection", "finishing");
and I want to go through each one of these and call a function within each instance of each module, how would I go about doing so. So far, I have the following:
private function changeStartViewDate(numDays:Number):void
{
startViewDate = rightDate(startViewDate.getMonth(), startViewDate.getDate() + numDays, startViewDate.getFullYear());
getDateInfo();
determineCalendarWeek();
var phaseNames:Array = new Array("directorsPrep", "checkIO", "pickupPhoto", "pickupPhoto", "syncing", "dailies", "pictureEdit", "soundEdit", "soundMix", "colorCorrection", "finishing");
for (var i:int = 0; i < wholeProject.length; i++)
{
wholeProject[i].moveProject(Number((1-2) * numDays));
}
for (i = 0; i < phaseNames.length; i++)
{
for (var j:int = 0; j < [phaseNames[i]].length; j++)
{
[phaseNames[i]].movePhase(Number((-1) * numDays));
}
}
}
But when I try to save it, I get the following error:
1084: Syntax Error: expecting identifier before dot.
It's telling me the error is on the following line:
[phaseNames[i]].movePhase(Number((-1) * numDays));
I tried doing something like the following, but it didn't work:
[phaseNames[i].movePhase(Number((-1) * numDays))];
The above attempt of trying to figure this out gave me the following error
1064: Invalid metadata.
Any help would be appreciated.
I am going to assume that:
Each value of your phaseNames array references an actual instance of some other class [and not the name of the class]
The instance defined in the phaseNames array is a child of the current class.
You should be able to do something like this:
var childName = phaseNames[0];
var myChild : myObjectType = this[childName];
// then call function
myChild.doStuff();
This approach is not dissimilar to what you have; I'm just doing it in more lines. I'm also adding the this keyword to access the child.
I bet if you tried this, directly, it would work:
this[phaseNames[i]].movePhase(Number((-1) * numDays));
I have to wonder why you haven't created an array of all the instances instead of an array of all the variables names that point to the instances.

Dynamic properties in Scala

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.

AS 3.0 Duplicate Variable Definition

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.

Resources