Search Results

Search found 647 results on 26 pages for 'rand mate'.

Page 12/26 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • in flashbuilder (flex 4) select enclosing element

    - by core07
    Seems Adobe ignores strong movement now towards the productive programming. E.g. flash builder ide lacks keyboard shortcuts that are very useful in eclipse. If code templates, extract method, extract local variables are covered by some not-free plugins (and not cheap) like source mate, expanding selection to enclosing element I cannot find how to enable. Maybe you guys know some plugins doing that? Usually in eclipse it is Alt Shift Up to select enclosing block.

    Read the article

  • best way to pick a random subset from a collection?

    - by Tom
    I have a set of objects in a Vector from which I'd like to select a random subset (e.g. 100 items coming back; pick 5 randomly). In my first (very hasty) pass I did an extremely simple and perhaps overly clever solution: Vector itemsVector = getItems(); Collections.shuffle(itemsVector); itemsVector.setSize(5); While this has the advantage of being nice and simple, I suspect it's not going to scale very well, i.e. Collections.shuffle() must be O(n) at least. My less clever alternative is Vector itemsVector = getItems(); Random rand = new Random(System.currentTimeMillis()); // would make this static to the class List subsetList = new ArrayList(5); for (int i = 0; i < 5; i++) { // be sure to use Vector.remove() or you may get the same item twice subsetList.add(itemsVector.remove(rand.nextInt(itemsVector.size()))); } Any suggestions on better ways to draw out a random subset from a Collection?

    Read the article

  • How to get the coordinate of Gridlayout

    - by Jessy
    Hi, I set my JPanel to GridLayout (6,6), with dimension (600,600) Each cell of the grid will display one pictures with different widths and heights. The picture first add to a JLabel, and the JLabel then added to the cells. How can retrieved the coordinate of the pictures in the cells and not the coordinate of cells? So far the out give these coordinate which equal height and width even on screen the pictures showed in different sizes. e.g. java.awt.Rectangle[x=100,y=100,width=100,height=100] java.awt.Rectangle[x=200,y=100,width=100,height=100] java.awt.Rectangle[x=300,y=100,width=100,height=100] The reason why I used GridLayout instead of gridBagLayout is that, I want each pictures to have boundary. If I use GridBagLayout, the grid will expand according to the picture size. I want grid size to be in fix size. JPanel pDraw = new JPanel(new GridLayout(6,6)); pDraw.setPreferredSize(new Dimension(600,600)); for (int i =0; i<(6*6); i++) { //get random number for height and width of the image int x = rand.nextInt(40)+(50); int y = rand.nextInt(40)+(50); ImageIcon icon = createImageIcon("bird.jpg"); //rescale the image according to the size selected Image img = icon.getImage().getScaledInstance(x,y,img.SCALE_SMOOTH); icon.setImage(img ); JLabel label = new JLabel(icon); pDraw.add(label); } for(Component component:components) { //retrieve the coordinate System.out.println(component.getBounds()); }

    Read the article

  • How do I pipe in FileMerge as a diff tool with git on OSX?

    - by doug
    I'm new to git, on OSX, using it via command line. I come from the world of Tortoise SVN and Beyond Compare on Windows. I want to be able to pipe in diffs to happen via FileMerge which I have installed already. I was able to do this with TextMate simply by using: git diff | mate But I'm not sure how to get that set up so I can use FileMerge instead?

    Read the article

  • Shouldn't prepared statements be much faster?

    - by silversky
    $s = explode (" ", microtime()); $s = $s[0]+$s[1]; $con = mysqli_connect ('localhost', 'test', 'pass', 'db') or die('Err'); for ($i=0; $i<1000; $i++) { $stmt = $con -> prepare( " SELECT MAX(id) AS max_id , MIN(id) AS min_id FROM tb "); $stmt -> execute(); $stmt->bind_result($M,$m); $stmt->free_result(); $rand = mt_rand( $m , $M ).'<br/>'; $res = $con -> prepare( " SELECT * FROM tb WHERE id >= ? LIMIT 0,1 "); $res -> bind_param("s", $rand); $res -> execute(); $res->free_result(); } $e = explode (" ", microtime()); $e = $e[0]+$e[1]; echo number_format($e-$s, 4, '.', ''); // and: $link = mysql_connect ("localhost", "test", "pass") or die (); mysql_select_db ("db") or die ("Unable to select database".mysql_error()); for ($i=0; $i<1000; $i++) { $range_result = mysql_query( " SELECT MAX(`id`) AS max_id , MIN(`id`) AS min_id FROM tb "); $range_row = mysql_fetch_object( $range_result ); $random = mt_rand( $range_row->min_id , $range_row->max_id ); $result = mysql_query( " SELECT * FROM tb WHERE id >= $random LIMIT 0,1 "); } defenitly prepared statements are much more safer but also every where it says that they are much faster BUT in my test on the above code I have: - 2.45 sec for prepared statements - 5.05 sec for the secon example What do you think I'm doing wrong? Should I use the second solution or I should try to optimize the prep stmt?

    Read the article

  • String method crashes program...

    - by TimothyTech
    Alright so i have two identical string methods... string CreateCust() { string nameArray[] ={"Tom","Timo","Sally","Kelly","Bob","Thomas","Samantha","Maria"}; int d = rand() % (8 - 1 + 1) + 1; string e = nameArray[d]; return e; } string CreateFood() { string nameArray[] = {"spagetti", "ChickenSoup", "Menudo"}; int d = rand() % (3 - 1 + 1) + 1; string f = nameArray[d]; return f; } however no matter what i do it the guts of CreateFood it will always crash. i created a test chassis for it and it always fails at the cMeal = CreateFood(); Customer Cnow; cout << "test1" << endl; cMeal = Cnow.CreateFood(); cout << "test1" << endl; cCustomer = Cnow.CreateCust(); cout << "test1" << endl; i even switched CreateCust with CreateFood and it still fails at the CreateFood Function... NOTE: if i make createFood a int method it does work...

    Read the article

  • lnk2019 error in very simple c++ program

    - by Erin
    I have tried removing various parts and building, but nothing makes the lnk2019 error go away, or even produces any normal errors. Everything is in the one file at the moment (it won't be later when it is finished). The program has three lists of words and makes a jargon phrase out of them, and you are supposed to be able to add words, remove words, view the lists, restore defaults, save changes to file, and load changes from file. #include "stdafx.h" #include <iostream> #include <string.h> using namespace std; const int maxlist = 20; string adj1[maxlist], adj2[maxlist], noun[maxlist]; void defaultlist(int list) { if(list == 1) { adj1[0] = "green"; adj1[1] = "red"; adj1[2] = "yellow"; adj1[3] = "blue"; adj1[4] = "purple"; int i = 5; while(i != maxlist) { adj1[i] = ""; i = i + 1; } } if(list == 2) { adj2[0] = "shiny"; adj2[1] = "hard"; adj2[2] = "soft"; adj2[3] = "spiky"; adj2[4] = "furry"; int i = 5; while(i != maxlist) { adj2[i] = ""; i = i + 1; } } if(list == 3) { noun[0] = "cat"; noun[1] = "dog"; noun[2] = "desk"; noun[3] = "chair"; noun[4] = "door"; int i = 5; while(i != maxlist) { noun[i] = ""; i = i + 1; } } return; } void printlist(int list) { if(list == 1) { int i = 0; while(!(i == maxlist)) { cout << adj1[i] << endl; i = i + 1; } } if(list == 2) { int i = 0; while(!(i == maxlist)) { cout << adj2[i] << endl; i = i + 1; } } if(list == 3) { int i = 0; while(!(i == maxlist)) { cout << noun[i] << endl; i = i + 1; } } return; } string makephrase() { int num1 = rand()%maxlist; int num2 = rand()%maxlist; int num3 = rand()%maxlist; int num4 = rand()%1; string word1, word2, word3; if(num4 = 0) { word1 = adj1[num1]; word2 = adj2[num2]; } else { word1 = adj2[num1]; word2 = adj1[num2]; } word3 = noun[num3]; return word1 + " ," + word2 + " " + word3; } string addword(string word, int list) { string result; if(list == 1) { int i = 0; while(!(adj1[i] == "" || i == maxlist)) { i = i + 1; } if(i == maxlist) result = "List is full. Please try again."; if(adj1[i] == "") { adj1[i] = word; result = "Word was entered successfully."; } } if(list == 2) { int i = 0; while(!(adj2[i] == "" || i == maxlist)) { i = i + 1; } if(i == maxlist) result = "List is full. Please try again."; if(adj2[i] == "") { adj2[i] = word; result = "Word was entered successfully."; } } if(list == 3) { int i = 0; while(!(noun[i] == "" || i == maxlist)) { i = i + 1; } if(i == maxlist) result = "List is full. Please try again."; if(noun[i] == "") { noun[i] = word; result = "Word was entered successfully."; } } return result; } string removeword(string word, int list) { string result; if(list == 1) { int i = 0; while(!(adj1[i] == word || i == maxlist)) { i = i + 1; } if(i == maxlist) result = "Word is not on the list. Please try again."; if(adj1[i] == word) { adj1[i] = ""; result = "Word was removed successfully."; } } if(list == 2) { int i = 0; while(!(adj2[i] == word || i == maxlist)) { i = i + 1; } if(i == maxlist) result = "Word is not on the list. Please try again."; if(adj2[i] == word) { adj2[i] = ""; result = "Word was removed successfully."; } } if(list == 3) { int i = 0; while(!(noun[i] == word || i == maxlist)) { i = i + 1; } if(i == maxlist) result = "Word is not on the list. Please try again."; if(noun[i] == word) { noun[i] = ""; result = "Word was removed successfully."; } } return result; } /////////////////////////////main/////////////////////////////////// int main() { string mainselection; string makeselection; string phrase; defaultlist(1); defaultlist(2); defaultlist(3); cout << "This program generates jargon phrases made of two adjectives and one noun,"; cout << " on three lists. Each list may contain a maximum of " << maxlist << "elements."; cout << " Please choose from the following menu by typing the appropriate number "; cout << "and pressing enter." << endl; cout << endl; cout << "1. Make a jargon phrase." << endl; cout << "2. View a list." << endl; cout << "3. Add a word to a list." << endl; cout << "4. Remove a word from a list." << endl; cout << "5. Restore default lists." << endl; cout << "More options coming soon!." << endl; cin mainselection if(mainselection == 1) { phrase = makephrase(); cout << "Your phrase is " << phrase << "." << endl; cout << "To make another phrase, press 1. To go back to the main menu,"; cout << " press 2. To exit the program, press 3." << endl; cin makeselection; while(!(makeselection == "1" || makeselection == "2" || makeselection == "3")) { cout << "You have entered an invalid selection. Please try again." << endl; cin makeselection; } while(makeselection == "1") { phrase = makephrase(); cout << "To make another phrase, press 1. To go back to the main menu,"; cout << " press 2. To exit the program, press 3." << endl; } if(makeselection == "2") main(); if(makeselection == "3") return 0; } return 0; } //Rest of the options coming soon!

    Read the article

  • about Quick Sort

    - by matin1234
    Hi I have written this code but it will print these stack traces in the console please help me thanks! (Aslo "p" and "q" are the first and last index of our array ,respectively) public class JavaQuickSort { public static void QuickSort(int A[], int p, int q) { int i, last = 0; Random rand = new Random(); if (q < 1) { return; } **swap(A, p, rand.nextInt() % (q+1));** for (i = p + 1; i <= q; i++) { if (A[i] < A[p]) { swap(A, ++last, i); } } swap(A, p, last); QuickSort(A, p, last - 1); QuickSort(A, last + 1, q); } private static void swap(int[] A, int i, int j) { int temp; temp = A[i]; **A[i] = A[j];** A[j] = temp; } public static void main(String[] args){ int[] A = {2,5,7,3,9,0,1,6,8}; **QuickSort(A, 0,8 );** System.out.println(Arrays.toString(A)); } } the Stack traces : run: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -3 at JavaQuickSort.swap(JavaQuickSort.java:38) at JavaQuickSort.QuickSort(JavaQuickSort.java:22) at JavaQuickSort.main(JavaQuickSort.java:45) Java Result: 1 BUILD SUCCESSFUL (total time: 2 seconds) I also bold those statements that cause these stack traces. like == ** ...**

    Read the article

  • How can I randomly iterate through a large Range?

    - by void
    I would like to randomly iterate through a range. Each value will be visited only once and all values will eventually be visited. For example: class Array def shuffle ret = dup j = length i = 0 while j > 1 r = i + rand(j) ret[i], ret[r] = ret[r], ret[i] i += 1 j -= 1 end ret end end (0..9).to_a.shuffle.each{|x| f(x)} where f(x) is some function that operates on each value. A Fisher-Yates shuffle is used to efficiently provide random ordering. My problem is that shuffle needs to operate on an array, which is not cool because I am working with astronomically large numbers. Ruby will quickly consume a large amount of RAM trying to create a monstrous array. Imagine replacing (0..9) with (0..99**99). This is also why the following code will not work: tried = {} # store previous attempts bigint = 99**99 bigint.times { x = rand(bigint) redo if tried[x] tried[x] = true f(x) # some function } This code is very naive and quickly runs out of memory as tried obtains more entries. What sort of algorithm can accomplish what I am trying to do? [Edit1]: Why do I want to do this? I'm trying to exhaust the search space of a hash algorithm for a N-length input string looking for partial collisions. Each number I generate is equivalent to a unique input string, entropy and all. Basically, I'm "counting" using a custom alphabet. [Edit2]: This means that f(x) in the above examples is a method that generates a hash and compares it to a constant, target hash for partial collisions. I do not need to store the value of x after I call f(x) so memory should remain constant over time. [Edit3/4/5/6]: Further clarification/fixes.

    Read the article

  • Intent Bundle returns Null every time?

    - by Max
    I have some extras sent to a new intent. There it grabs the bundle and tests if it is null. Every single time it is null even though I am able to get the values passed and use them. Can anyone see what is wrong with the if statement? Intent i = getIntent(); Bundle b = i.getExtras(); int picked = b.getInt("PICK"); int correct = b.getInt("CORR"); type = b.getString("RAND"); if(b == null || !b.containsKey("WELL")) { Log.v("BUNDLE", "bun is null"); } else { Log.v("BUNDLE", "Got bun well"); } EDIT: Heres where the bundle is created. Intent intent = new Intent(this, app.pack.son.class); Bundle b = new Bundle(); b.putInt("PICK", pick); b.putInt("CORR", corr); b.putString("RAND", "yes"); intent.putExtras(b); startActivity(intent);

    Read the article

  • How can I force PHP's fopen() to return the current version of a web page?

    - by Edward Tanguay
    The current content of this google docs page is: However, when reading this page with the following PHP fopen() script, I get an older, cached version: I've tried two solutions proposed in this question (a random attribute and using POST) and I also tried clearstatcache() but I always get the cached version of the web page. What do I have to change in the following script so that fopen() returns the current version of the web page? <?php $url = 'http://docs.google.com/View?id=dc7gj86r_32g68627ff&amp;rand=' . getRandomDigits(10); echo $url . '<hr/>'; echo loadFile($url); function loadFile($sFilename) { clearstatcache(); if (floatval(phpversion()) >= 4.3) { $sData = file_get_contents($sFilename); } else { if (!file_exists($sFilename)) return -3; $opts = array('http' => array( 'method' => 'POST', 'content'=>'' ) ); $context = stream_context_create($opts); $rHandle = fopen($sFilename, 'r'); if (!$rHandle) return -2; $sData = ''; while(!feof($rHandle)) $sData .= fread($rHandle, filesize($sFilename)); fclose($rHandle); } return $sData; } function getRandomDigits($numberOfDigits) { $r = ""; for($i=1; $i<=$numberOfDigits; $i++) { $nr=rand(0,9); $r .= $nr; } return $r; } ?>

    Read the article

  • Upload two files at once

    - by Keyo
    I am trying to upload two files at once (two file fields) with codeigniters upload class. Despite having provided the field name codeigniter produces errors on the second field. I this a limitation of codeigniter, php or html or am I simply using the class incorectly? $this->upload->do_upload('video_file') $this->upload->do_upload('image_file') Produces this on the image field: The filetype you are attempting to upload is not allowed. Here are my two functions function upload_image() { $thumb_size = 94; $config['upload_path'] = './assets/uploads/images/'; $config['allowed_types'] = 'jpg|png|gif'; $config['max_size'] = '2048'; $config['file_name'] = 'video_' . rand(999999, 999999999); $this->load->library('upload', $config); if (!$this->upload->do_upload('image_file')) { $error = array('error' => $this->upload->display_errors()); return $error; } else { function upload_video() { $config['upload_path'] = './assets/uploads/videos/'; $config['allowed_types'] = 'flv'; $config['max_size'] = '0'; $config['file_name'] = 'video_' . rand(999999, 999999999); $this->load->library('upload', $config); if (!$this->upload->do_upload('video_file')) { $error = array('error' => $this->upload->display_errors()); return $error; } else {

    Read the article

  • Why do I get two clicked or released signals when using a custom slot for a QPushButton ?

    - by Chris
    here's the main code at first I thought is was the message box but setting a label instead has the same effect. #include <time.h> #include "ui_mainwindow.h" #include <QMessageBox> class MainWindow : public QWidget, private Ui::MainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); void makeSum(void); private: int r1; int r2; private slots: void on_pushButton_released(void); }; MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { setupUi(this); } void MainWindow::on_pushButton_released(void) { bool ok; int a = lineEdit->text().toInt(&ok, 10); if (ok) { if (r1+r2==a) { QMessageBox::information( this, "Sums","Correct!" ); } else { QMessageBox::information( this, "Sums","Wrong!" ); } } else { QMessageBox::information( this, "Sums","You need to enter a number" ); } makeSum(); } void MainWindow::makeSum(void) { r1 = rand() % 10 + 1; r2 = rand() % 10 + 1; label->setText(QString::number(r1)); label_3->setText(QString::number(r2)); } int main(int argc, char *argv[]) { srand ( time(NULL) ); QApplication app(argc, argv); MainWindow mw; mw.makeSum(); mw.show(); return app.exec(); } #include "main.moc"

    Read the article

  • Animation using AniMate with Unity3D doesn't interact with physical objects

    - by Albz
    I'm designing a maze with Unity3D. The maze has a number of bifurcations and the player will stop before each bifurcation and simply choose left or right. Then an automatic animation will move the player through the next bifurcation till the end of the maze (or till a dead end). To animate the player I'm using AniMate and C# in my Unity project. Using AniMate I'm simply creating a point-to-point animation for each bifurcation (e.g. mage below: from the start/red arrow to point 5) My problem is that my animation script (associated to the "First Person Controller") is not working properly since physics is not respected (the player passes through walls). If in the same project I enable the standard character controls in Unity, then I can navigate in the maze with the physical contrains of walls etc... (i.e. I have colliders). This is an example of the code I'm using when I press left to pass from starting point, trough point 1 to point 2: void FixedUpdate () { if (Input.GetKey(KeyCode.LeftArrow)) { //To point 1 Hashtable props = new Hashtable(); props.Add("position", new Vector3(756f,112f,1124f)); props.Add("physics", true); Ani.Mate.To(transform, 2, props); //To point 2 Hashtable props2 = new Hashtable(); props2.Add("position", new Vector3(731f,112f,1124f)); props2.Add("physics", true); Ani.Mate.To(transform, 2, props2); } } What happens practically when I press the left arrow button is that the player moves directly to point 2 using a straight line passing through the wall. I tried to pass to AniMate "Physics = true" but it doesn't seem to help. Any idea on how to solve this issue? Alternatively... any hint on how to have a more optimized code and just use a series of vector3 coordinates (one for each point) to obtain the simple animation I want without having to declare new Hashtable(); etc... every time? I chose AniMate simply because 1. I'm a beginner with Unity 2. I don't need complex animations (e.g. I don't need to use iTween), just fixed animations along straight lines and I need something really simple and quick to implement in a script. However, if someone has an equally simple solution it will be welcome. thank you in advance for your help

    Read the article

  • Flex MVC Frameworks

    - by Rydell
    I'm currently using and enjoying using the Flex MVC framework PureMVC. I have heard some good things about Cairngorm, which is supported by Adobe and has first-to-market momentum. And there is a new player called Mate, which has a good deal of buzz. Has anyone tried two or three of these frameworks and formed an opinion? Thanks!

    Read the article

  • wx.NotificationMessage AttributeError: 'module' object has no attribute 'NotificationMessage'

    - by HughGrigg
    I get this error when trying to use wxPython's NotificationMessage class: wx.NotificationMessage("", "Hello world!").Show() AttributeError: 'module' object has no attribute 'NotificationMessage' The code is quite simply: #!/usr/bin/python import wx app = wx.App() wx.NotificationMessage("", "Hello world!").Show() app.MainLoop() What am I missing? This is running on Linux Mint 13, MATE 1.2 desktop environment, Python 2.7.3.

    Read the article

  • Producer consumer with qualifications

    - by tgguy
    I am new to clojure and am trying to understand how to properly use its concurrency features, so any critique/suggestions is appreciated. So I am trying to write a small test program in clojure that works as follows: there 5 producers and 2 consumers a producer waits for a random time and then pushes a number onto a shared queue. a consumer should pull a number off the queue as soon as the queue is nonempty and then sleep for a short time to simulate doing work the consumers should block when the queue is empty producers should block when the queue has more than 4 items in it to prevent it from growing huge Here is my plan for each step above: the producers and consumers will be agents that don't really care for their state (just nil values or something); i just use the agents to send-off a "consumer" or "producer" function to do at some time. Then the shared queue will be (def queue (ref [])). Perhaps this should be an atom though? in the "producer" agent function, simply (Thread/sleep (rand-int 1000)) and then (dosync (alter queue conj (rand-int 100))) to push onto the queue. I am thinking to make the consumer agents watch the queue for changes with add-watcher. Not sure about this though..it will wake up the consumers on any change, even if the change came from a consumer pulling something off (possibly making it empty) . Perhaps checking for this in the watcher function is sufficient. Another problem I see is that if all consumers are busy, then what happens when a producer adds something new to the queue? Does the watched event get queued up on some consumer agent or does it disappear? see above I really don't know how to do this. I heard that clojure's seque may be useful, but I couldn't find enough doc on how to use it and my initial testing didn't seem to work (sorry don't have the code on me anymore)

    Read the article

  • scalable background image of popup. html, css

    - by Mayur
    Hi All, I'm getting a problem in html and css, I used a bg image for my popup window whose size is 500px width and 400px height; having a scrollable text in it. but problem is that if i reduce a size of browser it get distorted. Please help me if i can make it scalable background and according to that text as per browser size. Thanks Mayur Mate

    Read the article

  • How to parallelize this groovy code?

    - by lucas
    I'm trying to write a reusable component in Groovy to easily shoot off emails from some of our Java applications. I would like to pass it a List, where Email is just a POJO(POGO?) with some email info. I'd like it to be multithreaded, at least running all the email logic in a second thread, or make one thread per email. I am really foggy on multithreading in Java so that probably doesn't help! I've attempted a few different ways, but here is what I have right now: void sendEmails(List<Email> emails) { def threads = [] def sendEm = emails.each{ email -> def th = new Thread({ Random rand = new Random() def wait = (long)(rand.nextDouble() * 1000) println "in closure" this.sleep wait sendEmail(email) }) println "putting thread in list" threads << th } threads.each { it.run() } threads.each { it.join() } } I was hoping the sleep would randomly slow some threads down so the console output wouldn't be sequential. Instead, I see this: putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list in closure sending email1 in closure sending email2 in closure sending email3 in closure sending email4 in closure sending email5 in closure sending email6 in closure sending email7 in closure sending email8 in closure sending email9 in closure sending email10 sendEmail basically does what you'd expect, including the println statement, and the client that calls this follows, void doSomething() { Mailman emailer = MailmanFactory.getExchangeEmailer() def to = ["one","two"] def from = "noreply" def li = [] def email (1..10).each { email = new Email(to,null,from,"email"+it,"hello") li << email } emailer.sendEmails li }

    Read the article

  • get Random in ArrayList has error of java.lang.IllegalArgumentException: n must be positive

    - by gabrielle fregil
    In my ArrayList, i have get a random Item from my ArrayList for the equip method. Whenever i use my tester, the terminal window prints java.lang.IllegalArgumentException: n must be positive when I try to call random for the size. I tried to change the value of totalElements to the integer size of the elements, then the error would be an OutOfBoundsExeption import java.util.*; import java.util.Scanner; import java.util.Random; public class GameMaster { private int turn, totalElements; private boolean winner; private Avatar x1; private Avatar x2; private ArrayList<Item> inventory; public GameMaster(Avatar a1, Avatar a2) { x2 = a1; x1 = a2; turn = 1; winner = false; inventory = new ArrayList<Item>(); totalElements = 0; } private void fillInventory() { inventory.add( new Item( "Zealot Blades", true, 8 ) ); inventory.add( new Item( "BFG", true, 13 ) ); inventory.add( new Item( "Synthetic Cloth", false, 7 ) ); // more items inventory.add( new Item( "Gauss Rifle", true, 9 ) ); inventory.add( new Item( "Flight Unit", false, 6 ) ); totalElements = inventory.size(); } public String equip() { Avatar w; String a; if (turn%2==1) w=x2; else w=x1; if (w.beltIsFull()) { a = w.getName() + "'s belt is full. \n"; } else { turn++; Random generator = new Random(); Item rand = inventory.get(generator.nextInt(totalElements)); //terminal window in blueJ: java.lang.IllegalArgumentException: n must be positive a = w.getName()+" is equiped with "+rand.getName()+"."; } return a; }

    Read the article

  • Mysql random rows

    - by n00b
    please read the whole question... 90% of you dont seem to do that and some of you only read the title obviously... and if you dont know the solution, dont answer - i wont have to downvote you -.-'' im entertaining the idea of getting random rows directly from mysql. what i found was SELECT * FROM tablename WHERE somefield='something' ORDER BY RAND() LIMIT 5 but even i see how slow that would be.. is the only way to do this doing something like SELECT * FROM tablename WHERE somefield='something' LIMIT RAND(aincrementvalue-5), 1 5 times? or is there a way that i with my little knowlege of databases cant come up with ? (no i dont want random indexes. i hate the idea of them...) @commenters - please first look, then think, then look again, think again and then post. i wont point fingers but i dislike stupid comments and why i think random indexes are a nasty hack ? it doesnt give you random results. it gives you x results from a random index in a predefined order its like a gapless id only in the wrong order if you fetch by 1 row and get true randomness you fall back to my method but with an additional junk field finally the reason the field exists is only to serve as a helper to something that can be done without it with almost same performance (but the quality (randomness) is better), so it is a nasty hack ;) i solved it, look @ my answer... if you think its incorrect please tell me :)

    Read the article

  • For loop index out of range ArgumentOutOfRangeException when multithreading

    - by Lirik
    I'm getting some strange behavior... when I iterate over the dummyText List in the ThreadTest method I get an index out of range exception (ArgumentOutOfRangeException), but if I remove the threads and I just print out the text, then everything works fine. This is my main method: public static Object sync = new Object(); static void Main(string[] args) { ThreadTest(); Console.WriteLine("Press any key to continue."); Console.ReadKey(); } This method throws the exception: private static void ThreadTest() { Console.WriteLine("Running ThreadTest"); Console.WriteLine("Running ThreadTest"); List<String> dummyText = new List<string>() { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"}; for (int i = 0; i < dummyText.Count; i++) { Thread t = new Thread(() => PrintThreadName(dummyText[i])); // <-- Index out of range?!? t.Name = ("Thread " + (i)); t.IsBackground = true; t.Start(); } } private static void PrintThreadName(String text) { Random rand = new Random(DateTime.Now.Millisecond); while (true) { lock (sync) { Console.WriteLine(Thread.CurrentThread.Name + " running " + text); Thread.Sleep(1000+rand.Next(0,2000)); } } } This does not throw the exception: private static void ThreadTest() { Console.WriteLine("Running ThreadTest"); List<String> dummyText = new List<string>() { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"}; for (int i = 0; i < dummyText.Count; i++) { Console.WriteLine(dummyText[i]); // <-- No exception here } } Does anybody know why this is happening?

    Read the article

  • Why is the compiler caching my "random" and NULLED variables?

    - by alex gray
    I am confounded by the fact that even using different programs (on the same machine) to run /compile, and after nilling the vaues (before and after) the function.. that NO MATTER WHAT.. I'll keep getting the SAME "random" numbers… each and every time I run it. I swear this is NOT how it's supposed to work.. I'm going to illustrate as simply as is possible… #import <Foundation/Foundation.h> int main(int argc, char *argv[]) { int rPrimitive = 0; rPrimitive = 1 + rand() % 50; NSNumber *rObject = nil; rObject = [NSNumber numberWithInt:rand() % 10]; NSLog(@"%i %@", rPrimitive, rObject); rPrimitive = 0; rObject = nil; NSLog(@"%i %@", rPrimitive, rObject); return 0; } Run it in TextMate: i686-apple-darwin11-llvm-gcc-4.2 8 9 0 (null) Run it in CodeRunner: i686-apple-darwin11-llvm-gcc-4.2 8 9 0 (null) Run it a million times, if you'd like. You can gues what it will always be. Why does this happen? Why oh why is this "how it is"?

    Read the article

  • How can I get an NPC to move randomly in XNA?

    - by Fishwaffles
    I basically want a character to walk in one direction for a while, stop, then go in another random direction. Right now my sprites look but don't move, randomly very quickly in all directions then wait and have another seizure. I will post the code I have so far in case that is useful. class NPC: Mover { int movementTimer = 0; public override Vector2 direction { get { Random rand = new Random(); int randDirection = rand.Next(8); Vector2 inputDirection = Vector2.Zero; if (movementTimer >= 50) { if (randDirection == 4) { inputDirection.X -= 1; movingLeft = true; } else movingLeft = false; if (randDirection == 1) { inputDirection.X += 1; movingRight = true; } else movingRight = false; if (randDirection == 2) { inputDirection.Y -= 1; movingUp = true; } else movingUp = false; if (randDirection == 3) { inputDirection.Y += 25; movingDown = true; } else movingDown = false; if (movementTimer >= 100) { movementTimer = 0; } } return inputDirection * speed; } } public NPC(Texture2D textureImage, Vector2 position, Point frameSize, int collisionOffset, Point currentFrame, Point sheetSize, Vector2 speed) : base(textureImage, position, frameSize, collisionOffset, currentFrame, sheetSize, speed) { } public NPC(Texture2D textureImage, Vector2 position, Point frameSize, int collisionOffset, Point currentFrame, Point sheetSize, Vector2 speed, int millisecondsPerframe) : base(textureImage, position, frameSize, collisionOffset, currentFrame, sheetSize, speed, millisecondsPerframe) { } public override void Update(GameTime gameTime, Rectangle clientBounds) { movementTimer++; position += direction; if (position.X < 0) position.X = 0; if (position.Y < 0) position.Y = 0; if (position.X > clientBounds.Width - frameSize.X) position.X = clientBounds.Width - frameSize.X; if (position.Y > clientBounds.Height - frameSize.Y) position.Y = clientBounds.Height - frameSize.Y; base.Update(gameTime, clientBounds); } }

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >