Search Results

Search found 255 results on 11 pages for 'pow'.

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

  • Polynomial operations using operator overloading

    - by Vlad
    I'm trying to use operator overloading to define the basic operations (+,-,*,/) for my polynomial class but when i run the program it crashes and my computer frozes. Update3 Ok i successfully done the first two operations(+,-). Now at multiplication, after multiplying each term of the first polynomial with each of the second i want to sort the poly list descending and then if there are more than one term with the same power to merge them in only one term, but for some reason it doesn't compile because of the sort function which doesn't work. Here's what I got: polinom operator*(const polinom& P) const { polinom Result; constIter i, j, lastItem = Result.poly.end(); Iter it1, it2; int nr_matches; for (i = poly.begin() ; i != poly.end(); i++) { for (j = P.poly.begin(); j != P.poly.end(); j++) Result.insert(i->coef * j->coef, i->pow + j->pow); } sort(Result.poly.begin(), Result.poly.end(), SortDescending()); lastItem--; while (true) { nr_matches = 0; for (it1 = Result.poly.begin(); it < lastItem; it1++) { for (it2 = it1 + 1;; it2 <= lastItem; it2++){ if (it2->pow == it1->pow) { it1->coef += it2->coef; nr_matches++; } } Result.poly.erase(it1 + 1, it1 + (nr_matches + 1)); } return Result; } Also here's SortDescending: struct SortDescending { bool operator()(const term& t1, const term& t2) { return t2.pow < t1.pow; } }; What did i do wrong? Thanks!

    Read the article

  • Remove redundant SQL code

    - by Dave Jarvis
    Code The following code calculates the slope and intercept for a linear regression against a slathering of data. It then applies the equation y = mx + b against the same result set to calculate the value of the regression line for each row. Can the two separate sub-selects be joined so that the data and its slope/intercept are calculated without executing the data gathering part of the query twice? SELECT AVG(D.AMOUNT) as AMOUNT, Y.YEAR * ymxb.SLOPE + ymxb.INTERCEPT as REGRESSION_LINE, Y.YEAR as YEAR, MAKEDATE(Y.YEAR,1) as AMOUNT_DATE FROM CITY C, STATION S, YEAR_REF Y, MONTH_REF M, DAILY D, (SELECT ((avg(t.AMOUNT * t.YEAR)) - avg(t.AMOUNT) * avg(t.YEAR)) / (stddev( t.AMOUNT ) * stddev( t.YEAR )) as CORRELATION, ((sum(t.YEAR) * sum(t.AMOUNT)) - (count(1) * sum(t.YEAR * t.AMOUNT))) / (power(sum(t.YEAR), 2) - count(1) * sum(power(t.YEAR, 2))) as SLOPE, ((sum( t.YEAR ) * sum( t.YEAR * t.AMOUNT )) - (sum( t.AMOUNT ) * sum(power(t.YEAR, 2)))) / (power(sum(t.YEAR), 2) - count(1) * sum(power(t.YEAR, 2))) as INTERCEPT FROM ( SELECT AVG(D.AMOUNT) as AMOUNT, Y.YEAR as YEAR, MAKEDATE(Y.YEAR,1) as AMOUNT_DATE FROM CITY C, STATION S, YEAR_REF Y, MONTH_REF M, DAILY D WHERE $X{ IN, C.ID, CityCode } AND SQRT( POW( C.LATITUDE - S.LATITUDE, 2 ) + POW( C.LONGITUDE - S.LONGITUDE, 2 ) ) < $P{Radius} AND S.STATION_DISTRICT_ID = Y.STATION_DISTRICT_ID AND Y.YEAR BETWEEN 1900 AND 2009 AND M.YEAR_REF_ID = Y.ID AND M.CATEGORY_ID = $P{CategoryCode} AND M.ID = D.MONTH_REF_ID AND D.DAILY_FLAG_ID <> 'M' GROUP BY Y.YEAR ) t ) ymxb WHERE $X{ IN, C.ID, CityCode } AND SQRT( POW( C.LATITUDE - S.LATITUDE, 2 ) + POW( C.LONGITUDE - S.LONGITUDE, 2 ) ) < $P{Radius} AND S.STATION_DISTRICT_ID = Y.STATION_DISTRICT_ID AND Y.YEAR BETWEEN 1900 AND 2009 AND M.YEAR_REF_ID = Y.ID AND M.CATEGORY_ID = $P{CategoryCode} AND M.ID = D.MONTH_REF_ID AND D.DAILY_FLAG_ID <> 'M' GROUP BY Y.YEAR Question How do I execute the duplicate bits only once per query, instead of twice? The duplicate bit is the WHERE clause: $X{ IN, C.ID, CityCode } AND SQRT( POW( C.LATITUDE - S.LATITUDE, 2 ) + POW( C.LONGITUDE - S.LONGITUDE, 2 ) ) < $P{Radius} AND S.STATION_DISTRICT_ID = Y.STATION_DISTRICT_ID AND Y.YEAR BETWEEN 1900 AND 2009 AND M.YEAR_REF_ID = Y.ID AND M.CATEGORY_ID = $P{CategoryCode} AND M.ID = D.MONTH_REF_ID AND D.DAILY_FLAG_ID <> 'M' Related http://stackoverflow.com/questions/1595659/how-to-eliminate-duplicate-calculation-in-sql Thank you!

    Read the article

  • Trying to sentinel loop this program.

    - by roger34
    Okay, I spent all this time making this for class but I have one thing that I can't quite get: I need this to sentinel loop continuously (exiting upon entering x) so that the System.out.println("What type of Employee? Enter 'o' for Office " + "Clerical, 'f' for Factory, or 's' for Saleperson. Enter 'x' to exit." ); line comes back up after they enter the first round of information. Also, I can't leave this up long on the (very) off chance a classmate might see this and steal the code. Full code following: import java.util.Scanner; public class Project1 { public static void main (String args[]){ Scanner inp = new Scanner( System.in ); double totalPay; System.out.println("What type of Employee? Enter 'o' for Office " + "Clerical, 'f' for Factory, or 's' for Saleperson. Enter 'x' to exit." ); String response= inp.nextLine(); while (!response.toLowerCase().equals("o")&&!response.toLowerCase().equals("f") &&!response.toLowerCase().equals("s")&&!response.toLowerCase().equals("x")){ System.out.print("\nInvalid selection,please enter your choice again:\n"); response=inp.nextLine(); } char choice = response.toLowerCase().charAt( 0 ); switch (choice){ case 'o': System.out.println("Enter your hourly rate:"); double officeRate=inp.nextDouble(); System.out.println("Enter the number of hours worked:"); double officeHours=inp.nextDouble(); totalPay = officeCalc(officeRate,officeHours); taxCalc(totalPay); break; case 'f': System.out.println("How many Widgets did you produce during the week?"); double widgets=inp.nextDouble(); totalPay=factoryCalc(widgets); taxCalc(totalPay); break; case 's': System.out.println("What were your total sales for the week?"); double totalSales=inp.nextDouble(); totalPay=salesCalc(totalSales); taxCalc(totalPay); break; } } public static double taxCalc(double totalPay){ double federal=totalPay*.22; double state =totalPay*.055; double netPay = totalPay - federal - state; federal =federal*Math.pow(10,2); federal =Math.round(federal); federal= federal/Math.pow(10,2); state =state*Math.pow(10,2); state =Math.round(state); state= state/Math.pow(10,2); totalPay =totalPay*Math.pow(10,2); totalPay =Math.round(totalPay); totalPay= totalPay/Math.pow(10,2); netPay =netPay*Math.pow(10,2); netPay =Math.round(netPay); netPay= netPay/Math.pow(10,2); System.out.printf("\nTotal Pay \t: %1$.2f.\n", totalPay); System.out.printf("State W/H \t: %1$.2f.\n", state); System.out.printf("Federal W/H : %1$.2f.\n", federal); System.out.printf("Net Pay \t: %1$.2f.\n", netPay); return totalPay; } public static double officeCalc(double officeRate,double officeHours){ double overtime=0; if (officeHours>=40) overtime = officeHours-40; else overtime = 0; if (officeHours >= 40) officeHours = 40; double otRate = officeRate * 1.5; double totalPay= (officeRate * officeHours) + (otRate*overtime); return totalPay; } public static double factoryCalc(double widgets){ double totalPay=widgets*.35 +300; return totalPay; } public static double salesCalc(double totalSales){ double totalPay = totalSales * .05 + 500; return totalPay; } }

    Read the article

  • Trying to sentinel loop this program. [java]

    - by roger34
    Okay, I spent all this time making this for class but I have one thing that I can't quite get: I need this to sentinel loop continuously (exiting upon entering x) so that the System.out.println("What type of Employee? Enter 'o' for Office " + "Clerical, 'f' for Factory, or 's' for Saleperson. Enter 'x' to exit." ); line comes back up after they enter the first round of information. Also, I can't leave this up long on the (very) off chance a classmate might see this and steal the code. Full code following: import java.util.Scanner; public class Project1 { public static void main (String args[]){ Scanner inp = new Scanner( System.in ); double totalPay; System.out.println("What type of Employee? Enter 'o' for Office " + "Clerical, 'f' for Factory, or 's' for Saleperson. Enter 'x' to exit." ); String response= inp.nextLine(); while (!response.toLowerCase().equals("o")&&!response.toLowerCase().equals("f") &&!response.toLowerCase().equals("s")&&!response.toLowerCase().equals("x")){ System.out.print("\nInvalid selection,please enter your choice again:\n"); response=inp.nextLine(); } char choice = response.toLowerCase().charAt( 0 ); switch (choice){ case 'o': System.out.println("Enter your hourly rate:"); double officeRate=inp.nextDouble(); System.out.println("Enter the number of hours worked:"); double officeHours=inp.nextDouble(); totalPay = officeCalc(officeRate,officeHours); taxCalc(totalPay); break; case 'f': System.out.println("How many Widgets did you produce during the week?"); double widgets=inp.nextDouble(); totalPay=factoryCalc(widgets); taxCalc(totalPay); break; case 's': System.out.println("What were your total sales for the week?"); double totalSales=inp.nextDouble(); totalPay=salesCalc(totalSales); taxCalc(totalPay); break; } } public static double taxCalc(double totalPay){ double federal=totalPay*.22; double state =totalPay*.055; double netPay = totalPay - federal - state; federal =federal*Math.pow(10,2); federal =Math.round(federal); federal= federal/Math.pow(10,2); state =state*Math.pow(10,2); state =Math.round(state); state= state/Math.pow(10,2); totalPay =totalPay*Math.pow(10,2); totalPay =Math.round(totalPay); totalPay= totalPay/Math.pow(10,2); netPay =netPay*Math.pow(10,2); netPay =Math.round(netPay); netPay= netPay/Math.pow(10,2); System.out.printf("\nTotal Pay \t: %1$.2f.\n", totalPay); System.out.printf("State W/H \t: %1$.2f.\n", state); System.out.printf("Federal W/H : %1$.2f.\n", federal); System.out.printf("Net Pay \t: %1$.2f.\n", netPay); return totalPay; } public static double officeCalc(double officeRate,double officeHours){ double overtime=0; if (officeHours>=40) overtime = officeHours-40; else overtime = 0; if (officeHours >= 40) officeHours = 40; double otRate = officeRate * 1.5; double totalPay= (officeRate * officeHours) + (otRate*overtime); return totalPay; } public static double factoryCalc(double widgets){ double totalPay=widgets*.35 +300; return totalPay; } public static double salesCalc(double totalSales){ double totalPay = totalSales * .05 + 500; return totalPay; } }

    Read the article

  • Representing robot's elbow angle in 3-D

    - by Onkar Deshpande
    I am given coordinates of two points in 3-D viz. shoulder point and object point(to which I am supposed to reach). I am also given the length from my shoulder-to-elbow arm and the length of my forearm. I am trying to solve for the unknown position(the position of the joint elbow). I am using cosine rule to find out the elbow angle. Here is my code - #include <stdio.h> #include <math.h> #include <stdlib.h> struct point { double x, y, z; }; struct angles { double clock_wise; double counter_clock_wise; }; double max(double a, double b) { return (a > b) ? a : b; } /* * Check if the combination can make a triangle by considering the fact that sum * of any two sides of a triangle is greater than the remaining side. The * overlapping condition of links is handled separately in main(). */ int valid_triangle(struct point p0, double l0, struct point p1, double l1) { double dist = sqrt(pow((fabs(p1.z - p0.z)), 2) + pow((fabs(p1.y - p0.y)), 2) + pow((fabs(p1.x - p0.x)), 2)); if((max(dist, l0) == dist) && max(dist, l1) == dist) { return (dist < (l0 + l1)); } else if((max(dist, l0) == l0) && (max(l0, l1) == l0)) { return (l0 < (dist + l1)); } else { return (l1 < (dist + l0)); } } /* * Cosine rule is used to find the elbow angle. Positive value indicates a * counter clockwise angle while negative value indicates a clockwise angle. * Since this problem has at max 2 solutions for any given position of P0 and * P1, I am returning a structure of angles which can be used to consider angles * from both direction viz. clockwise-negative and counter-clockwise-positive */ void return_config(struct point p0, double l0, struct point p1, double l1, struct angles *a) { double dist = sqrt(pow((fabs(p1.z - p0.z)), 2) + pow((fabs(p1.y - p0.y)), 2) + pow((fabs(p1.x - p0.x)), 2)); double degrees = (double) acos((l0 * l0 + l1 * l1 - dist * dist) / (2 * l0 * l1)) * (180.0f / 3.1415f); a->clock_wise = -degrees; a->counter_clock_wise = degrees; } int main() { struct point p0, p1; struct angles a; p0.x = 15, p0.y = 4, p0.z = 0; p1.x = 20, p1.y = 4, p1.z = 0; double l0 = 5, l1 = 8; if(valid_triangle(p0, l0, p1, l1)) { printf("Three lengths can make a valid configuration \n"); return_config(p0, l0, p1, l1, &a); printf("Angle of the elbow point (clockwise) = %lf, (counter clockwise) = %lf \n", a.clock_wise, a.counter_clock_wise); } else { double dist = sqrt(pow((fabs(p1.z - p0.z)), 2) + pow((fabs(p1.y - p0.y)), 2) + pow((fabs(p1.x - p0.x)), 2)); if((dist <= (l0 + l1)) && (dist > l0)) { a.clock_wise = -180.0f; a.counter_clock_wise = 180.0f; printf("Angle of the elbow point (clockwise) = %lf, (counter clockwise) = %lf \n", a.clock_wise, a.counter_clock_wise); } else if((dist <= fabs(l0 - l1)) && (dist < l0)){ a.clock_wise = -0.0f; a.counter_clock_wise = 0.0f; printf("Angle of the elbow point (clockwise) = %lf, (counter clockwise) = %lf \n", a.clock_wise, a.counter_clock_wise); } else printf("Given combination cannot make a valid configuration\n"); } return 0; } However, this solution makes sense only in 2-D. Because clockwise and counter-clockwise are meaningless without an axis and direction of rotation. Returning only an angle is technically correct but it leaves a lot of work for the client of this function to use the result in meaningful way. How can I make the changes to get the axis and direction of rotation ? Also, I want to know how many possible solution could be there for this problem. Please let me know your thoughts ! Any help is highly appreciated ...

    Read the article

  • Resizing an image using mouse dragging (C#)

    - by Gaax
    Hi all. I'm having some trouble resizing an image just by dragging the mouse. I found an average resize method and now am trying to modify it to use the mouse instead of given values. The way I'm doing it makes sense to me but maybe you guys can give me some better ideas. I'm basically using the distance between the current location of the mouse and the previous location of the mouse as the scaling factor. If the distance between the current mouse location and the center of of the image is less than the distance between previous mouse location and the center of the image then the image gets smaller, and vice-versa. With the code below I'm getting an Argument Exception (invalid parameter) when creating the new bitmap with the new height and width and I really don't understand why... any ideas? private static Image resizeImage(Image imgToResize, System.Drawing.Point prevMouseLoc, System.Drawing.Point currentMouseLoc) { int sourceWidth = imgToResize.Width; int sourceHeight = imgToResize.Height; float dCurrCent = 0; //Distance between current mouse location and the center of the image float dPrevCent = 0; //Distance between previous mouse location and the center of the image float dCurrPrev = 0; //Distance between current mouse location and the previous mouse location int sign = 1; System.Drawing.Point imgCenter = new System.Drawing.Point(); float nPercent = 0; imgCenter.X = imgToResize.Width / 2; imgCenter.Y = imgToResize.Height / 2; // Calculating the distance between the current mouse location and the center of the image dCurrCent = (float)Math.Sqrt(Math.Pow(currentMouseLoc.X - imgCenter.X, 2) + Math.Pow(currentMouseLoc.Y - imgCenter.Y, 2)); // Calculating the distance between the previous mouse location and the center of the image dPrevCent = (float)Math.Sqrt(Math.Pow(prevMouseLoc.XimgCenter.X,2) + Math.Pow(prevMouseLoc.Y - imgCenter.Y, 2)); // Calculating the sign value if (dCurrCent >= dPrevCent) { sign = 1; } else { sign = -1; } nPercent = sign * (float)Math.Sqrt(Math.Pow(currentMouseLoc.X - prevMouseLoc.X, 2) + Math.Pow(currentMouseLoc.Y - prevMouseLoc.Y, 2)); int destWidth = (int)(sourceWidth * nPercent); int destHeight = (int)(sourceHeight * nPercent); Bitmap b = new Bitmap(destWidth, destHeight); // exception thrown here Graphics g = Graphics.FromImage((Image)b); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(imgToResize, 0, 0, destWidth, destHeight); g.Dispose(); return (Image)b; }

    Read the article

  • Hard-coded 8191 10485 values in JavaScript rounding function

    - by Matthew Hegarty
    I've seen the following (bizarre) Javascript rounding function in some legacy code. After googling for it I can see that it crops up in a number of places online. However I can't work out why the hard-coded values 8191 and 10485 are present. Does anyone know if there's any sensible reason why these values are included? If not, hopefully we can kill off the meme! function roundNumber(num,dec) { var newnumber = 0; if (num > 8191 && num < 10485) { num = num-5000; newnumber = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); newnumber = newnumber+5000; } else { newnumber = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); } return newnumber; }

    Read the article

  • Power function in prolog

    - by NHans
    Exactly what's the prolog definition for power function. I wrote this code and it give some errors I wanna know exact code for the power function. pow(X,0,1). pow(X,Y,Z):-Y1=Y-1,pow(X,Y1,Z1),Z1=Z*X. Anything wrong with this code?

    Read the article

  • Isometric layer moving inside map

    - by gronzzz
    i'm created isometric map and now trying to limit layer moving. Main idea, that i have left bottom, right bottom, left top, right top points, that camera can not move outside, so player will not see map out of bounds. But i can not understand algorithm of how to do that. It's my layer scale/moving code. - (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event { _isTouchBegin = YES; } - (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event { NSArray *allTouches = [[event allTouches] allObjects]; UITouch *touchOne = [allTouches objectAtIndex:0]; CGPoint touchLocationOne = [touchOne locationInView: [touchOne view]]; CGPoint previousLocationOne = [touchOne previousLocationInView: [touchOne view]]; // Scaling if ([allTouches count] == 2) { _isDragging = NO; UITouch *touchTwo = [allTouches objectAtIndex:1]; CGPoint touchLocationTwo = [touchTwo locationInView: [touchTwo view]]; CGPoint previousLocationTwo = [touchTwo previousLocationInView: [touchTwo view]]; CGFloat currentDistance = sqrt( pow(touchLocationOne.x - touchLocationTwo.x, 2.0f) + pow(touchLocationOne.y - touchLocationTwo.y, 2.0f)); CGFloat previousDistance = sqrt( pow(previousLocationOne.x - previousLocationTwo.x, 2.0f) + pow(previousLocationOne.y - previousLocationTwo.y, 2.0f)); CGFloat distanceDelta = currentDistance - previousDistance; CGPoint pinchCenter = ccpMidpoint(touchLocationOne, touchLocationTwo); pinchCenter = [self convertToNodeSpace:pinchCenter]; CGFloat predictionScale = self.scale + (distanceDelta * PINCH_ZOOM_MULTIPLIER); if([self predictionScaleInBounds:predictionScale]) { [self scale:predictionScale scaleCenter:pinchCenter]; } } else { // Dragging _isDragging = YES; CGPoint previous = [[CCDirector sharedDirector] convertToGL:previousLocationOne]; CGPoint current = [[CCDirector sharedDirector] convertToGL:touchLocationOne]; CGPoint delta = ccpSub(current, previous); self.position = ccpAdd(self.position, delta); } } - (void)touchEnded:(UITouch *)touch withEvent:(UIEvent *)event { _isDragging = NO; _isTouchBegin = NO; // Check if i need to bounce _touchLoc = [touch locationInNode:self]; } #pragma mark - Update - (void)update:(CCTime)delta { CGPoint position = self.position; float scale = self.scale; static float friction = 0.92f; //0.96f; if(_isDragging && !_isScaleBounce) { _velocity = ccp((position.x - _lastPos.x)/2, (position.y - _lastPos.y)/2); _lastPos = position; } else { _velocity = ccp(_velocity.x * friction, _velocity.y *friction); position = ccpAdd(position, _velocity); self.position = position; } if (_isScaleBounce && !_isTouchBegin) { float min = fabsf(self.scale - MIN_SCALE); float max = fabsf(self.scale - MAX_SCALE); int dif = max > min ? 1 : -1; if ((scale > MAX_SCALE - SCALE_BOUNCE_AREA) || (scale < MIN_SCALE + SCALE_BOUNCE_AREA)) { CGFloat newSscale = scale + dif * (delta * friction); [self scale:newSscale scaleCenter:_touchLoc]; } else { _isScaleBounce = NO; } } }

    Read the article

  • Oval collision detection not working properly

    - by William
    So I'm trying to implement a test where a oval can connect with a circle, but it's not working. edist = (float) Math.sqrt(Math.pow((px + ((pwidth/2) )) - (bx + (bsize/2)), 2) + Math.pow(-((py + ((pwidth/2)) ) - (bx + (bsize/2))), 2)); and here is the full code (requires Slick2D): import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; public class ColTest extends BasicGame{ float px = 50; float py = 50; float pheight = 50; float pwidth = 50; float bx = 200; float by = 200; float bsize = 200; float edist; float pspeed = 3; Input input; public ColTest() { super("ColTest"); } @Override public void init(GameContainer gc) throws SlickException { } @Override public void update(GameContainer gc, int delta) throws SlickException { input = gc.getInput(); try{ if(input.isKeyDown(Input.KEY_UP)) py-=pspeed; if(input.isKeyDown(Input.KEY_DOWN)) py+=pspeed; if(input.isKeyDown(Input.KEY_LEFT)) px-=pspeed; if(input.isKeyDown(Input.KEY_RIGHT)) px+=pspeed; } catch(Exception e){} } public void render(GameContainer gc, Graphics g) throws SlickException { g.setColor(new Color(255,255,255)); g.drawString("col: " + col(), 10, 10); g.drawString("edist: " + edist + " dist: " + dist, 10, 100); g.fillRect(px, py, pwidth, pheight); g.setColor(new Color(255,0,255)); g.fillOval(px, py, pwidth, pheight); g.setColor(new Color(255,255,255)); g.fillOval(200, 200, 200, 200); } public boolean col(){ edist = (float) Math.sqrt(Math.pow((px + ((pwidth/2) )) - (bx + (bsize/2)), 2) + Math.pow(-((py + ((pwidth/2)) ) - (bx + (bsize/2))), 2)); if(edist <= (bsize/2) + (px + (pwidth/2))) return true; else return false; } public float rotate(float x, float y, float ox, float oy, float a, boolean b) { float dst = (float) Math.sqrt(Math.pow(x-ox,2.0)+ Math.pow(y-oy,2.0)); float oa = (float) Math.atan2(y-oy,x-ox); if(b) return (float) Math.cos(oa + Math.toRadians(a))*dst+ox; else return (float) Math.sin(oa + Math.toRadians(a))*dst+oy; } public static void main(String[] args) throws SlickException { AppGameContainer app = new AppGameContainer( new ColTest() ); app.setShowFPS(false); app.setAlwaysRender(true); app.setTargetFrameRate(60); app.setDisplayMode(800, 600, false); app.start(); } }

    Read the article

  • calculix data visualizor using QT

    - by Ann
    include "final1.h" include "ui_final1.h" include include include ifndef GL_MULTISAMPLE define GL_MULTISAMPLE 0x809D endif define numred 100 define numgrn 10 define numblu 6 final1::final1(QWidget *parent) : QGLWidget(parent) { setFormat(QGLFormat(QGL::SampleBuffers)); rotationX = -38.0; rotationY = -58.0; rotationZ = 0.0; scaling = .05; // glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); //createGradient(); createGLObject(); } final1::~final1() { makeCurrent(); glDeleteLists(glObject, 1); } void final1::paintEvent(QPaintEvent * /* event */) { QPainter painter(this); draw(); } void final1::mousePressEvent(QMouseEvent *event) { lastPos = event-pos(); } void final1::mouseMoveEvent(QMouseEvent *event) { GLfloat dx = GLfloat(event-x() - lastPos.x()) / width(); GLfloat dy = GLfloat(event-y() - lastPos.y()) / height(); if (event->buttons() & Qt::LeftButton) { rotationX += 180 * dy; rotationY += 180 * dx; update(); } else if (event->buttons() & Qt::RightButton) { rotationX += 180 * dy; rotationZ += 180 * dx; update(); } lastPos = event->pos(); } void final1::createGLObject() { makeCurrent(); GLfloat f1[150],f2[150],f3[150],length=0; qreal size=2; int k=1,a,b,c,d,e,f,g,h,element_node_no=0; GLfloat x,y,z; QString str1,str2,str3,str4,str5,str6,str7,str8; int red,green,blue,index=1,displacement; int LUT[1000][3]; for(red=100;red glShadeModel(GL_SMOOTH); glObject = glGenLists(1); glNewList(glObject, GL_COMPILE); // qglColor(QColor(255, 239, 191)); glLineWidth(1.0); QLinearGradient linearGradient(0, 0, 100, 100); linearGradient.setColorAt(0.0, Qt::red); linearGradient.setColorAt(0.2, Qt::green); linearGradient.setColorAt(1.0, Qt::black); //renderArea->setBrush(linearGradient); //glColor3f(1,0,0);pow((f1[e]-f1[a]),2) QFile file("/home/41407/input1.txt"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); if(k<=125) { str1= line.section(',', 1, 1); str2=line.section(',', 2, 2); str3=line.section(',', 3, 3); x=str1.toFloat(); y=str2.toFloat(); z=str3.toFloat(); f1[k]=x; f2[k]=y; f3[k]=z; /* glBegin(GL_TRIANGLES); // glColor3f(LUT[k][0],LUT[k][1],LUT[k][2]); //QColorAt();//setPointSize(size); glVertex3f(x,y,z); glEnd();*/ } else if(k>125) { element_node_no=0; qCount(line.begin(),line.end(),',',element_node_no); // printf("\n%d",element_node_no); str1= line.section(',', 1, 1); str2=line.section(',', 2, 2); str3=line.section(',', 3, 3); str4= line.section(',', 4, 4); str5=line.section(',', 5, 5); str6=line.section(',', 6, 6); str7= line.section(',', 7, 7); str8=line.section(',', 8, 8); a=str1.toInt(); b=str2.toInt(); c=str3.toInt(); d=str4.toInt(); e=str5.toInt(); f=str6.toInt(); g=str7.toInt(); h=str8.toInt(); glBegin(GL_POLYGON); glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); //brush.setColor(Qt::black);//setColor(QColor::black()); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); // pmp.setBrush(gradient); glVertex3f(f1[a],f2[a] ,f3[a]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glVertex3f(f1[b],f2[b] ,f3[b]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glVertex3f(f1[c],f2[c] ,f3[c]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glVertex3f(f1[d],f2[d] ,f3[d]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glVertex3f(f1[a],f2[a] ,f3[a]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); //glEnd(); //glBegin(GL_LINE_LOOP); glVertex3f(f1[e],f2[e] ,f3[e]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glVertex3f(f1[f],f2[f] ,f3[f]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glVertex3f(f1[g],f2[g], f3[g]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glVertex3f(f1[h],f2[h], f3[h]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glVertex3f(f1[d],f2[d] ,f3[d]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glVertex3f(f1[a],f2[a] ,f3[a]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glEnd(); glBegin(GL_POLYGON); //glVertex3f(f1[a],f2[a] ,f3[a]); glVertex3f(f1[e],f2[e] ,f3[e]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glVertex3f(f1[h],f2[h], f3[h]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); //glVertex3f(f1[d],f2[d] ,f3[d]); glVertex3f(f1[g],f2[g], f3[g]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glVertex3f(f1[c],f2[c] ,f3[c]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glVertex3f(f1[f],f2[f] ,f3[f]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glVertex3f(f1[b],f2[b] ,f3[b]); glColor3f(LUT[k][0],LUT[k][1],LUT[k++][2]); glEnd(); /*length=sqrt(pow((f1[e]-f1[a]),2)+pow((f2[e]-f2[a]),2)+pow((f3[e]-f3[a]),2)); printf("\n%d",length);*/ } k++; } glEndList(); file.close(); k=1; QFile file1("/home/41407/op.txt"); if (!file1.open(QIODevice::ReadOnly | QIODevice::Text)) return; QTextStream in1(&file1); k=1; while (!in1.atEnd()) { QString line = in1.readLine(); // if(k<=125) { str1= line.section(' ', 1, 1); x=str1.toFloat(); str2=line.section(' ', 2, 2); y=str2.toFloat(); str3=line.section(' ', 3, 3); z=str3.toFloat(); displacement=sqrt(pow( (x-f1[k]),2)+pow((y-f2[k]),2)+pow((z-f3[k]),2)); //printf("\n %d : %d",k,displacement); glBegin(GL_POLYGON); //glColor3f(LUT[displacement][0],LUT[displacement][1],LUT[displacement][2]); glVertex3f(f1[k],f2[k],f3[k]); glEnd(); a1[k]=x+f1[k]; a2[k]=y+f2[k]; a3[k]=z+f3[k]; //printf("\nc: %f %f %f",x,y,z); //printf("\nf: %f %f %f",f1[k],f2[k],f3[k]); //printf("\na: %f %f %f",a1[k],a2[k],a3[k]); } k++; glEndList(); } } void final1::draw() { glPushAttrib(GL_ALL_ATTRIB_BITS); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); GLfloat x = 3.0 * GLfloat(width()) / height(); glOrtho(-x, +x, -3.0, +3.0, 4.0, 15.0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTranslatef(0.0, 0.0, -10.0); glScalef(scaling, scaling, scaling); glRotatef(rotationX, 1.0, 0.0, 0.0); glRotatef(rotationY, 0.0, 1.0, 0.0); glRotatef(rotationZ, 0.0, 0.0, 1.0); glEnable(GL_MULTISAMPLE); glCallList(glObject); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); } /*uint final1::colorAt(int x) { generateShade(); QPolygonF pts = m_hoverPoints->points(); for (int i=1; i < pts.size(); ++i) { if (pts.at(i-1).x() <= x && pts.at(i).x() >= x) { QLineF l(pts.at(i-1), pts.at(i)); l.setLength(l.length() * ((x - l.x1()) / l.dx())); return m_shade.pixel(qRound(qMin(l.x2(), (qreal(m_shade.width() - 1)))), qRound(qMin(l.y2(), qreal(m_shade.height() - 1)))); } } return 0;*/ //final1:: //} /*void final1::createGLObject() { makeCurrent(); //QPainter painter; QPixmap pm(20, 20); QPainter pmp(&pm); pmp.fillRect(0, 0, 10, 10, Qt::blue); pmp.fillRect(10, 10, 10, 10, Qt::lightGray); pmp.fillRect(0, 10, 10, 10, Qt::darkGray); pmp.fillRect(10, 0, 10, 10, Qt::darkGray); pmp.end(); QPalette pal = palette(); pal.setBrush(backgroundRole(), QBrush(pm)); //setAutoFillBackground(true); setPalette(pal); //GLfloat f1[150],f2[150],f3[150],a1[150],a2[150],a3[150]; int k=1,a,b,c,d,e,f,g,h; //int p=0; GLfloat x,y,z; int displacement; QString str1,str2,str3,str4,str5,str6,str7,str8; int red,green,blue,index=1; int LUT[8000][3]; for(red=0;red //glShadeModel(GL_LINE); glObject = glGenLists(1); glNewList(glObject, GL_COMPILE); //qglColor(QColor(120,255,210)); glLineWidth(1.0); //glColor3f(1,0,0); QFile file("/home/41407/input.txt"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; QTextStream in(&file); while (!in.atEnd()) { //glColor3f(LUT[k][0],LUT[k][1],LUT[k][2]); QString line = in.readLine(); if(k<=125) { //printf("\nline :%c",line); str1= line.section(',', 1, 1); str2=line.section(',', 2, 2); str3=line.section(',', 3, 3); x=str1.toFloat(); y=str2.toFloat(); z=str3.toFloat(); f1[k]=x; f2[k]=y; f3[k]=z; //printf("\nf: %f %f %f",f1[k],f2[k],f3[k]); } else if(k125) //for(p=0;p<6;p++) { //glColor3f(LUT[k][0],LUT[k][1],LUT[k][2]); update(); str1= line.section(',', 1, 1); str2=line.section(',', 2, 2); str3=line.section(',', 3, 3); str4= line.section(',', 4, 4); str5=line.section(',', 5, 5); str6=line.section(',', 6, 6); str7= line.section(',', 7, 7); str8=line.section(',', 8, 8); a=str1.toInt(); b=str2.toInt(); c=str3.toInt(); d=str4.toInt(); e=str5.toInt(); f=str6.toInt(); g=str7.toInt(); h=str8.toInt(); //for (p = 0; p < 6; p++) { // glBegin(GL_LINE_WIDTH); //glColor3f(LUT[126][0],LUT[126][1],LUT[126][2]); //update(); //glNormal3fv(&n[p][0]); //glVertex3f(f1[i],f2[i],f3[i]); glVertex3fv(&v[faces[i][1]][0]); glVertex3fv(&v[faces[i][2]][0]); glVertex3fv(&v[faces[i][3]][0]); //glEnd(); //} glBegin(GL_LINE_LOOP); //glColor3f(p*20,p*20,p); glColor3f(1,0,0); glVertex3f(f1[a],f2[a] ,f3[a]); //painter.fillRect(QRectF(f1[a],f2[a] ,f3[a], 2), Qt::magenta); glVertex3f(f1[b],f2[b] ,f3[b]); glVertex3f(f1[c],f2[c] ,f3[c]); glVertex3f(f1[d],f2[d] ,f3[d]); glVertex3f(f1[a],f2[a] ,f3[a]); glVertex3f(f1[e],f2[e] ,f3[e]); glVertex3f(f1[f],f2[f] ,f3[f]); glVertex3f(f1[g],f2[g], f3[g]); glVertex3f(f1[h],f2[h], f3[h]); glVertex3f(f1[d],f2[d] ,f3[d]); glVertex3f(f1[a],f2[a] ,f3[a]); //glColor3f(1,0,0); //QLinearGradient ( f1[a], f2[a], f1[b], f2[b] ); glEnd(); glBegin(GL_LINES); //glNormal3fv(&n[p][0]); //glColor3f(LUT[k][0],LUT[k][1],LUT[k][2]); glVertex3f(f1[e],f2[e] ,f3[e]); glVertex3f(f1[h],f2[h], f3[h]); glVertex3f(f1[g],f2[g], f3[g]); glVertex3f(f1[c],f2[c] ,f3[c]); glVertex3f(f1[f],f2[f] ,f3[f]); glVertex3f(f1[b],f2[b] ,f3[b]); glEnd(); } } k++; } glEndList(); qglColor(QColor(239, 255, 191)); glLineWidth(1.0); glColor3f(0,1,0); k=1; QFile file1("/home/41407/op.txt"); if (!file1.open(QIODevice::ReadOnly | QIODevice::Text)) return; QTextStream in1(&file1); k=1; while (!in1.atEnd()) { QString line = in1.readLine(); // if(k<=125) { str1= line.section(' ', 1, 1); x=str1.toFloat(); str2=line.section(' ', 2, 2); y=str2.toFloat(); str3=line.section(' ', 3, 3); z=str3.toFloat(); displacement=sqrt(pow( (x-f1[k]),2)+pow((y-f2[k]),2)+pow((z-f3[k]),2)); printf("\n %d : %d",k,displacement); glBegin(GL_POINT); glColor3f(LUT[displacement][0],LUT[displacement][1],LUT[displacement][2]); glVertex3f(x,y,z); glLoadIdentity(); glEnd(); a1[k]=x+f1[k]; a2[k]=y+f2[k]; a3[k]=z+f3[k]; //printf("\nc: %f %f %f",x,y,z); //printf("\nf: %f %f %f",f1[k],f2[k],f3[k]); //printf("\na: %f %f %f",a1[k],a2[k],a3[k]); } k++; glEndList(); } }*/ /*void final1::draw() { glPushAttrib(GL_ALL_ATTRIB_BITS); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); GLfloat x = 3.0 * GLfloat(width()) / height(); glOrtho(-x, +x, -3.0, +3.0, 4.0, 15.0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTranslatef(0.0, 0.0, -10.0); glScalef(scaling, scaling, scaling); glRotatef(rotationX, 1.0, 0.0, 0.0); glRotatef(rotationY, 0.0, 1.0, 0.0); glRotatef(rotationZ, 0.0, 0.0, 1.0); glEnable(GL_MULTISAMPLE); glCallList(glObject); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); }*/ I need to change the color of a portion of beam where pressure is applied.But I am not able to color the front end back phase.

    Read the article

  • MBA and a Computer Science degree

    - by Chung Pow
    A similar question was asked a while back, but I want to know some people who both have an MBA and a Computer Science degree and advanced their careers. What kind of job did you have before and after achieving an MBA? I'm a programmer and I have thought about getting an MBA. What doors will that open for me?

    Read the article

  • Why does Raphael's framerate slow down on this code?

    - by Bob
    So I'm just doing a basic orbit simulator using Raphael JS, where I draw one circle as the "star" and another circle as the "planet". It seems to be working just fine, with the one snag that as the simulation continues, its framerate progressively slows down until the orbital motion no longer appears fluid. Here's the code (note: uses jQuery only to initialize the page): $(function() { var paper = Raphael(document.getElementById('canvas'), 640, 480); var star = paper.circle(320, 240, 10); var planet = paper.circle(320, 150, 5); var starVelocity = [0,0]; var planetVelocity = [20.42,0]; var starMass = 3.08e22; var planetMass = 3.303e26; var gravConstant = 1.034e-18; function calculateOrbit() { var accx = 0; var accy = 0; accx = (gravConstant * starMass * ((star.attr('cx') - planet.attr('cx')))) / (Math.pow(circleDistance(), 3)); accy = (gravConstant * starMass * ((star.attr('cy') - planet.attr('cy')))) / (Math.pow(circleDistance(), 3)); planetVelocity[0] += accx; planetVelocity[1] += accy; planet.animate({cx: planet.attr('cx') + planetVelocity[0], cy: planet.attr('cy') + planetVelocity[1]}, 150, calculateOrbit); paper.circle(planet.attr('cx'), planet.attr('cy'), 1); // added to 'trace' orbit } function circleDistance() { return (Math.sqrt(Math.pow(star.attr('cx') - planet.attr('cx'), 2) + Math.pow(star.attr('cy') - planet.attr('cy'), 2))); } calculateOrbit(); }); It doesn't appear, to me anyway, that any part of that code would cause the animation to gradually slow down to a crawl, so any help solving the problem will be appreciated!

    Read the article

  • Signals and Variables in VHDL - Problem

    - by Morano88
    I have a signal and this signal is a bitvector. The length of the bitvector depends on an input n, it is not fixed. In order to find the length, I have to do some computations. Can I define a signal after defining the variables ? It is ggiving me errors when I do that. It is working fine If I keep the signal before the variables .. but I don't want that .. the length of Z depends on the computations of the variables. What is the solution ? library IEEE; use IEEE.STD_LOGIC_1164.ALL; use IEEE.STD_LOGIC_ARITH.ALL; use IEEE.STD_LOGIC_UNSIGNED.ALL; entity BSD_Full_Comp is Generic (n:integer:=8); Port(X, Y : inout std_logic_vector(n-1 downto 0); FZ : out std_logic_vector(1 downto 0)); end BSD_Full_Comp; architecture struct of BSD_Full_Comp is Component BSD_BitComparator Port ( Ai_1 : inout STD_LOGIC; Ai_0 : inout STD_LOGIC; Bi_1 : inout STD_LOGIC; Bi_0 : inout STD_LOGIC; S1 : out STD_LOGIC; S0 : out STD_LOGIC ); END Component; Signal Z : std_logic_vector(2*n-3 downto 0); begin ass : process Variable length : integer := n; Variable pow : integer :=0 ; Variable ZS : integer :=0; begin while length /= 0 loop length := length/2; pow := pow+1; end loop; length := 2 ** pow; ZS := length - n; wait; end process; end struct;

    Read the article

  • Signals and Variables in VHDL (order) - Problem

    - by Morano88
    I have a signal and this signal is a bitvector (Z). The length of the bitvector depends on an input n, it is not fixed. In order to find the length, I have to do some computations. Can I define a signal after defining the variables ? It is giving me errors when I do that. It is working fine If I keep the signal before the variables (that what is showing below) .. but I don't want that .. the length of Z depends on the computations of the variables. What is the solution ? library IEEE; use IEEE.STD_LOGIC_1164.ALL; use IEEE.STD_LOGIC_ARITH.ALL; use IEEE.STD_LOGIC_UNSIGNED.ALL; entity BSD_Full_Comp is Generic (n:integer:=8); Port(X, Y : inout std_logic_vector(n-1 downto 0); FZ : out std_logic_vector(1 downto 0)); end BSD_Full_Comp; architecture struct of BSD_Full_Comp is Component BSD_BitComparator Port ( Ai_1 : inout STD_LOGIC; Ai_0 : inout STD_LOGIC; Bi_1 : inout STD_LOGIC; Bi_0 : inout STD_LOGIC; S1 : out STD_LOGIC; S0 : out STD_LOGIC ); END Component; Signal Z : std_logic_vector(2*n-3 downto 0); begin ass : process Variable length : integer := n; Variable pow : integer :=0 ; Variable ZS : integer :=0; begin while length /= 0 loop length := length/2; pow := pow+1; end loop; length := 2 ** pow; ZS := length - n; wait; end process; end struct;

    Read the article

  • C non-trivial constants

    - by user525869
    I want to make several constants in C with #define to speed up computation. Two of them are not simply trivial numbers, where one is a right shift, the other is a power. math.h in C gives the function pow() for doubles, whereas I need powers for integers, so I wrote my own function, ipow, so I wouldn't need to be casting everytime. My question is this: One of the #define constants I want to make is a power, say ipow(M, T), where M and T were also #define constants. ipow is a function in the actual code, so this actually seems to slows things down when I run the code (is it running ipow everytime the constant is mentioned?). However, when I ues the built in pow function and just do (int)pow(M,T), the code is sped up. I'm confused as to why this is, since the ipow and pow functions are just as fast. On a more general note, can I define constants using #define using functions inside the actual code? The above example has me confused on whether this speeds things up or actually slows things down.

    Read the article

  • iphone moving direction using accelerometer

    - by Ruchir Shah
    Hi, I want some help on UIAccelerometer class. I want to find some way to find out or distinguish when I wave iphone device from right-to-left and the left-to-right. I am getting x,y,z values as well as interval value. I am also getting velocity and distance calculated from normal physics rule. Distance = (prevDist + sqrt(pow((prevx - acceleration.x), 2) + pow((prevy - acceleration.y), 2) + pow((prevz - acceleration.z), 2))) Velocity = (Distance * timeintercal) { here distance means newdistance-prevdistance and timeinterval for that distance } When I am moving iphone device right-to-left then left-to-right I am getting total distance traveld in both direction and velocity at regular intervals. Can you help me how I can find out that I am moving iphone device left-to-right or right-to-left? Help would be appreciated. Thanks.

    Read the article

  • Pythagoras triangle

    - by Gogolo
    I would like to ask you about this programing part, is it everything ok? the task was: Write the pseudocode or flow diagram and code for the theorem of Pythagoras - for right-angle triangle with three ribs (a, b, and c) of type integer int KendiA = 0; int KendiB = 0; int H = 0; string Trekendeshi = null; int gjetja = 0; for (KendiA = 1; KendiA <= 15; KendiA++) { for (KendiB = 1; KendiB <= 15; KendiB++) { for (H = 1; H <= 30; H++) { if ((Math.Pow(KendiA, 2) + Math.Pow(KendiB, 2) == Math.Pow(H, 2))) { gjetja = gjetja + 1; Trekendeshi = gjetja + "\t" + KendiA + "\t" + KendiB + "\t" + H; Console.WriteLine(Trekendeshi); } } } }

    Read the article

  • improving drawing pythagoras tree

    - by sasquatch90
    Hello. I have written program for drawing pythagoras tree fractal. Can anybody see any way of improving it ? Now it is 120 LOc. I was hoping to shorten it to ~100... import javax.swing.*; import java.util.Scanner; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JComponent; public class Main extends JFrame {; public Main(int n) { setSize(900, 900); setTitle("Pythagoras tree"); Draw d = new Draw(n); add(d); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } private int pow(int n){ int pow = 2; for(int i = 1; i < n; i++){ if(n==0){ pow = 1; } pow = pow*2; } return pow; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Give amount of steps: "); int steps = sc.nextInt(); new Main(steps); } } class Draw extends JComponent { private int height; private int width; private int steps; public Draw(int n) { height = 800; width = 800; steps = n; Dimension d = new Dimension(width, height); setMinimumSize(d); setPreferredSize(new Dimension(d)); setMaximumSize(d); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.white); g.fillRect(0, 0, width, height); g.setColor(Color.black); int w = width; int h = height; int x1, x2, x3, x4, x5, y1, y2, y3, y4, y5; int base = w/7; x1 = (w/2)-(base/2); x2 = x1; x3 = (w/2)+(base/2); x4 = x3; x5 = w/2; y1 = (h-(h/15))-base; y2 = h-(h/15); y3 = y2; y4 = y1; y5 = (h-(h/15))-(base+(base/2)); //paint g.drawLine(x1, y1, x2, y2); g.drawLine(x2, y2, x3, y3); g.drawLine(x3, y3, x4, y4); g.drawLine(x1, y1, x4, y4); int n1 = steps; n1--; if(n1>0){ g.drawLine(x1, y1, x5, y5); g.drawLine(x4, y4, x5, y5); paintMore(n1, g, x1, x5, x4, y1, y5, y4); paintMore(n1, g, x4, x5, x1, y4, y5, y1); } } public void paintMore(int n1, Graphics g, double x1_1, double x2_1, double x3_1, double y1_1, double y2_1, double y3_1){ double x1, x2, x3, x4, x5, y1, y2, y3, y4, y5; //counting x1 = x1_1 + (x2_1-x3_1); x2 = x1_1; x3 = x2_1; x4 = x2_1 + (x2_1-x3_1); x5 = ((x2_1 + (x2_1-x3_1)) + ((x2_1-x3_1)/2)) + ((x1_1-x2_1)/2); y1 = y1_1 + (y2_1-y3_1); y2 = y1_1; y3 = y2_1; y4 = y2_1 + (y2_1-y3_1); y5 = ((y1_1 + (y2_1-y3_1)) + ((y2_1-y1_1)/2)) + ((y2_1-y3_1)/2); //paint g.setColor(Color.green); g.drawLine((int)x1, (int)y1, (int)x2, (int)y2); g.drawLine((int)x3, (int)y3, (int)x4, (int)y4); g.drawLine((int)x1, (int)y1, (int)x4, (int)y4); n1--; if(n1>0){ g.drawLine((int)x1, (int)y1, (int)x5, (int)y5); g.drawLine((int)x4, (int)y4, (int)x5, (int)y5); paintMore(n1, g, x1, x5, x4, y1, y5, y4); paintMore(n1, g, x4, x5, x1, y4, y5, y1); } } }

    Read the article

  • Implementing a popularity algorithm in Django

    - by TheLizardKing
    I am creating a site similar to reddit and hacker news that has a database of links and votes. I am implementing hacker news' popularity algorithm and things are going pretty swimmingly until it comes to actually gathering up these links and displaying them. The algorithm is simple: Y Combinator's Hacker News: Popularity = (p - 1) / (t + 2)^1.5` Votes divided by age factor. Where` p : votes (points) from users. t : time since submission in hours. p is subtracted by 1 to negate submitter's vote. Age factor is (time since submission in hours plus two) to the power of 1.5.factor is (time since submission in hours plus two) to the power of 1.5. I asked a very similar question over yonder http://stackoverflow.com/questions/1964395/complex-ordering-in-django but instead of contemplating my options I choose one and tried to make it work because that's how I did it with PHP/MySQL but I now know Django does things a lot differently. My models look something (exactly) like this class Link(models.Model): category = models.ForeignKey(Category) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add = True) modified = models.DateTimeField(auto_now = True) fame = models.PositiveIntegerField(default = 1) title = models.CharField(max_length = 256) url = models.URLField(max_length = 2048) def __unicode__(self): return self.title class Vote(models.Model): link = models.ForeignKey(Link) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add = True) modified = models.DateTimeField(auto_now = True) karma_delta = models.SmallIntegerField() def __unicode__(self): return str(self.karma_delta) and my view: def index(request): popular_links = Link.objects.select_related().annotate(karma_total = Sum('vote__karma_delta')) return render_to_response('links/index.html', {'links': popular_links}) Now from my previous question, I am trying to implement the algorithm using the sorting function. An answer from that question seems to think I should put the algorithm in the select and sort then. I am going to paginate these results so I don't think I can do the sorting in python without grabbing everything. Any suggestions on how I could efficiently do this? EDIT This isn't working yet but I think it's a step in the right direction: from django.shortcuts import render_to_response from linkett.apps.links.models import * def index(request): popular_links = Link.objects.select_related() popular_links = popular_links.extra( select = { 'karma_total': 'SUM(vote.karma_delta)', 'popularity': '(karma_total - 1) / POW(2, 1.5)', }, order_by = ['-popularity'] ) return render_to_response('links/index.html', {'links': popular_links}) This errors out into: Caught an exception while rendering: column "karma_total" does not exist LINE 1: SELECT ((karma_total - 1) / POW(2, 1.5)) AS "popularity", (S... EDIT 2 Better error? TemplateSyntaxError: Caught an exception while rendering: missing FROM-clause entry for table "vote" LINE 1: SELECT ((vote.karma_total - 1) / POW(2, 1.5)) AS "popularity... My index.html is simply: {% block content %} {% for link in links %} karma-up {{ link.karma_total }} karma-down {{ link.title }} Posted by {{ link.user }} to {{ link.category }} at {{ link.created }} {% empty %} No Links {% endfor %} {% endblock content %} EDIT 3 So very close! Again, all these answers are great but I am concentrating on a particular one because I feel it works best for my situation. from django.db.models import Sum from django.shortcuts import render_to_response from linkett.apps.links.models import * def index(request): popular_links = Link.objects.select_related().extra( select = { 'popularity': '(SUM(links_vote.karma_delta) - 1) / POW(2, 1.5)', }, tables = ['links_link', 'links_vote'], order_by = ['-popularity'], ) return render_to_response('links/test.html', {'links': popular_links}) Running this I am presented with an error hating on my lack of group by values. Specifically: TemplateSyntaxError at / Caught an exception while rendering: column "links_link.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...karma_delta) - 1) / POW(2, 1.5)) AS "popularity", "links_lin... Not sure why my links_link.id wouldn't be in my group by but I am not sure how to alter my group by, django usually does that.

    Read the article

  • Python - calculate multinomial probability density functions on large dataset?

    - by Seafoid
    Hi, I originally intended to use MATLAB to tackle this problem but the inbuilt functions has limitations that do not suit my goal. The same limitation occurs in NumPy. I have two tab-delimited files. The first is a file showing amino acid residue, frequency and count for an in-house database of protein structures, i.e. A 0.25 1 S 0.25 1 T 0.25 1 P 0.25 1 The second file consists of quadruplets of amino acids and the number of times they occur, i.e. ASTP 1 Note, there are 8,000 such quadruplets. Based on the background frequency of occurence of each amino acid and the count of quadruplets, I aim to calculate the multinomial probability density function for each quadruplet and subsequently use it as the expected value in a maximum likelihood calculation. The multinomial distribution is as follows: f(x|n, p) = n!/(x1!*x2!*...*xk!)*((p1^x1)*(p2^x2)*...*(pk^xk)) where x is the number of each of k outcomes in n trials with fixed probabilities p. n is 4 four in all cases in my calculation. I have created three functions to calculate this distribution. # functions for multinomial distribution def expected_quadruplets(x, y): expected = x*y return expected # calculates the probabilities of occurence raised to the number of occurrences def prod_prob(p1, a, p2, b, p3, c, p4, d): prob_prod = (pow(p1, a))*(pow(p2, b))*(pow(p3, c))*(pow(p4, d)) return prob_prod # factorial() and multinomial_coefficient() work in tandem to calculate C, the multinomial coefficient def factorial(n): if n <= 1: return 1 return n*factorial(n-1) def multinomial_coefficient(a, b, c, d): n = 24.0 multi_coeff = (n/(factorial(a) * factorial(b) * factorial(c) * factorial(d))) return multi_coeff The problem is how best to structure the data in order to tackle the calculation most efficiently, in a manner that I can read (you guys write some cryptic code :-)) and that will not create an overflow or runtime error. To data my data is represented as nested lists. amino_acids = [['A', '0.25', '1'], ['S', '0.25', '1'], ['T', '0.25', '1'], ['P', '0.25', '1']] quadruplets = [['ASTP', '1']] I initially intended calling these functions within a nested for loop but this resulted in runtime errors or overfloe errors. I know that I can reset the recursion limit but I would rather do this more elegantly. I had the following: for i in quadruplets: quad = i[0].split(' ') for j in amino_acids: for k in quadruplets: for v in k: if j[0] == v: multinomial_coefficient(int(j[2]), int(j[2]), int(j[2]), int(j[2])) I haven'te really gotten to how to incorporate the other functions yet. I think that my current nested list arrangement is sub optimal. I wish to compare the each letter within the string 'ASTP' with the first component of each sub list in amino_acids. Where a match exists, I wish to pass the appropriate numeric values to the functions using indices. Is their a better way? Can I append the appropriate numbers for each amino acid and quadruplet to a temporary data structure within a loop, pass this to the functions and clear it for the next iteration? Thanks, S :-)

    Read the article

  • java casting confusion

    - by Stardust
    Could anyone please tell me why the following casting is resulting in compile time error: Long l = (Long)Math.pow(5,2); But why not the following: long l = (long)Math.pow(5,2);

    Read the article

  • hibernate sybase db power function

    - by Vipin Thomas
    We are trying to use sybase function power to do mathematical calculation for one of the DB columns. The hibernate is generating power function as pow(?, xyzo0_.AmtScale) whereas sybase supports power function as Syntax POWER( numeric-expression-1, numeric-expression-2 ) We have tried modifying the hibernate.dialect. Have tried org.hibernate.dialect.SybaseASE15Dialect org.hibernate.dialect.Sybase11Dialect org.hibernate.dialect.SybaseAnywhereDialect but all dialects generate the power function as pow(?, xyzo0_.AmtScale). Is this hibernate issue or are we missing something?

    Read the article

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