I want to evaluate the string expression without using script engine:
string expression can be like:
"((true&&(!false)||true)&&true)&&true"
Anybody have any idea how this can be done in android using kotlin
Thanks
Kotlin Android
app.gradle file
Add a new dependency
dependencies {
implementation 'net.objecthunter:exp4j:0.4.8'
}
main.kt file
var value = TextView.text.toString()
var result = ExpressionBuilder(value).build().evaluate()
I know my answer will not help you in your case where your string expression contain true, false, &&, ||, ! and (). BUT for those who wants to evaluate mathematical expressions I found this library that handles almost all mathematical operators.
Add it to your project and use it this way
// In root build.gradle
repositories {
maven {
url "https://dl.bintray.com/kaendagger/KParser"
}
}
//Add in the dependencies
dependencies{
implementation 'io.kaen.dagger:KParser-jvm:0.1.1'
}
And then in your code you can do something like this
val parser = ExpressionParser()
val result = parser.evaluate("5+1+cos(PI)-2*2/4")
println(result)
Related
I am trying to add the following task so that I can get some coverage data in my java + kotlin project (for what it is worth, this is a gradle project)... but I get the following error :
"Cannot add task ':jacocoTestReport' as a task with that name already exists"
Here is the actual task I am trying to add :
task jacocoTestReport(type: JacocoReport, dependsOn: "testDebugUnitTest") {
group = "Reporting"
description = "Generate Jacoco coverage reports for Debug build"
reports {
xml.enabled = true
html.enabled = true
}
// what to exclude from coverage report
// UI, "noise", generated classes, platform classes, etc.
def excludes = [
'**/R.class',
'**/R$*.class',
'**/*$ViewInjector*.*',
'**/BuildConfig.*',
'**/Manifest*.*',
'**/*Test*.*',
'android/**/*.*',
'**/*Fragment.*',
'**/*Activity.*'
]
// generated classes
classDirectories = fileTree(
dir: "$buildDir/intermediates/classes/debug",
excludes: excludes
) + fileTree(
dir: "$buildDir/tmp/kotlin-classes/debug",
excludes: excludes
)
// sources
sourceDirectories = files([
android.sourceSets.main.java.srcDirs,
"src/main/kotlin"
])
executionData = files("$buildDir/jacoco/testDebugUnitTest.exec")
}
Now, the issue I am confused about here, is that I can't find another class of this name anywhere... so perhaps there is something funky going on? I have tried googling this, but haven't really been able to find anything which truly helps me solve the problem.
All help greatly appreciated. I realize this is not a java or kotlin specific problem - but since it is a joint java + kotlin project, I thought I would tag both in this question, in case there is some nuanced issue that somebody else has seen.
Assuming you're already applying the Jacoco Gradle plugin, then yes, it already defines a task called jacocoTestReport, hence the error.
All you need to do is define your specific settings as per the documentation https://docs.gradle.org/current/userguide/jacoco_plugin.html#sec:jacoco_report_configuration
an example is below:
jacocoTestReport {
dependsOn "testDebugUnitTest"
reports {
xml.enabled = true
html.enabled = true
}
}
Most of the other configuration items you've listed belong in the 'jacoco' configuration block.
https://docs.gradle.org/current/userguide/jacoco_plugin.html#sec:jacoco_specific_task_configuration
I have tried to get all the solution files(*.sln) in a given path and print it individually by split the string(each solution file path) using comma delimiter. Programming script language am using is Jenkins Groovy. Am getting the below specified error when build the Jenkins job. Any one please look into this and guide me to proceed in a right way.
def finder = new FileNameFinder()
def files = finder.getFileNames 'D:\jobs', '**/*.sln'
def resultList = files.tokenize(",")
for(i=0; i<resultList.size();i++)
{
println resultList[i]
}
Error Details:
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.tokenize() is applicable for argument types: (java.lang.String) values: [,]
Possible solutions: toUnique(), toUnique(), toUnique(java.util.Comparator), takeWhile(groovy.lang.Closure), toUnique(groovy.lang.Closure), toUnique(java.util.Comparator)
Thanks in advance!!
Myself itself found an answer for my above problem. Please find below the modified working code.
def finder = new FileNameFinder()
def files = finder.getFileNames 'D:\jobs', '**/*.sln'
assert files instanceof List
println files.size()+" solution files found in the given path. Below are the found solution files details. \n"
for(i=0;i<files.size();i++)
{
println files[i];
}
Thanks
This seems like a simple question, but it's very challenging to search for, so I'm asking a new question. My apologies if it's already been asked.
Due to the compiler bug described here Scala 2.11.5 compiler crash with type aliases and manifests (also here https://issues.scala-lang.org/browse/SI-9155), I need to use scala TypeTags and friends for discovery of type parameters to methods. However, I then need to use that type information in a Java library that uses java.lang.Class and java.lang.reflect.Type.
How can I convert a scala.reflect.runtime.universe Type into a java.lang.reflect.Type or java.lang.Class?
Put concretely, how would I fill out the body of this method:
def typeFor[T](implicit tag: TypeTag[T]): java.lang.reflect.Type = ...
or, if that's not possible:
def typeFor[T](implicit tag: TypeTag[T]): java.lang.Class[T] = ...
And note, due to the bug posted above, I cannot use scala.reflect.Manifest.
The short answer is no, but you can try to do something similar to this SO question. However there is an open ticket....
This may have some limitations I'm not aware of, but you could drop down to Java reflection and try something like:
import scala.util.control.Exception._
def typeMe[T](implicit t: TypeTag[T]) = {
catching(classOf[Exception]) opt Class.forName(t.tpe.typeSymbol.asClass.fullName)
}
println(typeMe[String])
println(typeMe[ClassTag[_]])
Results in:
Some(class java.lang.String)
Some(interface scala.reflect.ClassTag)
The way I solved it with manifests, was:
private def typeFromManifest(m: Manifest[_]): Type = {
if (m.typeArguments.isEmpty) { m.runtimeClass }
else new ParameterizedType {
def getRawType = m.runtimeClass
def getActualTypeArguments = m.typeArguments.map(typeFromManifest).toArray
def getOwnerType = null
}
}
Right now I'm trying to solve this using something other than Manifest which should be removed from scala runtime.
How can I specify a default value for this simple build.gradle script:
println "Hello $build_version"
So that I don't get the error:
A problem occurred evaluating root project 'hello_gradle'.
> Could not find property '$build_version' on root project 'hello_gradle'.
I tried some of the operators, checking for nulls etc, but I think just the reference to the property makes it fail. I could fix that by always providing the property, but that's less than ideal.
gradle -Pbuild_version=World
if (!project.hasProperty("build_version")) {
ext.build_version = "1.0"
}
This checks if the property exists and assigns a default value if not:
def build_version=project.properties['build_version'] ?: "nokey"
Starting from Gradle 2.13:
ext.buildVersion = project.findProperty('build_version') ?: '1.0'
This worked for me:
def AWS_ACCESS_KEY="nokey"
def AWS_SECRET_KEY="nokey"
if (project.hasProperty("AWS_ACCESS_KEY")) {
AWS_ACCESS_KEY=project.get("AWS_ACCESS_KEY")
}
if (project.hasProperty("AWS_SECRET_KEY")) {
AWS_SECRET_KEY=project.get("AWS_SECRET_KEY")
}
Another way to make it short and nice:
ext.buildVersion = project.getProperties().getOrDefault("build_version", "1.0")
I'm adding this to my build.gradle:
String propValue(String propName, String defValue) {
(project.hasProperty(propName) && project.getProperty(propName)) ? project.getProperty(propName) : defValue
}
then use when needed propValue('build_version', 'nokey').
Have you tried this?:
println "Hello ${project.getProperty('build_version', 'default_string_value')}"
One-liner using ternary operator:
println "Hello ${project.hasProperty('build_version') ? getProperty('build_version') : 'World'}"
gradle <your_task> -Pbuild_version=SomethingElse
In Gradle you need to define subprojects to be built in a 'settings.gradle' file. To build three child projects, you would do something like this:
include "child1", "child2", "child3"
The problem I'm having is that I have quite a few projects to include. Is there a way to use a wildcard in this definition? I'm looking for something like this:
include "*"
That of course does not work. This would be a lot easier to work with since I have many subprojects to include. Is there a way to automatically include subdirectories as projects?
include rootDir.listFiles().findAll {
it.isDirectory()
&& !( it =~ ".*/\\..*") // don't add directories starting with '.'
&& !( it =~ "^\\..*") // don't add directories starting with '.'
}.collect {
it.getName()
}.toArray(new java.lang.String[0])
Did the trick for me
The following code supports a project hierarchy of arbitrary depth:
rootDir.eachFileRecurse { f ->
if ( f.name == "build.gradle" ) {
String relativePath = f.parentFile.absolutePath - rootDir.absolutePath
String projectName = relativePath.replaceAll("[\\\\\\/]", ":")
include projectName
}
}
Can you do something like:
include (1..10).collect { "Child$it" }
To include "Child1" up to "Child10"?
Obviously, you'd need to change the collect to some sort of folder scan, but it that quick test works then the scan has a good chance