rJava: calling a Java function to retrieve a list of objects - rjava

I need to get in R a list of objects from Java. In the code below I succeeded in getting the list in R (the length of the list is correct) but I cannot see the objects content.
This class represents the objects:
package mypackage;
public class ValueObject
public String s;
public int i;
}
This class returns the list of objects:
package mypackage;
public class MyClass {
public ValueObject [] test(){
ValueObject [] array = new ValueObject [3];
ValueObject a = new ValueObject();
a.i = 1;
a.s = "A";
array[0] = a;
ValueObject b = new ValueObject();
b.i = 2;
b.s = "B";
array[1] = b;
ValueObject c = new ValueObject();
c.i = 3;
c.s = "C";
array[2] = c;
return array;
}
}
And I run it in R, like so:
obj = .jnew("mypackage/MyClass")
x = .jcall(obj,"[Lmypackage/ValueObject;","test")
print(length(x)) shows 3, meaning that the objects are there. But I can't figure out how to access the data in the objects. I tried:
x[1]$s
x[1]["s"]
x[1]#s
and always get NULL. what's wrong with this code?

this does the trick:
print(x[[1]]$s)

Related

Sort a List<object> by two properties one in ascending and the other in descending order in dart

I saw examples where I can sort a list in dart using one property in flutter(dart).
But how can I do the functionality which an SQL query does like for example:
order by points desc, time asc
You can sort the list then sort it again..
Here is a sample I made from dartpad.dev
void main() {
Object x = Object(name: 'Helloabc', i: 1);
Object y = Object(name: 'Othello', i: 3);
Object z = Object(name: 'Avatar', i: 2);
List<Object> _objects = [
x, y, z
];
_objects.sort((a, b) => a.name.length.compareTo(b.name.length));
/// second sorting
// _objects.sort((a, b) => a.i.compareTo(b.i));
for (Object a in _objects) {
print(a.name);
}
}
class Object {
final String name;
final int i;
Object({this.name, this.i});
}
I was able to find an answer for this. Thanks to #pskink and the url
https://www.woolha.com/tutorials/dart-sorting-list-with-comparator-and-comparable.
I implemented the Comparable to sort by the two properties.
class Sample implements Comparable<Sample> {
final int points;
final int timeInSeconds;
Sample(
{
this.points,
this.timeInSeconds});
#override
int compareTo(Sample other) {
int pointDifference = points- other.points;
return pointDifference != 0
? pointDifference
: other.timeInSeconds.compareTo(this.timeInSeconds);
}
}
sampleList.sort();

Class method accepting derived classes in Chapel

Consider the following code where I wish to store instances of a class (Class2 here) and its derived classes (Class3 here) in an array residing in another class (Class1 here). As notated, the compiler is not happy with the final line. What am I doing wrong?
class Class2 {
var y : int;
}
class Class3 : Class2 {
var z : int;
}
class Class1 {
var count : int;
var x : [0..10] owned Class2?;
proc add(ref a : Class2) {
x[count] = a;
count += 1;
}
}
var C1 = new owned Class1();
var C2 = new owned Class2();
var C3 = new owned Class3();
C1.add(C2); // OK
C1.add(C3); // Compiler not happy
Compiler output:
test2.chpl:25: error: unresolved call 'owned Class1.add(owned Class3)'
test2.chpl:14: note: this candidate did not match: Class1.add(ref a: Class2)
test2.chpl:25: note: because call actual argument #1 with type owned Class3
test2.chpl:14: note: is passed to formal 'ref a: owned Class2'
$CHPL_HOME/modules/internal/Atomics.chpl:557: note: candidates are: AtomicT.add(value: T, param order: memoryOrder = memoryOrder.seqCst)
$CHPL_HOME/modules/internal/NetworkAtomics.chpl:280: note: RAtomicT.add(value: T, param order: memoryOrder = memoryOrder.seqCst)
note: and 4 other candidates, use --print-all-candidates to see them
Try using the in intent instead of the ref intent on proc add:
class Class2 {
var y : int;
}
class Class3 : Class2 {
var z : int;
}
class Class1 {
var count : int;
var x : [0..10] owned Class2?;
proc add(in a : Class2) {
x[count] = a;
count += 1;
}
}
var C1 = new owned Class1();
var C2 = new owned Class2();
var C3 = new owned Class3();
C1.add(C2); // OK
C1.add(C3); // OK!
Why does this matter? It's not type-safe to pass a reference to a subclass (Class3) to an argument expecting a reference to a parent class (Class2). In particular you could imagine the method changing the class pointer to be a Class2 but not a Class3, and that could lead to other errors at the call site.
My guess is that the add function was using the ref intent just to enable ownership transfer from C3. The in intent is a better way to do that and supports passing a subtype (because the type error situation described above is not possible).

LINQ and removing duplicates from an array of objects

I'm trying to de-dupe an array of objects using two columns where the second column is a Dictionary. Best way to describe this is to show some code:
class MyClass
{
public int ID;
public Dictionary<int, int> Dict = new Dictionary<int, int>();
}
And now to create some objects:
List<MyClass> list = new List<MyClass>();
MyClass mc1 = new MyClass();
list.Add(mc1); mc1.ID = 1; mc1.Dict.Add(1, 1);
MyClass mc2 = new MyClass();
list.Add(mc2); mc2.ID = 1; mc2.Dict.Add(1, 1);
MyClass mc3 = new MyClass();
list.Add(mc3); mc3.ID = 1; mc3.Dict.Add(1, 2);
MyClass mc4 = new MyClass();
list.Add(mc4); mc4.ID = 2; mc4.Dict.Add(1, 1);
What I'm looking to accomplish is to distinct by ID and Dict. The results should look like this:
List of MyClass objects (not pretty)
1 //MyClass.ID
1,1 //MyClass.Dictionary
1
1,2
2
1,1
Notice that one of the objects was dropped from the original list because it had a duplicate ID and Dict (dictionary values). I've been playing around with alternate versions of:
var s = from p in list
group p by p.ID into group1
from group2 in
(from p in group1 group p by p.Dict)
group group2 by group1.Key;
but just haven't had any luck. Appreciate any insight folks might have on solving this problem.
PS - I'm not changing the rules but I believe a GROUP BY and a SELECTFIRST will be cleaner than a DISTINCT with its extra code for a Comparer. A pat on the back for anyone who can figure this out using GROUP BY.
For reference types you should add equality comparer in order to do what you want. Add the following class:
public class MyClassComparer : IEqualityComparer<MyClass>
{
public bool Equals(MyClass left, MyClass right)
{
if (left == null && right == null)
{
return true;
}
if (left == null || right == null)
{
return false;
}
if (left.ID == right.ID)
{
if (left.Dict == null && right.Dict == null)
{
return true;
}
if (left.Dict == null || right.Dict == null)
{
return false;
}
if (left.Dict.Count != right.Dict.Count)
{
return false;
}
foreach(var key in left.Dict.Keys)
{
if(!right.Dict.ContainsKey(key))
return false;
if (left.Dict[key] != right.Dict[key])
return false;
}
return true;
}
else return false;
}
public int GetHashCode(MyClass author)
{
return (author.ID).GetHashCode();
}
}
And use that comparer in Distinct override:
List<MyClass> list = new List<MyClass>();
MyClass mc1 = new MyClass();
list.Add(mc1); mc1.ID = 1; mc1.Dict.Add(1, 1);
MyClass mc2 = new MyClass();
list.Add(mc2); mc2.ID = 1; mc2.Dict.Add(1, 1);
MyClass mc3 = new MyClass();
list.Add(mc3); mc3.ID = 1; mc3.Dict.Add(1, 2);
MyClass mc4 = new MyClass();
list.Add(mc4); mc4.ID = 2; mc4.Dict.Add(1, 1);
var result = list.Distinct(new MyClassComparer()).ToList();
You should improve GetHashCode method. It will be your homework :)
Can I have half a pat for the following ? :)
var filteredList = list.GroupBy(mc => mc.ID)
.SelectMany(gr => gr.Distinct(new MyClassComparer()))
.ToList();
Comparer:
public class MyClassComparer : IEqualityComparer<MyClass>
{
public bool Equals(MyClass a, MyClass b)
{
return a.Dict.Count == b.Dict.Count && !a.Dict.Except(b.Dict).Any();
}
public int GetHashCode(MyClass a)
{
return a.ID;
}
}

How can I post a list then access it in my controller?

