Search Results

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

Page 9/26 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Do running times match with O(nlogn)?

    - by user472221
    Hi I have written a class(greedy strategy) that at first i used sort method which has O(nlogn) Collections.sort(array, new SortingObjectsWithProbabilityField()); and then i used the insert method of binary search tree which takes O(h) and h here is the tree height. for different n ,the running time will be : n,running time 17,515428 33,783340 65,540572 129,1285080 257,2052216 513,4299709 which I think is not correct because for increasing n , the running time should almost increase. This method will take the running time: Exponent = -1; for(int n = 2;n<1000;n+=Math.pow(2,exponent){ for (int j = 1; j <= 3; j++) { Random rand = new Random(); for (int i = 0; i < n; i++) { Element e = new Element(rand.nextInt(100) + 1, rand.nextInt(100) + 1, 0); for (int k = 0; k < i; k++) { if (e.getDigit() == randList.get(k).getDigit()) { e.setDigit(e.getDigit() + 1); } } randList.add(e); } double sum = 0.0; for (int i = 0; i < randList.size(); i++) { sum += randList.get(i).getProbability(); } for (Element i : randList) { i.setProbability(i.getProbability() / sum); } //Get time. long t2 = System.nanoTime(); GreedyVersion greedy = new GreedyVersion((ArrayList<Element>) randList); long t3 = System.nanoTime(); timeForGreedy = timeForGreedy + t3 - t2; } System.out.println(n + "," + "," + timeForGreedy/3 ); exponent++; } thanks

    Read the article

  • selected option not clearing from memory android

    - by user2980560
    I have a small random number spinner that when you click gives a random number. I am having two problems. The first is when the main activity loads it displays a random number on the screen without the random number spinner being clicked. I am unsure what to set to false to keep it from opening with the main activity. The second problem is that when you select an option from the spinner it does not clear. Meaning that If you click on option D6 or D20 then you can not click on the same option again until selecting the other option first. Essentially the selection does not clear out of memory after the random number is selected. Here is the random number code public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { Random rand = new Random(); int roll; // An item was selected. if (spinner1.getSelectedItemPosition()==0) { roll = rand.nextInt(6)+1; } else { roll = rand.nextInt(20)+1; } // Put the result into a string. String text = "You rolled a " + roll; // Build a dialog box and with the result string and a single button AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(text).setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // do things when the user clicks ok. } }); AlertDialog alert = builder.create(); // Show the dialog box. alert.show(); }

    Read the article

  • Get to Know a Candidate (10 of 25): Tom Stevens&ndash;Objectivist Party

    - by Brian Lanham
    DISCLAIMER: This is not a post about “Romney” or “Obama”. This is not a post for whom I am voting. Information sourced for Wikipedia. Stevens is an American professor, attorney, politician and blogger. He is the founder and chairman of the Objectivist Party and was that party's nominee for President in the 2008 and 2012 United States Presidential elections. He is the party's presidential nominee in the 2012 election as well. He is also the founder of the Personal Freedom Party of New York. Stevens was the first vice chairman of the political party Boston Tea Party. He resigned from that position in 2008. In 2010, he announced the formation of the Personal Freedom Party of New York. Stevens runs the blog site Liberty Lion. He is a graduate of New York University and Hofstra University School of Law. Stevens is on the ballot in CO, and FL. The Objectivist Party is a political party in the United States that seeks to promote Ayn Rand's philosophy of Objectivism in the political realm. The party was formed on February 2, 2008 by Thomas Stevens; the date was chosen to coincide with Rand's birthday. The party believes in the repeal of the federal income tax; thus the repeal of the 16th Amendment. The income tax would then be replaced by a Flat Tax of 10% or Federal sales tax. The party supports the 2nd Amendment, but only as long as violent criminals are not permitted to own any weapon. Learn more about Tom Stevens and Objectivist Party on Wikipedia.

    Read the article

  • Random Movement for multiple entities

    - by opiop65
    I have this code for a arraylist of entities. All the entities use the same random and so all of them move in the same direction. How can I change it so it generates a new random number for each entity? public void moveFemale() { for(int i = 0; i < 1000; i++){ random = rand.nextInt(99); } if (random >= 0 && random <= 25) { posX -= enemyWalkSpeed; // right } if (random >= 26 && random <= 50) { posX += enemyWalkSpeed; // left } if (random >= 51 && random <= 75) { posY -= enemyWalkSpeed; // up } if (random >= 76 && random <= 100) { posY += enemyWalkSpeed; // down } } Is this correct? public void moveFemale() { for (Female female: GameFrame.females){ female.lastChangedDirectionTime += elapsedTime; if (female.lastChangedDirectionTime >= CHANGE_DIRECTION_TIME) { female.lastChangedDirectionTime = 0; random = rand.nextInt(100); if (random >= 0 && random <= 25) { posX -= enemyWalkSpeed; // right } if (random >= 26 && random <= 50) { posX += enemyWalkSpeed; // left } if (random >= 51 && random <= 75) { posY -= enemyWalkSpeed; // up } if (random >= 76 && random <= 100) { posY += enemyWalkSpeed; // down } } } }

    Read the article

  • Inconsistent accessibility error in xna.

    - by Tom
    Hey all, you may remember me asking a question regarding a snake game I was creating about two weeks ago. Well I'm quite far now into making the game (thanks to a brilliant tutorial I found). But I've come across the error described named above. So heres my problem; I have a SnakeFood class that has a method called "Reposition". In the game1 class I have a method called "UpdateInGame" which calls the reposition method to load an orange that spawns in a random place every second. My latest piece of code changed the reposition method to allow the snake I have on the screen to not be overlapped by the orange that randomly spawns. Now I get the error (in full): Error 1 Inconsistent accessibility: parameter type 'TheMathsSnakeGame.Snake' is less accessible than method 'TheMathsSnakeGame.SnakeFood.Reposition(TheMathsSnakeGame.Snake)' C:\Users\Tom\Documents\Visual Studio 2008\Projects\TheMathsSnakeGame\TheMathsSnakeGame\SnakeFood.cs 33 21 TheMathsSnakeGame I understand what the errors trying to tell me but having changed the accessiblity of the methods, I still can't get it to work. Sorry about the longwinded question. Thanks in advance :) Edit: Code I'm using (Game1 Class) private void UpdateInGame(GameTime gameTime) { //Calls the oranges "reposition" method every second if (gameTime.TotalGameTime.Milliseconds % 1000 == 0) orange.Reposition(sidney); sidney.Update(gameTime); } (SnakeFood Class) public void Reposition(Snake snake) { do { position = new Point(rand.Next(Grid.maxHeight), rand.Next(Grid.maxWidth)); } while (snake.IsBodyOnPoint(position)); }

    Read the article

  • indexing and crawling

    - by ricky
    hello mate my site is dailytopup.com...earlier my site was indexed imediately i post anything but last month my website was crashed due to sever problem and i adont have back up at that time so i recover everything from cached copies but before doing that i remove old urls from the webmaster and then repost again.but after that my website is not indexed properly reaults in no optimsation.everytime i have to use fetch as google but this is not that effective..can you please tell where um lacking or what should i do now?

    Read the article

  • cannot install cinnimon 2.xx

    - by user207587
    Fetched 841 kB in 28s (29.3 kB/s) W: GPG error: http://packages.mate-desktop.org raring Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 68980A0EA10B4DE8 W: Failed to fetch http://ppa.launchpad.net/pmcenery/ppa/ubuntu/dists/raring/main/binary-i386/Packages 404 Not Found E: Some index files failed to download. They have been ignored, or old ones used instead. userx@bw:~$ How do I fix that? How do I add a PUBKEY to get needed files to complete install of Cinnamon?

    Read the article

  • Inserted DVD disc not recognized

    - by Vineen Malig Manarang
    com! I was trying to watch FairyTail on my Ubuntu laptop, however, whenever I insert the disc, the CD/DVD drive icon on the Computer pane disappears, seems that it cannot detect what type of disc was inserted. I am running on Ubuntu 12.04 LTS and new to these things as I used to be comfortable with Windows doing the things for me. IMMEDIATE HELP WILL BE APPRECIATED as I just borrowed this DVD from a mate and allowed me to watch it until I finish the episodes inside the CD. Many thanks, Vineen

    Read the article

  • IE 10 : quatrième pré-version disponible avec cinq nouveaux outils "fondamentaux pour les développeurs d'applications natives"

    IE 10 : Quatrième pré-version disponible Avec cinq nouveaux outils "fondamentaux pour les développeurs d'applications natives" Mise à jour du 30/11/11 [IMG]http://ftp-developpez.com/gordon-fowler/IE10/IE10Logo.png[/IMG] Microsoft vient de publier la quatrième Plateform Preview (équivalents des betas) de son navigateur Internet Explorer 10. IE 10 est intimement lié à Windows 8 puisqu'il ne tourne que sur cet OS, lui aussi en cours de développement. Cette quatrième pré-version améliore "le support du HTML5 [?] et l'accélération maté...

    Read the article

  • How to insert images using labels in NetBeans IDE, Java? [migrated]

    - by Vaishnavi Kanduri
    I'm making a virtual mall using NetBeans IDE 7.3.1 I inserted images using the following steps: Drag and drop label onto frame Go to label properties Click on ellipsis of 'icon' option Import to project, select desired image Resize or reposition it accordingly. Then, I saved the project, copied the project folder into a pendrive, tried to 'Open Project' in mate's laptop, using the same Java Netbeans IDE version. When I tried to open the frames, they displayed empty labels, without images. What went wrong?

    Read the article

  • I’m new to C++ and unsure about how to improve this code [migrated]

    - by Laian Alsabbagh
    The purpose of the following code is to get a random number of 100 nodes and to distribute these nodes randomly in range 500*500 …(X,Y).. this was the first step #include<iostream> #include <fstream> #include<cmath> using namespace std; int main() { const int x = 0, y = 1; int nodes[100][2]; ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; for (int i=0; i<100 ;i++) { nodes[i][x] = rand() % 501; nodes[i][y] = rand() % 501; myfile <<nodes[i][x]<<" "<<nodes[i][y]; } myfile.close(); } now the next step is to improve this code to distribute these nodes in order ( "Imust divide both xy_coordinates as : x= 0-100-200-300-400-500 & y=0-100-200-300-400-500) next is to distribute the nodes (regardless number of nodes) in order range Starting from (0,100 )….(100,100)..(100,200)…….untile i reach the last point (500,500),, ") I’m really confused of how to do it correctly I start to think to define 2 dimensional array , and then to define 2 for loops enter code here Int no_nodes=100; Int XY_coordinate [500][500]; For (int i=0;i<no_nodes; i++) { For (int j=0;j<no_nodes; j++)

    Read the article

  • Template problems: No matching function for call

    - by Nick Sweet
    I'm trying to create a template class, and when I define a non-member template function, I get the "No matching function for call to randvec()" error. I have a template class defined as: template <class T> class Vector { T x, y, z; public: //constructors Vector(); Vector(const T& x, const T& y, const T& z); Vector(const Vector& u); //accessors T getx() const; T gety() const; T getz() const; //mutators void setx(const T& x); void sety(const T& y); void setz(const T& z); //operations void operator-(); Vector plus(const Vector& v); Vector minus(const Vector& v); Vector cross(const Vector& v); T dot(const Vector& v); void times(const T& s); T length() const; //Vector<T>& randvec(); //operators Vector& operator=(const Vector& rhs); friend std::ostream& operator<< <T>(std::ostream&, const Vector<T>&); }; and the function in question, which I've defined after all those functions above, is: //random Vector template <class T> Vector<double>& randvec() { const int min=-10, max=10; Vector<double>* r = new Vector<double>; int randx, randy, randz, temp; const int bucket_size = RAND_MAX/(max-min +1); temp = rand(); //voodoo hackery do randx = (rand()/bucket_size)+min; while (randx < min || randx > max); r->setx(randx); do randy = (rand()/bucket_size)+min; while (randy < min || randy > max); r->sety(randy); do randz = (rand()/bucket_size)+min; while (randz < min || randz > max); r->setz(randz); return *r; } Yet, every time I call it in my main function using a line like: Vector<double> a(randvec()); I get that error. However, if I remove the template and define it using 'double' instead of 'T', the call to randvec() works perfectly. Why doesn't it recognize randvec()? P.S. Don't mind the bit labeled voodoo hackery - this is just a cheap hack so that I can get around another problem I encountered.

    Read the article

  • Cumulative +1/-1 Cointoss crashes on 1000 iterations. Please advise; c++ boost random libraries

    - by user1731972
    following some former advice Multithreaded application, am I doing it right? I think I have a threadsafe number generator using boost, but my program crashes when I input 1000 iterations. The output .csv file when graphed looks right, but I'm not sure why it's crashing. It's using _beginthread, and everyone is telling me I should use the more (convoluted) _beingthreadex, which I'm not familiar with. If someone could recommend an example, I would greatly appreciate it. Also... someone pointed out I should be applying a second parameter to my _beginthread for the array counting start positions, but I have no idea how to pass more than one parameter, other than attempting to use a structure, and I've read structure's and _beginthread don't get along (although, I could just use the boost threads...) #include <process.h> #include <windows.h> #include <iostream> #include <fstream> #include <time.h> #include <random> #include <boost/random.hpp> //for srand48_r(time(NULL), &randBuffer); which doesn't work #include <stdio.h> #include <stdlib.h> //#include <thread> using namespace std; using namespace boost; using namespace boost::random; void myThread0 (void *dummy ); void myThread1 (void *dummy ); void myThread2 (void *dummy ); void myThread3 (void *dummy ); //for random seeds void initialize(); //from http://stackoverflow.com/questions/7114043/random-number-generation-in-c11-how-to-generate-how-do-they-work uniform_int_distribution<> two(1,2); typedef std::mt19937 MyRNG; // the Mersenne Twister with a popular choice of parameters uint32_t seed_val; // populate somehow MyRNG rng1; // e.g. keep one global instance (per thread) MyRNG rng2; // e.g. keep one global instance (per thread) MyRNG rng3; // e.g. keep one global instance (per thread) MyRNG rng4; // e.g. keep one global instance (per thread) //only needed for shared variables //CRITICAL_SECTION cs1,cs2,cs3,cs4; // global int main() { ofstream myfile; myfile.open ("coinToss.csv"); int rNum; long numRuns; long count = 0; int divisor = 1; float fHolder = 0; long counter = 0; float percent = 0.0; //? //unsigned threadID; //HANDLE hThread; initialize(); HANDLE hThread[4]; const int size = 100000; int array[size]; printf ("Runs (uses multiple of 100,000) "); cin >> numRuns; for (int a = 0; a < numRuns; a++) { hThread[0] = (HANDLE)_beginthread( myThread0, 0, (void*)(array) ); hThread[1] = (HANDLE)_beginthread( myThread1, 0, (void*)(array) ); hThread[2] = (HANDLE)_beginthread( myThread2, 0, (void*)(array) ); hThread[3] = (HANDLE)_beginthread( myThread3, 0, (void*)(array) ); //waits for threads to finish before continuing WaitForMultipleObjects(4, hThread, TRUE, INFINITE); //closes handles I guess? CloseHandle( hThread[0] ); CloseHandle( hThread[1] ); CloseHandle( hThread[2] ); CloseHandle( hThread[3] ); //dump array into calculations //average array into fHolder //this could be split into threads as well for (int p = 0; p < size; p++) { counter += array[p] == 2 ? 1 : -1; //cout << array[p] << endl; //cout << counter << endl; } //this fHolder calculation didn't work //fHolder = counter / size; //so I had to use this cout << counter << endl; fHolder = counter; fHolder = fHolder / size; myfile << fHolder << endl; } } void initialize() { //seed value needs to be supplied //rng1.seed(seed_val*1); rng1.seed((unsigned int)time(NULL)); rng2.seed(((unsigned int)time(NULL))*2); rng3.seed(((unsigned int)time(NULL))*3); rng4.seed(((unsigned int)time(NULL))*4); }; void myThread0 (void *param) { //EnterCriticalSection(&cs1); //aquire the critical section object int *i = (int *)param; for (int x = 0; x < 25000; x++) { //doesn't work, part of merssene twister //i[x] = next(); i[x] = two(rng1); //original srand //i[x] = rand() % 2 + 1; //doesn't work for some reason. //uint_dist2(rng); //i[x] = qrand() % 2 + 1; //cout << i[x] << endl; } //LeaveCriticalSection(&cs1); // release the critical section object } void myThread1 (void *param) { //EnterCriticalSection(&cs2); //aquire the critical section object int *i = (int *)param; for (int x = 25000; x < 50000; x++) { //param[x] = rand() % 2 + 1; i[x] = two(rng2); //i[x] = rand() % 2 + 1; //cout << i[x] << endl; } //LeaveCriticalSection(&cs2); // release the critical section object } void myThread2 (void *param) { //EnterCriticalSection(&cs3); //aquire the critical section object int *i = (int *)param; for (int x = 50000; x < 75000; x++) { i[x] = two(rng3); //i[x] = rand() % 2 + 1; //cout << i[x] << endl; } //LeaveCriticalSection(&cs3); // release the critical section object } void myThread3 (void *param) { //EnterCriticalSection(&cs4); //aquire the critical section object int *i = (int *)param; for (int x = 75000; x < 100000; x++) { i[x] = two(rng4); //i[x] = rand() % 2 + 1; //cout << i[x] << endl; } //LeaveCriticalSection(&cs4); // release the critical section object }

    Read the article

  • Debian - Problems Unmounting External Hard Drives

    - by user331981
    I recently installed Debian Testing on a new laptop and I just noticed that I am having some issues with unmounting external hard drives. I am using Mate Desktop 1.8.1. With the 1st drive, if I right click on the drive and select “safely remove”: The drive unmounts, spins down, immediately spins back up an remounts. Unable to unmount. With the 2nd drive, if I right click on the drive and select “safely remove”: The drive unmounts but does not spin down. With the 3rd drive, if I right click on the drive and select “safely remove”: The drive unmounts but does not spin down, immediately spins back up but does not remount, and after 20 seconds, it spins down and stays that way. Behavior is the same on both USB 2.0 and USB 3.0 ports. On my last laptop, on which I also used Debian Testing + Mate desktop, the safe removal of drives worked out of the box and I never had an issue with it. The drives would unmount, spin down and stay that way. To remount the drive, one needed to unplug the device and plug it back in. I am unsure how to troubleshoot this issue and I am not sure if it is merely a matter of installing a “missing” package of editing a config file. Thank you in advance.

    Read the article

  • 2012 Oracle Fusion Innovation Awards - Part 2

    - by Michelle Kimihira
    Author: Moazzam Chaudry Continuing from Friday's blog on 2012 Oracle Fusion Innovation Awards, this blog (Part 2) will provide more details around the customers. It was a tremendous honor to be in single room of winners. We only wish we could have had more time to share stories from all the winners.  We received great insight from all the innovative solutions that our customers deploy and would like to share them broadly, so that others can benefit from best practices. There was a customer panel session joined by Ingersoll Rand, Nike and Motability and here is what was discussed: Barry Bonar, Enterprise Architect from Ingersoll Rand shared details around their solution, comprised of Oracle Exalogic, Oracle WebLogic Server and Oracle SOA Suite. This combined solutoin enabled their business transformation to increase decision-making, speed and efficiency, resulting in 40% reduced IT spend, 41X Faster response time and huge cost savings. Ashok Balakrishnan, Architect from Nike shared how they leveraged Oracle Coherence to analyze their digital "footprint" of activities. This helps them compete, collaborate and compare athletic data over time. Lastly, Ashley Doodly, Head of IT from Motability shared details around their solution compromised of Oracle SOA Suite, Service Bus, ADF, Coherence, BO and E-Business Suite. This solution helped Motability achieve 100% ROI within the first few months, performance in seconds vs. 10's of minutes and tremendous improvement in throughput that increased up to 50%.  This year's winners by category are: Oracle Exalogic Customer Results using Fusion Middleware Netshoes ATG on Exalogic: 6X Reduced H/W foot print, 6.2X increased throughput and 3 weeks time to market Claro Part of America Movil, running mission critical Java Application on Exalogic with 35X Faster Java response time, 5X Throughput Underwriters Laboratories Exalogic as an Apps Consolidation platform to power tremendous growth Ingersoll Rand EBS on Exalogic: Up to 40% Reduction in overall IT budget, 3x reduced foot print Oracle Cloud Application Foundation Customer Results using Fusion Middleware  Mazda Motor Corporation Tuxedo ART Batch runtime environment to migrate their batch apps on new open environment and reduce main frame cost. HOTELBEDS Technology Open Source to WebLogic transformation Globalia Corporation Introduced Oracle Coherence to fully reengineer DTH system and provide multiple business and technical benefits Nike Nike+, digital sports platform, has 8M users and is expecting an 5X increase in users, many of who will carry multiple devices that frequently sync data with the Digital Sport platform Comcast Corporation The solution is expected to increase availability, continuity, performance, and simplify and make the code at the application layer more flexible. Oracle SOA and Oracle BPM Customer Results using Fusion Middleware NTT Docomo Network traffic solution based on Oracle event processing and coherence - massive in scale: 12M users (50M in future) - 800,000 events/sec. Schneider National, Inc. SOA/B2B/ADF/Data Integration to orchestrate key order processes across Siebel, OTM & EBS.  Platform runs 60M trans/day and  50 million composite SOA instances per day across 10G and 11G Amadeus Oracle BPM solution: Business Rules and processes vary across local (80), regional (~10) and corporate approval process. Up to 10 levels of approval. Plans to deploy across 20+ markets Navitar SOA solution integrates a fully non-Oracle legacy application/ERP environment using Oracle’s SOA Suite and Oracle AIA Foundation Pack. Motability Uses SOA Suite to synchronize data across the systems and to manage the vehicle remarketing process Oracle WebCenter Customer Results using Fusion Middleware  News Limited Single platform running websites for 50% of Australia's newspapers University of Louisville “Facebook for Medicine”: Oracle Webcenter platform and Oracle BIEE to analyze patient test data and uncover potential health issues. Expecting annualized ROI of 277% China Mobile Jiangsu Company portal (25k users) to drive collaboration & productivity Life Technologies Portal for remotely monitoring & repairing biotech instruments LA Dept. of Water & Power Oracle WebCenter Portal to power ladwp.com on desktop and mobile for 1.6million users Oracle Identity Management Customer Results using Fusion Middleware Education Testing Service Identity Management platform for provisioning & SSO of 6 million GRE, GMAT, TOEFL customers Avea Oracle Identity Manager allowing call center personnel to quickly change Identity Profile to handle varying call loads based on a user self service interface. Decreased Admin Cost by 30% Oracle Data Integration Customer Results using Fusion Middleware Raymond James Near real-time integration for improved systems (throughput & performance) and enhanced operational flexibility in a 24 X 7 environment Wm Morrison Supermarkets Electronic Point of Sale integration handling over 80 million transactions a day in near real time (15 min intervals) Oracle Application Development Framework and Oracle Fusion Development Customer Results using Fusion Middleware Qualcomm Incorporated Solution providing  immediate business value enabling a self-service model necessary for growing the new customer base, an increase in customer satisfaction, reduced “time-to-deliver” Micros Systems, Inc. ADF, SOA Suite, WebCenter  enables services that include managing distribution of hotel rooms availability and rates to channels such as Hotel Web-site, Expedia, etc. Marfin Egnatia Bank A new web 2.0 UI provides a much richer experience through the ADF solution with the end result being one of boosting end-user productivity    Business Analytics (Oracle BI, Oracle EPM, Oracle Exalytics) Customer Results using Fusion Middleware INC Research Self-service customer portal delivering 5–10% of the overall revenue - expected to grow fast with the BI solution Experian Reduction in Time to Complete the Financial Close Process Hologic Inc Solution, saving months of decision-making uncertainty! We look forward to seeing many more innovative nominations. The nominatation process for 2013 begins in April 2013.    Additional Information: Blog: Oracle WebCenter Award Winners Blog: Oracle Identity Management Winners Blog: Oracle Exalogic Winners Blog: SOA, BPM and Data Integration will be will feature award winners in its respective areas this week Subscribe to our regular Fusion Middleware Newsletter Follow us on Twitter and Facebook

    Read the article

  • Random value from Flags enum

    - by Chris Porter
    Say I have a function that accepts an enum decorated with the Flags attribute. If the value of the enum is a combination of more than one of the enum elements how can I extract one of those elements at random? I have the following but it seems there must be a better way. [Flags] enum Colours { Blue = 1, Red = 2, Green = 4 } public static void Main() { var options = Colours.Blue | Colours.Red | Colours.Green; var opts = options.ToString().Split(','); var rand = new Random(); var selected = opts[rand.Next(opts.Length)].Trim(); var myEnum = Enum.Parse(typeof(Colours), selected); Console.WriteLine(myEnum); Console.ReadLine(); }

    Read the article

  • Where is the virtual function call overhead?

    - by Semen Semenych
    Hello everybody, I'm trying to benchmark the difference between a function pointer call and a virtual function call. To do this, I have written two pieces of code, that do the same mathematical computation over an array. One variant uses an array of pointers to functions and calls those in a loop. The other variant uses an array of pointers to a base class and calls its virtual function, which is overloaded in the derived classes to do absolutely the same thing as the functions in the first variant. Then I print the time elapsed and use a simple shell script to run the benchmark many times and compute the average run time. Here is the code: #include <iostream> #include <cstdlib> #include <ctime> #include <cmath> using namespace std; long long timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p) { return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) - ((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec); } void function_not( double *d ) { *d = sin(*d); } void function_and( double *d ) { *d = cos(*d); } void function_or( double *d ) { *d = tan(*d); } void function_xor( double *d ) { *d = sqrt(*d); } void ( * const function_table[4] )( double* ) = { &function_not, &function_and, &function_or, &function_xor }; int main(void) { srand(time(0)); void ( * index_array[100000] )( double * ); double array[100000]; for ( long int i = 0; i < 100000; ++i ) { index_array[i] = function_table[ rand() % 4 ]; array[i] = ( double )( rand() / 1000 ); } struct timespec start, end; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); for ( long int i = 0; i < 100000; ++i ) { index_array[i]( &array[i] ); } clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); unsigned long long time_elapsed = timespecDiff(&end, &start); cout << time_elapsed / 1000000000.0 << endl; } and here is the virtual function variant: #include <iostream> #include <cstdlib> #include <ctime> #include <cmath> using namespace std; long long timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p) { return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) - ((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec); } class A { public: virtual void calculate( double *i ) = 0; }; class A1 : public A { public: void calculate( double *i ) { *i = sin(*i); } }; class A2 : public A { public: void calculate( double *i ) { *i = cos(*i); } }; class A3 : public A { public: void calculate( double *i ) { *i = tan(*i); } }; class A4 : public A { public: void calculate( double *i ) { *i = sqrt(*i); } }; int main(void) { srand(time(0)); A *base[100000]; double array[100000]; for ( long int i = 0; i < 100000; ++i ) { array[i] = ( double )( rand() / 1000 ); switch ( rand() % 4 ) { case 0: base[i] = new A1(); break; case 1: base[i] = new A2(); break; case 2: base[i] = new A3(); break; case 3: base[i] = new A4(); break; } } struct timespec start, end; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); for ( int i = 0; i < 100000; ++i ) { base[i]->calculate( &array[i] ); } clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); unsigned long long time_elapsed = timespecDiff(&end, &start); cout << time_elapsed / 1000000000.0 << endl; } My system is LInux, Fedora 13, gcc 4.4.2. The code is compiled it with g++ -O3. The first one is test1, the second is test2. Now I see this in console: [Ignat@localhost circuit_testing]$ ./test2 && ./test2 0.0153142 0.0153166 Well, more or less, I think. And then, this: [Ignat@localhost circuit_testing]$ ./test2 && ./test2 0.01531 0.0152476 Where are the 25% which should be visible? How can the first executable be even slower than the second one? I'm asking this because I'm doing a project which involves calling a lot of small functions in a row like this in order to compute the values of an array, and the code I've inherited does a very complex manipulation to avoid the virtual function call overhead. Now where is this famous call overhead?

    Read the article

  • How do I get the cell value from a formula in Excel using VBA?

    - by Simon
    I have a formula in a range of cells in a worksheet which evaluate to numerical values. How do I get the numerical values in VBA from a range passed into a function? Let's say the first 10 rows of column A in a worksheet contain rand() and I am passing that as an argument to my function... public Function X(data as Range) as double for c in data.Cells c.Value 'This is always Empty c.Value2 'This is always Empty c.Formula 'This contains RAND() next end Function I call the function from a cell... =X(a1:a10) How do I get at the cell value, e.g. 0.62933645? Excel 2003, VB6

    Read the article

  • Allowing optional variables with Rewrite Cond

    - by James Doc
    I currently have the following code: RewriteCond %{REQUEST_URI} !assets/ RewriteCond %{REQUEST_URI} !uploads/ RewriteRule ^([a-z|0-9_&;=-]+)/([a-z|0-9_&;=-]+) index.php?method=$1&value=$2 [NC,L] This works perfectly to redirect 'page/home' to 'index.php?method=page&value=home. However at some points I need to add an extra variable or two to the query string such as 'admin/useraccounts/mod/2'. When I simply tack on bits to the end of the rewrite rule it works if all the variables are 'page/home/rand/rand' or 'admin/useraccounts/mod/2', but if anything is missing such as 'page/home' I get a 404. What am I doing wrong? Many thanks.

    Read the article

  • PHP get url out of a string and some more...

    - by pnm123
    Hello, I have a string like this The theme song of whatever - http://www.anydomain.com/pop_new.php?sid=10623&aid=1581&rand=0.6808111508818073 #string And now, I need to do the following thing. Get the url from above string http://www.anydomain.com/pop_new.php?sid=10623&aid=1581&rand=0.6808111508818073 Replace the url to {%url%} so It should look like The theme song of whatever - {%url%} #string Currently I am using the following code but it fails to replace the above url. $urlregex_ = "(https?)\:\/\/[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*(\/([a-z0-9+\$_-]\.?)+)*\/?(\?[a-z+&\$_.-][a-z0-9;:@/&%=+\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?"; preg_match('~'.$urlregex_.'~',preg_replace('/\+/',' ',$url),$url_only); $url_ = preg_replace('/ /','+',$url_only[0]); $text = preg_replace('~'.$url_.'~','{%url%} ',$url); return array('url' => $url_only[0], 'text' => $text);` Hope you can help, thanks, pnm123

    Read the article

  • How to add if statement in SQL ?

    - by shin
    I have a following MySQL with two parameters, $catname and $limit=1. And it is working fine. SELECT P.*, C.Name AS CatName FROM omc_product AS P LEFT JOIN omc_category AS C ON C.id = P.category_id WHERE C.Name = '$catname' AND p.status = 'active' ORDER BY RAND() LIMIT 0, $limit Now I want to add another parameter $order. $order can be either ODER BY RAND() or ORDER BY product_order in the table omc_product. Could anyone tell me how to write this query please? Thanks in advance.

    Read the article

  • SQL: select random row from table where the ID of the row isn't in another table?

    - by johnrl
    I've been looking at fast ways to select a random row from a table and have found the following site: http://74.125.77.132/search?q=cache:http://jan.kneschke.de/projects/mysql/order-by-rand/&hl=en&strip=1 What I want to do is to select a random url from my table 'urls' that I DON'T have in my other table 'urlinfo'.The query I am using now selects a random url from 'urls' but I need it modified to only return a random url that is NOT in the 'urlinfo' table. Heres the query: SELECT url FROM urls JOIN (SELECT CEIL(RAND() * (SELECT MAX(urlid) FROM urls ) ) AS urlid ) AS r2 USING(urlid); And the two tables: CREATE TABLE urls ( urlid INT NOT NULL AUTO_INCREMENT PRIMARY KEY, url VARCHAR(255) NOT NULL, ) ENGINE=INNODB; CREATE TABLE urlinfo ( urlid INT NOT NULL PRIMARY KEY, urlinfo VARCHAR(10000), FOREIGN KEY (urlid) REFERENCES urls (urlid) ) ENGINE=INNODB;

    Read the article

  • How to create a random string of characters in C#?

    - by Keltex
    I'm trying to create random strings of characters. I'm wondering if there might be a more efficient way. Here's my algorithm: string RANDOM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#@$^*()"; StringBuilder sb = new StringBuilder(); int length = rand.Next(10) + 1; for (int idx = 0; idx < length; ++idx) { sb.Append(RANDOM[rand.Next(RANDOM.Length)]); } string RandomString = sb.ToString(); I'm wondering if the StringBuilder is the best choice. Also if selecting a random character from my RANDOM string is the best way.

    Read the article

  • HTML wrapper div over embedded flash object cannot be "clickable" by jQuery

    - by Michael Mao
    Hi all: I've been trying to do as the client requested : redirect to campaign page then to destination page once a customer clicks on the top banner in swf format. You can check what's been done at :http://ausdcf.org If you are using Firefox, Chrome or Safari, I suspect you can reach the destination page. However, if you are using IE or Opera, I doubt it. I think to cause of such a weird problem is: The swf ojbects don't have a link to url, SO I have to hack the theme template file like this : <div id="header">'; /* * A quick and dirty way to put some swf into PHP, and rotate among them ... */ //available banners $banners = array( 'http://localhost/smf/flash/banner_fertalign_1.swf', 'http://localhost/smf/flash/banner_fertalign_2.swf', 'http://localhost/smf/flash/banner_fertalign_3.swf' ); //get random banner srand((double) microtime() * 1000000); $rand = rand(0,count($banners)-1); echo '<div id="top_banner_clickable">'; echo '<div id="top_banner_wrapper">'; echo '<object width="400" height="60">'; echo '<param name="wmode" value="transparent">'; echo '<embed wmode="transparent" src="'.$banners[$rand].'" '; echo 'width="400" height="60" type="application/x-shockwave-flash"'; echo 'pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" />'; echo '</object>'; echo '</div>'; echo '</div>'; And the related jQuery code is like this: /* master.js */ $(document).ready(function() { $("#top_banner_clickable").click(function() { window.location ="http://ausdcf.org/campaign/"; }); }); I absolutely know nothing about Flash or embedded objects. I guess that's the cause of this problem. Plus, I don't know why it works with some browsers but not all... I even tried to add a z-index to the wrapper div in css like this: #top_banner_clickable { z-index : 100; } No this wouldn't do, either... Is there a way to go around this issue? Many thanks in advance.

    Read the article

  • Do sockets opened with fsockopen stay open after you leave the page via your browser?

    - by Rob
    if(isset($_GET['host'])&&is_numeric($_GET['time'])){ $pakits = 0; ignore_user_abort(TRUE); set_time_limit(0); $exec_time = $_GET['time']; $time = time(); //print "Started: ".time('h:i:s')."<br>"; $max_time = $time+$exec_time; $host = $_GET['host']; for($i=0;$i<65000;$i++){ $out .= 'X'; } while(1){ $pakits++; if(time() > $max_time){ break; } $rand = rand(1,65000); $fp = fsockopen('udp://'.$host, $rand, $errno, $errstr, 5); if($fp){ fwrite($fp, $out); fclose($fp); } } echo "<br><b>UDP Flood</b><br>Completed with $pakits (" . round(($pakits*65)/1024, 2) . " MB) packets averaging ". round($pakits/$exec_time, 2) . " packets per second \n"; echo '<br><br> <form action="'.$surl.'" method=GET> <input type="hidden" name="act" value="phptools"> Host: <input type=text name=host value=localhost> Length (seconds): <input type=text name=time value=9999> <input type=submit value=Go></form>'; }else{ echo '<br><b>UDP Flood</b><br> <form action=? method=GET> <input type="hidden" name="act" value="phptools"> Host: <br><input type=text name=host value=localhost><br> Length (seconds): <br><input type=text name=time value=9999><br> <br> <input type=submit value=Go></form>'; } I've been looking around and asking my friends for awhile now, if I use this script to tell the server to open the sockets using fsockopen, if I leave the webpage will the sockets remain open until the duration is completed?

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >