I'm making a bedwars plugin for my minecraft server, actually i have to coding a generator for drop item every 1 secs, i have no idea how to make that, with internet i have done this code :
while(true) {
task = Bukkit.getServer().getScheduler().runTaskTimer(Main.plugin, () -> {
World w = null;
for(Player p : Bukkit.getServer().getOnlinePlayers()) {
w = p.getWorld();
}
String[] pos = Main.blue_spawn.split("\\*");
Location loc = new Location(w, Double.parseDouble(pos[0]), Double.parseDouble(pos[1]), Double.parseDouble(pos[2]));
w.dropItemNaturally(loc, new ItemStack(1));
}, 20, 20);
}
But i don't know how to drop iron ingot, beaucause do new ItemStack(Material.IRON_INGOT) just give me an error
Pls help
You should NOT use while(true) loop in minecraft. It will block the thread, which seems to be the main server thread. The scheduler is enough about staying running.
Then, it's not a good idea about the player loop for getting world. If someone is on the nether or something, it will not work. You can use Bukkit.getServer().getWorlds()[0] or Bukkit.getServer().getWorld("world").
Also, the new ItemStack(Material.IRON_INGOT) should work. Documentation about it.
Finally, the dropItemNaturally method is good. You can see doc here
Related
I'm using the Java Sound API and I know how to use a Sequencer for editing and performing tracks as well. My question now is how do I play multiple notes (not necessarily at the same time) on the fly correctly?
I used one track, added the MidiEvent NoteON and NoteOFF and then started the seuquencer to play the Note. On the second run I delete the previous events from the track and set the synthesizer to position 0 to start anew. That works fine.
The problem is that the previous notes will naturally be cut off even when their note off events are not fully executed therefore the note does not last as long as I wanted it to be.
Is the correct way to approach this via sending the note events to different tracks or are there better ways? The problem with this I encountered is, that starting the sequencer from position 0 will result in some previous notes being played again.
public void playSingleNote(int note, int velocity) throws InvalidMidiDataException, MidiUnavailableException {
long tick = 0;
sequencer.setTickPosition(0);// Start at beginning.
// Clean track
for (int i = 0; i < track.size(); i++) {
track.remove(track.get(i));
}
ShortMessage msg = new ShortMessage(ShortMessage.NOTE_ON, 0, note, velocity);
MidiEvent evt = new MidiEvent(msg, tick);
track.add(evt);
msg = new ShortMessage(ShortMessage.NOTE_OFF, 0, note, velocity);
evt = new MidiEvent(msg, tick + 28);
track.add(evt);
sequencer.start();
}
I checked some questions here but I couldn't find a proper answer. Maybe I am using wrong keywords to search. But what I found didn't help. So here is my question. I have some circles and line that are sliding in a certain way.
What I want is to update balance variable after the animations perform.
DoubleProperty balance = new SimpleDoubleProperty();
And I update the balance as follows:
if (shapeADone == false) {
intersecting = arc.centerXProperty().lessThan(boldLine.getEndX() - 13);
intersecting.addListener((obs, wasIntersecting, isNowIntersecting) -> {
System.out.println("Collision!");
animation1.stop();
animation2.stop();
animation3.stop();
});
again = true;
balance.setValue(-1);
} else {
fadeB();
balance.setValue(1);
}
But in main method I want to do something like this
level1.balance.addListener(ov -> {
System.out.println("The new value is " +
level1.balance.doubleValue());
if (level1.balance.getValue()==1) {
//delay setting scene
primaryStage.setScene(scene2);
}
});
I have some animations to perform before setting scene2 but since balance instantly updating, my animations can't be performed.
I want to know if there is a way to delay listening balance or setting scene.
I tried Thread.sleep and balance.wait but it gives runtime errors.
Edit: This question clearly shows that I was lack of knowlodge about javafx. What I want to do is simple and solution is even more simple. When animation perform to the end I update the value of balance. All I wanted was make sure that animation is showed to the end.
Here is the answer :
else{
animation3.setOnFinished(event -> balance.setValue(1));
fadeB();
}
As Sedrick's comment I change the code like this.
Adding setOnFinish to animations which need to be performed solve the problem. It's working.
I'm coding this in JavaFX using a FXMLController and the scene builder.
I'm currently creating an Instagram "liker" mostly just for practice as I'm a Computer Science major, and I just like coding.
My issue is, I have a for loop that "likes" 20 photos for each hashtag, I obviously need a delay or I'd get banned rather quickly. The user can choose the delay, then I randomize this delay so it's not too robotic.
The only way I've been able to use this delay is through the thread.sleep method, but since I'm coding on the FXMLController, it freezes the whole UI, and somehow stops other textareas from being updated. This is obviously not ideal.
I've looked everywhere trying to find an alternative to this, but I can't find anything that works in my program.
I'll give the whole method:
private void start() {
sleepWhen();
tagNumber++;
int delays = Integer.valueOf(delay.getText());
delays = delays * 1000;
if (loaded) {
runTime.clear();
runTime.appendText("Liking...");
for (int i = 0; i < 20; i++) {
webEngine.executeScript("document.getElementsByClassName('btn btn-default btn-xs likeButton')[" + i + "].click()");
try {
double random = Math.random() * 1000;
random = random + delays;
delays = (int) random;
System.out.println(delays);
likes++;
likesNumber.clear();
likesNumber.appendText(String.valueOf(likes));
System.out.println(String.valueOf(likes));
Thread.sleep(delays);
delays = Integer.valueOf(delay.getText());
delays = delays * 1000;
} catch (InterruptedException ex) {
//do nothing
}
System.out.println("tag number" + tagNumber + "numbertags" + numberTags);
if (!sleep) {
if (tagNumber < numberTags) {
System.out.println("Loading tag:" + tagNumber);
loadTag(tagNumber);
}
}
}
}
}
This likes 20 photos, then loads another hashtag, and repeats.
Any help with this would be great, thanks.
The freeze is because you are trying to do everything on the same thread, when you are using Thread.sleep(delays), you are actually putting your UI thread to sleep and hence the lag !
Try using different thread for your work, you can either use a worker thread, if whatever you are doing will not affect the UI
or you can use Platform.runLater(), if you want the changes to shown on the UI !
For more details :
concurrency in javafx !
Platform.runLater and Task in JavaFX
I am not sure how to explain this. But I'll try.. Fest slows down to crawl while working with JXTreeTable of swingx. It doesn't slow down initially. It works fine for a while, but after a while when the same actions are repeated it slows down badly.
I have raised a bug for this in github. Please tell me if this is something that I am doing wrong instead. I am not able to reproduce the problem when I tried to create an SSCCE.
Anyway, here's a video of it slowing down.
http://screencast.com/t/liNttCw2In0w
At times 0.39s to 0.40 a set of operations are performed. These are done when there is one row in the JXTreeTable.
At time 0.49 to end of recording the same operation is repeated but there are now 3 rows in the table, it takes very long for the mouse to click.
I have attached a screenshot taken at the time when fest slows down, which attempts to explain it more
This is the code that does the work:
Step 1) Selecting a node from the tree is done as below:
JTreeFixture folioTreeFixture = importShareholders.panel("treePanel").tree("folioTree");
folioTreeFixture.separator("~");
folioTreeFixture.selectPath(new StringWrapper("Shareholders", true)+"~"+
(ShareType.isEquity(shareType) ? new StringWrapper("Equity Folios", true) : new StringWrapper("Preference Folios", true))+"~"+
new FolioTreeRep(folio.getName(),folioNo, shareType).toString());
Step 2) Searching and selecting a row from the JXTreeTable
int selectRow=-1;
JTableFixture table=importShareholders.table("historyTable");
for(int i=0;i<table.rowCount();i++){
String certificateNumber = table.cell(TableCell.row(i).column(ShareholderHistoryTable.columnIndex(ShareholderHistoryTable.CERT_NO))).value();
String remarks=table.cell(TableCell.row(i).column(ShareholderHistoryTable.columnIndex(ShareholderHistoryTable.REMARKS))).value();
if(StringUtils.isEmpty(remarks) && StringUtils.isNotEmpty(certificateNumber) && Integer.parseInt(certificateNumber)==certNo){
selectRow=i;
break;
}
}
if(selectRow==-1){
fail("Couldn't find certificate number to transfer");
}
Step 3) Showing the pop up menu and clicking the row
table.showPopupMenuAt(TableCell.row(selectRow).column(0)).menuItem("btnTransfer").click();
I am not sure why its slowing down. Please let me know if there is any more info I can help with. Would be grateful for some help in solving the problem
I have profiled the application and I dont find anything untoward happening. I dont have a lot of experience profiling applications. I would be grateful if someone could have a second look at this. I profiled it with yourkit and have uploaded the snapshot dump here:
https://www.dropbox.com/s/dh976v01q9c3sgj/ImportShareholderData.shouldTransferAndSplit-2013-06-14-shutdown.snapshot.zip
Any help will be greatly appreciated..
EDIT:
I think I forgot to mention the same thing works when I do it manually. It only slows down with fest. That leads me to believe that there is an issue with fest maybe?
Sorry about that.
EDIT 2:
As request by Marcin (sorry for the delay Marcin).. Here's the code when the first row is getting split
public List<Integer> splitRowEqually(ShareType shareType, String date, int folioNo, int certNo, int... certnos) throws NoSuchFieldException, TorqueException {
//select a tree node
selectFolioInTree(shareType, folioNo);
Pause.pause(new Condition("Wait until tab is created") {
#Override
public boolean test() {
return importShareholders.tabbedPane().tabTitles().length>0;
}
});
//select a row on the table to split
int row=selectRowWithCertNunber(certNo);
List<Integer> rowsIndexes=new ArrayList<Integer>();
JTableFixture table = importShareholders.table();
//show popup menu on that row and select split
table.showPopupMenuAt(row(row).column(columnIndex(TRANS_TYPE))).menuItem("btnSplit").click();
DialogFixture splitDialog=FinderUtilities.getDialogWithTitle("Split Share Certificate");
splitDialog.textBox("tfDateOfSplit").setText(date);
int noOfShares= Integer.parseInt(table.cell(row(row).column(columnIndex(NO_OF_SHARES))).value());
int distFrom= Integer.parseInt(table.cell(row(row).column(columnIndex(DIST_NO_FROM))).value());
int distTo= Integer.parseInt(table.cell(row(row).column(columnIndex(DIST_NO_TO))).value());
//split the row into the number of times decided by the certnos array
int noOfSharesInEachSplit=noOfShares/certnos.length;
for(int i=0;i<certnos.length;i++){
int distToInSplit = distFrom + noOfSharesInEachSplit-1;
enterSplitRowDetails(splitDialog, certnos[i], distFrom, distToInSplit<=distTo ? distToInSplit : distTo);
distFrom=distToInSplit+1;
rowsIndexes.add(row++);
}
splitDialog.button("btnSplit").click();
return rowsIndexes;
}
//selects a node from the left hand side tree
public void selectFolioInTree(final ShareType shareType,final int folioNo) throws TorqueException {
JTreeFixture folioTreeFixture = importShareholders.panel("treePanel").tree("folioTree");
folioTreeFixture.separator("~");
// I use these wrapper classes - StringWrapper and FolioTreeRep, so that I can get a html
// string for the tree node like <html><b>Shareholder</b></html>
String treePath = new StringWrapper("Shareholders", true) + "~" +
(ShareType.isEquity(shareType) ? new StringWrapper("Equity Folios", true) : new StringWrapper("Preference Folios", true)) + "~" +
new FolioTreeRep(mapOfFolioNames.get(folioNo), folioNo, shareType).toString();
folioTreeFixture.clickPath(treePath);
}
//search the table for a row that contains the cert no provided in the Certificate Number column.
private int selectRowWithCertNunber(int certNo) throws NoSuchFieldException {
int selectRow=-1;
JTableFixture table=importShareholders.table("historyTable");
for(int i=0;i<table.rowCount();i++){
String certificateNumber = table.cell(row(i).column(columnIndex(CERT_NO))).value();
String remarks=table.cell(row(i).column(columnIndex(REMARKS))).value();
if(StringUtils.isEmpty(remarks) && StringUtils.isNotEmpty(certificateNumber)
&& Integer.parseInt(certificateNumber)==certNo){
selectRow=i;
break;
}
}
if(selectRow==-1){
fail("Couldn't find certificate number to transfer");
}
return selectRow;
}
// enter details on the table in the SplitDialog
private void enterSplitRowDetails(DialogFixture splitDialog, int cert, int distFrom, int distTo) {
splitDialog.button("btnAdd").click();
int row = splitDialog.table().rowCount();
splitDialog.table().enterValue(row(row - 1).column(0), String.valueOf(cert));
splitDialog.table().enterValue(row(row - 1).column(1), String.valueOf(distFrom));
splitDialog.table().enterValue(row(row - 1).column(2), String.valueOf(distTo));
}
Emm... It is quite interesting question;
I suppose the question contains less really required details especially the robot integration and IO solutions details so I cannot just give you a proper answer...
Anyway, I'll try to analyze the problem in voice a little bit in my way...
First. According to your screenshot comments, I can notice that all "30s pauses or so" occur on some, as I can get it, stream reading process "select/search" (your app gets some data to output etc). So maybe it is much deeper than you think because it is probably thread problem;
I couldn't find the GuiQuery/GuiTask/GuiActionRunne classes usage in your code snippets so I may suggest the "synch problem" may take place in the mentioned case...
Second. OK... If it is still the thread problem I may suggest the robot and IO solutions are both in some ONE thread (the Main thread or something) because, according to your tips as "At times 0.39s to 0.40 a set of operations are performed. These are done when there is one row in the JXTreeTable." ... GUI is waiting for some process to be completed...
Third.
And again... According to this issue as
"It is recommended to turn on an automated check to verify that all
Swing components updates are done in Swing’s EDT (Event Dispatcher
Thread). For those unfamiliar with the EDT, it is responsible for
handling and updating all Swing widgets in a separate thread, causing
that the application never loses responsiveness to user gestures (just
in short, more about the EDT here). To do that, we add the following
hook to the test:"
import org.fest.swing.edt.FailOnThreadViolationRepaintManager;
import org.junit.BeforeClass;
...
#BeforeClass
public static void setUpOnce() {
FailOnThreadViolationRepaintManager.install();
}
Next step is to launch the frame or dialog. As JUnit runs in its own
thread, we must launch the frame or dialog through Fest, to ensure,
again, that EDT is properly used:
import org.fest.swing.edt.GuiActionRunner;
import org.fest.swing.edt.GuiQuery;
import org.fest.swing.fixture.FrameFixture;
import org.junit.Before;
...
private FrameFixture testFrame;
private AllTypesFrame frame;
...
#Before
public void setUp() {
frame = GuiActionRunner.execute(new GuiQuery<AllTypesFrame>() {
protected AllTypesFrame executeInEDT() {
return new AllTypesFrame();
}
});
testFrame = new FrameFixture(frame);
testFrame.show();
}
... makes me think it is maybe the "thread-problem" which is described in the First and Second tips...
so, as a conclusion, I can say that maybe you have to multi-thread your test a little more because it is obviously some kind of synch problem...
P.S.
#sethu, before you start your debugging I want to point a little...
I still suspect threads conflict is taking place here (see my previous tips) because, as I may notice, your code snippets are showing static expressions usage to invoke methods like Pause.pause(...) or FinderUtilities.getDialogWithTitle(...) etc I cannot see the whole project architecture so it is hard to analyze according the represented bits but it is pretty clear the "manual testing" goes fine because action listeners react in real time but fest testing does the annoying delays because it uses some "timer" to countdown until a click emulation occurs etc and of course it is a background process which needs a separate thread... Watch debugging carefully maybe somewhere in your code UI thread and fest thread do conflict (see static methods, thread.sleep etc) the points where fest thread could block (override) the UI's one... :S By the way what method Pause.pause(...) does?
P.P.S.
If you have some additional information please comment my answer
Report if my answer helps you
I do not know what are your robot settings but you can at least try to set idleTimeout and other timeouts for the robot you use. The default timeout is 10 sec (look in org.fest.swing.core.Settings). After I decrease it (first 1000ms, next 100ms) I noticed that robot works faster.
robot().settings().idleTimeout(YOUR_TIMEOUT)
Here is my test setup and one test method. Hope is clear.
Here you have my before/after
private static int testMethodCounter = 0;
private static EmergencyAbortListener mEmergencyAbortListener;
private FrameFixture workbenchFrame;
private Robot robot2;
private static final int myIdleTimeout = 100;
#Before
public void setUp() throws Exception {
// my workaround to be able to start the app once and reuse for all tests
if (testMethodCounter == 0) {
robot2 = BasicRobot.robotWithNewAwtHierarchy();
GuiActionRunner.execute(new GuiTask() {
#Override
protected void executeInEDT() throws Throwable {
ApplicationLauncher.application(ProgramRun.class).start();
}
});
} else {
// the second test method see all before created gui components
robot2 = BasicRobot.robotWithCurrentAwtHierarchy();
}
testMethodCounter++;
robot2.settings().idleTimeout(myIdleTimeout);
workbenchFrame = WindowFinder.findFrame(FrameNames.WORKBENCH.getName()).withTimeout(10000)
.using(robot2);
}
#After
public void tearDown() {
// current window will not be closed
robot2.cleanUpWithoutDisposingWindows();
}
#Test
public void someSmokeTest() throws Exception {
Pause.pause(1000);
// perform some test specific gui actions
// here is very important moment, I need new robot because
// workbenchFrame.button(ButtonNames.SOME_BUTTON_NAME).click(); creates new dialog
// which will be avilable in AWT stack after creation
robot2.cleanUpWithoutDisposingWindows();
robot2 = BasicRobot.robotWithCurrentAwtHierarchy();
// the new Robot needs timeout setup
// without this I have long breaks between gui events
robot2.settings().idleTimeout(myIdleTimeout);
workbenchFrame.button(ButtonNames.SOME_BUTTON_NAME).click();
DialogFixture dialog = WindowFinder.findDialog("dialog2")
.withTimeout(5000).using(robot2);
// some actions on the dialog
// once again next new dialog
workbenchFrame.menuItem(MenuItemNames.NAME).click();
robot2.cleanUpWithoutDisposingWindows();
robot2 = BasicRobot.robotWithCurrentAwtHierarchy();
// and idleTimeout setup once again, new Robot needs new setup
robot2.settings().idleTimeout(myIdleTimeout);
// next actions + assertion
}
I'm desperately trying to get Java and gnuplot to play nice. I've started using JavaPlot and have added the jar to the classpath (using Eclipse).
I've also downloaded gnuplot and have placed it in a safe place.
First question, all examples given by JavaPlot are assuming you have put gnuplot in the right place, where this is I have no idea. Therefore their example of:
import com.panayotis.gnuplot.JavaPlot;
public class test {
public static void main(String[] args) {
JavaPlot p = new JavaPlot();
p.addPlot("sin(x)");
p.plot();
}
}
Will only work if gnuplot is added to the classpath, any ideas on where that might be and how?
Not to worry though, as you can define the location of gnuplot in the constructor of JavaPlot, like so:
import com.panayotis.gnuplot.JavaPlot;
public class test {
public static void main(String[] args) {
JavaPlot p = new JavaPlot("D:/Eclipse/gnuplot/binary/pgnuplot.exe");
p.addPlot("sin(x)");
p.plot();
}
}
This does something, if you're quick you can see a graph appear (correctly, can see the sine wave) and then immediately disappear. I've read online that in the actual gnuplot application this is common when using Windows and that a '-persist' must be added after the plot. Fortunately JavaPlot also has a function that does that:
p.setPersist(true);
But in my case it does nothing. So second question, anyone used gnuplot, JavaPlot, and Windows 7 64bit before and know how to do this? From my Googling I understand pgnuplot is the correct .exe to run?
What am I missing? What am I doing wrong?
I think I may have a workaround for you, as I ran into the same sort of thing today when accessing JavaPlot on Windows 7 (32 bit here though). Yes, pgnuplot.exe is the one you want, however you do not need to explicitly setPersist if you do not want to because JavaPlot does that for you. What I had to do was go through the source code and comment out a line.
In GnuPlotParameters, I see the code
/* Finish! */
bf.append("quit").append(NL);
This is lines 198-199. Then the plot windows stays open. Now, what this also does is leave open gnuplot. If you do not mind, you can see your graphs this way. Have not figured out yet how to close gnuplot while leaving the plot window open.
EDIT:
Maybe a more appropriate way is not to comment out line 199 and go with this:
bf.append("pause -1").append(NL);
/* Finish! */
bf.append("quit").append(NL);
In this manner, the pause dialog comes up. This allows you to see the plot. When you dismiss the dialog, everything goes bye-bye.
Try JavaGnuplotHybrid: https://github.com/mleoking/JavaGnuplotHybrid
It solves the problem of immediately disappear.
Here is the example for a 2D plot:
public void plot2d() {
JGnuplot jg = new JGnuplot();
Plot plot = new Plot("") {
{
xlabel = "x";
ylabel = "y";
}
};
double[] x = { 1, 2, 3, 4, 5 }, y1 = { 2, 4, 6, 8, 10 }, y2 = { 3, 6, 9, 12, 15 };
DataTableSet dts = plot.addNewDataTableSet("2D Plot");
dts.addNewDataTable("y=2x", x, y1);
dts.addNewDataTable("y=3x", x, y2);
jg.execute(plot, jg.plot2d);
}
I use eclipse for debugging and happen to be using this package. I figured out how to fix this. Add the following to your code. The setPersist(true) doesn't seem to work for some reason.
p.set("term", "x11 persist");
try this
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("D:/Projet/X-Gnuplot_4.6.0_rev6/Bin/gnuplot/bin/gnuplot.exe");
java.io.OutputStream opStream = proc.getOutputStream();
PrintWriter gp = new PrintWriter(new BufferedWriter(new OutputStreamWriter(opStream)));
gp.println("plot sin(x); pause mouse close;\n");
gp.close();
int exitVal = proc.waitFor();
System.out.println("Exited with error code "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
it works for me
replace your
p.addPlot("sin(x)");
by
p.addPlot("sin(x); pause 100;");
it only appears for 100 seconds
fsd