Kotlin unresolved reference when using mutlithreading - multithreading

So I'm trying to use kotlin together with selenium and threading, but one parameter doesnt work. Here's my code:
class myClass(parameter1 : String, parameter2 : String, parameter3 : Int) : Thread(){
init{
var driver : ChromeDriver = ChromeDriver()
}
override fun run() {
driver.get("somewebsite")
var id_field = driver.findElementByName("iD")
id_field.sendKeys(parameter1)
id_field.submit()
name = parameter2 + parameter3.toString()
//At this Point, Intellij Idea tells me: Unresolved reference: parameter3
name_field = driver.findElementByName("name")
name_field.sendKeys(name)
name_field.submit()
}
}
fun main() {
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver")
val threads: Array<myClass> = Array(2) { myClass("some_id", "name", it)}
}
What should happen is that the script goes to my website, enters the name and iD. But I want to be able to run mutiple threads of my script where the threads "iteration" (which is parameter 3) is being added to my name.
So for example:
- thread 1 logs in with: name1
- thread 2 logs in with: name2
(...)
- thread 20 logs in with: name20
But my question is:
Why doesnt kotlin say: Unsolved reference: parameter 3?

Related

GDScript modularization

Is it possible to modularize in GDScript?
What I have in mind is that I have a player class with variable input, of type IInput, like this:
Player.gd:
extends KinematicBody
var input = load("res://Scripts/Inputs/PlayerInput.gd").new()
func _physics_process(delta):
if input.is_down("left_trigger"): speed = sprintSpeed
else: speed = runSpeed
Where "res://Scripts/Inputs/PlayerInput.gd" would look like this
extends "res://Scripts/Inputs/IInput.gd"
class_name PlayerInput
var controlTranslatinos = {"left_stick_up" : "move_up",
"left_stick_down" : "move_down",
"left_stick_left" : "move_left",
"left_stick_right" : "move_right",
"right_stick_up" : "rotate_up",
"right_stick_down" : "rotate_down",
"right_stick_left" : "rotate_left",
"right_stick_right" : "rotate_right",
"x" : "attack",
"left_trigger" : "defend",
"a" : "jump",
"right_trigger" : "sprint"}
func pressure(controlName):
var translatedControl = controlTranslatinos[controlName]
var preasure = Input.get_action_strength(translatedControl)
return preasure
func is_down(controlName):
return Input.is_action_pressed(controlTranslatinos[controlName])
and where "res://Scripts/Inputs/IInput.gd" would look like this:
extends Node
class_name IInput
const controls = [ "move_up", "move_down", "move_left", "move_right",
"rotate_up", "rotate_down", "rotate_left", "rotate_right",
"attack", "defend", "jump", "sprint" ]
func pressure(controlName):
return 0
func is_down(controlName):
return false
Goal is to change actor's input to AIInput class and back to PlayerInput on demand. This would also be good for other stuff.
Is it possible to implement this in some other way?
Error at `PlayerInput.gd`
There's an error at first line of PlayerInput, saying:
`Script not fully loaded (cyclic preload?): "res://Scripts/Inputs/IInput.gd"
I get what cyclic preload would mean, but I don't get how cyclic loading is happening at this instance. Can you explain how/why this is happening? How can I overcome it?
If this error wouldn't show up I think the modularization would work (the way I imagine it works).

Retrofit 2 error - End of input at line 1 column 1 path $

Im using Retrofit 2 with RxJava -
#retrofit2.http.Multipart
#retrofit2.http.POST(APIEndPoint.BATCHES)
fun submitGenericMultiPart(#retrofit2.http.Part("data") batchRequests: RequestBody, #retrofit2.http.Part("identifier") multipartTypedOutput: MultipartBody): Single<Array<BatchRequestResponse>>
mDataManager.submitGenericMultiPart(body, files)
?.subscribeOn(Schedulers.io())
?.observeOn(AndroidSchedulers.mainThread())
?.subscribe(object : SingleObserver<Array<BatchRequestResponse>> {
override fun onSubscribe(d: Disposable) {
if(d!=null) compositeDisposable.add(d)
}
override fun onSuccess(it: Array<BatchRequestResponse>) {
// success block
}
override fun onError(e: Throwable) {
// error block
}
})
Is there any error in the way I have declared the data types handling it in RxJava because every time, I get the error - End of input at line 1 column 1 path $
Cause: data response is empty, you can add NullOnEmptyConverterFactory to handle when the data response is empty.
Issue: https://github.com/square/retrofit/issues/1968
Solution: https://github.com/square/retrofit/issues/1554

Object Array Declaration in Groovy

How come I cannot declare an array of People in Groovy as shown.
Maybe I'm lacking the deeper understanding of classes
class People {
Integer id
}
class Job {
def func() {
People[] p = new People[10]
}
}
I get an error of People[] cannot be applied to app.People[]
The code sample you have shown does not reproduce the error you mentioned in the question above. It's broken actually and does not compile - method func() is missing its body. If you correct the code to e.g.
class People {
Integer id
}
class Job {
def func() {
People[] p = new People[10]
assert p.size() == 10
println p
}
}
new Job().func()​
you will see it produces the expected result - check it out in the Groovy web console here. When you run it you will see following output to the console:
[null, null, null, null, null, null, null, null, null, null]
The difference between Groovy and Java
When it comes to array initialization there is one significant difference between Groovy and Java. In Java you can initialize an array of People[] like this:
People[] p = new People[] { new People(), new People(), /* ... */ new People() };
It wont work in Groovy, because Groovy reserves {} for closures. In Groovy you can initialize such array as:
People[] p = [new People(), new People(), new People()] as People[]
While Szymon Stepniak's answer is correct for Groovy 2.5 and below, Java-style array initialization are part of the enhancements of Groovy 3.0 and 2.6 made possible by the new parrot parser.
Example from the release notes:
def primes = new int[] {2, 3, 5, 7, 11}
assert primes.size() == 5 && primes.sum() == 28
assert primes.class.name == '[I'
def pets = new String[] {'cat', 'dog'}
assert pets.size() == 2 && pets.sum() == 'catdog'
assert pets.class.name == '[Ljava.lang.String;'
// traditional Groovy alternative still supported
String[] groovyBooks = [ 'Groovy in Action', 'Making Java Groovy' ]
assert groovyBooks.every{ it.contains('Groovy') }
Szymon Stepniak's answer is correct. I'll point another example of a real case in some unit test that I've worked (general Object type):
Object[] o = [YourModel] as Object[]
This is sufficient to mock a general Object with your model properties.

How can I retrieve the build parameters from a queued job?

I would like to write a system groovy script which inspects the queued jobs in Jenkins, and extracts the build parameters (and build cause as a bonus) supplied as the job was scheduled. Ideas?
Specifically:
def q = Jenkins.instance.queue
q.items.each { println it.task.name }
retrieves the queued items. I can't for the life of me figure out where the build parameters live.
The closest I am getting is this:
def q = Jenkins.instance.queue
q.items.each {
println("${it.task.name}:")
it.task.properties.each { key, val ->
println(" ${key}=${val}")
}
}
This gets me this:
4.1.next-build-launcher:
com.sonyericsson.jenkins.plugins.bfa.model.ScannerJobProperty$ScannerJobPropertyDescriptor#b299407=com.sonyericsson.jenkins.plugins.bfa.model.ScannerJobProperty#5e04bfd7
com.chikli.hudson.plugin.naginator.NaginatorOptOutProperty$DescriptorImpl#40d04eaa=com.chikli.hudson.plugin.naginator.NaginatorOptOutProperty#16b308db
hudson.model.ParametersDefinitionProperty$DescriptorImpl#b744c43=hudson.mod el.ParametersDefinitionProperty#440a6d81
...
The params property of the queue element itself contains a string with the parameters in a property file format -- key=value with multiple parameters separated by newlines.
def q = Jenkins.instance.queue
q.items.each {
println("${it.task.name}:")
println("Parameters: ${it.params}")
}
yields:
dbacher params:
Parameters:
MyParameter=Hello world
BoolParameter=true
I'm no Groovy expert, but when exploring the Jenkins scripting interface, I've found the following functions to be very helpful:
def showProps(inst, prefix="Properties:") {
println prefix
for (prop in inst.properties) {
def pc = ""
if (prop.value != null) {
pc = prop.value.class
}
println(" $prop.key : $prop.value ($pc)")
}
}
def showMethods(inst, prefix="Methods:") {
println prefix
inst.metaClass.methods.name.unique().each {
println " $it"
}
}
The showProps function reveals that the queue element has another property named causes that you'll need to do some more decoding on:
causes : [hudson.model.Cause$UserIdCause#56af8f1c] (class java.util.Collections$UnmodifiableRandomAccessList)

Can't call one closure from another

I am implementing a pluggable architecture based on http://fbflex.wordpress.com/2010/03/14/hot-pluggable-extensions-in-grails-adding-and-changing-your-application-behaviour-on-the-fly/.
As it turns out, one of my pluggable closures needs to invoke another closure in the same file.
However, during execution, the call from one closure to the other fails with this exception:
No signature of method: groovy.util.ConfigSlurper$_parse_closure5.criterion2() is applicable for argument types: (java.util.LinkedHashMap)
This error is not true. There actually is a closure that takes a map. I think the problem is with the scoping or qualifying of the closure.
name ="strategy1"
key ="strategy1"
criterion1 = { params ->
params.a > params.b
}
criterion2 = { params ->
params.a >= params.c && params.a >= params.d
}
constructWidget = { params ->
def base = [symbol:params.sym, price:params.pr, strategy:params.strat]
if( criterion2(base) ) { // this is where the exception occurs
// ...
}
}
Calls to these closures work fine from outside of the "plugin." What is the proper way to refer to the closure named criterion2 from inside of constructWidget?
The problem you describe is well-reproducible, when loading the plugins with the help of ConfigSlurper:
def plugin = new ConfigSlurper().parse( new File('plugin1.groovy').toURL() )
plugin.constructWidget([:])
the problem is solved by using GroovyShell instead of ConfigSlurper:
Binding binding = new Binding()
GroovyShell shell = new GroovyShell(binding)
def plugin = shell.evaluate(new File('plugin1.groovy'))
plugin.constructWidget([:])
update-20140104:
if you are loading plugins in a loop:
new File( grailsApplication.config.externalFiles ).eachFile { file ->
Binding binding = new Binding()
GroovyShell shell = new GroovyShell(binding)
shell.evaluate(file)
strategies.put( binding.variables.key, binding.variables )
}

Resources