Search Results

Search found 1698 results on 68 pages for 'loops'.

Page 3/68 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Why are Javascript for/in loops so verbose?

    - by Matthew Scharley
    I'm trying to understand the reasoning behind why the language designers would make the for (.. in ..) loops so verbose. For example: for (var x in Drupal.settings.module.stuff) { alert("Index: " + x + "\nValue: " + Drupal.settings.module.stuff[x]); } It makes trying to loop over anything semi-complex like the above a real pain as you either have to alias the value locally inside the loop yourself, or deal with long access calls. This is especially painful if you have two to three nested loops. I'm assuming there is a reason why they would do things this way, but I'm struggling with the reasoning.

    Read the article

  • Loops, Recursion and Memoization in JavaScript

    - by Ken Dason
    Originally posted on: http://geekswithblogs.net/kdason/archive/2013/07/25/loops-recursion-and-memoization-in-javascript.aspxAccording to Wikipedia, the factorial of a positive integer n (denoted by n!) is the product of all positive integers less than or equal to n. For example, 5! = 5 x 4 x 3 x 2 x 1 = 120. The value of 0! is 1. We can use factorials to demonstrate iterative loops and recursive functions in JavaScript.  Here is a function that computes the factorial using a for loop: Output: Time Taken: 51 ms Here is the factorial function coded to be called recursively: Output: Time Taken: 165 ms We can speed up the recursive function with the use of memoization.  Hence,  if the value has previously been computed, it is simply returned and the recursive call ends. Output: Time Taken: 17 ms

    Read the article

  • An observation on .NET loops – foreach, for, while, do-while

    It’s very common that .NET programmers use “foreach” loop for iterating through collections. Following is my observation whilst I was testing simple scenario on loops. “for” loop is 30% faster than “foreach” and “while” loop is 50% faster than “foreach”. “do-while” is bit faster than “while”. Someone may feel that how does it make difference if I’m iterating only 1000 times in a loop. This test case is only for simple iteration. According to the "Data structure" concepts, best and worst cases are completely based on the data we provide to the algorithm. so we can not conclude that a "foreach" algorithm is not good. All I want to tell that we need to be little cautious even choosing the loops. Example:- You might want to chose quick sort when you want to sort more numbers. At the same time bubble sort may be effective than quick sort when you want to sort less numbers. Take a simple scenario, a request of a simple web application fetches the data of 10000 (10K) rows and iterating them for some business logic. Think, this application is being accessed by 1000 (1K) people simultaneously. In this simple scenario you are ending up with 10000000 (10Million or 1 Crore) iterations. below is the test scenario with simple console application to test 100 Million records. using System;using System.Collections.Generic;using System.Diagnostics;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { var sw = new Stopwatch(); var numbers = GetSomeNumbers(); sw.Start(); foreach (var item in numbers) { } sw.Stop(); Console.WriteLine( String.Format("\"foreach\" took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); for (int i = 0; i < numbers.Count; i++) { } sw.Stop(); Console.WriteLine( String.Format("\"for\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); var it = 0; while (it++ < numbers.Count) { } sw.Stop(); Console.WriteLine( String.Format("\"while\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); var it2 = 0; do { } while (it2++ < numbers.Count); sw.Stop(); Console.WriteLine( String.Format("\"do-while\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); } #region Get me 10Crore (100 Million) numbers private static List<int> GetSomeNumbers() { var lstNumbers = new List<int>(); var count = 100000000; for (var i = 1; i <= count; i++) { lstNumbers.Add(i); } return lstNumbers; } #endregion Get me some numbers }} In above example, I was just iterating through 100 Million numbers. You can see the time to execute various  loops provided in .NET Output "foreach" took 1108 milliseconds "for" loop took 727 milliseconds "while" loop took 596 milliseconds "do-while" loop took 594 milliseconds   Press any key to continue . . . So I feel we need to be careful while choosing the looping strategy. Please comment your thoughts. span.fullpost {display:none;}

    Read the article

  • Input handling between game loops

    - by user48023
    This may be obvious and trivial for you but as I am a newbie in programming I come with a specific question. I have three loops in my game engine which are input-loop, update-loop and render-loop. Update-loop is set to 10 ticks per second with a fixed timestep, render-loop is capped at around 60 fps and the input-loop runs as fast as possible. I am using one of the Javascript frameworks which provide such things but it doesn't really matter. Let's say I am rendering a tile map and the view of which elements are rendered depends on camera-like movement variables which are modified during key pressing. This is only about camera/viewport and rendering, no game physics involved here. And now, how can I handle input events among these loops to keep consistent engine reaction? Am I supposed to read the current variable modified with input and do some needed calculations in a update-loop and share the result so it could be interpolated in a render-loop? Or read the input effect directly inside the render-loop and put needed calculations inside? I thought interpreting user input inside an update-loop with a low tick rate would be inaccurate and kind of unresponsive while rendering with interpolation in the final view. How it is done properly in games overall?

    Read the article

  • How Spanning Tree Protocol detects Loops

    - by AMIT
    For last few days I've been reading about Spanning Tree Protocol ,L2 protocol and understood how it prevents loop in network ,various steps in STP but one thing i wanted to know how STP actually detects the loops in network so that it can prevent it.Somewhere I read STP uses BPDU as probe and detects loops I mean how it happen is when switch send a BPDU with Destination Address as multicast and receive same BPDU again mean there is loop in network . But is it how STP detects loops in network?

    Read the article

  • Java Error Using Loops [migrated]

    - by Shaun
    I am facing a error in Java using the method Loops. I am a basic user learning Java and I am following a book with teaches you the basics of Java. I have this problem when I use this code in my Java Program. It gives me an red line under my code. Here's my code: public class Game{ public static void main(String[] args){ for (int dex = 0; dex < 1000; dex++) { if (dex % 12 == 0) { System.out.println(“#: “ + dex); } } } } I have been following the tutorials correctly. I am a bit lost where I have gone or done wrong. I have my public static codes and such as you'd require in any Java programming. Here's are the error given): Cannot resolve method: 'Println(? , ?)' Expression expected ',' or ')' expected Unexpected Token ';' expected

    Read the article

  • C# double &amp; nary for loops

    - by MarkPearl
    Something that I wasn’t aware was possible in C# was double for loops… they have the following format. for (int x = 0, y = 0; x < 10; x++, y=x*2) { Console.Write("{0} ", y); } Console.ReadLine(); This would give you the following output… 0 2 4 6 8 10 12 14 16 18 In fact you can use as many variables as you want, the following would also be valid… for (int x = 0, y = 0, z = 10; x < 10; x++, y=x*2) { Console.Write("{0} ", z); } Console.ReadLine();

    Read the article

  • Do you use i-->0 for backward loops?

    - by maaartinus
    Some people write for (int i=N; i-->0; ) doSomething(i); instead of for (int i=N-1; i>=0; --i) doSomething(i); for backward loops. The --> "operator"1 looks very confusing at the first glance, but it's trivial: i-->0 simply parses as (i--)>0, and once you get it, you see it immediately. The main disadvantage is the strange look. The advantage is that you'll get it always right (unlike the more verbose version offering the possibility to forget something, which really happened to me a couple of times). What do you think about using the --> "operator"? 1First time I saw the funny term in a comment to this question today.

    Read the article

  • Using prefix incremented loops in C#

    - by KChaloux
    Back when I started programming in college, a friend encouraged me to use the prefix incrementation operator ++i instead of the postfix i++, citing that there was a slight chance of better performance with no real chance of a downside. I realize this is true in C++, and it's become a general habit that I continue to do. I'm led to believe that it makes little to no difference when used in a loop in C#, regardless of data type. Apparently the ++ operator can't be overridden. Nevertheless, I like the appearance more, and don't see a direct downside to it. It did astonish a coworker just a moment ago though, he made the (fairly logical) assumption that my loop would terminate early as a result. He's a self-taught programmer, and apparently never came across the C++ convention. That made me question whether or not the equivalent behavior of pre- and post-fix increment and decrement operators in loops is well known enough. Is it acceptable for me to continue using ++i in looping constructs because of style preference, even though it has no real performance benefit? Or is it likely to cause confusion amongst other programmers? Note: This is assuming the ++i convention is used consistently throughout all code.

    Read the article

  • What's slowing for loops/assignment vs. C?

    - by Lee
    I have a collection of PHP scripts that are extremely CPU intensive, juggling millions of calculations across hundreds of simultaneous users. I'm trying to find a way to speed up the internals of PHP variable assignment, and looping sequences vs C. Although PHP is obviously loosely typed, is there any way/extension to specifically assign type (assign, not cast, which seems even more expensive) in a C-style fashion? Here's what I mean. This is some dummy code in C: #include <stdio.h> int main() { unsigned long add=0; for(unsigned long x=0;x<100000000;x++) { add = x*59328409238; } printf("x is %ld\n",add); } Pretty self-explanatory -- it loops 100 million times, multiples each iteration by an arbitrary number of some 59 billion, assigns it to a variable and prints it out. On my Macbook, compiling it and running it produced: lees-macbook-pro:Desktop lee$ time ./test2 x is 5932840864471590762 real 0m0.266s user 0m0.253s sys 0m0.002s Pretty darn fast! A similar script in PHP 5.3 CLI... <?php for($i=0;$i<100000000;$i++){ $a=$i*59328409238; } echo $a."\n"; ?> ... produced: lees-macbook-pro:Desktop lee$ time /Applications/XAMPP/xamppfiles/bin/php test3.php 5.93284086447E+18 real 0m22.837s user 0m22.110s sys 0m0.078s Over 22 seconds vs 0.2! I realize PHP is doing a heck of a lot more behind the scenes than this simple C program - but is there any way to make the PHP internals to behave more 'natively' on primitive types and loops?

    Read the article

  • C programming - How to print numbers with a decimal component using only loops?

    - by californiagrown
    I'm currently taking a basic intro to C programming class, and for our current assignment I am to write a program to convert the number of kilometers to miles using loops--no if-else, switch statements, or any other construct we haven't learned yet are allowed. So basically we can only use loops and some operators. The program will generate three identical tables (starting from 1 kilometer through the input value) for one number input using the while loop for the first set of calculations, the for loop for the second, and the do loop for the third. I've written the entire program, however I'm having a bit of a problem with getting it to recognize an input with a decimal component. Here is what I have for the while loop conversions: #include <stdio.h> #define KM_TO_MILE .62 main (void) { double km, mi, count; printf ("This program converts kilometers to miles.\n"); do { printf ("\nEnter a positive non-zero number"); printf (" of kilometers of the race: "); scanf ("%lf", &km); getchar(); }while (km <= 1); printf ("\n KILOMETERS MILES (while loop)\n"); printf (" ========== =====\n"); count = 1; while (count <= km) { mi = KM_TO_MILE * count; printf ("%8.3lf %14.3lf\n", count, mi); ++count; } getchar(); } The code reads in and converts integers fine, but because the increment only increases by 1 it won't print a number with a decimal component (e.g. 3.2, 22.6, etc.). Can someone point me in the right direction on this? I'd really appreciate any help! :)

    Read the article

  • Implementing Brainf*ck loops in an interpreter

    - by sub
    I want to build a Brainf*ck (Damn that name) interpreter in my freshly created programming language to prove it's turing-completeness. Now, everything is clear so far (<+-,.) - except one thing: The loops ([]). I assume that you know the (extremely hard) BF syntax from here on: How do I implement the BF loops in my interpreter? How could the pseudocode look like? What should I do when the interpreter reaches a loop beginning ([) or a loop end (])? Checking if the loop should continue or stop is not the problem (current cell==0), but: When and where do I have to check? How to know where the loop beginning is located? How to handle nested loops? As loops can be nested I suppose that I can't just use a variable containing the starting position of the current loop. I've seen very small BF interpreters implemented in various languages, I wonder how they managed to get the loops working but can't figure it out.

    Read the article

  • Can I use loops in repeater? Is it reccomended?

    - by iTayb
    My datasource has an Rating dataItem contains an integer from 0 to 5. I'd like to print stars accordignly. I'm trying to do it within Repeater control: <b>Rating:</b> <% for (int j = 1; j <= DataBinder.Eval(Container.DataItem, "Rating"); j++) { %> <img src="App_Pics/fullstar.png" /> <% } for (int j = 1; j <= 5 - DataBinder.Eval(Container.DataItem, "Rating"); j++) { %> <img src="App_Pics/emptystar.png" /> <%} %> I get the error The name 'Container' does not exist in the current context. It is weird, because when I used <%# DataBinder.Eval(Container.DataItem, "Name")%> a line before, it worked great. Is it clever to include loops in my aspx page? I think it's not very convenient. What's my alternatives? What's that # means? Thank you very much.

    Read the article

  • Can I use loops in repeater? Is it recommended?

    - by iTayb
    My datasource has an Rating dataItem contains an integer from 0 to 5. I'd like to print stars accordignly. I'm trying to do it within Repeater control: <b>Rating:</b> <% for (int j = 1; j <= DataBinder.Eval(Container.DataItem, "Rating"); j++) { %> <img src="App_Pics/fullstar.png" /> <% } for (int j = 1; j <= 5 - DataBinder.Eval(Container.DataItem, "Rating"); j++) { %> <img src="App_Pics/emptystar.png" /> <%} %> I get the error The name 'Container' does not exist in the current context. It is weird, because when I used <%# DataBinder.Eval(Container.DataItem, "Name")%> a line before, it worked great. Is it clever to include loops in my aspx page? I think it's not very convenient. What's my alternatives? What's that # means? Thank you very much.

    Read the article

  • How can I increment a counter every N loops in JMeter?

    - by Dave Hunt
    I want to test concurrency, and reliably replicate an issue that JMeter brought to my attention. What I want to do is set a unique identifier (currently the time in milliseconds with a counter appended) and increment the counter between loops but not between threads. The idea being that the number of threads I have set up is the number of identical identifiers before incrementing and using another. If I had 3 threads with a loop count of 2 I want: 1. Unique ID: <current-time-in-millis>000000 2. Unique ID: <current-time-in-millis>000000 3. Unique ID: <current-time-in-millis>000000 4. Unique ID: <current-time-in-millis>000001 5. Unique ID: <current-time-in-millis>000001 6. Unique ID: <current-time-in-millis>000001 I've tried using Throughput Controllers to increment a counter, as well as several other things that seemed they should work but had no luck. This seems like something JMeter should be able to do. Is there any way to get the value of the loop count?

    Read the article

  • R: Are there any alternatives to loops for subsetting from an optimization standpoint?

    - by Adam
    A recurring analysis paradigm I encounter in my research is the need to subset based on all different group id values, performing statistical analysis on each group in turn, and putting the results in an output matrix for further processing/summarizing. How I typically do this in R is something like the following: data.mat <- read.csv("...") groupids <- unique(data.mat$ID) #Assume there are then 100 unique groups results <- matrix(rep("NA",300),ncol=3,nrow=100) for(i in 1:100) { tempmat <- subset(data.mat,ID==groupids[i]) #Run various stats on tempmat (correlations, regressions, etc), checking to #make sure this specific group doesn't have NAs in the variables I'm using #and assign results to x, y, and z, for example. results[i,1] <- x results[i,2] <- y results[i,3] <- z } This ends up working for me, but depending on the size of the data and the number of groups I'm working with, this can take up to three days. Besides branching out into parallel processing, is there any "trick" for making something like this run faster? For instance, converting the loops into something else (something like an apply with a function containing the stats I want to run inside the loop), or eliminating the need to actually assign the subset of data to a variable?

    Read the article

  • Can we run two simultaneous non-nested loops in Perl?

    - by Mike
    Part of my code goes like this: while(1){ my $winmm = new Win32::MediaPlayer; $winmm->load('1.mp3'); $winmm->play; $winmm->volume(100); Do Some Stuff; last if some condition is met; } Problem is: I want the music to be always on when I'm in the Do Some Stuff stage in the while loop. But the length of the music is so short that it will come to a full stop before I go to the next stage, so I want the music to repeat itself, but the Win32::Mediaplayer module does not seem to have a repeat mode, so I'm thinking of doing an infinite loop for the music playing part. Like this: while(1){ my $winmm = new Win32::MediaPlayer; $winmm->load('1.mp3'); $winmm->play; $winmm->volume(100); } while(2){ Do some stuff; last if some condition is met } But based on my current Perl knowledge if I'm in the while(1) part, I can never go to the while(2) part. Even if it comes to a nested loop, I have to do something to break out of the inside loop before going to the other part of the outside loop. The answer to my question "Can we run two simultaneous non-nested loops in Perl?" may be a NO, but I assume there is some way of handling such situation. Correct me if I'm wrong. Thanks as always for any comments/suggestions :) UPDATE I really appreciate the help from everyone. Thanks :) So the answer to my question is a YES, not a NO. I'm happy that I've learned how to use fork() and threads to solve a real problem :)

    Read the article

  • Why does the order of the loops affect performance when iterating over a 2D array? [closed]

    - by Mark
    Possible Duplicate: Which of these two for loops is more efficient in terms of time and cache performance Below are two programs that are almost identical except that I switched the i and j variables around. They both run in different amounts of time. Could someone explain why this happens? Version 1 #include <stdio.h> #include <stdlib.h> main () { int i,j; static int x[4000][4000]; for (i = 0; i < 4000; i++) { for (j = 0; j < 4000; j++) { x[j][i] = i + j; } } } Version 2 #include <stdio.h> #include <stdlib.h> main () { int i,j; static int x[4000][4000]; for (j = 0; j < 4000; j++) { for (i = 0; i < 4000; i++) { x[j][i] = i + j; } } }

    Read the article

  • Ubuntu 12.04 LTS loops the login screen unless you login as Guest

    - by Mário Silva
    I am running a VMWare Player with a Ubuntu 12.04 LTS Precise Pangloin as Guest on my Windows 7. Sometimes I get the shutdown blue screen error in Windows, this time it happened when I was running the Player. When I restarted everything Ubuntu gave the not so unfamiliar in this forum Login Loop in adminstrator login. I login and there's this black screen where I can only read: "piix4...smbus:0.0.0.07.3 Host Smbus controller not enabled" . When I go to the Prompt in root mode it fails to update and only upgraded, specially some plugins ( I think graphic plugins) which also appear in one an error message after quitting the prompt, but they´are successfully installed. They are not the error message. After that I have been working with the Fail/safe Mode recovery panel. When I try to update via Root I get errors like this: W:failed to fetch http://extras.ubuntu.com/ubuntu/dists/precise/release.gpg could not resolve 'extras/ubuntu.com There are 8 more like this referring to areas like: -archive/canonical.com -ppa.Launchpad.net -security.Ubuntu.com -Us.archive.ubuntu.com - release.gpg precise-updates/release.gpg precise_backport/release.gpg Final Message: some index files failed to download.....they have been ignored or old files are used. The black screens most of the time pass by too fast for me to pick up any information. But in general I think I have done everything I was able to in the recovery panel including updating network and graphic packages and recovering filesystem packages and the basic stuff ( I am a beginner regarding Linux ) in the root prompt. Now I am stuck in this screen with graphic options: - Run in low-graphics mode just for one session - Reconfigure Graphics - Troubleshoot the error - Exit to console login I am trying to choose to reconfigure graphics but the mouse disappears in the virtual machine screen and sometimes when options change ity´s only the first and last option. ut this happens from the blue without messages. This particular option menu is in the regular GUI style against a black screen in Terminal style. Really strange. Thanx in advance, all is welcome and appreciated.

    Read the article

  • how to do event checks for loops?

    - by yao jiang
    I am having some trouble getting the logic down for this. Currently, I have an app that animates the astar pathfinding algorithm. On start of the app, the ui will show the following: User can press "space" to randomly choose start/end coords, then the app will animate it. Or, user can choose the start/end by left-click/right-click. During the animation, the user can also left-click to generate blocks, or right-click to choose a new destiantion. Where I am stuck at is how to handle the events while the app is animating. Right now, I am checking events in the main loop, then when the app is animating, I do event checks again. While it works fine, I feel that I am probably doing it wrong. What is the proper way of setting up the main loop that will handle the events while the app is animating? In main loop, the app start animating once user choose start/end. In my draw function, I am putting another event checker in there. def clear(rows): for r in range(rows): for c in range(rows): if r%3 == 1 and c%3 == 1: color = brown; grid[r][c] = 1; buildCoor.append(r); buildCoor.append(c); else: color = white; grid[r][c] = 0; pick_image(screen, color, width*c, height*r); pygame.display.flip(); os.system('cls'); # draw out the grid def draw(start, end, grid, route_coord): # draw the end coords color = red; pick_image(screen, color, width*end[1],height*end[0]); pygame.display.flip(); # then draw the rest of the route for i in range(len(route_coord)): # pausing because we want animation time.sleep(speed); # get the x/y coords x,y = route_coord[i]; event_on = False; if grid[x][y] == 2: color = green; elif grid[x][y] == 3: color = blue; for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 3: print "destination change detected, rerouting"; # get mouse position, px coords pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; grid[r][c] = 4; end = [r, c]; elif event.button == 1: print "user generated event"; pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; # mark it as a block for now grid[r][c] = 1; event_on = True; if check_events([x,y]) or event_on: # there is an event # mark it as a block for now grid[y][x] = 1; pick_image(screen, event_x, width*y, height*x); pygame.display.flip(); # then find a new route new_start = route_coord[i-1]; marked_grid, route_coord = find_route(new_start, end, grid); draw(new_start, end, grid, route_coord); return; # just end draw here so it wont throw the "index out of range" error elif grid[x][y] == 4: color = red; pick_image(screen, color, width*y, height*x); pygame.display.flip(); # clear route coord list, otherwise itll just add more unwanted coords route_coord_list[:] = []; clear(rows); # main loop while not done: # check the events for event in pygame.event.get(): # mouse events if event.type == pygame.MOUSEBUTTONDOWN: # get mouse position, px coords pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; # find which button pressed, highlight grid accordingly if event.button == 1: # left click, start coords if grid[r][c] == 2: grid[r][c] = 0; color = white; elif grid[r][c] == 0 or grid[r][c] == 4: grid[r][c] = 2; start = [r,c]; color = green; else: grid[r][c] = 1; color = brown; elif event.button == 3: # right click, end coords if grid[r][c] == 4: grid[r][c] = 0; color = white; elif grid[r][c] == 0 or grid[r][c] == 2: grid[r][c] = 4; end = [r,c]; color = red; else: grid[r][c] = 1; color = brown; pick_image(screen, color, width*c, height*r); # keyboard events elif event.type == pygame.KEYDOWN: clear(rows); # one way to quit program if event.key == pygame.K_ESCAPE: print "program will now exit."; done = True; # space key for random start/end elif event.key == pygame.K_SPACE: # first clear the ui clear(rows); # now choose random start/end coords buildLoc = zip(buildCoor,buildCoor[1:])[::2]; #print buildLoc; (start_x, start_y, end_x, end_y) = pick_point(); while (start_x, start_y) in buildLoc or (end_x, end_y) in buildLoc: (start_x, start_y, end_x, end_y) = pick_point(); clear(rows); print "chosen random start/end coords: ", (start_x, start_y, end_x, end_y); if (start_x, start_y) in buildLoc or (end_x, end_y) in buildLoc: print "error"; # draw the route marked_grid, route_coord = find_route([start_x,start_y],[end_x,end_y], grid); draw([start_x, start_y], [end_x, end_y], marked_grid, route_coord); # return key for user defined start/end elif event.key == pygame.K_RETURN: # first clear the ui clear(rows); # get the user defined start/end print "user defined start/end are: ", (start[0], start[1], end[0], end[1]); grid[start[0]][start[1]] = 1; grid[end[0]][end[1]] = 2; # draw the route marked_grid, route_coord = find_route(start, end, grid); draw(start, end, marked_grid, route_coord); # c to clear the screen elif event.key == pygame.K_c: print "clearing screen."; clear(rows); # go fullscreen elif event.key == pygame.K_f: if not full_sc: pygame.display.set_mode([1366, 768], pygame.FULLSCREEN); full_sc = True; rows = 15; clear(rows); else: pygame.display.set_mode(size); full_sc = False; # +/- key to change speed of animation elif event.key == pygame.K_LEFTBRACKET: if speed >= 0.1: print SPEED_UP; speed = speed_up(speed); print speed; else: print FASTEST; print speed; elif event.key == pygame.K_RIGHTBRACKET: if speed < 1.0: print SPEED_DOWN; speed = slow_down(speed); print speed; else: print SLOWEST print speed; # second method to quit program elif event.type == pygame.QUIT: print "program will now exit."; done = True; # limit to 20 fps clock.tick(20); # update the screen pygame.display.flip();

    Read the article

  • The Infinite Jukebox Creates Seamless Loops from Your Favorite Songs

    - by Jason Fitzpatrick
    Why limit yourself to simply listening to a song on repeat when The Infinite Jukebox can use algorithms to turn your song into a seamless and never ending tune? Unlike simply looping a song from the start to the end over and over, The Infinite Jukebox analyzes the song and looks for spots where it can seamlessly transition from one point in the song to a previous point to create a sense of never-ending music. Some songs worked better than others in our testing–Superstition by Stevie Wonder, for example, worked flawlessly but Gangnam Style by Psy got stuck in a short loop that sounded unnatural. Hit up the link below to play with already uploaded MP3s or upload your own to take it for a spin. The Infinite Jukebox How To Use USB Drives With the Nexus 7 and Other Android Devices Why Does 64-Bit Windows Need a Separate “Program Files (x86)” Folder? Why Your Android Phone Isn’t Getting Operating System Updates and What You Can Do About It

    Read the article

  • Prefer algorithms to hand-written loops?

    - by FredOverflow
    Which of the following to you find more readable? The hand-written loop: for (std::vector<Foo>::const_iterator it = vec.begin(); it != vec.end(); ++it) { bar.process(*it); } Or the algorithm invocation: #include <algorithm> #include <functional> std::for_each(vec.begin(), vec.end(), std::bind1st(std::mem_fun_ref(&Bar::process), bar)); I wonder if std::for_each is really worth it, given such a simple example already requires so much code. What are your thoughts on this matter?

    Read the article

  • Impact of variable-length loops on GPU shaders

    - by Will
    Its popular to render procedural content inside the GPU e.g. in the demoscene (drawing a single quad to fill the screen and letting the GPU compute the pixels). Ray marching is popular: This means the GPU is executing some unknown number of loop iterations per pixel (although you can have an upper bound like maxIterations). How does having a variable-length loop affect shader performance? Imagine the simple ray-marching psuedocode: t = 0.f; while(t < maxDist) { p = rayStart + rayDir * t; d = DistanceFunc(p); t += d; if(d < epsilon) { ... emit p return; } } How are the various mainstream GPU families (Nvidia, ATI, PowerVR, Mali, Intel, etc) affected? Vertex shaders, but particularly fragment shaders? How can it be optimised?

    Read the article

  • Struct Method for Loops Problem

    - by Annalyne
    I have tried numerous times how to make a do-while loop using the float constructor for my code but it seems it does not work properly as I wanted. For summary, I am making a TBRPG in C++ and I encountered few problems. But before that, let me post my code. #include <iostream> #include <string> #include <ctime> #include <cstdlib> using namespace std; int char_level = 1; //the starting level of the character. string town; //town string town_name; //the name of the town the character is in. string charname; //holds the character's name upon the start of the game int gems = 0; //holds the value of the games the character has. const int MAX_ITEMS = 15; //max items the character can carry string inventory [MAX_ITEMS]; //the inventory of the character in game int itemnum = 0; //number of items that the character has. bool GameOver = false; //boolean intended for the game over scr. string monsterTroop [] = {"Slime", "Zombie", "Imp", "Sahaguin, Hounds, Vampire"}; //monster name float monsterTroopHealth [] = {5.0f, 10.0f, 15.0f, 20.0f, 25.0f}; // the health of the monsters int monLifeBox; //life carrier of the game's enemy troops int enemNumber; //enemy number //inventory[itemnum++] = "Sword"; class RPG_Game_Enemy { public: void enemyAppear () { srand(time(0)); enemNumber = 1+(rand()%3); if (enemNumber == 1) cout << monsterTroop[1]; //monster troop 1 else if (enemNumber == 2) cout << monsterTroop[2]; //monster troop 2 else if (enemNumber == 3) cout << monsterTroop[3]; //monster troop 3 else if (enemNumber == 4) cout << monsterTroop[4]; //monster troop 4 } void enemDefeat () { cout << "The foe has been defeated. You are victorious." << endl; } void enemyDies() { //if the enemy dies: //collapse declaration cout << "The foe vanished and you are victorious!" << endl; } }; class RPG_Scene_Battle { public: RPG_Scene_Battle(float ini_health) : health (ini_health){}; float getHealth() { return health; } void setHealth(float rpg_val){ health = rpg_val;}; private: float health; }; //---------------------------------------------------------------// // Conduct Damage for the Scene Battle's Damage //---------------------------------------------------------------// float conductDamage(RPG_Scene_Battle rpg_tr, float damage) { rpg_tr.setHealth(rpg_tr.getHealth() - damage); return rpg_tr.getHealth(); }; // ------------------------------------------------------------- // void RPG_Scene_DisplayItem () { cout << "Items: \n"; for (int i=0; i < itemnum; ++i) cout << inventory[i] <<endl; }; In this code I have so far, the problem I have is the battle scene. For example, the player battles a Ghost with 10 HP, when I use a do while loop to subtract the HP of the character and the enemy, it only deducts once in the do while. Some people said I should use a struct, but I have no idea how to make it. Is there a way someone can display a code how to implement it on my game? Edit: I made the do-while by far like this: do RPG_Scene_Battle (player, 20.0f); RPG_Scene_Battle (enemy, 10.0f); cout << "Battle starts!" <<endl; cout << "You used a blade skill and deducted 2 hit points to the enemy!" conductDamage (enemy, 2.0f); while (enemy!=0) also, I made something like this: #include <iostream> using namespace std; int gems = 0; class Entity { public: Entity(float startingHealth) : health(startingHealth){}; // initialize health float getHealth(){return health;} void setHealth(float value){ health = value;}; private: float health; }; float subtractHealthFrom(Entity& ent, float damage) { ent.setHealth(ent.getHealth() - damage); return ent.getHealth(); }; int main () { Entity character(10.0f); Entity enemy(10.0f); cout << "Hero Life: "; cout << subtractHealthFrom(character, 2.0f) <<endl; cout << "Monster Life: "; cout << subtractHealthFrom(enemy, 2.0f) <<endl; cout << "Hero Life: "; cout << subtractHealthFrom(character, 2.0f) <<endl; cout << "Monster Life: "; cout << subtractHealthFrom(enemy, 2.0f) <<endl; }; Struct method, they say, should solve this problem. How can I continously deduct hp from the enemy? Whenever I deduct something, it would return to its original value -_-

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >