Adding Elements to Arrays in Grails - arrays

I am new to Grails and I tried to work with an Array. I can't believe that I don't get it working, but its really like this. I researched now for an hour, but I'm somehow too stupid! ;)
I've got this class:
package com.test
class SimuCacheService {
static transactional = false
def questionList = []
def getQuestionList() {
return questionList
}
}
From antoher class I want to access the questionList and for example simply add an element
package com.test
class SimulatorController {
def startSimu = {
SimuCacheService cacheService = new SimuCacheService();
def questionList = cacheService.getQuestionList();
params.eins.each{i->
System.out.println(i);
**questionList.add(i);**
}
System.out.println(questionList[0]);
System.out.println(questionList[1]);
}
}
thats not working, because "add" doesn't exist. I tried with questionList[i], this did not work either. Its so annoying, I just want to use that array! Can anybody help me please? :-)
this is not working either:
questionList[questionList.length-1] = i;
:-(

try:
package com.test
class SimuCacheService {
static transactional = false
List questionList = []
}
all other your code can stay the same

Related

Custom Layer with kwargs in tfjs

I'm new to tensorflowjs and I'm struggling to implement some custom layers, if someone could point me in the right direction that would be really helpful!
For example, I have a layer in InceptionResnetV1 architecture where I'm multiplying the layer by a constant scale (this was originally an unsupported Lambda layer which I'm switching out for a custom layer), but the value of this scale changes per block. This works fine in Keras with an implementation such as below, and using load_model with ScaleLayer in the custom objects
class ScaleLayer(tensorflow.keras.layers.Layer):
def __init__(self, **kwargs):
super(ScaleLayer, self).__init__(**kwargs)
def call(self, inputs, **kwargs):
return tensorflow.multiply(inputs, kwargs.get('scale'))
def get_config(self):
return {}
x = ScaleLayer()(x, scale = tensorflow.constant(scale))
I tried defining this in a similar way in javascript and then registered the class
class ScaleLayer extends tf.layers.Layer {
constructor(config?: any) {
super(config || {});
}
call(input: tf.Tensor, kwargs: Kwargs) {
return tf.tidy(() => {
this.invokeCallHook(input, kwargs);
const a = input;
const b = kwargs['scale'];
return tf.mul(a, b);
});
}
static get className() {
return 'ScaleLayer';
}
}
tf.serialization.registerClass(ScaleLayer);
However I'm finding that the kwargs are always empty. I tried another similar method where I passed scale as another dimension of the input, then did input[0] * input[1], which again worked fine for the keras model but not in javascript.
I feel like I'm missing something key on the way to defining this kind of custom layer with a changing value per block on the javascript end, so if someone would be able to point me in the right direction it would be much appreciated! Thanks.
constructor(config?: any) {
super(config || {});
}
The config are passed to the parent constructor. But as indicated by the question, the ScaleLayer layer also needs to keep some config properties
constructor(config?: any) {
super(config || {});
// this.propertyOfInterest = config.propertyOfInterest
// make sure that config is an object;
this.scale = config.scale
}
Then for the computation, the ScaleLayer property propertyOfInterest can be used
call(input: tf.Tensor) {
return tf.tidy(() => {
this.invokeCallHook(input, kwargs);
const a = input;
return tf.mul(a, this.scale);
});
}
Use the layer this way:
const model = tf.sequential();
...
model.add(new ScaleLayer({scale: 1}));
...

Extending class with no copying constructor (with private param)

During trying to enhance Angular's ComponetFixture I noticed that this can not be done because of no copying constructor for this class. (Or am I wrong?)
Let's suppose we have a class:
class A
{
constructor(public pub, private priv) { }
}
And I want to create class BetterA based on class A, so:
class BetterA extends A
{
constructor(a: A)
{
// super(a); <----- this can not be done, so maybe...
// super(a.pub, a.priv) // ...this could be better option, but...
}
myFunction(a: string) { return a; }
}
...second parameter is PRIVATE. I can not access it ;/
What can I do in that case?
I know that one of solutions is to use prototype like this:
A.prototype['myFunction'] = function(a: string) { return a; } // this must be done with function keyword, it's not working with ()=>{} !!! /there are problem with this pointer/
But then I have to write something weird like this:
console.log( classAobject['myFunction']("abc") );
Instead of
console.log( classAobject.myFunction("abc") );
or
I can do it by composition:
class B
{
public a: A; // or constructor(public a: A)
myFunction(a) { return a; }
}
But is seems not too elegant.
Is there any better solution?
Edit #1
I've just discovered that this syntax:
Class.prototype.NewFunction = function() { this.x.y.z = 123 }
is valid but it produces compiler errors, code works but we get:
'Property 'TextOf' does not exist on type 'Class'
and when you try to call it like this:
objectOfClass.NewFunction()
makes:
'Property 'NewFunction' does not exist on type 'Class'
BUT
It's gonna working only when we use function keyword. When we use lambda expression there will be same strange invisible problems with some functions.
I think composition is the way to go here. please remember that you are building a class and not a method which requires the new operator in order to instantiate your object. this may be what your looking for
class A{
tPub;
constructor(public pub, private priv) {
this.tPub=pub
}
}
class B extends A{
constructor(pub){
super(pub)
}
myFunc(){} //equiv to B.prototype.myFunc
}
export const myClass=new B();
//another file
import {myClass} from './file'
let m=myClass.myFunc();
unfortunately, by setting priv to private it will do exactly what it is told and make it a private object. you also could do without the constructor depending on what you would like to do with your class.

