I've pulled an expression from SQL db and that expression is stored as String in jmeter beanshell assertion.
Now I would like to use that expression to evaluate different values
String LeftTank_conv = vars.get("Conv_formula_5") + ""; LeftTank_conv = "{x*100*245/345;}"(something like this)
how can I use this string as an expression to evaluate for different x values
TIA
If you really need the possibility to evaluate arbitrary arithmetic formulae you could use JEXL engine which is being used in JMeter's __jexl3() function
Since JMeter 3.1 it's recommended to use Groovy for scripting so I'll provide the example solution using Groovy syntax:
def context = new org.apache.commons.jexl3.MapContext()
context.set('x', 1)
def engine = new org.apache.commons.jexl3.JexlBuilder().create()
def e = engine.createExpression(vars.get('Conv_formula_5'))
def result = e.evaluate(context)
log.info('Execution result: ' + result as String)
Demo:
Related
I have a string that might eventually contain spaces. I would like to replace those spaces with a regex that matches against \t,\r,\n. After replacing I would like to call regexp_like (an oracle function) to match a field against this string.
I know it is possible to call db functions using criteria builder as described for example in this link
I am not very familiar with the difference between regex in java versus oracle or how to cobble this together (I have never called functions from criteriabuilder). Here are my tentative steps with places where I am stuck in the comments
// first replace all spaces with regex for \s,\r,\t, value is the original string
value.replaceAll(" +", "[\\t\\n\\r]+")
// build the db function call expression, seems I cant do table.<String>get(field) and cant pass value as a string
Expression<String> regExp = cb.function("regexp_like", String.class, table.<String>get(field), value);
// now create a predicate not sure how
Predicate fieldMatch = cb.equal(...)
Is this possible?
Its possible. You only need to do few small changes.
Extends your Oracle dialog
public class Oracle10gCustomDialect extends Oracle10gDialect {
public Oracle10gCustomDialect() {
super();
registerFunction("regexp_like", new SQLFunctionTemplate(StandardBasicTypes.BOOLEAN,
"(case when (regexp_like(?1, ?2)) then 1 else 0 end)"));
}
}
Then use this path at your application.properties or hibernate properties config.
Then in your specification, need to do something like this.
Expression<Boolean> regExprLike = criteriaBuilder.function("regexp_like", Boolean.class, root.get("yourColumn"), criteriaBuilder.literal("<your regexp value>"));
predicates.add(criteriaBuilder.isTrue(regExprLike));
...
And thats all!
I am trying to add a filter on my dataframe, for some reason the || condition is not working in Java, it works perfectly in Scala. The code doesn't even compile. How do we use || operator in filter condition in java
The message says
The operator || is undefined for the argument type(s) org.apache.spark.sql.Column, org.apache.spark.sql.Column
df.filter((df.col("eventNumbers").contains("2") )|| (df.col("eventNumbers").contains("45")))
First, you have to:
import static org.apache.spark.sql.functions.*;
And that scala code in java would be:
df.filter((df.col("eventNumbers").contains("2") ).or(df.col("eventNumbers").contains("45")))
In Java 8, you can use String conditionExpr to filter.
Dataset<Row> df = spark.sqlContext().read()
.option("multiLine", true)
.json(dnsRecordFile)
.filter("type=='A'") // <--- filter by ConditionExpr Str
.select("name", "value");
I want to use the Mule Expression Language to send two input parameters to an API (ex: CodePostal and LibelleVoie).
I do that :
[payload[1].getAdresseNonNormalisee().getObjetAttributs().getCodePostal()] && #[payload[1].getAdresseNonNormalisee().getObjetAttributs().getLibelleVoie()]]
But it does not work, it returns me a String
have you an idea please ?
You have to write everything in one MEL expression:
#[payload[1].getAdresseNonNormalisee().getObjetAttributs().getCodePostal() &&
payload[1].getAdresseNonNormalisee().getObjetAttributs().getLibelleVoie()]]
You used two expressions with some String in between: " && "
I am looking for a way to expand a logical expression (in a string) of the form:
'(A or B) and ((C and D) or E)'
in Python to produce a list of all positive sets, i.e.
['A and C and D',
'A and E',
'B and C and D',
'B and E']
but I have been unable to find how to do this. I have investigated pyparser, but I cannot work out which example is relevant in this case. This may be very easy with some sort of logic manipulation but I do not know any formal logic. Any help, or a reference to a resource that might help would be greatly appreciated.
Here's the pyparsing bit, taken from the example SimpleBool.py. First, use infixNotation (formerly known as operatorPrecedence) to define an expression grammar that supports parenthetical grouping, and recognizes precedence of operations:
from pyparsing import *
term = Word(alphas)
AND = Keyword("and")
OR = Keyword("or")
expr = infixNotation(term,
[
(AND, 2, opAssoc.LEFT),
(OR, 2, opAssoc.LEFT),
])
sample = '(A or B) and ((C and D) or E)'
result = expr.parseString(sample)
from pprint import pprint
pprint(result.asList())
prints:
[[['A', 'or', 'B'], 'and', [['C', 'and', 'D'], 'or', 'E']]]
From this, we can see that the expression is at least parsed properly.
Next, we add parse actions to each level of the hierarchy of operations. For parse actions here, we actually pass classes, so that instead of executing functions and returning some value, the parser will call the class constructor and initializer and return a class instance for the particular subexpression:
class Operation(object):
def __init__(self, tokens):
self._tokens = tokens[0]
self.assign()
def assign(self):
"""
function to copy tokens to object attributes
"""
def __repr__(self):
return self.__class__.__name__ + ":" + repr(self.__dict__)
__str__ = __repr__
class BinOp(Operation):
def assign(self):
self.op = self._tokens[1]
self.terms = self._tokens[0::2]
del self._tokens
class AndOp(BinOp):
pass
class OrOp(BinOp):
pass
expr = infixNotation(term,
[
(AND, 2, opAssoc.LEFT, AndOp),
(OR, 2, opAssoc.LEFT, OrOp),
])
sample = '(A or B) and ((C and D) or E)'
result = expr.parseString(sample)
pprint(result.asList())
returns:
[AndOp:{'terms': [OrOp:{'terms': ['A', 'B'], 'op': 'or'},
OrOp:{'terms': [AndOp:{'terms': ['C', 'D'],
'op': 'and'}, 'E'], 'op': 'or'}],
'op': 'and'}]
Now that the expression has been converted to a data structure of subexpressions, I leave it to you to do the work of adding methods to AndOp and OrOp to generate the various combinations of terms that will evaluate overall to True. (Look at the logic in the invregex.py example that inverts regular expressions for ideas on how to add generator functions to the parsed classes to generate the different combinations of terms that you want.)
It sounds as if you want to convert these expressions to Disjunctive Normal Form. A canonical algorithm for doing that is the Quine-McCluskey algorithm; you can find some information about Python implementations thereof in the relevant Wikipedia article and in the answers to this SO question.
I am aware that you can create global expressions with Esper's Statement Object Model using CreateExpressionClause and ExpressionDeclaration, but I'm not exactly sure how you are able to refer to their aliases when building an EPStatementObjectModel for a pattern. For example, say I have a pattern like this:
every (a=Event(fizz = 3 and buzz = 5) -> b=Event(fizz = 3 and buzz = 5 and foo = 1 and bar = 2))
I would like to declare fizz = 3 and buzz = 5 as a global expression as such:
create expression fizzbuzz alias for {fizz = 3 and buzz = 5}
Therefore, with EPL I could successfully simplify the pattern to the following:
every (a=Event(fizzbuzz) -> b=Event(fizzbuzz and foo = 1 and bar = 2))
I cannot seem to find a method in any of the classes in com.espertech.esper.client.soda in which I can refer to the global expression alias as I build the statement object. The best thing I could think of that would give me a valid pattern when converting the statement object to EPL would involve Expressions.property(alias), but I get the following error when I add the complete statement object to the Esper engine:
Failed to validate filter expression 'fizzbuzz': Property named 'fizzbuzz' is not valid in any stream [every (a=Event(fizzbuzz) -> b=Event(fizzbuzz and foo = 1 and bar = 2))]
Take note that a) global expressions were already declared at this point, b) If I add the pattern containing the global expression aliases in EPL form to the Esper engine, it works.
Any ideas? While it's an option, I'd prefer not to convert from EPStatementObjectModel to an EPL string everytime I add a new pattern to the engine.
You could inspect a generated object model in a debugger to find out. So in order to generate one, you could call "epadmin.compile("some epl with the expression") and see what comes back.
Following user650839's advice, I found through debugging that the way to go about including the alias to named global expressions is to incorporate a DotExpression into your statement object tree as such:
DotExpression globalExpression = new DotExpression();
globalExpression.add("fizzbuzz", new ArrayList<Expression>(), true);