I'm using lambdaj 2.4 with dependencies. My code (very simple):
List<Person> persons = Arrays.asList(
new Person(13,"Steve",22,"London, UK"),
new Person(25,"Greg",28,"New York, USA"),
new Person(5,"Emily",22,"Bali, Indonesia"),
new Person(9,"Malih",14,"Jakarta, Indonesia"));
List<String> personNames = extract(persons, on(Person.class).getName());
System.out.println("personNames: "+personNames);
But it does not work, exception is:
java.lang.ExceptionInInitializerError
at ch.lambdaj.proxy.ProxyUtil.createEnhancer(ProxyUtil.java:89)
at ch.lambdaj.proxy.ProxyUtil.createProxy(ProxyUtil.java:49)
at ch.lambdaj.function.argument.ArgumentsFactory.createPlaceholder(ArgumentsFactory.java:68)
Any ideas how to make it working on Android?
If you have the choice, you should consider using Retro Lambda. It's a backport of the full Java 8 Lambda Expression syntax for JDK 6 & 7 - and offers full, real closures (LambdaJ was pretty good alternative in the absence of language level support).
Retro Lambda
Retro Lambda Gradle Plugin
Stream Support - backport of Streams
Blog post on setting up RetroLambda for Android Studio
Related
I am upgrading a legacy application from Java 8 to Java 11 (Oracle Version) and having issue while getting the corbaloc reference.
I have read below
articles here and here that specifies that CORBA support is removed form JAVA 11 and with the help of Glassfish Corba I can use the packages again.
The issue I am facing is with below function call
((com.sun.corba.se.spi.orb.ORB) orb.orb()).register_initial_reference(idStr, ref);
In Eclipse the Error is ORB cannot be resolved to a type.
As I know we should not use any package related to sun but this is old code and not sure about the replacement.
I have changed the package from com.sun.corba.se.spi.orb.ORB to org.omg.CORBA.ORB but the method register_initial_reference(idStr, ref) is not found.
I am not sure what needs to be changed or any example that will help to get the possible alternate change. Any guide or help is highly appreciated. Even I have almost NO idea about CORBA and very less examples are available.
Below is the function that starts the service
final byte[] id = "\u00ffPNS_Service\u0000PNS_Study".getBytes();
final String idStr = new String(id);
final Policy[] policies = new Policy[] {
root.create_lifespan_policy(LifespanPolicyValue.PERSISTENT) };
final POA poa = root.create_POA("PNS_Service",root.the_POAManager(),policies);
poa.the_POAManager().activate();
poa.activate_object(studyService);
final org.omg.CORBA.Object ref = poa.servant_to_reference(studyService);
((com.sun.corba.se.spi.orb.ORB) orb.orb()).register_initial_reference(idStr , ref);```
I am trying to build a deep learning model with transformer model architecture. In that case when I am trying to cleaning the dataset following error occurred.
I am using Pytorch and google colab for that case & trying to clean Java methods and comment dataset.
Tested Code
import re
from fast_trees.core import FastParser
parser = FastParser('java')
def get_cmt_params(cmt: str) -> List[str]:
'''
Grabs the parameter identifier names from a JavaDoc comment
:param cmt: the comment to extract the parameter identifier names from
:returns: an array of the parameter identifier names found in the given comment
'''
params = re.findall('#param+\s+\w+', cmt)
param_names = []
for param in params:
param_names.append(param.split()[1])
return param_name
Occured Error
Downloading repo https://github.com/tree-sitter/tree-sitter-java to /usr/local/lib/python3.7/dist-packages/fast_trees/tree-sitter-java.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-31-64f6fa6ed39b> in <module>()
3 from fast_trees.core import FastParser
4
----> 5 parser.set_language = FastParser('java')
6
7 def get_cmt_params(cmt: str) -> List[str]:
3 frames
/usr/local/lib/python3.7/dist-packages/fast_trees/core.py in FastParser(lang)
96 }
97
---> 98 return PARSERS[lang]()
/usr/local/lib/python3.7/dist-packages/fast_trees/core.py in __init__(self)
46
47 def __init__(self):
---> 48 super().__init__()
49
50 def get_method_parameters(self, mthd: str) -> List[str]:
/usr/local/lib/python3.7/dist-packages/fast_trees/core.py in __init__(self)
15 class BaseParser:
16 def __init__(self):
---> 17 self.build_parser()
18
19 def build_parser(self):
/usr/local/lib/python3.7/dist-packages/fast_trees/core.py in build_parser(self)
35 self.language = Language(build_dir, self.LANG)
36 self.parser = Parser()
---> 37 self.parser.set_language(self.language)
38
39 # Cell
ValueError: Incompatible Language version 13. Must not be between 9 and 12
an anybody help me to solve this issue?
fast_trees uses tree_sitter and according to tree_sitter repo it is an incomatibility issue. If you know the owner of fast_trees ask them to upgrade their tree_sitter version.
Or you can fork it and upgrade it yourself, but keep in mind it may not be backwards compatible if you take it upon yourself and it may not be just a simple new version install.
The fast-trees library uses the tree-sitter library and since they recommended using the 0.2.0 version of tree-sitter in order to use fast-trees. Although downgrade the tree-sitter to the 0.2.0 version will not be resolved your problem. I also tried out it by downgrading it.
So, without investing time to figure out the bug in tree-sitter it is better to move to another stable library that satisfies your requirements. So, as your requirement, you need to extract features from a given java code. So, you can use javalang library to extract features from a given java code.
javalang is a pure Python library for working with Java source code.
javalang provides a lexer and parser targeting Java 8. The
implementation is based on the Java language spec available at
http://docs.oracle.com/javase/specs/jls/se8/html/.
you can refer it from - https://pypi.org/project/javalang/0.13.0/
Since javalang is a pure library it will help go forward on your research without any bugs
I'm trying to capture values in my test
...
final Capture<MyDTO> myDTOCaptured = new Capture<MyDTO>();
EasyMock.expect(this.serviceMock.execute(capture(myDTOCaptured)).andReturn(someResult);
...
The Documentation says:
Deprecated API
org.easymock.EasyMock.capture(Capture)
Because of harder erasure enforcement, doesn't compile in Java 7
http://easymock.sourceforge.net/api/easymock/3.1/deprecated-list.html
Version 3.1 is the version we are using.
Is there any alternative for capture in Java 8+? I guess the alternative is upgrading the version.
Upgrade to latest EasyMock (4.2) and use generic method capture(Capture<T> captured) as a replacement
Expect any object but captures it for later use
Example:
final Capture<TwoWayChannelMessage> initiateCapture = new Capture<>();
connection.sendToClient(capture(initiateCapture));
This website is obsolete. The real up-to-date EasyMock website is http://easymock.org/. EasyMock moved out of SourceForge a long time ago.
Latest EasyMock would be
Capture<TwoWayChannelMessage> initiateCapture = EasyMock.newCapture();
connection.sendToClient(capture(initiateCapture));
I am using the below code to walk a directory and fetch the first file . I am not able to fix the two sonar lint issues . Please help.
List<String> result = walk.filter(Files::isRegularFile).map(x -> x.toString()).collect(Collectors.toList());
Please make this change:
List<String> result = walk.filter(p -> p.toFile().isFile()).map(Path::toString).collect(Collectors.toList());
SonarLint also state the reason for the suggestion.
Lambdas should be replaced with method references
Java 8's "Files.exists" should not be used
Look at the 3725 Sonar rule :
The Files.exists method has noticeably poor performance in JDK 8, and
can slow an application significantly when used to check files that
don't actually exist.
The same goes for Files.notExists, Files.isDirectory and
Files.isRegularFile.
Note that this rule is automatically disabled when the project's
sonar.java.source is not 8.
Your project very probably relies on JDK/JRE 8.
If you dig into the OpenJDK issues you could see that on Linux the issue was partially solved but not on Windows.
About the second issue :
map(x -> x.toString())
Just replace it by a method reference :
map(Path::toString)
So finally to be compliant with Sonar, it gives :
//FIXME use Files::isRegularFile when update with Java>8
List<String> result = walk.filter(p -> p.toFile().exists())
.map(Path::toString)
.collect(Collectors.toList());
I am using OpenCV 3.0 (the latest version) in Java, but when I use SURF algorithm or SIFT algorithm it doesn't work and throws Exception which says: OpenCV Error: Bad argument (Specified feature detector type is not supported.) in cv::javaFeatureDetector::create
I have googled, but the answers which was given to this kind of questions did not solve my problem. If anyone knows about this problem please let me know.
Thanks in advance!
Update: The code below in third line throws exception.
Mat img_object = Imgcodecs.imread("data/img_object.jpg");
Mat img_scene = Imgcodecs.imread("data/img_scene.jpg");
FeatureDetector detector = FeatureDetector.create(FeatureDetector.SURF);
MatOfKeyPoint keypoints_object = new MatOfKeyPoint();
MatOfKeyPoint keypoints_scene = new MatOfKeyPoint();
detector.detect(img_object, keypoints_object);
detector.detect(img_scene, keypoints_scene);
If you compile OpenCV from source, you can fix the missing bindings by editing opencv/modules/features2d/misc/java/src/cpp/features2d_manual.hpp yourself.
I fixed it by making the following changes:
(line 6)
#ifdef HAVE_OPENCV_FEATURES2D
#include "opencv2/features2d.hpp"
#include "opencv2/xfeatures2d.hpp"
#include "features2d_converters.hpp"
...(line 121)
case SIFT:
fd = xfeatures2d::SIFT::create();
break;
case SURF:
fd = xfeatures2d::SURF::create();
break;
...(line 353)
case SIFT:
de = xfeatures2d::SIFT::create();
break;
case SURF:
de = xfeatures2d::SURF::create();
break;
The only requirement is that you build opencv_contrib optional module along with your sources (you can download the git project from https://github.com/Itseez/opencv_contrib and just set its local path on opencv's ccmake settings.
Oh, and keep in mind that SIFT and SURF are non-free software ^^;
That is because they are not free in newer versions of OpenCV (3+). I faced that problem some time ago. You have to:
Download OpenCV (if you have not)
Download the nonfree part from opencv github repo
Generate the makefiles with cmake -DBUILD_SHARED_LIBS=OFF specifying the nonfree part with DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules option and build with make -j8 (or whatever Java version you use)
Edit features2d_manual.hpp file, including opencv2/xfeatures2d.hpp and including the necessary code for SIFT and SURF case, which are commented and not defined:
fd=xfeatures2d::SIFT::create(); for SIFT descriptor and de = xfeatures2d::SIFT::create(); for SIFT extractor. Do the same for SURF if you want to use it too.
I wrote this post explaining step by step how to compile the non-free OpenCV part in order to use privative tools like SIFT or SURF.
Compile OpenCV non-free part.
I believe changing features2d module (FeatureDetector class or any other classes from features2d_manual.hpp) to enable methods from OpenCV contrib modules is less attractive approach because it leads to circular dependency between the "core" OpenCV and extensions (which can be non-free or experimental).
There is another way to fix this issue without affecting feature2d classes. Making changes in xfeatures2d CMakeLists.txt as described here leads to generation of java wrappers for SIFT and SURF - opencv-310.jar has org.opencv.xfeatures2d package now. Some fix was required in /opencv/modules/java/generator/gen_java.py. Namely inserted 2 lines as shown below:
def addImports(self, ctype):
if ctype.startswith('vector_vector'):
self.imports.add("org.opencv.core.Mat")
self.imports.add("org.opencv.utils.Converters")
self.imports.add("java.util.List")
self.imports.add("java.util.ArrayList")
self.addImports(ctype.replace('vector_vector', 'vector'))
elif ctype.startswith('Feature2D'): #added
self.imports.add("org.opencv.features2d.Feature2D") #added
elif ctype.startswith('vector'):
self.imports.add("org.opencv.core.Mat")
self.imports.add('java.util.ArrayList')
if type_dict[ctype]['j_type'].startswith('MatOf'):
self.imports.add("org.opencv.core." + type_dict[ctype]['j_type'])
else:
self.imports.add("java.util.List")
self.imports.add("org.opencv.utils.Converters")
self.addImports(ctype.replace('vector_', ''))
After these changes wrappers are generated successfully. However the main problem still remains, how to use these wrappers from Java )). For example SIFT.create() gives the pointer to a new SIFT class but calling any class method (for instance detect()) crashes Java. I also noticed that using MSER.create() directly from Java leads to the same crash.
So it looks like the problem is isolated to the way how Feature2D.create() methods are wrapped in Java. The solution seems to be the following (again, changing /opencv/modules/java/generator/gen_java.py):
Find the string:
ret = "%(ctype)s* curval = new %(ctype)s(_retval_);return (jlong)curval->get();" % { 'ctype':fi.ctype }
Replace it with the following:
ret = "%(ctype)s* curval = new %(ctype)s(_retval_);return (jlong)curval;" % { 'ctype':fi.ctype }
Rebuild the opencv. That is it, all create() methods will start working properly for all children of Feature2D class including experimental and non-free methods. FeatureDescriptor/DescriptorExtractor wrappers can be deprecated I think as Feature2D is much easier to use.
BUT! I'm not sure if the suggested fix is safe for other OpenCV modules. Is there a scenario when (jlong)curval needs to be dereferenced? It looks like the same fix was suggested already here.