I have a string like the following:
def slurper = new JsonSlurper()
def request = slurper.parseText(dataRequest)
def response1 = slurper.parseText(dataResponse)
Eval.me('request.variable1 = request.variable2')
But I got an error: javax.script.ScriptException: ReferenceError: "request" is not defined in at line number 1
Use groovy expression like
def a = 2
def b = 3
Eval.me("$a == $b")
or use the xy method instead
Eval.xy(a, b, 'x == y')
http://docs.groovy-lang.org/latest/html/api/groovy/util/Eval.html
Related
Given any iterator, I want to be able to pass this iterator into my function, to return a new iter object that cycles through the given iter infinitely. E.G
class range:
def __init__(self, min, max, step):
self.min = min
self.max = max
self.step = counter
[...] other vars
def __next__(self):
if [.............]
You get the jist. I have a bunch of custom iterators like this, all created with diff args/params. I know I can use vars to get the variables... but how do you distinguish between vars passed into init to create this object, and others vars? Vars returnsmin/max/counter + all the other vars
I have a class like this:
class Cycle:
def __init__(self, iterable):
self.iterable = iterable
def __next__(self):
next_val = next(self.iterable, None)
if next_val is None:
#RESET iterable or create new instance of iterable with same _init_ args used to create it
next_val = next(self.iterable)
return next_val
Intended use:
r = range(0,4,2)
next(r) = 0
next(r) = 2
next(r) = 4
next(r) = stopiterationerror
c = Cycle(r)
next(c) = 0
next(c) = 2
next(c) = 4
next(c) = 0
next(c) = 2
next(c) = 4
.......
I want to keep this cycle function clean and simple if I can. Ideally I would want to simply self.iterable.reset, but it seems like resetting an iterable is not possible in python and I need to create a brand new instance. I know I could pass in *args into cycle, but is it possible to avoid that?
edit currently working:
class Cycle:
def __init__(self, iterable):
self.iterable = iterable
self.copy = copy(iterable)
def __next__(self):
next_val = next(self.iterable, None)
if next_val is None:
self.iterable = self.copy
self.copy = copy(self.copy)
next_val = next(self.iterable, None)
return next_val
all the examples shown just explain how to create a singleton of a class without the instantiation of any members.
But how can I produce a singleton of the following class in Python 3:
class NotOneOnly:
def __init__(self, a, b):
print("Instatiation of objects.")
self.a = a
self.b = b
def run(self):
print("Variable a = " + str(self.a) + " and variable b = " +
str(self.b))
In the main program, the use would be:
not_one_only = NotOneOnly(5, 10)
not_one_only.run()
Thanks 4 help.
After investigating a little bit, I've discovered this. So my conclusion is:
class OneOnly:
_singleton = None
a = None
b = None
def __new__(cls, a, b):
if not cls._singleton:
print("Object is created and the variables are instantiated.")
cls._singleton = super(OneOnly, cls).__new__(cls)
cls.a = a
cls.b = b
else:
print("Sorry, byt object is already made.")
return cls._singleton
def run(self):
print("Variable a = " + str(self.a) + " and variable b = " + str(self.b))
Now in the mainfile I made the following experiments showing that the singleton was created in the right way:
print("Singleton Experiment:")
a = 10
b = 5
one_only1 = OneOnly(a, b)
print(one_only1)
one_only1.run()
one_only2 = OneOnly(1, 2)
print(one_only2)
one_only2.run()
one_only1.a = 100
one_only1.run()
one_only2.run()
Now the output is:
Singleton Experiment:
Object is created and the variables are instantiated.
<__main__.OneOnly object at 0x7fa4295cbcc0>
Variable a = 10 and variable b = 5
Sorry, byt object is already made.
<__main__.OneOnly object at 0x7fa4295cbcc0>
Variable a = 10 and variable b = 5
Variable a = 100 and variable b = 5
Variable a = 100 and variable b = 5
guys how can I make it so that calling make_repeater(square, 0)(5) return 5 instead of 25? I'm guessing I would need to change the line "function_successor = h" because then I'm just getting square(5) but not sure what I need to change it to...
square = lambda x: x * x
def compose1(h, g):
"""Return a function f, such that f(x) = h(g(x))."""
def f(x):
return h(g(x))
return f
def make_repeater(h, n):
iterations = 1
function_successor = h
while iterations < n:
function_successor = compose1(h, function_successor)
iterations += 1
return function_successor
it needs to satisfy a bunch of other requirements like:
make_repeater(square, 2)(5) = square(square(5)) = 625
make_repeater(square, 4)(5) = square(square(square(square(5)))) = 152587890625
To achieve that, you have to use the identity function (f(x) = x) as the initial value for function_successor:
def compose1(h, g):
"""Return a function f, such that f(x) = h(g(x))."""
def f(x):
return h(g(x))
return f
IDENTITY_FUNCTION = lambda x: x
def make_repeater(function, n):
function_successor = IDENTITY_FUNCTION
# simplified loop
for i in range(n):
function_successor = compose1(function, function_successor)
return function_successor
if __name__ == "__main__":
square = lambda x: x * x
print(make_repeater(square, 0)(5))
print(make_repeater(square, 2)(5))
print(make_repeater(square, 4)(5))
and the output is
5
625
152587890625
This isn't most optimal for performance though since the identity function (which doesn't do anything useful) is always part of the composed function, so an optimized version would look like this:
def make_repeater(function, n):
if n <= 0:
return IDENTITY_FUNCTION
function_successor = function
for i in range(n - 1):
function_successor = compose1(function, function_successor)
return function_successor
Dears,
I'm trying to run this code into an eval function, but i'm getting the error below:
"name 'self' is not defined"
. Is there a way to avoid it without using global variables? Thanks!!!
This is basically the eval:
eval(sum(
sum(
self.dataset['Exposure'][c]
* self.suggested_decisions[c][d]
* int(self.constants['scaling_factor'] * self.decisions[d].variables[
'Recovery_Percentage_Segment_2'])
* self.dataset['Segment2'][c]
for c in self.all_records
)
for d in self.all_decisions
)
)
To give a bit of context I'm putting here a simplified version of my code where I'm using the eval:
class Engine:
def __init__(self, xmlpath=None, timeout=30, expr=None):
self.xml_path = xmlpath
self.decisions = None
self.dataset = None
self.constants = None
self.expr = expr
self.load_problem(self.xml_path)
self.num_records = len(self.dataset['ID'])
self.all_records = range(self.num_records)
self.all_decisions = range(len(self.decisions))
self.suggested_decisions = {}
self.timeout = timeout
def run(self):
eval("recovered_amn_segment_1 ==" + self.Sum_ForAllRecordsAndDecisions(self.expr))
def Sum_ForAllRecordsAndDecisions(self, expr):
return "sum(sum(" + expr + "for r in self.all_records) for d in self.all_decisions)"
def client():
expr = "self.suggested_decisions[r][d]*(self.dataset['Exposure'][r]*int(self.constants['scaling_factor'] * self.decisions[d].variables['Recovery_Percentage_Segment_1']*self.dataset['Segment1'][r]))"
xml_path = 'C:/Documenti/S1/Requirements/ottimizzatore/CollectionProblem.xml'
timeout = 30
engine = Engine(xml_path, timeout, expr)
engine.run()
client()
Basically from the client I'm passing a string "expr" to a class that manipulate the string and execute it. I hope it clarifies.
Thanks!!!
I have this code:
static def parseString(String inputRow, Particle particle) {
//input row is:
//static final inputRow = "1 -5.2 3.8"
def map = inputRow.split()
particle.mass = Integer.parseInt(map[0])
particle.x = Integer.parseInt(map[1])
particle.y = Integer.parseInt(map[2])
}
This code is throwing this error:
java.lang.NumberFormatException: For input string: "-5.2"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.valueOf(Integer.java:582)
at RepulsionForce.parseString(RepulsionForce.groovy:13)
at RepulsionForceTest.string should be parsed into particles(RepulsionForceTest.groovy:27)
How do I avoid this exception?
You can cut down redundant lines as shown below where particle is a map:
def arr = inputRow.split()
def mass, x, y
(mass, x, y) = arr*.toDouble()
def particle = [:] << [mass: mass, x: x, y: y]
Missed the part where Particle class has been referred instead.
Whoops, figured this out... 5.2 is not an integer.
static def parseString(String inputRow, Particle particle) {
def map = inputRow.split()
particle.mass = Double.parseDouble(map[0])
particle.x = Double.parseDouble(map[1])
particle.y = Double.parseDouble(map[2])
}
Here is one way to do it... Answer within a full solution:
// setup
class Particle {
def mass
def x
def y
}
def particle = new Particle()
def inputRow = "1 -5.2 3.8"
def fieldsByIndex = [0: "mass", 1: "x", 2: "y"]
// answer
inputRow.split().eachWithIndex { val, index ->
def field = fieldsByIndex.get(index)
particle."${field}" = val.toDouble()
}
// output
println "mass : " + particle.mass
println "x : " + particle.x
println "y : " + particle.y
Explanation: You Mistakenly trying to parse Double number to Integer number and it's not applicable, not sharing the same type ( integer != double) , and not gonna work - Therefore you getting java.lang.NumberFormatException: For input string exception which explicitly inform you for the type issue.
Solution: Convert it to to double using Double Class.
Double.parseDouble(map[i])