Search Results

Search found 13 results on 1 pages for 'upperbound'.

Page 1/1 | 1 

  • Powerbuilder Dynamic Array Manipulation

    - by TomatoSandwich
    string array[] long lBound, uBound lBound = LowerBound(array[]) // = 1, empty array value uBound = UpperBound(array[]) // = 0, empty array value array[1] = 'Item 1' array[2] = 'Item 2' array[3] = 'Item 3' lBound = LowerBound(array[]) // = 1 uBound = UpperBound(array[]) // = 3 array[3] = '' //removing item 3 lBound = LowerBound(array[]) // = 1, still uBound = UpperBound(array[]) // = 3, still (but array[3] is nulled? I think the line 'array[3]' is wrong, but I think I've read that this should remove the array cell. What would be the right way to remove an array cell? Does it depend on object type? (String vs Number vs Object) Or Can one manipulate the UpperBound value to make it work? i.e. after removing Item 3, I want the UpperBound, or arraylength, to be 2, since this is logically correct.

    Read the article

  • Solving Euler Project Problem Number 1 with Microsoft Axum

    - by Jeff Ferguson
    Note: The code below applies to version 0.3 of Microsoft Axum. If you are not using this version of Axum, then your code may differ from that shown here. I have just solved Problem 1 of Project Euler using Microsoft Axum. The problem statement is as follows: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. My Axum-based solution is as follows: namespace EulerProjectProblem1{ // http://projecteuler.net/index.php?section=problems&id=1 // // If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. // The sum of these multiples is 23. // Find the sum of all the multiples of 3 or 5 below 1000. channel SumOfMultiples { input int Multiple1; input int Multiple2; input int UpperBound; output int Sum; } agent SumOfMultiplesAgent : channel SumOfMultiples { public SumOfMultiplesAgent() { int Multiple1 = receive(PrimaryChannel::Multiple1); int Multiple2 = receive(PrimaryChannel::Multiple2); int UpperBound = receive(PrimaryChannel::UpperBound); int Sum = 0; for(int Index = 1; Index < UpperBound; Index++) { if((Index % Multiple1 == 0) || (Index % Multiple2 == 0)) Sum += Index; } PrimaryChannel::Sum <-- Sum; } } agent MainAgent : channel Microsoft.Axum.Application { public MainAgent() { var SumOfMultiples = SumOfMultiplesAgent.CreateInNewDomain(); SumOfMultiples::Multiple1 <-- 3; SumOfMultiples::Multiple2 <-- 5; SumOfMultiples::UpperBound <-- 1000; var Sum = receive(SumOfMultiples::Sum); System.Console.WriteLine(Sum); System.Console.ReadLine(); PrimaryChannel::ExitCode <-- 0; } }} Let’s take a look at the various parts of the code. I begin by setting up a channel called SumOfMultiples that accepts three inputs and one output. The first two of the three inputs will represent the two possible multiples, which are three and five in this case. The third input will represent the upper bound of the problem scope, which is 1000 in this case. The lone output of the channel represents the sum of all of the matching multiples: channel SumOfMultiples{ input int Multiple1; input int Multiple2; input int UpperBound; output int Sum;} I then set up an agent that uses the channel. The agent, called SumOfMultiplesAgent, received the three inputs from the channel sent to the agent, stores the results in local variables, and performs the for loop that iterates from 1 to the received upper bound. The agent keeps track of the sum in a local variable and stores the sum in the output portion of the channel: agent SumOfMultiplesAgent : channel SumOfMultiples{ public SumOfMultiplesAgent() { int Multiple1 = receive(PrimaryChannel::Multiple1); int Multiple2 = receive(PrimaryChannel::Multiple2); int UpperBound = receive(PrimaryChannel::UpperBound); int Sum = 0; for(int Index = 1; Index < UpperBound; Index++) { if((Index % Multiple1 == 0) || (Index % Multiple2 == 0)) Sum += Index; } PrimaryChannel::Sum <-- Sum; }} The application’s main agent, therefore, simply creates a new SumOfMultiplesAgent in a new domain, prepares the channel with the inputs that we need, and then receives the Sum from the output portion of the channel: agent MainAgent : channel Microsoft.Axum.Application{ public MainAgent() { var SumOfMultiples = SumOfMultiplesAgent.CreateInNewDomain(); SumOfMultiples::Multiple1 <-- 3; SumOfMultiples::Multiple2 <-- 5; SumOfMultiples::UpperBound <-- 1000; var Sum = receive(SumOfMultiples::Sum); System.Console.WriteLine(Sum); System.Console.ReadLine(); PrimaryChannel::ExitCode <-- 0; }} The result of the calculation (which, by the way, is 233,168) is sent to the console using good ol’ Console.WriteLine().

    Read the article

  • Merge method in MergeSort Algorithm .

    - by Tony
    I've seen many mergeSort implementations .Here is the version in Data Structures and Algorithms in Java (2nd Edition) by Robert Lafore : private void recMergeSort(long[] workSpace, int lowerBound,int upperBound) { if(lowerBound == upperBound) // if range is 1, return; // no use sorting else { // find midpoint int mid = (lowerBound+upperBound) / 2; // sort low half recMergeSort(workSpace, lowerBound, mid); // sort high half recMergeSort(workSpace, mid+1, upperBound); // merge them merge(workSpace, lowerBound, mid+1, upperBound); } // end else } // end recMergeSort() private void merge(long[] workSpace, int lowPtr, int highPtr, int upperBound) { int j = 0; // workspace index int lowerBound = lowPtr; int mid = highPtr-1; int n = upperBound-lowerBound+1; // # of items while(lowPtr <= mid && highPtr <= upperBound) if( theArray[lowPtr] < theArray[highPtr] ) workSpace[j++] = theArray[lowPtr++]; else workSpace[j++] = theArray[highPtr++]; while(lowPtr <= mid) workSpace[j++] = theArray[lowPtr++]; while(highPtr <= upperBound) workSpace[j++] = theArray[highPtr++]; for(j=0; j<n; j++) theArray[lowerBound+j] = workSpace[j]; } // end merge() One interesting thing about merge method is that , almost all the implementations didn't pass the lowerBound parameter to merge method . lowerBound is calculated in the merge . This is strange , since lowerPtr = mid + 1 ; lowerBound = lowerPtr -1 ; that means lowerBound = mid ; Why the author didn't pass mid to merge like merge(workSpace, lowerBound,mid, mid+1, upperBound); ? I think there must be a reason , otherwise I can't understand why an algorithm older than half a center ,and have all coincident in the such little detail.

    Read the article

  • Deriving arrays in mathematics

    - by Gio Borje
    So I found some similarities between arrays and set notation while learning about sets and sequences in precalc e.g. set notation: {a | cond } = { a1, a2, a3, a4, ..., an} given that n is the domain (or index) of the array, a subset of Natural numbers (or unsigned integer). Most programming languages would provide similar methods to arrays that are applied to sets e.g. upperbounds & lowerbounds; possibly suprema and infima too. Where did arrays come from?

    Read the article

  • Uva's 3n+1 problem

    - by dmindreader
    I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far. import java.io.*; public class NewClass{ /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { int maxCounter= 0; int input; int lowerBound; int upperBound; int counter; int numberOfCycles; int maxCycles= 0; int lowerInt; BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in)); String line = consoleInput.readLine(); String [] splitted = line.split(" "); lowerBound = Integer.parseInt(splitted[0]); upperBound = Integer.parseInt(splitted[1]); int [] recentlyused = new int[1000001]; if (lowerBound > upperBound ) { int h = upperBound; upperBound = lowerBound; lowerBound = h; } lowerInt = lowerBound; while (lowerBound <= upperBound) { counter = lowerBound; numberOfCycles = 0; if (recentlyused[counter] == 0) { while ( counter != 1 ) { if (recentlyused[counter] != 0) { numberOfCycles = recentlyused[counter] + numberOfCycles; counter = 1; } else { if (counter % 2 == 0) { counter = counter /2; } else { counter = 3*counter + 1; } numberOfCycles++; } } } else { numberOfCycles = recentlyused[counter] + numberOfCycles; counter = 1; } recentlyused[lowerBound] = numberOfCycles; if (numberOfCycles > maxCycles) { maxCycles = numberOfCycles; } lowerBound++; } System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1)); } }

    Read the article

  • Recursion with Func

    - by David in Dakota
    Is it possible to do recursion with an Func delegate? I have the following, which doesn't compile because the name of the Func isn't in scope... Func<long, long, List<long>, IEnumerable<long>> GeneratePrimesRecursively = (number, upperBound, primeFactors) => { if (upperBound > number) { return new List<long>(); } else { if (!primeFactors.Any(factor => number % factor == 0)) primeFactors.Add(number); return GeneratePrimesRecursively(++number, upperBound, primeFactors); // breaks here. } };

    Read the article

  • how to use 3D map Actionscript class in mxml file for display map.

    - by nemade-vipin
    hello friends, I have created the application in which I have to use 3D map Action Script class in mxml file to display a map in form. that is in tab navigator last tab. My ActionScript 3D map class is(FlyingDirections):- package src.SBTSCoreObject { import src.SBTSCoreObject.JSONDecoder; import com.google.maps.InfoWindowOptions; import com.google.maps.LatLng; import com.google.maps.LatLngBounds; import com.google.maps.Map3D; import com.google.maps.MapEvent; import com.google.maps.MapOptions; import com.google.maps.MapType; import com.google.maps.MapUtil; import com.google.maps.View; import com.google.maps.controls.NavigationControl; import com.google.maps.geom.Attitude; import com.google.maps.interfaces.IPolyline; import com.google.maps.overlays.Marker; import com.google.maps.overlays.MarkerOptions; import com.google.maps.services.Directions; import com.google.maps.services.DirectionsEvent; import com.google.maps.services.Route; import flash.display.Bitmap; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.filters.DropShadowFilter; import flash.geom.Point; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.navigateToURL; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import flash.utils.Timer; import flash.utils.getTimer; public class FlyingDirections extends Map3D { /** * Panoramio home page. */ private static const PANORAMIO_HOME:String = "http://www.panoramio.com/"; /** * The icon for the car. */ [Embed("assets/car-icon-24px.png")] private static const Car:Class; /** * The Panoramio icon. */ [Embed("assets/iw_panoramio.png")] private static const PanoramioIcon:Class; /** * We animate a zoom in to the start the route before the car starts * to move. This constant sets the time in seconds over which this * zoom occurs. */ private static const LEAD_IN_DURATION:Number = 3; /** * Duration of the trip in seconds. */ private static const TRIP_DURATION:Number = 40; /** * Constants that define the geometry of the Panoramio image markers. */ private static const BORDER_T:Number = 3; private static const BORDER_L:Number = 10; private static const BORDER_R:Number = 10; private static const BORDER_B:Number = 3; private static const GAP_T:Number = 2; private static const GAP_B:Number = 1; private static const IMAGE_SCALE:Number = 1; /** * Trajectory that the camera follows over time. Each element is an object * containing properties used to generate parameter values for flyTo(..). * fraction = 0 corresponds to the start of the trip; fraction = 1 * correspondsto the end of the trip. */ private var FLY_TRAJECTORY:Array = [ { fraction: 0, zoom: 6, attitude: new Attitude(0, 0, 0) }, { fraction: 0.2, zoom: 8.5, attitude: new Attitude(30, 30, 0) }, { fraction: 0.5, zoom: 9, attitude: new Attitude(30, 40, 0) }, { fraction: 1, zoom: 8, attitude: new Attitude(50, 50, 0) }, { fraction: 1.1, zoom: 8, attitude: new Attitude(130, 50, 0) }, { fraction: 1.2, zoom: 8, attitude: new Attitude(220, 50, 0) }, ]; /** * Number of panaramio photos for which we load data. We&apos;ll select a * subset of these approximately evenly spaced along the route. */ private static const NUM_GEOTAGGED_PHOTOS:int = 50; /** * Number of panaramio photos that we actually show. */ private static const NUM_SHOWN_PHOTOS:int = 7; /** * Scaling between real trip time and animation time. */ private static const SCALE_TIME:Number = 0.001; /** * getTimer() value at the instant that we start the trip. If this is 0 then * we have not yet started the car moving. */ private var startTimer:int = 0; /** * The current route. */ private var route:Route; /** * The polyline for the route. */ private var polyline:IPolyline; /** * The car marker. */ private var marker:Marker; /** * The cumulative duration in seconds over each step in the route. * cumulativeStepDuration[0] is 0; cumulativeStepDuration[1] adds the * duration of step 0; cumulativeStepDuration[2] adds the duration * of step 1; etc. */ private var cumulativeStepDuration:/*Number*/Array = []; /** * The cumulative distance in metres over each vertex in the route polyline. * cumulativeVertexDistance[0] is 0; cumulativeVertexDistance[1] adds the * distance to vertex 1; cumulativeVertexDistance[2] adds the distance to * vertex 2; etc. */ private var cumulativeVertexDistance:Array; /** * Array of photos loaded from Panoramio. This array has the same format as * the &apos;photos&apos; property within the JSON returned by the Panoramio API * (see http://www.panoramio.com/api/), with additional properties added to * individual photo elements to hold the loader structures that fetch * the actual images. */ private var photos:Array = []; /** * Array of polyline vertices, where each element is in world coordinates. * Several computations can be faster if we can use world coordinates * instead of LatLng coordinates. */ private var worldPoly:/*Point*/Array; /** * Whether the start button has been pressed. */ private var startButtonPressed:Boolean = false; /** * Saved event from onDirectionsSuccess call. */ private var directionsSuccessEvent:DirectionsEvent = null; /** * Start button. */ private var startButton:Sprite; /** * Alpha value used for the Panoramio image markers. */ private var markerAlpha:Number = 0; /** * Index of the current driving direction step. Used to update the * info window content each time we progress to a new step. */ private var currentStepIndex:int = -1; /** * The fly directions map constructor. * * @constructor */ public function FlyingDirections() { key="ABQIAAAA7QUChpcnvnmXxsjC7s1fCxQGj0PqsCtxKvarsoS-iqLdqZSKfxTd7Xf-2rEc_PC9o8IsJde80Wnj4g"; super(); addEventListener(MapEvent.MAP_PREINITIALIZE, onMapPreinitialize); addEventListener(MapEvent.MAP_READY, onMapReady); } /** * Handles map preintialize. Initializes the map center and zoom level. * * @param event The map event. */ private function onMapPreinitialize(event:MapEvent):void { setInitOptions(new MapOptions({ center: new LatLng(-26.1, 135.1), zoom: 4, viewMode: View.VIEWMODE_PERSPECTIVE, mapType:MapType.PHYSICAL_MAP_TYPE })); } /** * Handles map ready and looks up directions. * * @param event The map event. */ private function onMapReady(event:MapEvent):void { enableScrollWheelZoom(); enableContinuousZoom(); addControl(new NavigationControl()); // The driving animation will be updated on every frame. addEventListener(Event.ENTER_FRAME, enterFrame); addStartButton(); // We start the directions loading now, so that we&apos;re ready to go when // the user hits the start button. var directions:Directions = new Directions(); directions.addEventListener( DirectionsEvent.DIRECTIONS_SUCCESS, onDirectionsSuccess); directions.addEventListener( DirectionsEvent.DIRECTIONS_FAILURE, onDirectionsFailure); directions.load("48 Pirrama Rd, Pyrmont, NSW to Byron Bay, NSW"); } /** * Adds a big blue start button. */ private function addStartButton():void { startButton = new Sprite(); startButton.buttonMode = true; startButton.addEventListener(MouseEvent.CLICK, onStartClick); startButton.graphics.beginFill(0x1871ce); startButton.graphics.drawRoundRect(0, 0, 150, 100, 10, 10); startButton.graphics.endFill(); var startField:TextField = new TextField(); startField.autoSize = TextFieldAutoSize.LEFT; startField.defaultTextFormat = new TextFormat("_sans", 20, 0xffffff, true); startField.text = "Start!"; startButton.addChild(startField); startField.x = 0.5 * (startButton.width - startField.width); startField.y = 0.5 * (startButton.height - startField.height); startButton.filters = [ new DropShadowFilter() ]; var container:DisplayObjectContainer = getDisplayObject() as DisplayObjectContainer; container.addChild(startButton); startButton.x = 0.5 * (container.width - startButton.width); startButton.y = 0.5 * (container.height - startButton.height); var panoField:TextField = new TextField(); panoField.autoSize = TextFieldAutoSize.LEFT; panoField.defaultTextFormat = new TextFormat("_sans", 11, 0x000000, true); panoField.text = "Photos provided by Panoramio are under the copyright of their owners."; container.addChild(panoField); panoField.x = container.width - panoField.width - 5; panoField.y = 5; } /** * Handles directions success. Starts flying the route if everything * is ready. * * @param event The directions event. */ private function onDirectionsSuccess(event:DirectionsEvent):void { directionsSuccessEvent = event; flyRouteIfReady(); } /** * Handles click on the start button. Starts flying the route if everything * is ready. */ private function onStartClick(event:MouseEvent):void { startButton.removeEventListener(MouseEvent.CLICK, onStartClick); var container:DisplayObjectContainer = getDisplayObject() as DisplayObjectContainer; container.removeChild(startButton); startButtonPressed = true; flyRouteIfReady(); } /** * If we have loaded the directions and the start button has been pressed * start flying the directions route. */ private function flyRouteIfReady():void { if (!directionsSuccessEvent || !startButtonPressed) { return; } var directions:Directions = directionsSuccessEvent.directions; // Extract the route. route = directions.getRoute(0); // Draws the polyline showing the route. polyline = directions.createPolyline(); addOverlay(directions.createPolyline()); // Creates a car marker that is moved along the route. var car:DisplayObject = new Car(); marker = new Marker(route.startGeocode.point, new MarkerOptions({ icon: car, iconOffset: new Point(-car.width / 2, -car.height) })); addOverlay(marker); transformPolyToWorld(); createCumulativeArrays(); // Load Panoramio data for the region covered by the route. loadPanoramioData(directions.bounds); var duration:Number = route.duration; // Start a timer that will trigger the car moving after the lead in time. var leadInTimer:Timer = new Timer(LEAD_IN_DURATION * 1000, 1); leadInTimer.addEventListener(TimerEvent.TIMER, onLeadInDone); leadInTimer.start(); var flyTime:Number = -LEAD_IN_DURATION; // Set up the camera flight trajectory. for each (var flyStep:Object in FLY_TRAJECTORY) { var time:Number = flyStep.fraction * duration; var center:LatLng = latLngAt(time); var scaledTime:Number = time * SCALE_TIME; var zoom:Number = flyStep.zoom; var attitude:Attitude = flyStep.attitude; var elapsed:Number = scaledTime - flyTime; flyTime = scaledTime; flyTo(center, zoom, attitude, elapsed); } } /** * Loads Panoramio data for the route bounds. We load data about more photos * than we need, then select a subset lying along the route. * @param bounds Bounds within which to fetch images. */ private function loadPanoramioData(bounds:LatLngBounds):void { var params:Object = { order: "popularity", set: "full", from: "0", to: NUM_GEOTAGGED_PHOTOS.toString(10), size: "small", minx: bounds.getWest(), miny: bounds.getSouth(), maxx: bounds.getEast(), maxy: bounds.getNorth() }; var loader:URLLoader = new URLLoader(); var request:URLRequest = new URLRequest( "http://www.panoramio.com/map/get_panoramas.php?" + paramsToString(params)); loader.addEventListener(Event.COMPLETE, onPanoramioDataLoaded); loader.addEventListener(IOErrorEvent.IO_ERROR, onPanoramioDataFailed); loader.load(request); } /** * Transforms the route polyline to world coordinates. */ private function transformPolyToWorld():void { var numVertices:int = polyline.getVertexCount(); worldPoly = new Array(numVertices); for (var i:int = 0; i < numVertices; ++i) { var vertex:LatLng = polyline.getVertex(i); worldPoly[i] = fromLatLngToPoint(vertex, 0); } } /** * Returns the time at which the route approaches closest to the * given point. * @param world Point in world coordinates. * @return Route time at which the closest approach occurs. */ private function getTimeOfClosestApproach(world:Point):Number { var minDistSqr:Number = Number.MAX_VALUE; var numVertices:int = worldPoly.length; var x:Number = world.x; var y:Number = world.y; var minVertex:int = 0; for (var i:int = 0; i < numVertices; ++i) { var dx:Number = worldPoly[i].x - x; var dy:Number = worldPoly[i].y - y; var distSqr:Number = dx * dx + dy * dy; if (distSqr < minDistSqr) { minDistSqr = distSqr; minVertex = i; } } return cumulativeVertexDistance[minVertex]; } /** * Returns the array index of the first element that compares greater than * the given value. * @param ordered Ordered array of elements. * @param value Value to use for comparison. * @return Array index of the first element that compares greater than * the given value. */ private function upperBound(ordered:Array, value:Number, first:int=0, last:int=-1):int { if (last < 0) { last = ordered.length; } var count:int = last - first; var index:int; while (count > 0) { var step:int = count >> 1; index = first + step; if (value >= ordered[index]) { first = index + 1; count -= step - 1; } else { count = step; } } return first; } /** * Selects up to a given number of photos approximately evenly spaced along * the route. * @param ordered Array of photos, each of which is an object with * a property &apos;closestTime&apos;. * @param number Number of photos to select. */ private function selectEvenlySpacedPhotos(ordered:Array, number:int):Array { var start:Number = cumulativeVertexDistance[0]; var end:Number = cumulativeVertexDistance[cumulativeVertexDistance.length - 2]; var closestTimes:Array = []; for each (var photo:Object in ordered) { closestTimes.push(photo.closestTime); } var selectedPhotos:Array = []; for (var i:int = 0; i < number; ++i) { var idealTime:Number = start + ((end - start) * (i + 0.5) / number); var index:int = upperBound(closestTimes, idealTime); if (index < 1) { index = 0; } else if (index >= ordered.length) { index = ordered.length - 1; } else { var errorToPrev:Number = Math.abs(idealTime - closestTimes[index - 1]); var errorToNext:Number = Math.abs(idealTime - closestTimes[index]); if (errorToPrev < errorToNext) { --index; } } selectedPhotos.push(ordered[index]); } return selectedPhotos; } /** * Handles completion of loading the Panoramio index data. Selects from the * returned photo indices a subset of those that lie along the route and * initiates load of each of these. * @param event Load completion event. */ private function onPanoramioDataLoaded(event:Event):void { var loader:URLLoader = event.target as URLLoader; var decoder:JSONDecoder = new JSONDecoder(loader.data as String); var allPhotos:Array = decoder.getValue().photos; for each (var photo:Object in allPhotos) { var latLng:LatLng = new LatLng(photo.latitude, photo.longitude); photo.closestTime = getTimeOfClosestApproach(fromLatLngToPoint(latLng, 0)); } allPhotos.sortOn("closestTime", Array.NUMERIC); photos = selectEvenlySpacedPhotos(allPhotos, NUM_SHOWN_PHOTOS); for each (photo in photos) { var photoLoader:Loader = new Loader(); // The images aren&apos;t on panoramio.com: we can&apos;t acquire pixel access // using "new LoaderContext(true)". photoLoader.load( new URLRequest(photo.photo_file_url)); photo.loader = photoLoader; // Save the loader info: we use this to find the original element when // the load completes. photo.loaderInfo = photoLoader.contentLoaderInfo; photoLoader.contentLoaderInfo.addEventListener( Event.COMPLETE, onPhotoLoaded); } } /** * Creates a MouseEvent listener function that will navigate to the given * URL in a new window. * @param url URL to which to navigate. */ private function createOnClickUrlOpener(url:String):Function { return function(event:MouseEvent):void { navigateToURL(new URLRequest(url)); }; } /** * Handles completion of loading an individual Panoramio image. * Adds a custom marker that displays the image. Initially this is made * invisible so that it can be faded in as needed. * @param event Load completion event. */ private function onPhotoLoaded(event:Event):void { var loaderInfo:LoaderInfo = event.target as LoaderInfo; // We need to find which photo element this image corresponds to. for each (var photo:Object in photos) { if (loaderInfo == photo.loaderInfo) { var imageMarker:Sprite = createImageMarker(photo.loader, photo.owner_name, photo.owner_url); var options:MarkerOptions = new MarkerOptions({ icon: imageMarker, hasShadow: true, iconAlignment: MarkerOptions.ALIGN_BOTTOM | MarkerOptions.ALIGN_LEFT }); var latLng:LatLng = new LatLng(photo.latitude, photo.longitude); var marker:Marker = new Marker(latLng, options); photo.marker = marker; addOverlay(marker); // A hack: we add the actual image after the overlay has been added, // which creates the shadow, so that the shadow is valid even if we // don&apos;t have security privileges to generate the shadow from the // image. marker.foreground.visible = false; marker.shadow.alpha = 0; var imageHolder:Sprite = new Sprite(); imageHolder.addChild(photo.loader); imageHolder.buttonMode = true; imageHolder.addEventListener( MouseEvent.CLICK, createOnClickUrlOpener(photo.photo_url)); imageMarker.addChild(imageHolder); return; } } trace("An image was loaded which could not be found in the photo array."); } /** * Creates a custom marker showing an image. */ private function createImageMarker(child:DisplayObject, ownerName:String, ownerUrl:String):Sprite { var content:Sprite = new Sprite(); var panoramioIcon:Bitmap = new PanoramioIcon(); var iconHolder:Sprite = new Sprite(); iconHolder.addChild(panoramioIcon); iconHolder.buttonMode = true; iconHolder.addEventListener(MouseEvent.CLICK, onPanoramioIconClick); panoramioIcon.x = BORDER_L; panoramioIcon.y = BORDER_T; content.addChild(iconHolder); // NOTE: we add the image as a child only after we&apos;ve added the marker // to the map. Currently the API requires this if it&apos;s to generate the // shadow for unprivileged content. // Shrink the image, so that it doesn&apos;t obcure too much screen space. // Ideally, we&apos;d subsample, but we don&apos;t have pixel level access. child.scaleX = IMAGE_SCALE; child.scaleY = IMAGE_SCALE; var imageW:Number = child.width; var imageH:Number = child.height; child.x = BORDER_L + 30; child.y = BORDER_T + iconHolder.height + GAP_T; var authorField:TextField = new TextField(); authorField.autoSize = TextFieldAutoSize.LEFT; authorField.defaultTextFormat = new TextFormat("_sans", 12); authorField.text = "author:"; content.addChild(authorField); authorField.x = BORDER_L; authorField.y = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B; var ownerField:TextField = new TextField(); ownerField.autoSize = TextFieldAutoSize.LEFT; var textFormat:TextFormat = new TextFormat("_sans", 14, 0x0e5f9a); ownerField.defaultTextFormat = textFormat; ownerField.htmlText = "<a href=\"" + ownerUrl + "\" target=\"_blank\">" + ownerName + "</a>"; content.addChild(ownerField); ownerField.x = BORDER_L + authorField.width; ownerField.y = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B; var totalW:Number = BORDER_L + Math.max(imageW, ownerField.width + authorField.width) + BORDER_R; var totalH:Number = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B + ownerField.height + BORDER_B; content.graphics.beginFill(0xffffff); content.graphics.drawRoundRect(0, 0, totalW, totalH, 10, 10); content.graphics.endFill(); var marker:Sprite = new Sprite(); marker.addChild(content); content.x = 30; content.y = 0; marker.graphics.lineStyle(); marker.graphics.beginFill(0xff0000); marker.graphics.drawCircle(0, totalH + 30, 3); marker.graphics.endFill(); marker.graphics.lineStyle(2, 0xffffff); marker.graphics.moveTo(30 + 10, totalH - 10); marker.graphics.lineTo(0, totalH + 30); return marker; } /** * Handles click on the Panoramio icon. */ private function onPanoramioIconClick(event:MouseEvent):void { navigateToURL(new URLRequest(PANORAMIO_HOME)); } /** * Handles failure of a Panoramio image load. */ private function onPanoramioDataFailed(event:IOErrorEvent):void { trace("Load of image failed: " + event); } /** * Returns a string containing cgi query parameters. * @param Associative array mapping query parameter key to value. * @return String containing cgi query parameters. */ private static function paramsToString(params:Object):String { var result:String = ""; var separator:String = ""; for (var key:String in params) { result += separator + encodeURIComponent(key) + "=" + encodeURIComponent(params[key]); separator = "&"; } return result; } /** * Called once the lead-in flight is done. Starts the car driving along * the route and starts a timer to begin fade in of the Panoramio * images in 1.5 seconds. */ private function onLeadInDone(event:Event):void { // Set startTimer non-zero so that the car starts to move. startTimer = getTimer(); // Start a timer that will fade in the Panoramio images. var fadeInTimer:Timer = new Timer(1500, 1); fadeInTimer.addEventListener(TimerEvent.TIMER, onFadeInTimer); fadeInTimer.start(); } /** * Handles the fade in timer&apos;s TIMER event. Sets markerAlpha above zero * which causes the frame enter handler to fade in the markers. */ private function onFadeInTimer(event:Event):void { markerAlpha = 0.01; } /** * The end time of the flight. */ private function get endTime():Number { if (!cumulativeStepDuration || cumulativeStepDuration.length == 0) { return startTimer; } return startTimer + cumulativeStepDuration[cumulativeStepDuration.length - 1]; } /** * Creates the cumulative arrays, cumulativeStepDuration and * cumulativeVertexDistance. */ private function createCumulativeArrays():void { cumulativeStepDuration = new Array(route.numSteps + 1); cumulativeVertexDistance = new Array(polyline.getVertexCount() + 1); var polylineTotal:Number = 0; var total:Number = 0; var numVertices:int = polyline.getVertexCount(); for (var stepIndex:int = 0; stepIndex < route.numSteps; ++stepIndex) { cumulativeStepDuration[stepIndex] = total; total += route.getStep(stepIndex).duration; var startVertex:int = stepIndex >= 0 ? route.getStep(stepIndex).polylineIndex : 0; var endVertex:int = stepIndex < (route.numSteps - 1) ? route.getStep(stepIndex + 1).polylineIndex : numVertices; var duration:Number = route.getStep(stepIndex).duration; var stepVertices:int = endVertex - startVertex; var latLng:LatLng = polyline.getVertex(startVertex); for (var vertex:int = startVertex; vertex < endVertex; ++vertex) { cumulativeVertexDistance[vertex] = polylineTotal; if (vertex < numVertices - 1) { var nextLatLng:LatLng = polyline.getVertex(vertex + 1); polylineTotal += nextLatLng.distanceFrom(latLng); } latLng = nextLatLng; } } cumulativeStepDuration[stepIndex] = total; } /** * Opens the info window above the car icon that details the given * step of the driving directions. * @param stepIndex Index of the current step. */ private function openInfoForStep(stepIndex:int):void { // Sets the content of the info window. var content:String; if (stepIndex >= route.numSteps) { content = "<b>" + route.endGeocode.address + "</b>" + "<br /><br />" + route.summaryHtml; } else { content = "<b>" + stepIndex + ".</b> " + route.getStep(stepIndex).descriptionHtml; } marker.openInfoWindow(new InfoWindowOptions({ contentHTML: content })); } /** * Displays the driving directions step appropriate for the given time. * Opens the info window showing the step instructions each time we * progress to a new step. * @param time Time for which to display the step. */ private function displayStepAt(time:Number):void { var stepIndex:int = upperBound(cumulativeStepDuration, time) - 1; var minStepIndex:int = 0; var maxStepIndex:int = route.numSteps - 1; if (stepIndex >= 0 && stepIndex <= maxStepIndex && currentStepIndex != stepIndex) { openInfoForStep(stepIndex); currentStepIndex = stepIndex; } } /** * Returns the LatLng at which the car should be positioned at the given * time. * @param time Time for which LatLng should be found. * @return LatLng. */ private function latLngAt(time:Number):LatLng { var stepIndex:int = upperBound(cumulativeStepDuration, time) - 1; var minStepIndex:int = 0; var maxStepIndex:int = route.numSteps - 1; if (stepIndex < minStepIndex) { return route.startGeocode.point; } else if (stepIndex > maxStepIndex) { return route.endGeocode.point; } var stepStart:Number = cumulativeStepDuration[stepIndex]; var stepEnd:Number = cumulativeStepDuration[stepIndex + 1]; var stepFraction:Number = (time - stepStart) / (stepEnd - stepStart); var startVertex:int = route.getStep(stepIndex).polylineIndex; var endVertex:int = (stepIndex + 1) < route.numSteps ? route.getStep(stepIndex + 1).polylineIndex : polyline.getVertexCount(); var stepVertices:int = endVertex - startVertex; var stepLeng

    Read the article

  • Factorising program not working. Help required.

    - by Ender
    I am working on a factorisation problem using Fermat's Factorization and for small numbers it is working well. I've been able to calculate the factors (getting the answers from Wolfram Alpha) for small numbers, like the one on the Wikipedia page (5959). Just when I thought I had the problem licked I soon realised that my program was not working when it came to larger numbers. The program follows through the examples from the Wikipedia page, printing out the values a, b, a2 and b2; the results printed for large numbers are not correct. I've followed the pseudocode provided on the Wikipedia page, but am struggling to understand where to go next. Along with the Wikipedia page I have been following this guide. Once again, as my Math knowledge is pretty poor I cannot follow what I need to do next. The code I am using so far is as follows: import java.math.BigInteger; /** * * @author AlexT */ public class Fermat { private BigInteger a, b; private BigInteger b2; private static final BigInteger TWO = BigInteger.valueOf(2); public void fermat(BigInteger N) { // floor(sqrt(N)) BigInteger tmp = getIntSqrt(N); // a <- ceil(sqrt(N)) a = tmp.add(BigInteger.ONE); // b2 <- a*a-N b2 = (a.multiply(a)).subtract(N); final int bitLength = N.bitLength(); BigInteger root = BigInteger.ONE.shiftLeft(bitLength / 2); root = root.add(b2.divide(root)).divide(TWO); // while b2 not square root while(!(isSqrt(b2, root))) { // a <- a + 1 a = a.add(BigInteger.ONE); // b2 <- (a * a) - N b2 = (a.multiply(a)).subtract(N); root = root.add(b2.divide(root)).divide(TWO); } b = getIntSqrt(b2); BigInteger a2 = a.pow(2); // Wrong BigInteger sum = (a.subtract(b)).multiply((a.add(b))); //if(sum.compareTo(N) == 0) { System.out.println("A: " + a + "\nB: " + b); System.out.println("A^2: " + a2 + "\nB^2: " + b2); //} } /** * Is the number provided a perfect Square Root? * @param n * @param root * @return */ private static boolean isSqrt(BigInteger n, BigInteger root) { final BigInteger lowerBound = root.pow(2); final BigInteger upperBound = root.add(BigInteger.ONE).pow(2); return lowerBound.compareTo(n) <= 0 && n.compareTo(upperBound) < 0; } public BigInteger getIntSqrt(BigInteger x) { // It returns s where s^2 < x < (s+1)^2 BigInteger s; // final result BigInteger currentRes = BigInteger.valueOf(0); // init value is 0 BigInteger currentSum = BigInteger.valueOf(0); // init value is 0 BigInteger sum = BigInteger.valueOf(0); String xS = x.toString(); // change input x to a string xS int lengthOfxS = xS.length(); int currentTwoBits; int i=0; // index if(lengthOfxS % 2 != 0) {// if odd length, add a dummy bit xS = "0".concat(xS); // add 0 to the front of string xS lengthOfxS++; } while(i < lengthOfxS){ // go through xS two by two, left to right currentTwoBits = Integer.valueOf(xS.substring(i,i+2)); i += 2; // sum = currentSum*100 + currentTwoBits sum = currentSum.multiply(BigInteger.valueOf(100)); sum = sum.add(BigInteger.valueOf(currentTwoBits)); // subtraction loop do { currentSum = sum; // remember the value before subtract // in next 3 lines, we work out // currentRes = sum - 2*currentRes - 1 sum = sum.subtract(currentRes); // currentRes++ currentRes = currentRes.add(BigInteger.valueOf(1)); sum = sum.subtract(currentRes); } while(sum.compareTo(BigInteger.valueOf(0)) >= 0); // the loop stops when sum < 0 // go one step back currentRes = currentRes.subtract(BigInteger.valueOf(1)); currentRes = currentRes.multiply(BigInteger.valueOf(10)); } s = currentRes.divide(BigInteger.valueOf(10)); // go one step back return s; } /** * @param args the command line arguments */ public static void main(String[] args) { Fermat fermat = new Fermat(); //Works //fermat.fermat(new BigInteger("5959")); // Doesn't Work fermat.fermat(new BigInteger("90283")); } } If anyone can help me out with this problem I'll be eternally grateful.

    Read the article

  • Layout form fields horizontally

    - by Don
    I'm using Ext JS 2.3.0 and have a bunch of fields contained within a FieldSet I'd like to have them laid out side-by-side instead, ideally with the label on top of the field instead of to the left of it. The relevant code is: var kpiFilterCombo = new Ext.form.ComboBox({ name: 'kpi', store: this.dashboardInst.servicesModel.getAvailableKPIsStore() }); var kpiLower = new Ext.form.TextField({ fieldLabel: "Lower", name: 'lowerBound' }); var kpiUpper = new Ext.form.TextField({ fieldLabel: "Higher", name: 'upperBound' }); var kpiFilterFieldset = new Ext.form.FieldSet({ title: locale['label.kpi.condition'], checkboxToggle: true, collapsed: true, autoHeight:true, items : [ kpiLower, kpiFilterCombo, kpiUpper, ] });

    Read the article

  • How to not specify ruleset name when reading from config file?

    - by user102533
    When I read rules from a configuration file, I do something like this: IConfigurationSource configurationSource = new FileConfigurationSource("myvalidation.config"); var validator = ValidationFactory.CreateValidator<Salary>(configurationSource); The config file looks like this: <ruleset name="Default"> <properties> <property name="Address"> <validator lowerBound="10" lowerBoundType="Inclusive" upperBound="15" upperBoundType="Inclusive" negated="false" messageTemplate="" messageTemplateResourceName="" messageTemplateResourceType="" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.1.0.0, Culture=neutral, PublicKeyToken=null" name="String Length Validator" /> </property> </properties> </ruleset> My question is - is there a way to not specify the ruleset name? It's not required for me to specify a ruleset name if I am using the attribute approach and I can validate using: ValidationResults results = Validation.Validate(salary); Now when reading from config files, I have to specify the ruleset name. There is no overload of the CreateValidator method that accepts the configuration source without specifying the ruleset name. Also, the xml in the config file requires a name attribute for ruleset

    Read the article

  • wpf & validation application block > message localization > messageTemplateResource Name&Type

    - by Shaboboo
    I'm trying to write validation rules for my data objects in a WPF application. I'm writing them in the configuration file, and so far they are working fine. I'm stumped on how to localize the messages using messageTemplateResourceName and messageTemplateResourceType. What I know is that the strings can be writen in a resource file, given a name and referenced by that name. I get the idea, but i haven't been able to make this work. <ruleset name="Rule Set"> <properties> <property name="StringValue"> <validator lowerBound="0" lowerBoundType="Ignore" upperBound="25" upperBoundType="Inclusive" negated="false" messageTemplate="" messageTemplateResourceName="msg1" messageTemplateResourceType="Resources" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.EnterpriseLibrary.Validation" name="String Length Validator" /> </property> </properties> </ruleset> Where is the resource file and what value do I pass to messageTemplateResourceType? I have tried writing the messages in the shell project's resource file but no sucess trying to retrieve the value. I only get the default built-in message. I've tried messageTemplateResourceType="typeof(Resources)" messageTemplateResourceType="Resources" messageTemplateResourceType="Resources.resx" messageTemplateResourceType="typeof(Shell)" messageTemplateResourceType="Shell" messageTemplateResourceType="Shell, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" I've also tried adding a new resource file in the shell project, and adding a resource file to the data object's library. I'm all out of ideas Does anyone have any suggestions? I'm not even married to the idea of resource files, so if there are other ways to localize these messages I'd love to know! thanks

    Read the article

  • EMF ecore and xsd out of sync, how to resolve ?

    - by SeB
    Hi there, My application is using a model base on an xsd that have been converted to an ecore before generation of the java classes. One of my team member modified the .ecore metamodel in a previous version ,one attribute that used to be generated. He modified the attribute name but not the Extended MetaData specifying the element name used for xml persistance. <eStructuralFeatures xsi:type="ecore:EReference" name="javaDocsAndUserApi" upperBound="-1" eType="#//JavaDocsAndUserApi" containment="true" resolveProxies="false"> <eAnnotations source="http:///org/eclipse/emf/ecore/util/ExtendedMetaData"> <details key="kind" value="element"/> <details key="name" value="docsAndUserApi"/> </eAnnotations> </eStructuralFeatures> so we have an attribute name which is javaDocsAndUserApi and the persisted element named docsAndUserApi, and of course if I create change the attribute in the xsd to be named javaDocsAndUserApi, the ecore transformation will generate a metadata name javaDocsAndUserApi as well, which will break compatibility with previously persisted models. I have looked at xsd authoring guide to find an ecore:som_attribute that would allow me to specify which key to use in the xsd to force the metadata to be named docsAndUserApi during the xsd to ecore transformation but did not find anything. Does anybody have an idea to help me? Thank you.

    Read the article

  • How to create an array of User Objects in Powerbuilder?

    - by TomatoSandwich
    The application has many different windows. One is a single 'row' window, which relates to a single row of data in a table, say 'Order'. Another is a 'multiple row' datawindow, where each row in the datawindow relates to a row in 'Order', used for spreadsheet-like data entry Functionality extentions have create a detail table, say 'Suppliers', where an order may require multiple suppliers to fill the order. Normally, suppliers are not required, because they are already in the warehouse (0), or there may need to be an order to a supplier to complete an order (1), or multiple suppliers may need to be contacted (more than one). As a single order is entered, once the items are entered, a User Object is populated depending on the status of the items in the warehouse. If required, this creates a 1-to-many relationship between the order and the "backorder". In the PB side, there is a single object uo_backorder which is created on the window, and is referenced by the window depending on the command (button popup, save, etc) I have been tasked to create the 'backorder' functionality on the spreadsheet-line window. Previously the default options for backorders were used when orders were created from the multiple-row window. A workaround already exists where unconfirmed orders could be opened in the single-row window, and the backorder information manipulated there. However, the userbase wants this functionality on the one window. Since the functionality of uo_backorder already exists, I assumed I could just copy the code from the single-order window, but create an array of uo_backorder objects to cope with multiple rows. I tried the following: forward .. type uo_backorder from popupdwpb within w_order_conv end type end forward global type w_order_conv from singleform .. uo_backorder uo_backorder end type type variables .. uo_backorder iuo_backorders[] end variables .. public function boolean iuo_backorders(); .. long ll_count ll_count = UpperBound(iuo_backorders[]) iuo_backorders[ll_count+1] = uo_backorder //THIS ISN'T RIGHT lb_ok = iuo_backorders[ll_count+1].init('w_backorder_popup', '', '', '', 'd_backorder_popup', sqlca, useTransObj()) return lb_ok end function .. <utility functions> .. type uo_backorder from popupdwpb within w_order_conv integer x = 28 integer y = 28 integer width ... end type on uo_backorder.destroy call popupdwpb::destroy end on The issue I face now is that the code commented "THIS ISN'T RIGHT" isn't correct. It is associating the visual object placed on the face of the main window to each array cell, so anytime I reference the array cell object it's actually referencing the one original object, not the new instances that I (thought) I was creating. If I change the code iuo_backorders[ll_count+1] = create uo_backorder the code doesn't run, saying that it failed to initalize the popup window. I think this is related to the class being called the same thing as the instance. What I want to end up with is an array of uo_backorder objects that I can associate to each row of my datawindow (first row = first cell, etc). I think the issue lays in the fact it's a visual object, and I can't seem to get the window to run without adding a dummy object on the face of the window (functionality from the original single-row window). Since it's a VISUAL object, does the object indeed need to be embedded on the windowface for the window to know what object I'm talking about? If so, how does one create multiple windowface objects (one to many, depending on when a row is added)? Don't hesitate to inquire regarding any more information this issue may require from myself. I have no idea what is 'standard' or 'default' in PB, or what is custom and needs more explaining.

    Read the article

1