How to initialise a 2D array using CodeModel - sun-codemodel

I need to initialise a 2d array like below
Object[][] someName = {
{"param1","param2","param3"},
{"param4","param5","param6"}
};
I tried like
JExpression exp = JExpr.newArray(codeModel.ref(String.class)).add(JExpr.lit("param1").add(JExpr.lit("param2"));
methodBlock.decl(JMod.NONE, codeModel.ref(Object.class).array().array(), dataProviderName, exp);
but it initilases 1d array,
any help is appreciated

It might not be exactly the same, but the following code initializes the example 2d array:
JDefinedClass testClass = codeModel._class("TestClass");
JMethod runme = testClass.method(JMod.PUBLIC, codeModel.VOID, "runme");
JBlock methodBlock = runme.body();
JExpression exp = JExpr.newArray(codeModel.ref(String.class).array())
.add(JExpr.newArray(codeModel.ref(String.class))
.add(JExpr.lit("param1")).add(JExpr.lit("param2")).add(JExpr.lit("param3")))
.add(JExpr.newArray(codeModel.ref(String.class))
.add(JExpr.lit("param4")).add(JExpr.lit("param5")).add(JExpr.lit("param6")));
methodBlock.decl(JMod.NONE, codeModel.ref(Object.class).array().array(), "someName", exp);
This generates the following, which explicitly declares the inner arrays:
public class TestClass {
public void runme() {
Object[][] someName = new String[][] {new String[] {"param1", "param2", "param3"}, new String[] {"param4", "param5", "param6"}};
}
}
The code you tried was almost correct, you just needed to declare the array within the newArray() call: JExpr.newArray(codeModel.ref(String.class).array())

Related

How to get the same attribute from all objects in a list in one line

I have a list of objects of the same class.
This class contains an attribute I want to use.
I would like to get a list of all these attributes in one line. Is this possible?
Here is a small example: I just want a list of all the colors.
It is important that I return directly a list of these attributes, without the normal forEach statement.
void main() {
List<Car> listOfCars = [
Car('blue'),
Car('green'),
Car('yellow'),
];
}
//List<String> listOfColors = listOfCars[all].color;
class Car{
String color;
Car(this.color);
}
You can use the map function to achieve this
List<String> listOfColors = listOfCars.map((car) => car.color).toList();
print(listOfColors);
Just check out this code below:
void main() {
List<Car> listOfCars = [
Car('blue'),
Car('green'),
Car('yellow'),
];
List<String> stringList = List();
// This is where you get the single car object and then you add it the list of string
for (int i = 0; i < listOfCars.length; i++) {
stringList.add(listOfCars[i].color);
}
// this is the desired out put i have just printed your list :
print('This is the string length : ' + stringList.length.toString());
for (int i = 0; i < stringList.length; i++) {
print('This is the string list :' + stringList[i]);
}
}
class Car {
final String color;
Car(this.color);
}
Blow is the output :
This is the string length : 3
This is the string list :blue
This is the string list :green
This is the string list :yellow

How to get a Java string from a char pointer in C++

I am porting the openvr sample to jogl, after we created the binding with jna.
Almost at the end (before rendering the controllers and the tracking base stations), I got stuck trying to translate a char pointer in C to a String in Java.
C++ code here:
//-----------------------------------------------------------------------------
// Purpose: Helper to get a string from a tracked device property and turn it
// into a std::string
//-----------------------------------------------------------------------------
std::string GetTrackedDeviceString( vr::IVRSystem *pHmd, vr::TrackedDeviceIndex_t unDevice, vr::TrackedDeviceProperty prop, vr::TrackedPropertyError *peError = NULL )
{
uint32_t unRequiredBufferLen = pHmd->GetStringTrackedDeviceProperty( unDevice, prop, NULL, 0, peError );
if( unRequiredBufferLen == 0 )
return "";
char *pchBuffer = new char[ unRequiredBufferLen ];
unRequiredBufferLen = pHmd->GetStringTrackedDeviceProperty( unDevice, prop, pchBuffer, unRequiredBufferLen, peError );
std::string sResult = pchBuffer;
delete [] pchBuffer;
return sResult;
}
GetStringTrackedDeviceProperty here:
/** Returns a string property. If the device index is not valid or the property is not a string type this function will
* return 0. Otherwise it returns the length of the number of bytes necessary to hold this string including the trailing
* null. Strings will generally fit in buffers of k_unTrackingStringSize characters. */
virtual uint32_t GetStringTrackedDeviceProperty( vr::TrackedDeviceIndex_t unDeviceIndex, ETrackedDeviceProperty prop, VR_OUT_STRING() char *pchValue, uint32_t unBufferSize, ETrackedPropertyError *pError = 0L ) = 0;
Where VR_OUT_STRING() is defined here as:
# define VR_CLANG_ATTR(ATTR)
#define VR_OUT_STRING() VR_CLANG_ATTR( "out_string: ;" )
I have already done something similar where I had to call a function that expect the pointer to an array of TrackedDevicePose_t structures:
private TrackedDevicePose_t.ByReference trackedDevicePosesReference = new TrackedDevicePose_t.ByReference();
public TrackedDevicePose_t[] trackedDevicePose
= (TrackedDevicePose_t[]) trackedDevicePosesReference.toArray(VR.k_unMaxTrackedDeviceCount);
I created first the reference and then from it the actual array.
But here I can't have a class extending the char array..
private String getTrackedDeviceString(IVRSystem hmd, int device, int prop, IntBuffer propError) {
int requiredBufferLen = hmd.GetStringTrackedDeviceProperty.apply(device, prop, Pointer.NULL, 0, propError);
if(requiredBufferLen == 0) {
return "";
}
CharArray.ByReference charArrayReference = new CharArray.ByReference();
char[] cs = charArrayReference.toArray(requiredBufferLen);
return null;
}
Where apply (here) is:
public interface GetStringTrackedDeviceProperty_callback extends Callback {
int apply(int unDeviceIndex, int prop, Pointer pchValue, int unBufferSize, IntBuffer pError);
};
CharArray class, crap attempt here
Any ideas?
I've done some porting of C and C++ code to Java, and while it's probably horribly hacky, the best I've come up with to solve cases where a pointer to an int primitive or a char*/String is needed for a function call, is to create a small wrapper class with a single property, pass that object into the function, change the property as needed, and retrieve the new value after the function call. So something like:
public class StringPointer {
public String value = "";
}
StringPointer pchBuffer = new StringPointer();
unRequiredBufferLen = pHmd.GetStringTrackedDeviceProperty( unDevice, prop, pchBuffer, unRequiredBufferLen, peError );
String sResult = pchBuffer.value;
and inside GetStringTrackedDeviceProperty()
...
pchValue.value = "some string";
...
In this case, you can use a String, since that's what your code is doing with the char* after the function call, but if it actually really needs to be a char[], you can just create char[] pchBuffer = new char[unRequiredBufferLen]; and pass that into the function. It will be just like you were using a char* in C++, and any changes you make inside the array will be visible after the function ends, and you can even do String sResult = new String(pchBuffer);.

Can't Access Properties From Object Stored In Vector

Hey hey I'm a c++ newb here... i would appriciate someone pointing out an apparent misunderstanding i have about pointers and vectors (may be something else). I'm trying to create a switch element that handles several sub states
class MotionSwitch: public StateSwitch, public IMotion
{
public:
MotionSwitch(){ initialize(); };
~MotionSwitch(){};
//Make Motion States
MotionState restState; //Initialized In _states at 0
MotionState motionState;//" " 1
MotionState spinState;//" " 2
std::vector<MotionState*> _states;
};
class MotionState: public State, public IMotion
{
...
String msg = "Hello Is Motion";
...
};
The _states vector is initialized like this...
void MotionSwitch::initialize()
{
//Add States In Order Of ENUM (Because It Matters!)
_states.push_back(&restState);
_states.push_back(&motionState);
_states.push_back(&spinState);
}
The in following application code only one of the following will print
MotionState *currentState = widget._motionSwitch._states.at(0);
widget._com.log( "State Message...");
widget._com.log( currentState -> msg); //Won't Print
widget._com.log( widget._motionSwitch.restState.msg ); //This WILL Print
I would appreciate any help i can get here from you code gods!

List and Map in java programing

I need to convert:
List<Map>([{1,2},{2,3}])
To:
List<List>([[1,2],[2,3]])
Can anyone help me with example for this ...
Thanks
I would suggest making a list of specific objects instead of a raw list that the get(0) returns the key and get(1) the value as follows:
List<List<Pair>> convert(List<Map<Integer,Integer> mapList){
List<List<Pair>> listOfList = new ArrayList<List<Pair>>();
for(Map<Integer,Integer> map:mapList){
List<Pair> list = new ArrayList<Pair>();
for(Entry<Integer,Integer> e:map.entrySet()){
list.add(Pair(e.getKey(),e.getValue());
}
listOfList.add(list);
}
return listOfList;
}
class Pair{
Integer first;
Integer second;
//constructor
}
You can try the following Code:
import java.util.*;
class ListOfMapToListOfList
{
public static List<List> toList(List<Map<Integer,Integer>> lList)//method to convert List<Map> to List<List>
{
List<List> list = new ArrayList<List>();
for (int i = 0 ; i < lList.size() ; i++)
{
Map<Integer,Integer> map = lList.get(i);
List<Integer> aList = new ArrayList<Integer>();
Set<Integer> keySet = map.keySet();
for (Integer key : keySet)
{
aList.add(key);
aList.add(map.get(key));
}
list.add(aList);
}
return list;
}
public static void main(String[] args) //main body
{
List<Map<Integer,Integer>> list1 = new ArrayList<Map<Integer,Integer>>();
Map<Integer,Integer> map1 = new HashMap<Integer,Integer>();
map1.put(1,2);
Map<Integer,Integer> map2 = new HashMap<Integer,Integer>();
map2.put(1,2);
list1.add(map1);list1.add(map2);
System.out.println(list1);
System.out.println(toList(list1));//Conversion is done here..and out put is shown.
}
}

How do I pass a list of objects from C++ to Lua?

I'm the lead dev for Bitfighter, and am adding user-scripted bots using Lua. I'm working with C++ and Lua using Lunar to glue them together.
I'm trying to do something that I think should be pretty simple: I have an C++ object in Lua (bot in the code below), and I call a method on it that (findItems) which causes C++ to search the area around the robot and return a list of objects it finds (TestItems and others not shown here). My question is simply how do I assemble and return the list of found items in C++, and then iterate over them in Lua?
Basically, I want to fill in the <<<< Create list of items, return it to lua >>>> block below, and make any corrections I may need in the Lua code itself, included below that.
I've tried to keep the code simple but complete. Hope there's not too much here! Thanks!
C++ Header file
class TestItem : public LuaObject
{
public:
TestItem(); // C++ constructor
///// Lua Interface
TestItem(lua_State *L) { } ; // Lua constructor
static const char className[];
static Lunar<TestItem>::RegType methods[];
S32 getClassID(lua_State *L) { return returnInt(L, TestItemType); }
};
class LuaRobot : public Robot
{
LuaRobot(); // C++ constructor
///// Lua Interface
LuaRobot(lua_State *L) { } ; // Lua constructor
static const char className[];
static Lunar<LuaRobot>::RegType methods[];
S32 findItems(lua_State *L);
}
C++ .cpp file
const char LuaRobot::className[] = "Robot"; // Class name in Lua
// Define the methods we will expose to Lua
Lunar<LuaRobot>::RegType LuaRobot::methods[] =
{
method(LuaRobot, findItems),
{0,0} // End method list
};
S32 LuaRobot::findItems(lua_State *L)
{
range = getIntFromStack(L, 1); // Pop range from the stack
thisRobot->findObjects(fillVector, range); // Put items in fillVector
<<<< Create list of items, return it to lua >>>>
for(int i=0; i < fillVector.size(); i++)
do something(fillVector[i]); // Do... what, exactly?
return something;
}
/////
const char TestItem::className[] = "TestItem"; // Class name in Lua
// Define the methods we will expose to Lua
Lunar<TestItem>::RegType TestItem::methods[] =
{
// Standard gameItem methods
method(TestItem, getClassID),
{0,0} // End method list
};
Lua Code
bot = LuaRobot( Robot ) -- This is a reference to our bot
range = 10
items = bot:findItems( range )
for i, v in ipairs( items ) do
print( "Item Type: " .. v:getClassID() )
end
So you need to fill a vector and push that to Lua.
Some example code follows. Applications is a std::list.
typedef std::list<std::string> Applications;
I create a table and fill it with the data in my list.
int ReturnArray(lua_State* L) {
lua_createtable(L, applications.size(), 0);
int newTable = lua_gettop(L);
int index = 1;
Applications::const_iterator iter = applications.begin();
while(iter != applications.end()) {
lua_pushstring(L, (*iter).c_str());
lua_rawseti(L, newTable, index);
++iter;
++index;
}
return 1;
}
This leaves me with an array in the stack. If it were returned to Lua, then I could write the following:
for k,v in ipairs( ReturnArray() ) do
print(v)
end
Of course so far, this just gets me a Lua array of strings. To get an array of Lua objects we just tweak your method a bit:
S32 LuaRobot::findItems(lua_State *L)
{
range = getIntFromStack(L, 1); // Pop range from the stack
thisRobot->findObjects(fillVector, range); // Put items in fillVector
// <<<< Create list of items, return it to lua >>>>
lua_createtable(L, fillVector.size(), 0);
int newTable = lua_gettop(L);
for(int i=0; i < fillVector.size(); i++) {
TestItem* item = fillVector[i];
item->push(L); // put an object, not a string, in Lua array
lua_rawseti(L, newTable, i + 1);
}
return 1;
}
This works perfectly. To clarify to others who are reading this, the method
item->push(L)
is
void push(lua_State *L) { Lunar<TestItem>::push(L, this); }
By encapsulating this in a method, it's possible to make the findItems agnostic to what it's finding.
Thank you for the help!