Search Results

Search found 3425 results on 137 pages for 'polynomial math'.

Page 77/137 | < Previous Page | 73 74 75 76 77 78 79 80 81 82 83 84  | Next Page >

  • C# Vector maths questions

    - by Mark
    Im working in a screen coordinate space that is different to that of the classical X/Y coordinate space, where my Y direction goes down in the positive instead of up. Im also trying to figure out how to make a Circle on my screen always face away from the center point of the screen. If the center point of my screen is at x(200) y(300) and the point of my circle's center is at x(150) and y(380) then I would like to calculate the angle that the circle should be facing. At the moment I have this: Point centerPoint = new Point(200, 300); Point middleBottom = new Point(200, 400); Vector middleVector = new Vector(centerPoint.X - middleBottom.X, centerPoint.Y - middleBottom.Y); Vector vectorOfCircle = new Vector(centerPoint.X - 150, centerPoint.Y - 400); middleVector.Normalize(); vectorOfCircle.Normalize(); var angle = Math.Acos(Vector.CrossProduct(vectorOfCircle, middleVector)); Console.WriteLine("Angle: {0}", angle * (180/Math.PI)); Im not getting what I would expect. I would say that when I enter in x(150) and y(300) of my circle, I would expect to see the rotation of 90 deg, but Im not getting that... Im getting 180!! Any help here would be greatly appreciated. Cheers, Mark

    Read the article

  • Trying to draw a dynamic rectangle in SVG

    - by Shaun
    To be more specific, here are the steps I need: onmousedown - set x and y of rect as mouse coordinates onmousemove - using the current x and y mouse coordinates calculate height and width of the rect, set these and append onmouseup - remove the rectangle, and call a function based off some calculations from the rect. Here is what I have but isn't quite working (right now I have it drawing a line to make it simpler): onmousedown: startbox(evt) function startbox(evt) { if(evt.button === 0) { x1 = evt.clientX + div.scrollLeft-5; y1 = evt.clientY + div.scrollTop-30; obj.setAttributeNS(null, "x1", x1); obj.setAttributeNS(null, "y1", y1); Root.setAttributeNS(null, "onmousemove", "updatebox(evt)"); } } onmousemove: updatebox(evt) function updatebox(evt) { if(evt.button === 0) { x2 = evt.clientX + div.scrollLeft-5; y2 = evt.clientY + div.scrollTop-30; Root.appendChild(.obj); w = Math.abs(x2-x1); h = Math.abs(y2-y1); var strokecolor; if(w>20 && h>20) { strokecolor = "green"; validbox = true; } else { strokecolor = "red"; validbox = false; } var Attr={ x2:x2, y2:y2, stroke:strokecolor } assignAttr(obj, Attr); //just loops thru adding multiple attributes } } onmouseup: endbox() function endbox(evt) { if(evt.button===0) { Root.setAttributeNS(null, "onmousemove", ""); Root.removeChild(obj); if(validbox) { //do stuff validbox = !validbox; } } } Some of my problems with this are: Its slow in Chrome making drawing the line/rect feel sluggish. It won't work two times in a row. This is the real problem that I can't fix. Any and all feedback is welcome.

    Read the article

  • C#: Wrong answer when finding "cool" numbers.

    - by user300484
    Hello you all! In my application, a "cool" number is a number that is both a square and a cube, like for example: 64 = 8^2 and 64 = 4^3. My application is supposed to find the number of "cool numbers" between a range given by the user. I wrote my code and the application runs fine, but it is giving me the wrong answer. Can you help me here please? for example: IMPUT 1 100 OUTPUT 1 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { double a = Convert.ToDouble(Console.ReadLine()); // first number in the range double b = Convert.ToDouble(Console.ReadLine()); // second number in the range long x = 0; for (double i = a; i <= b; i++) { double cube = 1.0 / 3.0; double cuad = 1.0 / 2.0; double crt = Math.Pow(i, cube); // cube root double sqrt = Math.Pow(i, cuad); // square root if ((crt * 10) % 10 == 0 || (sqrt * 10) % 10 == 0) // condition to determine if it is a cool number. x++; } Console.WriteLine(x); Console.ReadLine(); } } }

    Read the article

  • multiple ajax requests with jquery

    - by Emil
    I got problems with the async nature of Javascript / JQuery. Lets say the following (no latency is counted for, in order to not make it so troublesome); I got three buttons (A, B, C) on a page, each of the buttons adds an item into a shopping cart with one ajax-request each. If I put an intentional delay of 5 seconds in the serverside script (PHP) and pushes the buttons with 1 second apart, I want the result to be the following: Request A, 5 seconds Request B, 6 seconds Request C, 7 seconds However, the result is like this Request A, 5 seconds Request B, 10 seconds Request C, 15 seconds This have to mean that the requests are queued and not run simultaneously, right? Isnt this opposite to what async is? I also tried to add a random get-parameter to the url in order to force some uniqueness to the request, no luck though. I did read a little about this. If you avoid using the same "request object (?)" this problem wont occure. Is it possible to force this behaviour in JQuery? This is the code that I am using $.ajax( { url : strAjaxUrl + '?random=' + Math.floor(Math.random()*9999999999), data : 'ajax=add-to-cart&product=' + product, type : 'GET', success : function(responseData) { // update ui }, error : function(responseData) { // show error } }); I also tried both GET and POST, no difference. I want the requests to be sent right when the button is clicked, not when the previous request is finnished. I want the requests to be run simultaneously, not in a queue.

    Read the article

  • How to handle alpha in a manual "Overlay" blend operation?

    - by quixoto
    I'm playing with some manual (walk-the-pixels) image processing, and I'm recreating the standard "overlay" blend. I'm looking at the "Photoshop math" macros here: http://www.nathanm.com/photoshop-blending-math/ (See also here for more readable version of Overlay) Both source images are in fairly standard RGBA (8 bits each) format, as is the destination. When both images are fully opaque (alpha is 1.0), the result is blended correctly as expected: But if my "blend" layer (the top image) has transparency in it, I'm a little flummoxed as to how to factor that alpha into the blending equation correctly. I expect it to work such that transparent pixels in the blend layer have no effect on the result, opaque pixels in the blend layer do the overlay blend as normal, and semitransparent blend layer pixels have some scaled effect on the result. Can someone explain to me the blend equations or the concept behind doing this? Bonus points if you can help me do it such that the resulting image has correctly premultiplied alpha (which only comes into play for pixels that are not opaque in both layers, I think.) Thanks! // factor in blendLayerA, (1-blendLayerA) somehow? resultR = ChannelBlend_Overlay(baseLayerR, blendLayerR); resultG = ChannelBlend_Overlay(baseLayerG, blendLayerG); resultB = ChannelBlend_Overlay(baseLayerB, blendLayerB); resultA = 1.0; // also, what should this be??

    Read the article

  • Jquery draggable not working in chrome/safari

    - by jbatson
    I have created a page that uses ajax calls to load product images. The jquery code for drag, drop and clone would not work when in the index.php page so I moved it to the page that gets called to request the products as each product has drag, drop code created for it. Works fine in FF, even IE but not in Safari or Chrome. Below is the jquery code in load_products.php that gets created when the ajax call is made to load the products. http://tandyleatherfactory.net/ Anyone have any idea why wouldn't work in Safari? $(function() {$("#concho_4_2").draggable({ helper: 'clone', cursor: 'pointer', zIndex: '1001', stop: function(event, ui) { offsetElement = $(ui.helper).offset(); offNewContainer = $('#belts').offset(); var dataId = $(ui.helper).attr('id'); ajaxRequest('http://tandyleatherfactory.net/includes/ahah/add_product.php', 'product=4', '#conchos'); var randomnumber = Math.floor(Math.random()*1000000); var newId = 'concho_4_2_'+randomnumber; $(ui.helper).clone(true).removeAttr('id').attr('id',newId).css("left", offsetElement.left-offNewContainer.left-10).css("top", offsetElement.top-offNewContainer.top-10).appendTo('#belts'); $('#'+newId).draggable(); } });

    Read the article

  • Function in JS returns undefined

    - by megapool020
    Hello there, I have the following problem. The alert allways returns undefined, but I know it has a value. What am I doing wrong. I'm out of solutions... I'm using JQUERY jquery-1.4.2.min.js Tnx in advance $(document).ready(function(){ $('#generateButton').click(createIBAN); }); function createIBAN(){ //---- First check if a bank has been selected, //---- if not, then show error if($('#selectBank').val()==''){ alert('Selecte a bank!'); }else{ var bankAccount = generateBankAccount(); alert(bankAccount); } return false; } function generateBankAccount(){ //---- Create "elfproef" bankaccount var bankAccount = ''; //---- Set the amount of digits in a bankaccount digitAmount = 9; //---- Make random digitstring for (var i = 0; i < digitAmount; i++) { bankAccount += Math.floor(Math.random() * digitAmount); } //---- validate the string, if not "elf-proef" if (elfProef(bankAccount)==false) { //---- regenerate the string generateBankAccount(); }else{ return bankAccount; } } function elfProef(bankAccount) { //---- set sum to 0 and start the for-loop for counting var sum = 0; for (var i = 0; i < digitAmount; i++) { //---- for every digit multiply it times 9 - number //---- of the digit and count it to the sum var sum += bankAccount.charAt(i) * (digitAmount - i); } //---- Check if sum can be devided by 11 without having ##,## if(sum % 11==0){ //---- return true means string is "elf-proef" return true; }else { //---- String is not "elf-proef", try again return false; } }

    Read the article

  • convert list of relative widths to pixel widths

    - by mkoryak
    This is a code review question more then anything. I have the following problem: Given a list of relative widths (no unit whatsoever, just all relative to each other), generate a list of pixel widths so that these pixel widths have the same proportions as the original list. input: list of proportions, total pixel width. output: list of pixel widths, where each width is an int, and the sum of these equals the total width. Code: var sizes = "1,2,3,5,7,10".split(","); //initial proportions var totalWidth = 1024; // total pixel width var sizesTotal = 0; for (var i = 0; i < sizes.length; i++) { sizesTotal += parseInt(sizes[i], 10); } if(sizesTotal != 100){ var totalLeft = 100;; for (var i = 0; i < sizes.length; i++) { sizes[i] = Math.floor(parseInt(sizes[i], 10) / sizesTotal * 100); totalLeft -= sizes[i]; } sizes[sizes.lengh - 1] = totalLeft; } totalLeft = totalWidth; for (var i = 0; i < sizes.length; i++) { widths[i] = Math.floor(totalWidth / 100 * sizes[i]) totalLeft -= widths[i]; } widths[sizes.lenght - 1] = totalLeft; //return widths which contains a list of INT pixel sizes

    Read the article

  • Rotate MapView in Android

    - by Matthew B.
    I am writing an Android app where one of the features is that the map will rotate according to the compass (i.e. if the phone is pointing east, the map will be oriented so that the east side of the map is on top). Previous answers that I have found suggested over writing the onDraw() method in mapView, however, the api changed the method to final so it cannot be overwritten. As a result I have tried to overwrite the dispatchDraw() method like so: Note: -compass is a boolean that if true, rotate the view -bearing is a float variable that has the degrees that the view should rotate protected void dispatchDraw(Canvas canvas) { canvas.save(); if (compass) { final float w = this.getWidth(); final float h = this.getHeight(); final float scaleFactor = (float)(Math.sqrt(h * h + w * w) / Math.min(w, h)); final float centerX = w / 2.0f; final float centerY = h / 2.0f; canvas.rotate(bearing, centerX, centerY); canvas.scale(scaleFactor, scaleFactor, centerX, centerY); } super.dispatchDraw(canvas); canvas.restore(); }

    Read the article

  • How can I convert seconds to minutes in jQuery while updating an element with the current time?

    - by pghtech
    So I see a number of ways to display allot of seconds in a (static) hr/min/sec. However, I am trying to produce a visual count down timer: $('#someelement').html(minCounter + ' minutes ' + ((secCounter == 0) ? '' : (secCounter + ' seconds'))); My counter is reduced inside a SetInterval that triggers ever 1 second: //....... var counter = redirectTimer; jQuery('#WarningDialogMsg').html(minCounter + ' minutes ' + ((secCounter == 0) ? '' : (secCounter + ' seconds'))); //........ SetInternval( function() { counter -= 1; secCounter = Math.floor(counter % 60); minCounter = Math.floor(counter / 60); //....... $('#someelement').html(minCounter + ' minutes ' + ((secCounter == 0) ? '' : (secCounter + ' seconds'))); }, 1000) It is a two minute counter but I don't want to display 120 seconds. I want to display 1 : 59 (and counting down). I have managed to get it to work using the above, but my main question is: is there a more elegant way to accomplish the above? (note: I am redirecting once "counter == 0").

    Read the article

  • Apply Quaternion to Camera in libGDX

    - by Alex_Hyzer_Kenoyer
    I am trying to rotate my camera using a Quaternion in libGDX. I have a Quaternion created and being manipulated but I have no idea how to apply it to the camera, everything I've tried hasn't moved the camera at all. Here is how I set up the rotation Quaternion: public void rotateX(float amount) { tempQuat.set(tempVector.set(1.0f, 0.0f, 0.0f), amount * MathHelper.PIOVER180); rotation = rotation.mul(tempQuat); } public void rotateY(float amount) { tempQuat.set(tempVector.set(0.0f, 1.0f, 0.0f), amount * MathHelper.PIOVER180); rotation = tempQuat.mul(rotation); } Here is how I am trying to update the camera (Same update method as the original libGDX version but I added the part about the rotation matrix to the top): public void update(boolean updateFrustum) { float[] matrix = new float[16]; rotation.toMatrix(matrix); Matrix4 m = new Matrix4(); m.set(matrix); camera.view.mul(m); //camera.direction.mul(m).nor(); //camera.up.mul(m).nor(); float aspect = camera.viewportWidth / camera.viewportHeight; camera.projection.setToProjection(Math.abs(camera.near), Math.abs(camera.far), camera.fieldOfView, aspect); camera.view.setToLookAt(camera.position, tempVector.set(camera.position).add(camera.direction), camera.up); camera.combined.set(camera.projection); Matrix4.mul(camera.combined.val, camera.view.val); if (updateFrustum) { camera.invProjectionView.set(camera.combined); Matrix4.inv(camera.invProjectionView.val); camera.frustum.update(camera.invProjectionView); } }

    Read the article

  • Drawing an honeycomb with as3

    - by vitto
    Hi, I'm trying to create an honeycomb with as3 but I have some problem on cells positioning. I've already created the cells (not with code) and for cycled them to a funcion and send to it the parameters which what I thought was need (the honeycomb cell is allready on a sprite container in the center of the stage). to see the structure of the cycle and which parameters passes, please see the example below, the only thing i calculate in placeCell is the angle which I should obtain directly inside tha called function Note: the angle is reversed but it isn't important, and the color are useful in example only for visually divide cases. My for cycle calls placeCell and passes cell, current_case, counter (index) and the honeycomb cell_lv (cell level). I thought it was what i needed but I'm not skilled in geometry and trigonometry, so I don't know how to position cells correctly: function placeCell (cell:Sprite, current_case:int, counter:int, cell_lv:int):void { var margin:int = 2; var angle:Number = (360 / (cell_lv * 6)) * (current_case + counter); var radius:Number = (cell.width + margin) * cell_lv; cell.x = radius * Math.cos (angle); cell.y = radius * Math.sin (angle); trace ("LV " + cell_lv + " current_case " + current_case + " counter " + counter + " angle " + angle + " radius " + radius) } how can I do to solve it?

    Read the article

  • Refresher on Java classes in separate files

    - by JohnFaig
    I need a refresher on moving classes from one file into two files. My sample code is in one file called "external_class_file_main". The program runs fine and the code is shown below: Public class external_class_file_main { public static int get_a_random_number (int min, int max) { int n; n = (int)(Math.random() * (max - min +1)) + min; return (n); } public static void main(String[] args) { int r; System.out.println("Program starting..."); r = get_a_random_number (1, 5); System.out.println("random number = " + r); System.out.println("Program ending..."); } } I move the get_a_random_number class to a separate file called "external_class_file". When I do this, I get the following error: Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method get_a_random_number(int, int) is undefined for the type external_class_file_main at external_class_file_main.main(external_class_file_main.java:20) The "external_class_file_main" now contains: public class external_class_file_main { public static void main(String[] args) { int r; System.out.println("Program starting..."); r = get_a_random_number (1, 5); System.out.println("random number = " + r); System.out.println("Program ending..."); } } The "external_class_file" now contains: public class external_class_file { public static int get_a_random_number (int min, int max) { int n; n = (int)(Math.random() * (max - min +1)) + min; return (n); } }

    Read the article

  • Data Structures for Junior Java Developer

    - by user1639637
    Ok,still learning Arrays. I wrote this code which fills the array named "rand" with random numbers between 0 and 1( exclusive). I want to start learning Complexity. the For loop executes n times (100 times) ,every time it takes O(1) time,so the worse case scenario is O(n),am I right? Also,I used ArrayList to store the 100 elements and I imported "Collections" and used Collections.sort() method to sort the elements. import java.util.Arrays; public class random { public static void main(String args[]) { double[] rand=new double[10]; for(int i=0;i<rand.length;i++) { rand[i]=(double) Math.random(); System.out.println(rand[i]); } Arrays.sort(rand); System.out.println(Arrays.toString(rand)); } } ArrayList: import java.util.ArrayList; import java.util.Collections; public class random { public static void main(String args[]) { ArrayList<Double> MyArrayList=new ArrayList<Double>(); for(int i=0;i<100;i++) { MyArrayList.add(Math.random()); } Collections.sort(MyArrayList); for(int j=0;j<MyArrayList.size();j++) { System.out.println(MyArrayList.get(j)); } } }

    Read the article

  • Console Errors - Not a Jquery Guru Yet

    - by user2528902
    I am hoping that someone can help me to correct some issues that I am having with a custom script. I took over the management of a site and there seems to be an issue with the following code: /* jQUERY CUSTOM FUNCTION ------------------------------ */ jQuery(document).ready(function($) { $('.ngg-gallery-thumbnail-box').mouseenter(function(){ var elmID = "#"+this.id+" img"; $(elmID).fadeOut(300); }); $('.ngg-gallery-thumbnail-box').mouseleave(function(){ var elmID = "#"+this.id+" img"; $(elmID).fadeIn(300); }); var numbers = $('.ngg-gallery-thumbnail-box').size(); function A(i){ setInterval(function(){autoSlide(i)}, 7000); } A(0); function autoSlide(i) { var numbers = $('.ngg-gallery-thumbnail-box').size(); var elmCls = $("#ref").attr("class"); $(elmCls).fadeIn(300); var randNum = Math.floor((Math.random()*numbers)+1); var elmClass = ".elm"+randNum+" img"; $("#ref").attr("class", elmClass); $(elmClass).fadeOut(300); setInterval(function(){arguments.callee.caller(randNum)}, 7000); } }); The error that I am seeing in the console on Firebug is "TypeError: arguments.callee.caller is not a function. I am just getting started with jQuery and have no idea how to fix this issue. Any assistance with altering the code so that it still works but doesn't throw up all of these errors (if I load the site and let it sit in my browser for 10 minutes I have over 10000 errors in the console) would be greatly appreciated!

    Read the article

  • How can I differentiate a manual scroll (via mousewheel/scrollbar) from a Javascript/jQuery scroll?

    - by David Murdoch
    UPDATE: Here is a jsbin example demonstrating the problem. Basically, I have the following javascript which scrolls the window to an anchor on the page: // get anchors with href's that start with "#" $("a[href^=#]").live("click", function(){ var target = $($(this).attr("href")); // if the target exists: scroll to it... if(target[0]){ // If the page isn't long enough to scroll to the target's position // we want to scroll as much as we can. This part prevents a sudden // stop when window.scrollTop reaches its maximum. var y = Math.min(target.offset().top, $(document).height() - $(window).height()); // also, don't try to scroll to a negative value... y=Math.max(y,0); // OK, you can scroll now... $("html,body").stop().animate({ "scrollTop": y }, 1000); } return false; }); It works perfectly......until I manually try to scroll the window. When the scrollbar or mousewheel is scrolled I need to stop the current scroll animation...but I'm not sure how to do this. This is probably my starting point... $(window).scroll(e){ if(IsManuallyScrolled(e)){ $("html,body").stop(); } } ...but I'm not sure how to code the IsManuallyScrolled function. I've checked out e (the event object) in Google Chrome's console and AFAIK there is not way to differentiate between a manual scroll and jQuery's animate() scroll. How can I differentiate between a manual scroll and one called via jQuery's $.fn.animate function?

    Read the article

  • Python optimization problem?

    - by user342079
    Alright, i had this homework recently (don't worry, i've already done it, but in c++) but I got curious how i could do it in python. The problem is about 2 light sources that emit light. I won't get into details tho. Here's the code (that I've managed to optimize a bit in the latter part): import math, array import numpy as np from PIL import Image size = (800,800) width, height = size s1x = width * 1./8 s1y = height * 1./8 s2x = width * 7./8 s2y = height * 7./8 r,g,b = (255,255,255) arr = np.zeros((width,height,3)) hy = math.hypot print 'computing distances (%s by %s)'%size, for i in xrange(width): if i%(width/10)==0: print i, if i%20==0: print '.', for j in xrange(height): d1 = hy(i-s1x,j-s1y) d2 = hy(i-s2x,j-s2y) arr[i][j] = abs(d1-d2) print '' arr2 = np.zeros((width,height,3),dtype="uint8") for ld in [200,116,100,84,68,52,36,20,8,4,2]: print 'now computing image for ld = '+str(ld) arr2 *= 0 arr2 += abs(arr%ld-ld/2)*(r,g,b)/(ld/2) print 'saving image...' ar2img = Image.fromarray(arr2) ar2img.save('ld'+str(ld).rjust(4,'0')+'.png') print 'saved as ld'+str(ld).rjust(4,'0')+'.png' I have managed to optimize most of it, but there's still a huge performance gap in the part with the 2 for-s, and I can't seem to think of a way to bypass that using common array operations... I'm open to suggestions :D

    Read the article

  • Display X divs randomly out of a possible Y.

    - by Jordan
    How do I randomly display 3 divs out of a possible 10 in total? This is what I have tried so far: HTML: <div id="1">Content 1</div> <div id="2">Content 2</div> <div id="3">Content 3</div> <div id="4">Content 4</div> <div id="5">Content 5</div> <div id="6">Content 6</div> Javascript: function randomiseDiv() { // Define how many divs we have var divCount = 6; // Get our random ID (based on the total above) var randomId = Math.floor(Math.random()*divCount+1); // Get the div that's been randomly selectted var chosenDiv= document.getElementById(randomId); // If the content is available on the page if (chosenDiv) { // Update the display chosenDiv.style.display = 'block'; } } window.onload = randomiseDiv; I would prefer a PHP solution, although anything at this stage would be beneficial.

    Read the article

  • OnClickListener error: Source not found

    - by fordays
    Hi, I'm brand new to Android development and right now I am building a simple calculator for healthcare workers. My program implements the OnClickListener class, but every time I click on the button to initiate the calculation, I get an error saying the "Source is not Found". Here is the code: public class KidneyeGFR extends Activity implements OnClickListener { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Calculate = (Button)this.findViewById(R.id.Calculate); Calculate.setOnClickListener(this); } public void onClick(View v) { if (Female.isChecked()) { gender = 0.742; } else { gender = 1.0; } if (African.isChecked()) { race = 1.212; } else { race = 1.0; } calculateBone(); } protected void calculateBone() { int age = Integer.parseInt(EditAge.getText().toString()); double serum = Double.parseDouble(EditSerum.getText().toString()); finalgfr = BONECONST * Math.pow(serum, -1.154) * Math.pow(age, -0.203) * gender * race; BONEtext.setText(Double.toString(finalbone)); }

    Read the article

  • Why is my simple python gtk+cairo program running so slowly/stutteringly?

    - by synapz
    My program draws circles moving on the window. I think I must be missing some basic gtk/cairo concept because it seems to be running too slowly/stutteringly for what I am doing. Any ideas? Thanks for any help! #!/usr/bin/python import gtk import gtk.gdk as gdk import math import random import gobject # The number of circles and the window size. num = 128 size = 512 # Initialize circle coordinates and velocities. x = [] y = [] xv = [] yv = [] for i in range(num): x.append(random.randint(0, size)) y.append(random.randint(0, size)) xv.append(random.randint(-4, 4)) yv.append(random.randint(-4, 4)) # Draw the circles and update their positions. def expose(*args): cr = darea.window.cairo_create() cr.set_line_width(4) for i in range(num): cr.set_source_rgb(1, 0, 0) cr.arc(x[i], y[i], 8, 0, 2 * math.pi) cr.stroke_preserve() cr.set_source_rgb(1, 1, 1) cr.fill() x[i] += xv[i] y[i] += yv[i] if x[i] > size or x[i] < 0: xv[i] = -xv[i] if y[i] > size or y[i] < 0: yv[i] = -yv[i] # Self-evident? def timeout(): darea.queue_draw() return True # Initialize the window. window = gtk.Window() window.resize(size, size) window.connect("destroy", gtk.main_quit) darea = gtk.DrawingArea() darea.connect("expose-event", expose) window.add(darea) window.show_all() # Self-evident? gobject.idle_add(timeout) gtk.main()

    Read the article

  • Most Elegant Way to write isPrime in java

    - by Anantha Kumaran
    public class Prime { public static boolean isPrime1(int n) { if (n <= 1) { return false; } if (n == 2) { return true; } for (int i = 2; i <= Math.sqrt(n) + 1; i++) { if (n % i == 0) { return false; } } return true; } public static boolean isPrime2(int n) { if (n <= 1) { return false; } if (n == 2) { return true; } if (n % 2 == 0) { return false; } for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) { if (n % i == 0) { return false; } } return true; } } public class PrimeTest { public PrimeTest() { } @Test public void testIsPrime() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { Prime prime = new Prime(); TreeMap<Long, String> methodMap = new TreeMap<Long, String>(); for (Method method : Prime.class.getDeclaredMethods()) { long startTime = System.currentTimeMillis(); int primeCount = 0; for (int i = 0; i < 1000000; i++) { if ((Boolean) method.invoke(prime, i)) { primeCount++; } } long endTime = System.currentTimeMillis(); Assert.assertEquals(method.getName() + " failed ", 78498, primeCount); methodMap.put(endTime - startTime, method.getName()); } for (Entry<Long, String> entry : methodMap.entrySet()) { System.out.println(entry.getValue() + " " + entry.getKey() + " Milli seconds "); } } } I am trying to find the fastest way to check whether the given number is prime or not. This is what is finally came up with. Is there any better way than the second implementation(isPrime2).

    Read the article

  • Making a Javascript game, Having a little problem with scrolling.

    - by RobertWHurst
    I have a #wrapper div and a #grid div nested inside. currently I can scroll around with this function below. getCursorPos : function(){ // set the empty cursor object var cursor = {}; //get the offset from the left of the grid container var grid //offset loop $(function getCursorPos(){ grid = $('#grid').offset(); setTimeout(getCursorPos, game.loopSpeed); }); //continuosly get the position var that = this; $(document).mousemove(function(e){ //if game mode is menu exit if(game.mode === 'menu'){ return; } // NOTE: this looks a litle over done but don't remove anything // its like this because javascript uses floating points // and so in order to line up to the nearest hunderedth I // had to make the cursor and div position intergers by // muliplying by ten. one the two are added I reduced them // and rounded them. that.x = Math.round(((e.pageX * 10) - (grid.left * 10)) / 10); that.y = Math.round(((e.pageY * 10) - (grid.top * 10)) / 10); }); }, the problem is that the mouse coordinates only update when the mouse moves. is there any way to get the coordinates with out moving the mouse?

    Read the article

  • Load random swf object with jquery

    - by Eggnog
    I'm working on a site that utilizes full screen background video. I have three flash videos I'd like to load into the page which would be displayed randomly on page refresh. I know you can achieve this through action script loading the movies into one main .swf, but I'm rubbish with Flash and am looking for an alternative solution. My search so far has uncovered a method using jquery. Unfortunately my attempts to implement it have failed. I'm hoping someone more knowledgeable than myself can tell me if this technique is valid or what I'm doing wrong. Here's my code to date: <script type="text/javascript" src="files/js/swfobject.js"></script> <script type="text/javascript"> $(document).ready(function() { var sPath; var i = Math.floor(Math.random()*2); switch(i) { case 0: sPath = "flash/homepage_video.swf"; break; case 1: sPath = "flash/homepage_video.swf"; break; } // load the flash version of the image var so = new SWFObject(sPath, "flash-background", "100%", "100%"); so.addParam("scale", "exactFit"); so.addParam("movie", sPath); // NOTE: the sPath variable is also used here so.addParam("quality", "high"); so.addParam("wmode", "transparent"); so.write("homeBackground"); // NOTE: The value in this call to write() MUST match the name of the // HTML element (<div>) you're expecting the swf to show up in }); </script> <body> <div id="homeBackground"> <p>This is alternative content</p> </div> </body> I'm open to other suggestions that don't involve jquery (php perhaps). Thanks.

    Read the article

  • How do I make this nested for loop, testing sums of cubes, more efficient?

    - by Brian J. Fink
    I'm trying to iterate through all the combinations of pairs of positive long integers in Java and testing the sum of their cubes to discover if it's a Fibonacci number. I'm currently doing this by using the value of the outer loop variable as the inner loop's upper limit, with the effect being that the outer loop runs a little slower each time. Initially it appeared to run very quickly--I was up to 10 digits within minutes. But now after 2 full days of continuous execution, I'm only somewhere in the middle range of 15 digits. At this rate it may end up taking a whole year just to finish running this program. The code for the program is below: import java.lang.*; import java.math.*; public class FindFib { public static void main(String args[]) { long uLimit=9223372036854775807L; //long maximum value BigDecimal PHI=new BigDecimal(1D+Math.sqrt(5D)/2D); //Golden Ratio for(long a=1;a<=uLimit;a++) //Outer Loop, 1 to maximum for(long b=1;b<=a;b++) //Inner Loop, 1 to current outer { //Cube the numbers and add BigDecimal c=BigDecimal.valueOf(a).pow(3).add(BigDecimal.valueOf(b).pow(3)); System.out.print(c+" "); //Output result //Upper and lower limits of interval for Mobius test: [c*PHI-1/c,c*PHI+1/c] BigDecimal d=c.multiply(PHI).subtract(BigDecimal.ONE.divide(c,BigDecimal.ROUND_HALF_UP)), e=c.multiply(PHI).add(BigDecimal.ONE.divide(c,BigDecimal.ROUND_HALF_UP)); //Mobius test: if integer in interval (floor values unequal) Fibonacci number! if (d.toBigInteger().compareTo(e.toBigInteger())!=0) System.out.println(); //Line feed else System.out.print("\r"); //Carriage return instead } //Display final message System.out.println("\rDone. "); } } Now the use of BigDecimal and BigInteger was delibrate; I need them to get the necessary precision. Is there anything other than my variable types that I could change to gain better efficiency?

    Read the article

  • Groovy as a substitute for Java when using BigDecimal?

    - by geejay
    I have just completed an evaluation of Java, Groovy and Scala. The factors I considered were: readability, precision The factors I would like to know: performance, ease of integration I needed a BigDecimal level of precision. Here are my results: Java void someOp() { BigDecimal del_theta_1 = toDec(6); BigDecimal del_theta_2 = toDec(2); BigDecimal del_theta_m = toDec(0); del_theta_m = abs(del_theta_1.subtract(del_theta_2)) .divide(log(del_theta_1.divide(del_theta_2))); } Groovy void someOp() { def del_theta_1 = 6.0 def del_theta_2 = 2.0 def del_theta_m = 0.0 del_theta_m = Math.abs(del_theta_1 - del_theta_2) / Math.log(del_theta_1 / del_theta_2); } Scala def other(){ var del_theta_1 = toDec(6); var del_theta_2 = toDec(2); var del_theta_m = toDec(0); del_theta_m = ( abs(del_theta_1 - del_theta_2) / log(del_theta_1 / del_theta_2) ) } Note that in Java and Scala I used static imports. Java: Pros: it is Java Cons: no operator overloading (lots o methods), barely readable/codeable Groovy: Pros: default BigDecimal means no visible typing, least surprising BigDecimal support for all operations (division included) Cons: another language to learn Scala: Pros: has operator overloading for BigDecimal Cons: some surprising behaviour with division (fixed with Decimal128), another language to learn

    Read the article

< Previous Page | 73 74 75 76 77 78 79 80 81 82 83 84  | Next Page >