I'm trying to make quite simple game, you're just wandering in rooms, when you use the door you get to other room.
Here's how it looks
i use this simple if to change
if(input.isKeyDown(Input.KEY_UP)) {
sprite = up;
if(!isBlocked(x,y - delta * 0.1f) && y > 0) {
sprite.update(delta); // lower delta = lower speed animation
y -= delta * 0.1f;
}
if(isDoor(x,y - delta * 0.1f)) {
currentMap = currentRoom.getNorth().getMap();
currentRoom = currentRoom.getNorth();
}
}
"currentMap" is TiledMap which currently is being rendered. "currentRoom" is current Room who has TiledMap inside it, because i need some more stuff to store about room. And the problem is that when i go to door, game immediately shuts down with null pointer, however before crashing i can see a glimpse that map is changed.
Full error report:
ERROR:null
java.lang.NullPointerException
at not.zuul.world.GameMain.update(GameMain.java:143)
at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:663)
at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:411)
at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:321)
at not.zuul.world.GameMain.main(GameMain.java:40)
Sat Oct 25 21:18:51 CEST 2014 ERROR:Game.update() failure - check the game code.
org.newdawn.slick.SlickException: Game.update() failure - check the game code.
at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:669)
at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:411)
at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:321)
at not.zuul.world.GameMain.main(GameMain.java:40)
Some additional code, these are called on init. Rooms - hashmap of strings containing letter for what direction doors it has (key) , and tiledmap for value ( there 15 diferrent rooms because of diferrent door combinations.
And game_map is again hashmap with String (name) for key and class Room for value. and i use "setRooms" to set "neighbour" for that room, or in other where those doors leads, order is (north, south, east, west)
public void initAllRooms() throws SlickException {
rooms = new HashMap<String, TiledMap>();
rooms.put("N", new TiledMap("resources/map/Rooms/room_north.tmx"));
rooms.put("S", new TiledMap("resources/map/Rooms/room_south.tmx"));
rooms.put("E", new TiledMap("resources/map/Rooms/room_east.tmx"));
rooms.put("W", new TiledMap("resources/map/Rooms/room_west.tmx"));
rooms.put("NE", new TiledMap("resources/map/Rooms/room_north_east.tmx"));
rooms.put("NS", new TiledMap("resources/map/Rooms/room_north_south.tmx"));
rooms.put("NW", new TiledMap("resources/map/Rooms/room_north_west.tmx"));
rooms.put("SE", new TiledMap("resources/map/Rooms/room_south_east.tmx"));
rooms.put("SW", new TiledMap("resources/map/Rooms/room_south_west.tmx"));
rooms.put("EW", new TiledMap("resources/map/Rooms/room_east_west.tmx"));
rooms.put("NSE", new TiledMap("resources/map/Rooms/room_north_south_east.tmx"));
rooms.put("NSW", new TiledMap("resources/map/Rooms/room_north_south_west.tmx"));
rooms.put("NEW", new TiledMap("resources/map/Rooms/room_north_east_west.tmx"));
rooms.put("SEW", new TiledMap("resources/map/Rooms/room_south_east_west.tmx"));
rooms.put("NSEW", new TiledMap("resources/map/Rooms/room_north_south_east_west.tmx"));
}
public void initMap() throws SlickException {
game_map = new HashMap<String, Room>();
game_map.put("outside", new Room(rooms.get("N"), "You're outside."));
game_map.put("mainHall", new Room(rooms.get("NSEW"), "You're in main hall."));
game_map.put("emptyRoom", new Room(rooms.get("NE"), "You're in empty room."));
game_map.put("bathRoom", new Room(rooms.get("S"), "You're in bathroom"));
game_map.put("kitchen", new Room(rooms.get("NW"), "You're in kitchen"));
game_map.put("diningRoom", new Room(rooms.get("NS"), "You;re in dining room"));
game_map.put("backYard", new Room(rooms.get("SE"), "You're in back yard"));
game_map.put("storageRoom", new Room(rooms.get("W"), "You're in storage room"));
game_map.get("outside").setRooms(game_map.get("mainHall"), null, null, null);
game_map.get("mainHall").setRooms(game_map.get("diningRoom"), game_map.get("outside"),
game_map.get("emptyRoom"), game_map.get("kitchen"));
game_map.get("emptyRoom").setRooms(game_map.get("bathRoom"), null, game_map.get("mainHall"), null );
game_map.get("bathRoom").setRooms(null, game_map.get("emptyRoom"), null, null);
game_map.get("kitchen").setRooms(null, null, null, game_map.get("mainHall"));
game_map.get("diningRoom").setRooms(game_map.get("backYard"), game_map.get("mainHall)"), null, null);
game_map.get("backYard").setRooms(null, game_map.get("diningRoom"), game_map.get("storageRoom"), null);
game_map.get("storageRoom").setRooms(null, null, null, game_map.get("backYard"));
}
Can't really help unless you provide the stacktrace and the line(s) the stacktrace is coming from.
EDIT: Still need to see what line the crash is occurring on.
Related
Null Pinter Exception simply means that it is because of value is getting null. But In case of using APis such as GeoTiff it becomes annoying to find out the error in usage.
My code is as follows:
System.out.println("vectorization starts");
GridCoverage2D srcCoverage = new GeoTiffReader(new File("E:/output/ll_processed.TIFF")).read(new GeneralParameterValue[]{policy, gridsize, useJaiRead});
SimpleFeatureCollection fc = RasterToVectorProcess.process(srcCoverage, 3, cov.getEnvelope(), Collections.singletonList(0.0d), true, null);
System.out.println("process ends");
System.out.println("vectorization ends");
//MapContext map = new DefaultMapContext();
//map.setTitle("raster to vector conversion");
Style style = SLD.createPolygonStyle(Color.BLUE, Color.CYAN, 1.0f);
//map.addLayer(fc, style);
//map.getLayerBounds();
//JMapFrame.showMap(map);
MapContent mapContent= new MapContent();
mapContent.setTitle("Illegal Mining");
Layer layer = new FeatureLayer(fc, style,"VectorLayer");
//int boundary = 10;
// ReferencedEnvelope env2 = new ReferencedEnvelope(srcCoverage.getEnvelope().getMinimum(0) - boundary, srcCoverage.getEnvelope().getMaximum(0) + boundary,
//srcCoverage.getEnvelope().getMinimum(1) - boundary, srcCoverage.getEnvelope().getMaximum(1) + boundary, srcCoverage.getCoordinateReferenceSystem());
//mapContent.getViewport().setBounds(fc.getBounds());
Line 199 : if(layer.getBounds()!=null) // here the error is coming also tried with if(layer != null && layer.getBounds()!=null)
{
mapContent.addLayer(layer);
}else{
System.out.println("Layer bounds are null");
}
mapContent.getViewport().setCoordinateReferenceSystem(
DefaultGeographicCRS.WGS84);
Error
at org.geotools.map.FeatureLayer.getBounds(FeatureLayer.java:199)
I am trying to convert Tiff to Vector image and Then I want to store it on disk.
Most likely, your featureSource is null, since the geotools FeatureLayer class method getBounds() uses the featureSource to retrieve the bounds, but in the constructor FeatureLayer doesn't check whether the featureSource is null.
The featureSource is the first argument to the constructor of FeatureLayer. In your case, that's variable SimpleFeatureCollection fc.
Most likely, the method process.process returned null so fc is null.
Minor Change in RasterToVectorProcess.java
//features.add(builder.buildFeature(null));
//System.out.println("ignored");
//add
System.out.println("adding...");
SimpleFeature feature = builder.buildFeature(null);
((Collection<SimpleFeature>) features).add(feature);
Like you see in this code, I want to get all the information about friends in twitter, people I follow.
But doing this :
PagableResponseList<User> users = twitter.getFriendsList(USER_ID, CURSOR);
... only gives me the first 20 recent friends... What can I do?
Complete code about it :
PagableResponseList<User> users = twitter.getFriendsList(USER_ID, CURSOR);
User user = null;
max = users.size();
System.out.println("Following: "+max);
for (int i = 0 ; i < users.size() ; i++){
user = users.get(i);
System.out.print("\nID: "+user.getId()+" / User: "+user.getName()+" /");
System.out.print("\nFollowers: "+user.getFollowersCount()+"\n");
tid.add(Long.parseLong(String.valueOf(user.getId())));
tusername.add(user.getName());
tfollowers.add(Long.parseLong(String.valueOf(user.getFollowersCount())));
tname.add(user.getScreenName());
}
Thanks..
you can try this code to get the list of people you follow.
long cursor = -1;
PagableResponseList<User> users;
while ((cursor = followers.getNextCursor()) != 0);
{
users = twitter.getFriendsList(userId, cursor);
}
I've taken a peek at the documentation at Twitter4J and Twitter themselves and it's all about that cursor.
To prevent you're getting loaded with a whole bunch of friends at once, Twitter only returns the first 20 results. It doesn't return just the first 20 results, but it also returns a cursor. That cursor is just a random number that's managed by Twitter. When you make a call again and pass this cursor, the next 20 entries (friends) will be returned, again with a cursor that's different now. You can repeat this until the cursor returned is zero. That means there are no more entries available.
In case you want to know more, check these two links: Twitter DEV and Twitter4J documentation.
Concerning your Java, you just need to find a way to get the current cursor, and pass that cursor to your method again, making the app load the next 20 entries. According to this piece of information, that should do the trick.
List<User> allUsers = new ArrayList<User>();
PagableResponseList<User> users;
long cursor = -1;
while (cursor != 0) {
users = twitter.getFriendsList(USER_ID, cursor);
cursor = users.getNextCursor();
allUsers.add(users);
}
You should be able to request up to 200 results at a time:
final PagableResponseList<User> users = twitter.getFriendsList(USER_ID, cursor, 200);
cursor = users.getNextCursor();
If you need to start from where you left off between invocations of your program then you need to store the value of cursor somewhere.
Improvements to Sander's answer!
You can set a count value to the getFriendsList method as in Jonathan's Answer. The maximum value allowed for count is 200. The loop construct will help to collect more than 200 friends now. 200 friends per page or per iteration!
Yet, there are rate limits for any request you make. The getFriendsList method will use this api endpoint: GET friends/list which has a rate limit of 15 hits per 15 minutes. Each hit can fetch a maximum of 200 friends which equates to a total of 3000 friends (15 x 200 = 3000) per 15 minutes. So, there will be no problem if you have only 3000 friends. If you have more than 3000 friends, an exception will be thrown. You can use the RateLimitStatus class to avoid that exception. The following code is an example implementation to achieve this.
Method 1: fetchFriends(long userId)
public List<User> fetchFriends(long userId) {
List<User> friends = new ArrayList<User>();
PagableResponseList<User> page;
long cursor = -1;
try {
while (cursor != 0) {
page = twitter.getFriendsList(userId, cursor, 200);
friends.addAll(page);
System.out.println("Total number of friends fetched so far: " + friends.size());
cursor = page.getNextCursor();
this.handleRateLimit(page.getRateLimitStatus());
}
} catch (TwitterException e) {
e.printStackTrace();
}
return friends;
}
Method 2: handleRateLimit(RateLimitStatus rls)
private void handleRateLimit(RateLimitStatus rls) {
int remaining = rls.getRemaining();
System.out.println("Rate Limit Remaining: " + remaining);
if (remaining == 0) {
int resetTime = rls.getSecondsUntilReset() + 5;
int sleep = (resetTime * 1000);
try {
if(sleep > 0) {
System.out.println("Rate Limit Exceeded. Sleep for " + (sleep / 1000) + " seconds..");
Thread.sleep(sleep);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
By doing so, your program will sleep for some time period based on the rate limiting threshold. It will continue to run from where it left after the sleep. This way we can avoid our program stopping in the midway of collecting friends counting more than 3000.
I have the solution to my post... thanks to Sander, give me some ideas...
The thing was change the for to while ((CURSOR = ids.getNextCursor()) != 0);.
And... user = twitter.showUser(id);
Playing with showUser makes it possible to get, with a slowly time, all the info about all my friends...
That's all. Don't use user.get(i);
I am beginner in java and Weka tool, I want to use Logitboost algorithm with DecisionStump as weak learner in my java code, but I don't know how do this work. I create a vector with six feature(without label feature) and I want feed it into logitboost for labeling and probability of its assignment. Labels are 1 or -1 and train/test data is in an arff file.This is my code, but algorithm always return 0 !
Thanks
double candidate_similarity(ha_nodes ha , WeightMatrix[][] wm , LogitBoost lgb ,ArrayList<Attribute> atts){
LogitBoost lgb = new LogitBoost();
lgb.buildClassifier(newdata);//newdata is an arff file with some labeled data
Evaluation eval = new Evaluation(newdata);
eval.crossValidateModel(lgb, newdata, 10, new Random(1));
try {
feature_vector[0] = IP_sim(Main.a_new.dip, ha.candidate.dip_cand);
feature_vector[1] = IP_sim(Main.a_new.sip, ha.candidate.sip_cand);
feature_vector[2] = IP_s_d_sim(Main.a_new.sip, ha);
feature_vector[3] = Dport_sim(Main.a_new.dport, ha);
freq_weight(Main.a_new.Atype, ha, freq_avg, weight_avg , wm);
feature_vector[4] = weight_avg;
feature_vector[5] = freq_avg;
double[] values = new double[]{feature_vector[0],feature_vector[1],feature_vector[2],feature_vector[3],feature_vector[4],feature_vector[5]};
DenseInstance newInst = new DenseInstance(1.0,values);
Instances dataUnlabeled = new Instances("TestInstances", atts, 0);
dataUnlabeled.add(newInst);
dataUnlabeled.setClassIndex(dataUnlabeled.numAttributes() - 1);
double clslable = lgb.classifyInstance(inst);
} catch (Exception ex) {
//Logger.getLogger(Module2.class.getName()).log(Level.SEVERE, null, ex);
}
return clslable;}
Where did this newdata come from? you need to load the file properly to get a correct classification, use this class to load features from the file:
http://weka.sourceforge.net/doc/weka/core/converters/ArffLoader.html
I'm not posting an example code because I use weka with MATLAB, so I dont have examples in Java.
I am trying to put a collision-shape onto my model.
But everytime I init the game, I get an NegativeArraySizeException.
private void createSoundBit(float x, float y, float z)
{
Spatial npc1 = assetManager.loadModel("Models/sound/sound.j3o");
npcNode.attachChild(npc1);
CollisionShape noteshape = CollisionShapeFactory.createDynamicMeshShape(npc1);
npcRigid = new RigidBodyControl(noteshape,123.0f);
npcRigid.setFriction(0f);
npcRigid.setMass(60f);
npcRigid.setPhysicsLocation(new Vector3f(x,y,z));
collmanager = new CollManager();
getPhysicsSpace().addCollisionListener(collmanager);
npc1.addControl(npcRigid);
bulletAppState.getPhysicsSpace().add(npcRigid);
rootNode.attachChild(npcNode);
}
I don't know why it happens
Stacktrace:
java.lang.NegativeArraySizeException
at com.jme3.bullet.collision.shapes.HullCollisionShape.getPoints(HullCollisionShape.java:71)
at com.jme3.bullet.collision.shapes.HullCollisionShape.<init>(HullCollisionShape.java:24)
at com.jme3.bullet.util.CollisionShapeFactory.createSingleDynamicMeshShape(CollisionShapeFactory.java:241)
at com.jme3.bullet.util.CollisionShapeFactory.createCompoundShape(CollisionShapeFactory.java:112)
at com.jme3.bullet.util.CollisionShapeFactory.createCompoundShape(CollisionShapeFactory.java:94)
at com.jme3.bullet.util.CollisionShapeFactory.createDynamicMeshShape(CollisionShapeFactory.java:188)
at Main.createSoundBit(Main.java:206)
at Main.simpleInitApp(Main.java:83)
at com.jme3.app.SimpleApplication.initialize(SimpleApplication.java:225)
at com.jme3.system.lwjgl.LwjglAbstractDisplay.initInThread(LwjglAbstractDisplay.java:130)
at com.jme3.system.lwjgl.LwjglAbstractDisplay.run(LwjglAbstractDisplay.java:207)
at java.lang.Thread.run(Thread.java:722)
For me it can be one of two things: your file sound.j3o is corrupted or there is a bug in jmonkeyengine. Try to load some other file and see what's happening. Part of source where is a problem:
FloatBuffer vertices = mesh.getFloatBuffer(Type.Position);
vertices.rewind();
int components = mesh.getVertexCount() * 3;
float[] pointsArray = new float[components];
// ...
So, looks like mesh.getVertexCount() returned negative value.
I am modeling a supply chain with an customer, retailer and supplier. They are connected in a node. I have found this code. But I do not understand, why this code creates the double amount of outedges. Perhaps, someone can help?
while (it.hasNext()) {
// Find the next agent to link to.
tempAgent = (supply_chain_agent) it.next();
System.out.println(tempAgent);
// Create an edge from the last agent to the temp agent.
tempEdge = new supply_chain_edge("Orders", 1, this.initialOrderPerTimeStep);
// Connect the new edge.
tempAgent.addInEdge(tempEdge);
System.out.println(tempEdge.getLabel());
lastAgent.addOutEdge(tempEdge);
System.out.println(tempEdge.getLabel());
tempEdge.setTo(tempAgent);
tempEdge.setFrom(lastAgent);
// Create an edge from the temp agent to the last agent.
if (lastAgent.getNodeLabel().startsWith("Customer")) {
tempEdge = new supply_chain_edge("Shipments", this.ordering_delay, this.initialOrderPerTimeStep);
} else {
tempEdge = new supply_chain_edge("Shipments", this.delivery_delay, this.initialOrderPerTimeStep);
}
// Connect the new edge.
lastAgent.addInEdge(tempEdge);
System.out.println(tempEdge.getLabel());
tempAgent.addOutEdge(tempEdge);
System.out.println(tempEdge.getLabel());
tempEdge.setTo(lastAgent);
tempEdge.setFrom(tempAgent);
// Move on.
lastAgent = tempAgent;
System.out.println(lastAgent);
}