ReactJS, ES6: Using Arrow( => ) to modify state arrays' individual elements' member, a better way?

I have itemList as my state array of objects.
this.state = {
.....
itemList: [],
.....
}
itemList has title, desc, expState. The code present below works perfect. I want to know is there a better way to do it, like using arrow of ES6. I am new to ReactJS as well as ES6, so can't figure out.
var index = this.state.itemList.indexOf(item);
item.expState = !(item.expState);
var newItemList = itemList;
newItemList[index] = item;
this.setState({itemList: newItemList});
item.expState = !item.expState;
this.setState({ itemList: this.state.itemList });
The code above is the simplified version of what you have (it's pretty much ES5.1 still, since there is no place to use anything from the new standards).
The part
var newItemList = itemList;
newItemList[index] = item;
was entirely removed since in JS arrays are not cloned on assignment, but only references to them are assigned to a variable. Hence you are working with the same array anyway.

How to properly save self reference with ES6 classes?

Honestly, I'm not sure of what is the cause for the behavior: systemjs, babel or my own fault. I'm using class for custom control controller and saving class reference in self variable. Apparently that gets overriden by any subsequent controller instances.
I created a simple repository to demonstrate:
clone, install, run live-server or your preferred server. You will see 2 buttons, each is a custom control. Clicking on a button only affects one control.
https://github.com/alexkolt/selfIsThis
How can I get this working with ES6 class?
I should have posted the code, sorry.
The reason you'd want to save reference to self is for example in callbacks calling this might result in a different reference.
I was trying to do this:
var self;
class Test {
constructor(dependency) {
self = this;
self.dependency = dependency;
}
method() {
self.dependency().then(value => self.property = value);
}
}
Like it was mentioned before the self becomes shared when declared outside of the module. I didn't realize that would happen as files would be wrapped in a closure. Joe Clay answer is correct, but to do what I was trying to do self needs to be declared in every method that needs it.
class Test {
constructor(dependency) {
this.dependency = dependency;
}
method() {
var self = this;
this.dependency().then(value => self.property = value);
}
}
You're not really using ES6 classes right. You don't need to save a reference to this - just access it directly in class methods. The way you have it at the minute, all your instances of CustomControlController are sharing a single self variable.
class CustomControlController {
constructor() {
this.value = 0;
}
click() {
var newValue = this.value * 2;
this.value = newValue;
}
}
export default CustomControlController;

Looping through array and setting visible property of instances - ActionScript3

I have variable names stored in an array, and I want to loop through array and set the visible property of that instance to false. However, I'm getting error;
Error #1056: Cannot create property visible on String.
Here is my code:
package {
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class touch extends MovieClip
{
public function touch()
{
var menuitems:Array = new Array("menu_One", "menu_Two", "menu_Three", "menu_Three", "menu_Four", "menu_Five");//array with instance names
for(var i:int=0;i<6;i++){
var tempName = menuitems[i];
bsF_txt.text = tempName;
trace(tempName);
tempName.visible = false;
//menu_One.visible = false;
}
}
}
}
Is. what I'm trying to do possible in AS3?
First yes it is possible!
The problem is your looping through an array of strings, not variables or anything that references a DisplayObject (maybe a MovieClip in your case?)
Assuming those strings are either instance names of MovieClips that are on your stage or vars that are referencing them you could try something like this:
public function touch()
{
var menuitems:Array = new Array(menu_One, menu_Two, menu_Three, menu_Three, "menu_Four", menu_Five);//if this gives you an error please paste some more code because these are not instance names or vars
for(var i:int=0; i<menuitems.length ;i++){ //you don't need to explicitly use 6 here you can check the menuitems arrays length
var tempName = menuitems[i]; //note, this is not needed
bsF_txt.text = tempName.name; //I think you're looking for this?
trace(tempName);
tempName.visible = false;
//menu_One.visible = false;
}
}
}
Try using the following code (I just noticed you said those are instance names...)
package {
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class touch extends MovieClip
{
public function touch()
{
var menuitems:Array = new Array("menu_One", "menu_Two", "menu_Three", "menu_Three", "menu_Four", "menu_Five");//array with instance names
for(var i:int=0;i<6;i++){
var tempName = menuitems[i];
bsF_txt.text = tempName;
trace(tempName);
getChildByName(tempName).visible = false;
//menu_One.visible = false;
}
}
}
}
The main change is that you need to tell flash that the string in your array is an instance name. So use getChildByName assuming they are added to to the stage.
The reason your current code is failing is because you are trying to access the visible property on a String, but String does not have a visible property. But the actually instance of that string name might.

Resources