Search Results

Search found 440 results on 18 pages for 'abs'.

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

  • HMTL5 Anti Aliasing Browser Disable

    - by Tappa Tappa
    I am forced to consider writing a library to handle the fundamental basics of drawing lines, thick lines, circles, squares etc. of an HTML5 canvas because I can't disable a feature embedded in the browser rendering of the core canvas algorithms. Am I forced to build the HTML5 Canvas rendering process from the ground up? If I am, who's in with me to do this? Who wants to change the world? Imagine a simple drawing application written in HTML5... you draw a shape... a closed shape like a rudimentary circle, free hand, more like an onion than a circle (well, that's what mine would look like!)... then imagine selecting a paint bucket icon and clicking inside that shape you drew and expecting it to be filled with a color of your choice. Imagine your surprise as you selected "Paint Bucket" and clicked in the middle of your shape and it filled your shape with color... BUT, not quite... HANG ON... this isn't right!!! On the inside of the edge of the shape you drew is a blur between the background color and your fill color and the edge color... the fill seems to be flawed. You wanted a straight forward "Paint Bucket" / "Fill"... you wanted to draw a shape and then fill it with a color... no fuss.... fill the whole damned inside of your shape with the color you choose. Your web browser has decided that when you draw the lines to define your shape they will be anti-aliased. If you draw a black line for your shape... well, the browser will draw grey pixels along the edges, in places... to make it look like a "better" line. Yeah, a "better" line that **s up the paint / flood fill process. How much does is cost to pay off the browser developers to expose a property to disable their anti-aliasing rendering? Disabling would save milliseconds for their rendering engine, surely! Bah, I really don't want to have to build my own canvas rendering engine using Bresenham line rendering algorithm... WHAT CAN BE DONE... HOW CAN THIS BE CHANGED!!!??? Do I need to start a petition aimed at the WC3???? Will you include your name if you are interested??? UPDATED function DrawLine(objContext, FromX, FromY, ToX, ToY) { var dx = Math.abs(ToX - FromX); var dy = Math.abs(ToY - FromY); var sx = (FromX < ToX) ? 1 : -1; var sy = (FromY < ToY) ? 1 : -1; var err = dx - dy; var CurX, CurY; CurX = FromX; CurY = FromY; while (true) { objContext.fillRect(CurX, CurY, objContext.lineWidth, objContext.lineWidth); if ((CurX == ToX) && (CurY == ToY)) break; var e2 = 2 * err; if (e2 > -dy) { err -= dy; CurX += sx; } if (e2 < dx) { err += dx; CurY += sy; } } }

    Read the article

  • Object array updates one instance repeatedly [on hold]

    - by MGN001
    I'm making a 2D shooter, and the player object holds an array of bullets that represent how many shots the player can have on screen at once. At least, this is what I'm trying for. What's happening is that each time any of the objects in the array is called, it seems to update a single object in memory. So, if I fire and then fire again, the object "starts over" from where I shot from and moves twice as fast. I've spent weeks trying to fix this and I've managed nothing. Hopefully another pair of eyes will see something I've missed. Player.cpp #include "Player.h" const int startLives = 3; const int maxHealth = 2; const float speed = 1; const int maxVelocity = 500; const int topBound = WINDOW_HEIGHT / 5 * 3; const int slowRate = 500; const int accRate = 1000; const int maxBullets = 5; const float spriteWidth = 99; const float spriteHeight = 75; const Vector2f startPosition = { (WINDOW_WIDTH / 2) - (spriteWidth / 2), (WINDOW_HEIGHT / 4 * 3) - (spriteHeight / 2) }; Bullet bullets[maxBullets]; Bullet * bulletPointers[maxBullets]; SDL_Texture * playerHealthy; SDL_Texture * playerDamaged; SDL_Texture * currentSprite; SDL_Rect * rect; Vector2f position; Vector2f velocity; int Health; int Lives; Player::Player() { rect = new SDL_Rect(); } Player::~Player() { SDL_DestroyTexture(playerHealthy); SDL_DestroyTexture(playerDamaged); SDL_DestroyTexture(currentSprite); rect = NULL; } void Player::Initialize(SDL_Renderer * renderer) { SDL_Surface * temp; temp = IMG_Load(".\\Sprites\\player.png"); if (temp == NULL) { printf("Initialization Error: %s\n", IMG_GetError()); exit(PLAYER_INITIALIZATION_ERROR); } playerHealthy = SDL_CreateTextureFromSurface(renderer, temp); temp = IMG_Load(".\\Sprites\\playerDamaged.png"); if (temp == NULL) { printf("Initialization Error: %s\n", IMG_GetError()); exit(PLAYER_INITIALIZATION_ERROR); } playerDamaged = SDL_CreateTextureFromSurface(renderer, temp); temp = IMG_Load(".\\Sprites\\laserGreen.png"); if (temp == NULL) { printf("Initialization Error: %s\n", IMG_GetError()); exit(PLAYER_INITIALIZATION_ERROR); } SDL_Texture * bullet = SDL_CreateTextureFromSurface(renderer, temp); temp = IMG_Load(".\\Sprites\\laserGreenShot.png"); if (temp == NULL) { printf("Initialization Error: %s\n", IMG_GetError()); exit(PLAYER_INITIALIZATION_ERROR); } SDL_Texture * explosion = SDL_CreateTextureFromSurface(renderer, temp); for (int i = 0; i < maxBullets; i++) { bullets[i].Initialize(renderer, bullet, explosion); bulletPointers[i] = NULL; } temp = NULL; rect->h = spriteHeight; rect->w = spriteWidth; Reset(); } void Player::Update(Input input, float deltaTime) { if (abs(velocity.x) < slowRate * deltaTime) { velocity.x = 0; } else if (velocity.x > 0) { velocity.x -= slowRate * deltaTime; } else if (velocity.x < 0) { velocity.x += slowRate * deltaTime; } if (abs(velocity.y) < slowRate * deltaTime) { velocity.y = 0; } if (velocity.y > 0) { velocity.y -= slowRate * deltaTime; } else if (velocity.y < 0) { velocity.y += slowRate * deltaTime; } if (Health <= 0) { --Lives; Spawn(); } velocity.x += UnitVector(input.InputNew.movement).x * accRate * deltaTime; velocity.y += UnitVector(input.InputNew.movement).y * accRate * deltaTime; if (Magnitude(velocity) > maxVelocity) { velocity.x = UnitVector(velocity).x * maxVelocity; velocity.y = UnitVector(velocity).y * maxVelocity; } position.x += velocity.x * deltaTime * speed; position.y += velocity.y * deltaTime * speed; if (input.InputNew.JumpLeft && !input.InputOld.JumpLeft) { position.x -= spriteWidth; } if (input.InputNew.JumpRight && !input.InputOld.JumpRight) { position.x += spriteWidth; } Boundaries(); rect->x = position.x; rect->y = position.y; if (input.InputNew.Fire && !input.InputOld.Fire) { Fire(); } for (int i = 0; i < maxBullets; ++i) { if (bulletPointers[i] != NULL) { bullets[i].Update(deltaTime); if (bullets[i].getPosition().y < -33) { bulletPointers[i] = NULL; } } } } void Player::Draw(SDL_Renderer * renderer) { for (int i = 0; i < maxBullets; ++i) { if (bulletPointers[i] != NULL) { bullets[i].Draw(renderer); } } SDL_RenderCopy(renderer, currentSprite, NULL, rect); } void Player::Spawn() { position = startPosition; Health = maxHealth; currentSprite = playerHealthy; rect->x = position.x; rect->y = position.y; } void Player::Boundaries() { if (position.x < 0) { position.x = 0; velocity.x *= -1; } else if (position.x > WINDOW_WIDTH - spriteWidth) { position.x = WINDOW_WIDTH - spriteWidth; velocity.x *= -1; } if (position.y < topBound) { position.y = topBound; velocity.y *= -1; } else if (position.y > WINDOW_HEIGHT - spriteHeight) { position.y = WINDOW_HEIGHT - spriteHeight; velocity.y *= -1; } } int Player::getLives() { return Lives; } void Player::Reset() { Lives = startLives; Spawn(); } void Player::Fire() { for (int i = 0; i < maxBullets; ++i) { if (bulletPointers[i] == NULL) { bulletPointers[i] = &bullets[i]; bullets[i].Fire(position,velocity.x/2); break; } } } Bullet.cpp #include "Bullet.h" const int speed = 500; Vector2f bulletVelocity; float ExplosionMax = 0.5f; float ExplosionTimer; const Vector2f fireOffset = { 45.5f, 10.0f }; const Vector2f explosionOffset = { 23.5f, -27.0f }; const Vector2i bulletSize = { 9, 33 }; const Vector2i explosionSize = { 56, 54 }; Vector2f bulletPosition; SDL_Texture * bulletSprite; SDL_Texture * explosionSprite; SDL_Texture * bulletCurrentSprite; SDL_Rect * bulletRect; Bullet::Bullet() { } Bullet::~Bullet() { } void Bullet::Initialize(SDL_Renderer * renderer, SDL_Texture * bullet, SDL_Texture * explosion) { bulletSprite = bullet; explosionSprite = explosion; bulletRect = new SDL_Rect(); } void Bullet::Update(float deltaTime) { bulletPosition.y -= bulletVelocity.y * deltaTime; bulletPosition.x += bulletVelocity.x * deltaTime; bulletRect->x = static_cast<int>(bulletPosition.x); bulletRect->y = static_cast<int>(bulletPosition.y); } void Bullet::Draw(SDL_Renderer * renderer) { SDL_RenderCopy(renderer, bulletCurrentSprite, NULL, bulletRect); } void Bullet::Fire(Vector2f pos, float xSpeed) { bulletPosition.x = pos.x + fireOffset.x; bulletPosition.y = pos.y + fireOffset.y; bulletVelocity.x = xSpeed; bulletVelocity.y = speed; bulletCurrentSprite = bulletSprite; bulletRect->h = bulletSize.y; bulletRect->w = bulletSize.x; bulletRect->x = static_cast<int>(bulletPosition.x); bulletRect->y = static_cast<int>(bulletPosition.y); } Vector2f Bullet::getPosition() { return bulletPosition; } void Bullet::Hit() { bulletCurrentSprite = explosionSprite; bulletVelocity = { 0.0f, 0.0f }; ExplosionTimer = ExplosionMax; bulletPosition.x += explosionOffset.x; bulletPosition.y += explosionOffset.y; bulletRect->w = explosionSize.x; bulletRect->h = explosionSize.y; }

    Read the article

  • Is there a Math.atan2 substitute for j2ME? Blackberry development

    - by Kai
    I have a wide variety of locations stored in my persistent object that contain latitudes and longitudes in double(43.7389, 7.42577) format. I need to be able to grab the user's latitude and longitude and select all items within, say 1 mile. Walking distance. I have done this in PHP so I snagged my PHP code and transferred it to Java, where everything plugged in fine until I figured out J2ME doesn't support atan2(double, double). So, after some searching, I find a small snippet of code that is supposed to be a substitute for atan2. Here is the code: public double atan2(double y, double x) { double coeff_1 = Math.PI / 4d; double coeff_2 = 3d * coeff_1; double abs_y = Math.abs(y)+ 1e-10f; double r, angle; if (x >= 0d) { r = (x - abs_y) / (x + abs_y); angle = coeff_1; } else { r = (x + abs_y) / (abs_y - x); angle = coeff_2; } angle += (0.1963f * r * r - 0.9817f) * r; return y < 0.0f ? -angle : angle; } I am getting odd results from this. My min and max latitude and longitudes are coming back as incredibly low numbers that can't possibly be right. Like 0.003785746 when I am expecting something closer to the original lat and long values (43.7389, 7.42577). Since I am no master of advanced math, I don't really know what to look for here. Perhaps someone else may have an answer. Here is my complete code: package store_finder; import java.util.Vector; import javax.microedition.location.Criteria; import javax.microedition.location.Location; import javax.microedition.location.LocationException; import javax.microedition.location.LocationListener; import javax.microedition.location.LocationProvider; import javax.microedition.location.QualifiedCoordinates; import net.rim.blackberry.api.invoke.Invoke; import net.rim.blackberry.api.invoke.MapsArguments; import net.rim.device.api.system.Bitmap; import net.rim.device.api.system.Display; import net.rim.device.api.ui.Color; import net.rim.device.api.ui.Field; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.Manager; import net.rim.device.api.ui.component.BitmapField; import net.rim.device.api.ui.component.RichTextField; import net.rim.device.api.ui.component.SeparatorField; import net.rim.device.api.ui.container.HorizontalFieldManager; import net.rim.device.api.ui.container.MainScreen; import net.rim.device.api.ui.container.VerticalFieldManager; public class nearBy extends MainScreen { private HorizontalFieldManager _top; private VerticalFieldManager _middle; private int horizontalOffset; private final static long animationTime = 300; private long animationStart = 0; private double latitude = 43.7389; private double longitude = 7.42577; private int _interval = -1; private double max_lat; private double min_lat; private double max_lon; private double min_lon; private double latitude_in_degrees; private double longitude_in_degrees; public nearBy() { super(); horizontalOffset = Display.getWidth(); _top = new HorizontalFieldManager(Manager.USE_ALL_WIDTH | Field.FIELD_HCENTER) { public void paint(Graphics gr) { Bitmap bg = Bitmap.getBitmapResource("bg.png"); gr.drawBitmap(0, 0, Display.getWidth(), Display.getHeight(), bg, 0, 0); subpaint(gr); } }; _middle = new VerticalFieldManager() { public void paint(Graphics graphics) { graphics.setBackgroundColor(0xFFFFFF); graphics.setColor(Color.BLACK); graphics.clear(); super.paint(graphics); } protected void sublayout(int maxWidth, int maxHeight) { int displayWidth = Display.getWidth(); int displayHeight = Display.getHeight(); super.sublayout( displayWidth, displayHeight); setExtent( displayWidth, displayHeight); } }; add(_top); add(_middle); Bitmap lol = Bitmap.getBitmapResource("logo.png"); BitmapField lolfield = new BitmapField(lol); _top.add(lolfield); Criteria cr= new Criteria(); cr.setCostAllowed(true); cr.setPreferredResponseTime(60); cr.setHorizontalAccuracy(5000); cr.setVerticalAccuracy(5000); cr.setAltitudeRequired(true); cr.isSpeedAndCourseRequired(); cr.isAddressInfoRequired(); try{ LocationProvider lp = LocationProvider.getInstance(cr); if( lp!=null ){ lp.setLocationListener(new LocationListenerImpl(), _interval, 1, 1); } } catch(LocationException le) { add(new RichTextField("Location exception "+le)); } //_middle.add(new RichTextField("this is a map " + Double.toString(latitude) + " " + Double.toString(longitude))); int lat = (int) (latitude * 100000); int lon = (int) (longitude * 100000); String document = "<location-document>" + "<location lon='" + lon + "' lat='" + lat + "' label='You are here' description='You' zoom='0' />" + "<location lon='742733' lat='4373930' label='Hotel de Paris' description='Hotel de Paris' address='Palace du Casino' postalCode='98000' phone='37798063000' zoom='0' />" + "</location-document>"; // Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, new MapsArguments( MapsArguments.ARG_LOCATION_DOCUMENT, document)); _middle.add(new SeparatorField()); surroundingVenues(); _middle.add(new RichTextField("max lat: " + max_lat)); _middle.add(new RichTextField("min lat: " + min_lat)); _middle.add(new RichTextField("max lon: " + max_lon)); _middle.add(new RichTextField("min lon: " + min_lon)); } private void surroundingVenues() { double point_1_latitude_in_degrees = latitude; double point_1_longitude_in_degrees= longitude; // diagonal distance + error margin double distance_in_miles = (5 * 1.90359441) + 10; getCords (point_1_latitude_in_degrees, point_1_longitude_in_degrees, distance_in_miles, 45); double lat_limit_1 = latitude_in_degrees; double lon_limit_1 = longitude_in_degrees; getCords (point_1_latitude_in_degrees, point_1_longitude_in_degrees, distance_in_miles, 135); double lat_limit_2 = latitude_in_degrees; double lon_limit_2 = longitude_in_degrees; getCords (point_1_latitude_in_degrees, point_1_longitude_in_degrees, distance_in_miles, -135); double lat_limit_3 = latitude_in_degrees; double lon_limit_3 = longitude_in_degrees; getCords (point_1_latitude_in_degrees, point_1_longitude_in_degrees, distance_in_miles, -45); double lat_limit_4 = latitude_in_degrees; double lon_limit_4 = longitude_in_degrees; double mx1 = Math.max(lat_limit_1, lat_limit_2); double mx2 = Math.max(lat_limit_3, lat_limit_4); max_lat = Math.max(mx1, mx2); double mm1 = Math.min(lat_limit_1, lat_limit_2); double mm2 = Math.min(lat_limit_3, lat_limit_4); min_lat = Math.max(mm1, mm2); double mlon1 = Math.max(lon_limit_1, lon_limit_2); double mlon2 = Math.max(lon_limit_3, lon_limit_4); max_lon = Math.max(mlon1, mlon2); double minl1 = Math.min(lon_limit_1, lon_limit_2); double minl2 = Math.min(lon_limit_3, lon_limit_4); min_lon = Math.max(minl1, minl2); //$qry = "SELECT DISTINCT zip.zipcode, zip.latitude, zip.longitude, sg_stores.* FROM zip JOIN store_finder AS sg_stores ON sg_stores.zip=zip.zipcode WHERE zip.latitude<=$lat_limit_max AND zip.latitude>=$lat_limit_min AND zip.longitude<=$lon_limit_max AND zip.longitude>=$lon_limit_min"; } private void getCords(double point_1_latitude, double point_1_longitude, double distance, int degs) { double m_EquatorialRadiusInMeters = 6366564.86; double m_Flattening=0; double distance_in_meters = distance * 1609.344 ; double direction_in_radians = Math.toRadians( degs ); double eps = 0.000000000000005; double r = 1.0 - m_Flattening; double point_1_latitude_in_radians = Math.toRadians( point_1_latitude ); double point_1_longitude_in_radians = Math.toRadians( point_1_longitude ); double tangent_u = (r * Math.sin( point_1_latitude_in_radians ) ) / Math.cos( point_1_latitude_in_radians ); double sine_of_direction = Math.sin( direction_in_radians ); double cosine_of_direction = Math.cos( direction_in_radians ); double heading_from_point_2_to_point_1_in_radians = 0.0; if ( cosine_of_direction != 0.0 ) { heading_from_point_2_to_point_1_in_radians = atan2( tangent_u, cosine_of_direction ) * 2.0; } double cu = 1.0 / Math.sqrt( ( tangent_u * tangent_u ) + 1.0 ); double su = tangent_u * cu; double sa = cu * sine_of_direction; double c2a = ( (-sa) * sa ) + 1.0; double x= Math.sqrt( ( ( ( 1.0 /r /r ) - 1.0 ) * c2a ) + 1.0 ) + 1.0; x= (x- 2.0 ) / x; double c= 1.0 - x; c= ( ( (x * x) / 4.0 ) + 1.0 ) / c; double d= ( ( 0.375 * (x * x) ) -1.0 ) * x; tangent_u = distance_in_meters /r / m_EquatorialRadiusInMeters /c; double y= tangent_u; boolean exit_loop = false; double cosine_of_y = 0.0; double cz = 0.0; double e = 0.0; double term_1 = 0.0; double term_2 = 0.0; double term_3 = 0.0; double sine_of_y = 0.0; while( exit_loop != true ) { sine_of_y = Math.sin(y); cosine_of_y = Math.cos(y); cz = Math.cos( heading_from_point_2_to_point_1_in_radians + y); e = (cz * cz * 2.0 ) - 1.0; c = y; x = e * cosine_of_y; y = (e + e) - 1.0; term_1 = ( sine_of_y * sine_of_y * 4.0 ) - 3.0; term_2 = ( ( term_1 * y * cz * d) / 6.0 ) + x; term_3 = ( ( term_2 * d) / 4.0 ) -cz; y= ( term_3 * sine_of_y * d) + tangent_u; if ( Math.abs(y - c) > eps ) { exit_loop = false; } else { exit_loop = true; } } heading_from_point_2_to_point_1_in_radians = ( cu * cosine_of_y * cosine_of_direction ) - ( su * sine_of_y ); c = r * Math.sqrt( ( sa * sa ) + ( heading_from_point_2_to_point_1_in_radians * heading_from_point_2_to_point_1_in_radians ) ); d = ( su * cosine_of_y ) + ( cu * sine_of_y * cosine_of_direction ); double point_2_latitude_in_radians = atan2(d, c); c = ( cu * cosine_of_y ) - ( su * sine_of_y * cosine_of_direction ); x = atan2( sine_of_y * sine_of_direction, c); c = ( ( ( ( ( -3.0 * c2a ) + 4.0 ) * m_Flattening ) + 4.0 ) * c2a * m_Flattening ) / 16.0; d = ( ( ( (e * cosine_of_y * c) + cz ) * sine_of_y * c) + y) * sa; double point_2_longitude_in_radians = ( point_1_longitude_in_radians + x) - ( ( 1.0 - c) * d * m_Flattening ); heading_from_point_2_to_point_1_in_radians = atan2( sa, heading_from_point_2_to_point_1_in_radians ) + Math.PI; latitude_in_degrees = Math.toRadians( point_2_latitude_in_radians ); longitude_in_degrees = Math.toRadians( point_2_longitude_in_radians ); } public double atan2(double y, double x) { double coeff_1 = Math.PI / 4d; double coeff_2 = 3d * coeff_1; double abs_y = Math.abs(y)+ 1e-10f; double r, angle; if (x >= 0d) { r = (x - abs_y) / (x + abs_y); angle = coeff_1; } else { r = (x + abs_y) / (abs_y - x); angle = coeff_2; } angle += (0.1963f * r * r - 0.9817f) * r; return y < 0.0f ? -angle : angle; } private Vector fetchVenues(double max_lat, double min_lat, double max_lon, double min_lon) { return new Vector(); } private class LocationListenerImpl implements LocationListener { public void locationUpdated(LocationProvider provider, Location location) { if(location.isValid()) { nearBy.this.longitude = location.getQualifiedCoordinates().getLongitude(); nearBy.this.latitude = location.getQualifiedCoordinates().getLatitude(); //double altitude = location.getQualifiedCoordinates().getAltitude(); //float speed = location.getSpeed(); } } public void providerStateChanged(LocationProvider provider, int newState) { // MUST implement this. Should probably do something useful with it as well. } } } please excuse the mess. I have the user lat long hard coded since I do not have GPS functional yet. You can see the SQL query commented out to know how I plan on using the min and max lat and long values. Any help is appreciated. Thanks

    Read the article

  • Android - HorizontalScrollView within ScrollView Touch Handling

    - by Joel
    Hi, I have a ScrollView that surrounds my entire layout so that the entire screen is scrollable. The first element I have in this ScrollView is a HorizontalScrollView block that has features that can be scrolled through horizontally. I've added an ontouchlistener to the horizontalscrollview to handle touch events and force the view to "snap" to the closest image on the ACTION_UP event. So the effect I'm going for is like the stock android homescreen where you can scroll from one to the other and it snaps to one screen when you lift your finger. This all works great except for one problem: I need to swipe left to right almost perfectly horizontally for an ACTION_UP to ever register. If I swipe vertically in the very least (which I think many people tend to do on their phones when swiping side to side), I will receive an ACTION_CANCEL instead of an ACTION_UP. My theory is that this is because the horizontalscrollview is within a scrollview, and the scrollview is hijacking the vertical touch to allow for vertical scrolling. How can I disable the touch events for the scrollview from just within my horizontal scrollview, but still allow for normal vertical scrolling elsewhere in the scrollview? Here's a sample of my code: public class HomeFeatureLayout extends HorizontalScrollView { private ArrayList<ListItem> items = null; private GestureDetector gestureDetector; View.OnTouchListener gestureListener; private static final int SWIPE_MIN_DISTANCE = 5; private static final int SWIPE_THRESHOLD_VELOCITY = 300; private int activeFeature = 0; public HomeFeatureLayout(Context context, ArrayList<ListItem> items){ super(context); setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); setFadingEdgeLength(0); this.setHorizontalScrollBarEnabled(false); this.setVerticalScrollBarEnabled(false); LinearLayout internalWrapper = new LinearLayout(context); internalWrapper.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); internalWrapper.setOrientation(LinearLayout.HORIZONTAL); addView(internalWrapper); this.items = items; for(int i = 0; i< items.size();i++){ LinearLayout featureLayout = (LinearLayout) View.inflate(this.getContext(),R.layout.homefeature,null); TextView header = (TextView) featureLayout.findViewById(R.id.featureheader); ImageView image = (ImageView) featureLayout.findViewById(R.id.featureimage); TextView title = (TextView) featureLayout.findViewById(R.id.featuretitle); title.setTag(items.get(i).GetLinkURL()); TextView date = (TextView) featureLayout.findViewById(R.id.featuredate); header.setText("FEATURED"); Image cachedImage = new Image(this.getContext(), items.get(i).GetImageURL()); image.setImageDrawable(cachedImage.getImage()); title.setText(items.get(i).GetTitle()); date.setText(items.get(i).GetDate()); internalWrapper.addView(featureLayout); } gestureDetector = new GestureDetector(new MyGestureDetector()); setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (gestureDetector.onTouchEvent(event)) { return true; } else if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL ){ int scrollX = getScrollX(); int featureWidth = getMeasuredWidth(); activeFeature = ((scrollX + (featureWidth/2))/featureWidth); int scrollTo = activeFeature*featureWidth; smoothScrollTo(scrollTo, 0); return true; } else{ return false; } } }); } class MyGestureDetector extends SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { try { //right to left if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { activeFeature = (activeFeature < (items.size() - 1))? activeFeature + 1:items.size() -1; smoothScrollTo(activeFeature*getMeasuredWidth(), 0); return true; } //left to right else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { activeFeature = (activeFeature > 0)? activeFeature - 1:0; smoothScrollTo(activeFeature*getMeasuredWidth(), 0); return true; } } catch (Exception e) { // nothing } return false; } } }

    Read the article

  • WPF: how to find an element in a datatemplate from an itemscontrol

    - by EV
    Hi, I have the following problem: the application is using the custom itemscontrol called ToolBox. The elements of a toolbox are called toolboxitems and are custom contentcontrol. Now, the toolbox stores a number of images that are retrieved from a database and displayed. For that I use a datatemplate inside the toolbox control. However, when I try to drag and drop the elements, I don't get the image object but the database component. I thought that I should then traverse the structure to find the Image element. here's the code: Toolbox: public class Toolbox : ItemsControl { private Size defaultItemSize = new Size(65, 65); public Size DefaultItemSize { get { return this.defaultItemSize; } set { this.defaultItemSize = value; } } protected override DependencyObject GetContainerForItemOverride() { return new ToolboxItem(); } protected override bool IsItemItsOwnContainerOverride(object item) { return (item is ToolboxItem); } } ToolBoxItem: public class ToolboxItem : ContentControl { private Point? dragStartPoint = null; static ToolboxItem() { FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(ToolboxItem), new FrameworkPropertyMetadata(typeof(ToolboxItem))); } protected override void OnPreviewMouseDown(MouseButtonEventArgs e) { base.OnPreviewMouseDown(e); this.dragStartPoint = new Point?(e.GetPosition(this)); } public String url { get; private set; } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (e.LeftButton != MouseButtonState.Pressed) { this.dragStartPoint = null; } if (this.dragStartPoint.HasValue) { Point position = e.GetPosition(this); if ((SystemParameters.MinimumHorizontalDragDistance <= Math.Abs((double)(position.X - this.dragStartPoint.Value.X))) || (SystemParameters.MinimumVerticalDragDistance <= Math.Abs((double)(position.Y - this.dragStartPoint.Value.Y)))) { string xamlString = XamlWriter.Save(this.Content); MessageBoxResult result = MessageBox.Show(xamlString); DataObject dataObject = new DataObject("DESIGNER_ITEM", xamlString); if (dataObject != null) { DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Copy); } } e.Handled = true; } } private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject child = VisualTreeHelper.GetChild(obj, i); if (child != null && child is childItem) return (childItem)child; else { childItem childOfChild = FindVisualChild<childItem>(child); if (childOfChild != null) return childOfChild; } } return null; } } here is the xaml file for ToolBox and toolbox item: <Style TargetType="{x:Type s:ToolboxItem}"> <Setter Property="Control.Padding" Value="5" /> <Setter Property="ContentControl.HorizontalContentAlignment" Value="Stretch" /> <Setter Property="ContentControl.VerticalContentAlignment" Value="Stretch" /> <Setter Property="ToolTip" Value="{Binding ToolTip}" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type s:ToolboxItem}"> <Grid> <Rectangle Name="Border" StrokeThickness="1" StrokeDashArray="2" Fill="Transparent" SnapsToDevicePixels="true" /> <ContentPresenter Content="{TemplateBinding ContentControl.Content}" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" ContentTemplate="{TemplateBinding ContentTemplate}"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter TargetName="Border" Property="Stroke" Value="Gray" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style TargetType="{x:Type s:Toolbox}"> <Setter Property="SnapsToDevicePixels" Value="true" /> <Setter Property="Focusable" Value="False" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <Border BorderThickness="{TemplateBinding Border.BorderThickness}" Padding="{TemplateBinding Control.Padding}" BorderBrush="{TemplateBinding Border.BorderBrush}" Background="{TemplateBinding Panel.Background}" SnapsToDevicePixels="True"> <ScrollViewer VerticalScrollBarVisibility="Auto"> <ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" /> </ScrollViewer> </Border> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="ItemsPanel"> <Setter.Value> <ItemsPanelTemplate> <WrapPanel Margin="0,5,0,5" ItemHeight="{Binding Path=DefaultItemSize.Height, RelativeSource={RelativeSource AncestorType=s:Toolbox}}" ItemWidth="{Binding Path=DefaultItemSize.Width, RelativeSource={RelativeSource AncestorType=s:Toolbox}}" /> </ItemsPanelTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> Example usage: <Toolbox x:Name="NewLibrary" DefaultItemSize="55,55" ItemsSource="{Binding}" > <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel> <Image Source="{Binding Path=url}" /> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </Toolbox> The object that I get is a database object. When using a static resource I get the Image object. How to retrieve this Image object from a datatemplate? I though that I could use this tutorial: http://msdn.microsoft.com/en-us/library/bb613579.aspx But it does not seem to solve the problem. Could anyone suggest a solution? Thanks!

    Read the article

  • idioms for returning multiple values in shell scripting

    - by Wang
    Are there any idioms for returning multiple values from a bash function within a script? http://tldp.org/LDP/abs/html/assortedtips.html describes how to echo multiple values and process the results (e.g., example 35-17), but that gets tricky if some of the returned values are strings with spaces in. A more structured way to return would be to assign to global variables, like foo () { FOO_RV1="bob" FOO_RV2="bill" } foo echo "foo returned ${FOO_RV1} and ${FOO_RV2}" I realize that if I need re-entrancy in a shell script I'm probably doing it wrong, but I still feel very uncomfortable throwing global variables around just to hold return values. Is there a better way? I would prefer portability, but it's probably not a real limitation if I have to specify #!/bin/bash.

    Read the article

  • iphone setting UITextView delegate breaks auto completion

    - by Tristan
    Hi there! I have a UITextField that I would like to enable auto completion on by: [self.textView setAutocorrectionType:UITextAutocorrectionTypeYes]; This works normally, except when I give the UITextView a delegate. When a delegate is set, auto complete just stops working. The delegate has only the following method: - (void)textViewDidChange:(UITextView *)textView { self.textView.text = [self.textView.text stringByReplacingOccurrencesOfString:@"\n" withString:@""]; int left = LENGTH_MAX -[self.textView.text length]; self.characterCountLabel.text = [NSString stringWithFormat:@"%i",abs(left)]; } Does anyone know how to have both auto complete enabled and a delegate set? Thanks!Tristan

    Read the article

  • Getting BeautifulSoup to find a specific <p>

    - by Ryan
    I'm trying to put together a basic HTML scraper for a variety of scientific journal websites, specifically trying to get the abstract or introductory paragraph. The current journal I'm working on is Nature, and the article I've been using as my sample can be seen at http://www.nature.com/nature/journal/v463/n7284/abs/nature08715.html. I can't get the abstract out of that page, however. I'm searching for everything between the <p class="lead">...</p> tags, but I can't seem to figure out how to isolate them. I thought it would be something simple like from BeautifulSoup import BeautifulSoup import re import urllib2 address="http://www.nature.com/nature/journal/v463/n7284/full/nature08715.html" html = urllib2.urlopen(address).read() soup = BeautifulSoup(html) abstract = soup.find('p', attrs={'class' : 'lead'}) print abstract Using Python 2.5, BeautifulSoup 3.0.8, running this returns 'None'. I have no option of using anything else that needs to be compiled/installed (like lxml). Is BeautifulSoup confused, or am I?

    Read the article

  • Python 3: timestamp to datetime: where does this additional hour come from?

    - by Beau Martínez
    I'm using the following functions: # The epoch used in the datetime API. EPOCH = datetime.datetime.fromtimestamp(0) def timedelta_to_seconds(delta): seconds = (delta.microseconds * 1e6) + delta.seconds + (delta.days * 86400) seconds = abs(seconds) return seconds def datetime_to_timestamp(date, epoch=EPOCH): # Ensure we deal with `datetime`s. date = datetime.datetime.fromordinal(date.toordinal()) epoch = datetime.datetime.fromordinal(epoch.toordinal()) timedelta = date - epoch timestamp = timedelta_to_seconds(timedelta) return timestamp def timestamp_to_datetime(timestamp, epoch=EPOCH): # Ensure we deal with a `datetime`. epoch = datetime.datetime.fromordinal(epoch.toordinal()) epoch_difference = timedelta_to_seconds(epoch - EPOCH) adjusted_timestamp = timestamp - epoch_difference date = datetime.datetime.fromtimestamp(adjusted_timestamp) return date And using them with the passed code: twenty = datetime.datetime(2010, 4, 4) print(twenty) print(datetime_to_timestamp(twenty)) print(timestamp_to_datetime(datetime_to_timestamp(twenty))) And getting the following results: 2010-04-04 00:00:00 1270339200.0 2010-04-04 01:00:00 For some reason, I'm getting an additional hour added in the last call, despite my code having, as far as I can see, no flaws. Where is this additional hour coming from?

    Read the article

  • Method to Create an Entity Framework Object Context

    - by Kubi
    public RBSEntities GetContext() { SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(); sqlBuilder.DataSource = "a-pc"; sqlBuilder.InitialCatalog = "ABS"; sqlBuilder.IntegratedSecurity = true; string providerString = sqlBuilder.ToString(); EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(); entityBuilder.Provider = "System.Data.SqlClient"; entityBuilder.ProviderConnectionString = providerString; entityBuilder.Metadata = @"res://*/RBSModel.csdl| res://*/RBSModel.ssdl| res://*/RBSModel.msl"; RBSEntities entities = new RBSEntities(entityBuilder.ToString()); return entities; } Something wrong with the Metadata. Anybody having an idea about how to fix this ?

    Read the article

  • Compare two String with MySQL

    - by Scorpi0
    Hi, I wan't to compare two strings in a SQL request so I can retrieve the best match, the aim is to propose to an operator the best zip code possible. For example, in France, we have Integer Zip code, so I made an easy request : SELECT * FROM myTable ORDER BY abs(zip_code - 75000) This request returns first the data closest of Paris. Unfortunatelly, United Kingdom have zip code like AB421RS, so my request can't do it. I see in SQL Server a function 'Difference' : http://www.java2s.com/Code/SQLServer/String-Functions/DIFFERENCEworkoutwhenonestringsoundssimilartoanotherstring.htm But I use MySQL.. Is there anyone who have a good idea to do the trick in one simple request ? PS : the Levenshtein Distance will not do it, as I really wan't to compare string like if they were number. ABCDEF have to be closer to AWXYZ than to ZBCDEF.

    Read the article

  • Python File Meta Tag reading

    - by Jeff
    Anyone know of a Python module that can pull Tag data from multiple media formats? Trying to build an app that allows for manipulation of ASF (Windows Media Player files, ie WMA, WMV, etc), ID3, including both ID3v1 and ID3v2 (MPEG files, ie MP3), MPEG Audio Bit Stream (ie ABS, MP1, MP2, MP3), MPEG Program Stream (MPEG movies, and DVD and HD DVD video discs, ie MPG, MPEG, VOB, EVO), and ISO Base Media File Format (eg QuickTime, MPEG-4 and iTunes AAC files, ie QT, MOV, MP4, M4A, M4B, M4P, M4V, etc). Don't need ALL of that but just most standard consumer formats like mov and mpeg. I can't seem to find a good module to support that or a library. Any recommendations?

    Read the article

  • Calculating Percentiles (Ruby).

    - by zxcvbnm
    My code is based on the methods described here and here. def fraction?(number) number - number.truncate end def percentile(param_array, percentage) another_array = param_array.to_a.sort r = percentage.to_f * (param_array.size.to_f - 1) + 1 if r <= 1 then return another_array[0] elsif r >= another_array.size then return another_array[another_array.size - 1] end ir = r.truncate another_array[ir] + fraction?((another_array[ir].to_f - another_array[ir - 1].to_f).abs) end Example usage: test_array = [95.1772, 95.1567, 95.1937, 95.1959, 95.1442, 95.061, 95.1591, 95.1195, 95.1065, 95.0925, 95.199, 95.1682] test_values = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] test_values.each do |value| puts value.to_s + ": " + percentile(test_array, value).to_s end Output: 0.0: 95.061 0.1: 95.1205 0.2: 95.1325 0.3: 95.1689 0.4: 95.1692 0.5: 95.1615 0.6: 95.1773 0.7: 95.1862 0.8: 95.2102 0.9: 95.1981 1.0: 95.199 The problem here is that the 80th percentile is higher than the 90th and the 100th. However, as far as I can tell my implementation is as described, and it returns the right answer for the example given (0.9). Is there an error in my code I'm not seeing? Or is there a better way to do this?

    Read the article

  • Changing Emacs Forward-Word Behaviour

    - by gvkv
    As the title says, how does one change the behaviour of emacs forward-word function? For example, suppose [] is the cursor. Then: my $abs_target_path[]= abs_path($target); <M-f> my $abs_target_path = abs[_]path($target); I know I could just use M-f M-b but as far as I'm concerned, that shouldn't be necessary and I'd like to change it. In particular, I want two things: When I press M-f, I want to go to the first character of the next word regardless of whether the point is within a word, within a group of spaces or somewhere else. Customize word-characters on a mode-by-mode basis. After all, moving around in CPerl mode is different than, say, TeX mode. So, in the above example, item 1 would have the cursor would move to the 'a' (and the point to it's left) after hitting M-f. Item 2 would allow me to define underscores and sigils as word characters.

    Read the article

  • whats the diference between train, validation and test set, in neural networks?

    - by Daniel
    Im using this library http://pastebin.com/raw.php?i=aMtVv4RZ to implement a learning agent. I have generated the train cases, but i dont know for sure what are the validation and test sets, the teacher says: 70% should be train cases, 10% will be test cases and the rest 20% should be validation cases. Thanks. edit i have this code, for training.. but i have no ideia when to stop training.. def train(self, train, validation, N=0.3, M=0.1): # N: learning rate # M: momentum factor accuracy = list() while(True): error = 0.0 for p in train: input, target = p self.update(input) error = error + self.backPropagate(target, N, M) print "validation" total = 0 for p in validation: input, target = p output = self.update(input) total += sum([abs(target - output) for target, output in zip(target, output)]) #calculates sum of absolute diference between target and output accuracy.append(total) print min(accuracy) print sum(accuracy[-5:])/5 #if i % 100 == 0: print 'error %-14f' % error if ? < ?: break

    Read the article

  • How can I further optimize this color difference function?

    - by aLfa
    I have made this function to calculate color differences in the CIE Lab colorspace, but it lacks speed. Since I'm not a Java expert, I wonder if any Java guru around has some tips that can improve the speed here. The code is based on the matlab function mentioned in the comment block. /** * Compute the CIEDE2000 color-difference between the sample color with * CIELab coordinates 'sample' and a standard color with CIELab coordinates * 'std' * * Based on the article: * "The CIEDE2000 Color-Difference Formula: Implementation Notes, * Supplementary Test Data, and Mathematical Observations,", G. Sharma, * W. Wu, E. N. Dalal, submitted to Color Research and Application, * January 2004. * available at http://www.ece.rochester.edu/~gsharma/ciede2000/ */ public static double deltaE2000(double[] lab1, double[] lab2) { double L1 = lab1[0]; double a1 = lab1[1]; double b1 = lab1[2]; double L2 = lab2[0]; double a2 = lab2[1]; double b2 = lab2[2]; // Cab = sqrt(a^2 + b^2) double Cab1 = Math.sqrt(a1 * a1 + b1 * b1); double Cab2 = Math.sqrt(a2 * a2 + b2 * b2); // CabAvg = (Cab1 + Cab2) / 2 double CabAvg = (Cab1 + Cab2) / 2; // G = 1 + (1 - sqrt((CabAvg^7) / (CabAvg^7 + 25^7))) / 2 double CabAvg7 = Math.pow(CabAvg, 7); double G = 1 + (1 - Math.sqrt(CabAvg7 / (CabAvg7 + 6103515625.0))) / 2; // ap = G * a double ap1 = G * a1; double ap2 = G * a2; // Cp = sqrt(ap^2 + b^2) double Cp1 = Math.sqrt(ap1 * ap1 + b1 * b1); double Cp2 = Math.sqrt(ap2 * ap2 + b2 * b2); // CpProd = (Cp1 * Cp2) double CpProd = Cp1 * Cp2; // hp1 = atan2(b1, ap1) double hp1 = Math.atan2(b1, ap1); // ensure hue is between 0 and 2pi if (hp1 < 0) { // hp1 = hp1 + 2pi hp1 += 6.283185307179586476925286766559; } // hp2 = atan2(b2, ap2) double hp2 = Math.atan2(b2, ap2); // ensure hue is between 0 and 2pi if (hp2 < 0) { // hp2 = hp2 + 2pi hp2 += 6.283185307179586476925286766559; } // dL = L2 - L1 double dL = L2 - L1; // dC = Cp2 - Cp1 double dC = Cp2 - Cp1; // computation of hue difference double dhp = 0.0; // set hue difference to zero if the product of chromas is zero if (CpProd != 0) { // dhp = hp2 - hp1 dhp = hp2 - hp1; if (dhp > Math.PI) { // dhp = dhp - 2pi dhp -= 6.283185307179586476925286766559; } else if (dhp < -Math.PI) { // dhp = dhp + 2pi dhp += 6.283185307179586476925286766559; } } // dH = 2 * sqrt(CpProd) * sin(dhp / 2) double dH = 2 * Math.sqrt(CpProd) * Math.sin(dhp / 2); // weighting functions // Lp = (L1 + L2) / 2 - 50 double Lp = (L1 + L2) / 2 - 50; // Cp = (Cp1 + Cp2) / 2 double Cp = (Cp1 + Cp2) / 2; // average hue computation // hp = (hp1 + hp2) / 2 double hp = (hp1 + hp2) / 2; // identify positions for which abs hue diff exceeds 180 degrees if (Math.abs(hp1 - hp2) > Math.PI) { // hp = hp - pi hp -= Math.PI; } // ensure hue is between 0 and 2pi if (hp < 0) { // hp = hp + 2pi hp += 6.283185307179586476925286766559; } // LpSqr = Lp^2 double LpSqr = Lp * Lp; // Sl = 1 + 0.015 * LpSqr / sqrt(20 + LpSqr) double Sl = 1 + 0.015 * LpSqr / Math.sqrt(20 + LpSqr); // Sc = 1 + 0.045 * Cp double Sc = 1 + 0.045 * Cp; // T = 1 - 0.17 * cos(hp - pi / 6) + // + 0.24 * cos(2 * hp) + // + 0.32 * cos(3 * hp + pi / 30) - // - 0.20 * cos(4 * hp - 63 * pi / 180) double hphp = hp + hp; double T = 1 - 0.17 * Math.cos(hp - 0.52359877559829887307710723054658) + 0.24 * Math.cos(hphp) + 0.32 * Math.cos(hphp + hp + 0.10471975511965977461542144610932) - 0.20 * Math.cos(hphp + hphp - 1.0995574287564276334619251841478); // Sh = 1 + 0.015 * Cp * T double Sh = 1 + 0.015 * Cp * T; // deltaThetaRad = (pi / 3) * e^-(36 / (5 * pi) * hp - 11)^2 double powerBase = hp - 4.799655442984406; double deltaThetaRad = 1.0471975511965977461542144610932 * Math.exp(-5.25249016001879 * powerBase * powerBase); // Rc = 2 * sqrt((Cp^7) / (Cp^7 + 25^7)) double Cp7 = Math.pow(Cp, 7); double Rc = 2 * Math.sqrt(Cp7 / (Cp7 + 6103515625.0)); // RT = -sin(delthetarad) * Rc double RT = -Math.sin(deltaThetaRad) * Rc; // de00 = sqrt((dL / Sl)^2 + (dC / Sc)^2 + (dH / Sh)^2 + RT * (dC / Sc) * (dH / Sh)) double dLSl = dL / Sl; double dCSc = dC / Sc; double dHSh = dH / Sh; return Math.sqrt(dLSl * dLSl + dCSc * dCSc + dHSh * dHSh + RT * dCSc * dHSh); }

    Read the article

  • Searching with Linq

    - by Phil
    I have a collection of objects, each with an int Frame property. Given an int, I want to find the object in the collection that has the closest Frame. Here is what I'm doing so far: public static void Search(int frameNumber) { var differences = (from rec in _records select new { FrameDiff = Math.Abs(rec.Frame - frameNumber), Record = rec }).OrderBy(x => x.FrameDiff); var closestRecord = differences.FirstOrDefault().Record; //continue work... } This is great and everything, except there are 200,000 items in my collection and I call this method very frequently. Is there a relatively easy, more efficient way to do this?

    Read the article

  • Java Math.cos() Method Does Not Return 0 When Expected

    - by dimo414
    Using Java on a Windows 7 PC (not sure if that matters) and calling Math.cos() on values that should return 0 (like pi/2) instead returns small values, but small values that, unless I'm misunderstanding, are much greater than 1 ulp off from zero. Math.cos(Math.PI/2) = 6.123233995736766E-17 Math.ulp(Math.cos(Math.PI/2)) = 1.232595164407831E-32 Is this in fact within 1 ulp and I'm simply confused? And would this be an acceptable wrapper method to resolve this minor inaccuracy? public static double cos(double a){ double temp = Math.abs(a % Math.PI); if(temp == Math.PI/2) return 0; return Math.cos(a); }

    Read the article

  • Find subset with K elements that are closest to eachother

    - by Nima
    Given an array of integers size N, how can you efficiently find a subset of size K with elements that are closest to each other? Let the closeness for a subset (x1,x2,x3,..xk) be defined as: 2 <= N <= 10^5 2 <= K <= N constraints: Array may contain duplicates and is not guaranteed to be sorted. My brute force solution is very slow for large N, and it doesn't check if there's more than 1 solution: N = input() K = input() assert 2 <= N <= 10**5 assert 2 <= K <= N a = [] for i in xrange(0, N): a.append(input()) a.sort() minimum = sys.maxint startindex = 0 for i in xrange(0,N-K+1): last = i + K tmp = 0 for j in xrange(i, last): for l in xrange(j+1, last): tmp += abs(a[j]-a[l]) if(tmp > minimum): break if(tmp < minimum): minimum = tmp startindex = i #end index = startindex + K? Examples: N = 7 K = 3 array = [10,100,300,200,1000,20,30] result = [10,20,30] N = 10 K = 4 array = [1,2,3,4,10,20,30,40,100,200] result = [1,2,3,4]

    Read the article

  • Using LINQ to Obtain Max of Columns for Two Dimensional Arrays

    - by Ngu Soon Hui
    Is there anyway to use LINQ to obtain the maximum of each columns for two dimensional arrays? Assume that I have the following: var arrays = new double[5,100](); I want to get the maximum of arrays[0,:], arrays[1,:] .... arrays[4,:]. How to use LINQ to do it? I could have use such method public double GetMax(double[,] arr, int rowIndex) { var colCount = arr.GetLength(1); double max = 0.0; for(int i=0; i<colCount; i++) { max=Math.Max(Math.Abs(arr[rowIndex, i]), max); } return max; } But I would prefer a more succinct ways of doing things.

    Read the article

  • Are mathamatical Algorithms protected by copyright

    - by analogy
    I wish to implement an algorithm which i read in a journal paper in my software (commercial). I want to know if this is allowed or not. The algorithm in question is described in http://arxiv.org/abs/0709.2938 It is a very simple algorithm and a number of implementations exist in python (http://igraph.sourceforge.net/) and java. One of them is in gpl another which i got from a different researcher and had no license attached. There are significant differences in two implementations, e.g. second one uses threads and multiple cores. It is possible to rewrite/ (not translate) the algorithm. So can I use it in my software or on a server for commercial purpose. Thanks

    Read the article

  • ActionBarSherlock + ViewPager caching more then just prev/next view

    - by miroslavign
    on the page: onCreate called for two tabs each time one tab is selected there is explained how the ABS(actually ViewPager) is working in order for ViewPager to be able to do a scrolling. It is clear that at least a prev/next page need all to be created at the same time. Would it be possible to "cache" more than just prev/next Views(Fragments), in a way: I am on Page 1 and there I have a network call to fetch some data(doing this in Activity, not in Fragment - btw. is this OK?) switch to Page 2, and then switch to Page 3, and then switch to Page 1 = Here my page is recreated (using some caching though, BUT, I do not need any recreation if possible) So, it would be nice to cache all the pages. How to accomplish this If possible in current version (4), or this would be some new feature? Or even better question, how to postpond/disable destroying of views?

    Read the article

  • Unittest and mock

    - by user1410756
    I'm testing with unittest in python and it's ok. Now, I have introduced mock and I need to resolve a question. This is my code: from mock import Mock import unittest class Matematica(object): def __init__(self, op1, op2): self.op1 = op1 self.op2 = op2 def adder(self): return self.op1 + self.op2 def subs(self): return abs(self.op1 - self.op2) def molt(self): return self.op1 * self.op2 def divid(self): return self.op1 / self.op2 class TestMatematica(unittest.TestCase): """Test della classe Matematica""" def testing(self): """Somma""" mat = Matematica(10,20) self.assertEqual(mat.adder(),30) """Sottrazione""" self.assertEqual(mat.subs(),10) class test_mock(object): def __init__(self, matematica): self.matematica = matematica def execute(self): self.matematica.adder() self.matematica.adder() self.matematica.subs() if __name__ == "__main__": result = unittest.TextTestRunner(verbosity=2).run(TestMatematica('testing')) a = Matematica(10,20) b = test_mock(a) b.execute() mock_foo = Mock(b.execute)#return_value = 'rafa') mock_foo() print mock_foo.called print mock_foo.call_count print mock_foo.method_calls This code is functionally and result of print is: True, 1, [] . Now, I need to count how many times are called self.matematica.adder() and self.matematica.subs() . THANKS

    Read the article

  • Detecting periodic repetitions in the data stream

    - by pulegium
    Let's say I have an array of zeros: a = numpy.zeros(1000) I then introduce some repetitive 'events': a[range(0, 1000, 30)] = 1 Question is, how do I detect the 'signal' there? Because it's far from the ideal signal if I do the 'regular' FFT I don't get a clear indication of where my 'true' signal is: f = abs(numpy.fft.rfft(a)) Is there a method to detect these repetitions with some degree of certainty? Especially if I have few of those mixed in, for example here: a[range(0, 1000, 30)] = 1 a[range(0, 1000, 110)] = 1 a[range(0, 1000, 48)] = 1 I'd like to get three 'spikes' on the resulting data...

    Read the article

  • VBA Add to Array and Use Previous Value

    - by MattHead93
    I'm trying to write some code that will take a value WeekNum, and add it to an array Week(1 To 51), and then associate a value from a Textbox TargDef. Once this has been added to the array, I want to look up the value of the array for the previous WeekNum and add it to a value ProdTarg. I've created this much so far: Dim Week(1 To 51) Dim Count As Integer If TargDef < 0 Then Count = WeekNum Week(Count) = Abs(Val(TargDef)) If Val(Week((Count) - 1)) = 0 Then ProdTarg = Val(ProdTarg) Else ProdTard = Val(ProdTarg) + Val(Week((Count) - 1)) End If End If I am currently receiving the error "Subscript out of Range" for the line If Val(Week((Count) - 1)) = 0 Then Any help will be greatly appreciated!

    Read the article

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