I created a list property in my model like so
public virtual List<String> listOfDays { get; set; }
then I converted and stored it in the list like this:
for (int i = 0; i < 30 i++)
{
var enrollment = new Enrollment();
enrollment.StudentID = id;
enrollment.listOfDays = searchString.ToList();
db.Enrollments.Add(enrollment);
db.SaveChanges();
}
I put a breakpoint here... enrollment.listOfDays = searchString.ToList(); ... and all is well. I see that the conversion was performed and I can see the values in listOfDays.
So I thought I would find a column in my database called listOfDays since I'm doing code first but the property is not there.
Then I thought I'd try accessing it anyway like this...
var classdays = from e in db.Enrollments where e.StudentID == id select e.listOfDays;
var days = classdays.ToList();
//here I get an error message about this not being supported in Linq.
Questions:
Why do you think the property was not in the database?
How can I post this array to my model then access it in a controller?
Thanks for any help.
Thanks to Decker: http://forums.asp.net/members/Decker%20Dong%20-%20MSFT.aspx
Here’s how it works:
Using form collection here…
In [HttpPost]…
private void Update (FormCollection formCollection, int id)
for (int sc = 0; sc < theSelectedCourses.Count(); sc++)
{
var enrollment = new Enrollment();
enrollment.CourseID = Convert.ToInt32(theSelectedCourses[sc]);
enrollment.StudentID = id;
enrollment.listOfDays = formCollection["searchString"] ;//bind this as a string instead of a list or array.
Then in [HttpGet]…
private void PopulateAssignedenrolledData(Student student, int id)
{
var dayList = from e in db.Enrollments where e.StudentID == id select e;
var days = dayList.ToList();
if (days.Count > 0)
{
string dl = days.FirstOrDefault().listOfDays;
string[] listofdays = dl.Split(',');
ViewBag.classDay = listofdays.ToList();
}
Thanks to Decker: http://forums.asp.net/members/Decker%20Dong%20-%20MSFT.aspx
Here’s how it works:
Using form collection here…
In [HttpPost]…
private void Update (FormCollection formCollection, int id)
for (int sc = 0; sc < theSelectedCourses.Count(); sc++)
{
var enrollment = new Enrollment();
enrollment.CourseID = Convert.ToInt32(theSelectedCourses[sc]);
enrollment.StudentID = id;
enrollment.listOfDays = formCollection["searchString"] ;//bind this as a string instead of a list or array.
Then in [HttpGet]…
private void PopulateAssignedenrolledData(Student student, int id)
{
var dayList = from e in db.Enrollments where e.StudentID == id select e;
var days = dayList.ToList();
if (days.Count > 0)
{
string dl = days.FirstOrDefault().listOfDays;
string[] listofdays = dl.Split(',');
ViewBag.classDay = listofdays.ToList();
}

Linq PredicateBuilder

public static IQueryable<SearchProfile> FilterData(string Filter, Repository<SearchProfileContext> dc)
{
IQueryable<SearchProfile> data = null;
var predicate = PredicateBuilder.True<SearchProfile>();
Filter = ExcludedParam(Filter);
if (!string.IsNullOrEmpty(Filter))`enter code here`
{
var stringToSplit = Filter;`enter code here`
List<string[]> arrays = new List<string[]>();
var primeArray = stringToSplit.Split('|');
for (int i = 0; i < primeArray.Length; i++)
{
string first = primeArray[i];
if (first.Contains("chkOrientation") == true)
{
string[] Array = first.Replace("chkOrientation=", "").Split(',');
predicate = predicate.And(a => Array.Contains(a.OrientaionID.ToString()));
}
if (first.Contains("chkProfession") == true)
{
string[] Array = first.Replace("chkProfession=", "").Split(',');
**predicate = predicate.And(a => Array.Contains(SqlFunctions.StringConvert((Double)a.ProfessionID)));**
}
}
data = dc.Select<SearchProfile>().Where(predicate).Distinct();
return data;
}
data = (from a in dc.Select<SearchProfile>().Where(a => a.PersonID > 0) select a).Distinct();
return data;
}
When I ran my program, I got this nasty error below:
LINQ to Entities does not recognize the method Int32 ToInteger(System.Object) method, and this method cannot be translated into a store expression.
then,I used SqlFunctions.StringConvert to make it work but the SQL LINQ generated was not evaluating. This is the sample output (it is comparing '1' and '2' instead of 1 and 2)**
Why are you casting a.ProfessionID to double? What type is a.ProfessionID of?
I think there is implicit conversion to integer, which causes calling the ToInteger method.
And why don't you convert items in Array to integer in the first place, and then use Array of ints in the query?

Resources