Array cycling - a better way?
Is there a better way of doing this? I use this a lot, and feel there must be a better way, but don't know what. gridSize is an array that contains x and y dimensions. Some code needs to be executed for each square on the grid. I was once told that avoiding refering to arrays explicitly (i.e. ar[2]) is a good way to go, but I can't figure out how to do that in this instance!
for (int i = 0; i < gridSize[0]; i++) {
for (int j = 0; j < gridSize[1]; j++) {
//...code...
}
Yeah, I don't think you mean to use gridSize[0], but length. Still, you shouldn't need to specify it like ar[2], keep it a variable. This is how you could loop through every square:for(int i = 0; i < gridSize.length; i++)
for(int j = 0; j < gridSize.length; j++)
//...code...
}Just note that the <i> is really [i] because of a forum software bug.
Similar Messages
-
Is there a better way to add int arrays together?
I'm working on a project that will add arrays of integer together...all element are nonnegative integers
For example
A = [0 1 2 3]
I need to find an algorithm to find 2A= A + A, 3A = A+A+A....., hA = A +...A ( h times)
For 2A, the result array will look like this
2A = [ 0 1 2 3 1 2 3 4 2 3 4 5 3 4 5 6]
Then using Array.sort(2A) i will have 2A= [ 0 1 1 2 2 2 3 3 3 3 4 4 4 5 5 6].
Lastly I will write another code to get rid of repetitions to get the desired array 2A = [ 0 1 2 3 4 5 6]
public static int[] hA(int[] a, int h){
// mon = null;
//mon = MonitorFactory.start("myFirstMonitor");
if (h==1) return a;
if (h==2){
int[] b = new int[(a.length)*(a.length)];
int count = 0;
int maxa = a.length,maxb=b.length;
for (int i = 0 ; i < maxa; i++)
for (int j=0 ; j <maxa; j++)
b[count]=a[i]+a[j];
count++;
return b;
else
return hA(a,h-1);
}I still don't know how to write recursive code to get it to find 3A, 4A....hA....
is there any better way to do this?sorry for not defining it better
2A ={ a + a' | a,a' E A}
that means for A = { 0 1 3} , 2A ={ 0 1 2 3 4 6}
but to get to [ 0 1 2 3 4 6], i don't know of any better way to achieve it.
Also to find 3A = { a+a'+a'' |a,a',a'' E A}
that means for A = { 0 1 3} ,3A={ 0 1 2 3 4 5 6 7 9}
the idea is simple but to put into java code is not...at least for me -
Better way for inserting column into array?
I have to insert a 2-D array(20x10) into the end (column) of a bigger 2-D array(1000x10). I am seeing two ways to do that:
1. Insert smaller 2D array at the end of bigger array.
2. Insert the bigger array at the 0th column of smaller array.
Which one would be more efficient? Will there be any performance difference?
Or any other better way to do this?
The second one looks simpler but I think it would require a bigger copying of memory.Both methods use a buffer allocation, so they might be very similar. Since we don't know what the compiler is doing, you could also try this:
I am assumung that you only need to append once and not append more and more columns as the program progresses. Is this correct? In any case, you should consider operating on the transposed version, because it is always easier to append rows instead of columns (rows are adjacent in memory, while appending columns require more data shuffling under the hood
In any case, you should simply wire up the alternatives and do a proper benchmark if you are planning to use this on much larger arrays in the future, for example. Can you give us some context how you are planning to use this?
LabVIEW Champion . Do more with less code and in less time .
Attachments:
AppendColumns.png 3 KB -
Have you got a better idea? Is there a better way? ( arrays )
Hello!
First post here and ofcourse it is a question I hopo you people don't mind. I will get right to the point:
I have a picture , or to be precise the pixels of a picture stored as a 3 dimensional array in the form of
img[y][x][color].
Since I am working on grayscale the color doesn't matter , so de facto I have a 2dim array of X-Y coordinates. For my programm ( a line tracker of sorts) I need to be able to select a subgroup of this array. This subgroup should be equivalent to a small (appr. 10x20 pixels wide) box in the original picture. My problem is that this box could be at any angle, that is it's side do not have to run parallel to the x-y-Axis.
Now how would be the best way of doing this?
My idea is to calculate the lines of the rectangle geometricaly and then try to approximate them onto the array. After that I can use them as boundaries to select every pixel that is inside the box.
Is there a better way? Does somebody have any experience with something similar?
Any help would be greatly appreciated...
AlexisTwo things to try. Try rebuilding the mailbox. This can take awhile if you have a lot of mail.
Rebuild mailbox
Try reindexing the mailbox. This can take awhile if you have a lot of mail.
Reindex messages -
A better way to execute a series of external commands?
Hi,
Consider the code snippet...
Process proc1 = rt.exec("Some external command");
Vector vecOutput = outputGobbler.getOutput() ;
String[] strAlterCmds = new String[vecOutput.size()];
for ( int k = 0 ; k < vecOutput.size() ; k++ )
strAlterCmds[k] = new String();
strAlterCmds[k] = "cmd.exe /c blah.... " +(String) vecOutput.elementAt( k )+ " ;
Process proc2 = rt.exec(strAlterCmds[k], null);
StreamGobbler errorG = new
StreamGobbler( proc2.getErrorStream(), "Error") ;
StreamGobbler outputG = new
StreamGobbler( proc2.getInputStream(), "Output") ;
errorG.start() ;
outputG.start() ;
int exitVal1 = proc2.waitFor();
The second part of the execution is taking AGES and I am not sure forking a new process for runtime execution is the best alternative here.
I would be glad if someone can point me to a smarter solution.
In short: I intend to execute a series of commands using RTE depending on the values I get in the loop.
Thanks.Jared,
Thank you for responding to my posted message. Rendezvous is a new concept to me, maybe
it's the solution to my problem. I have been trying to read the on line manual and
example VIs from National Instruments website. I still have a hard time to understand
the concept.
One of the example I saw is using rendezvous to run some sub VIs. But in my case, I have
only one VI that is a while loop. Inside the while loop, there are a few tasks running
simultaneously. I don't know whether it will serve my purpose.
Guangde Wang
Jared O'Mara wrote:
> Guangde,
>
> Referring to your 2nd method, use rendezvous (under advanced>>synchronize
> on function palette) to synchronize two processes. There are good examples
> that come with labview. basically, you cre
ate a rendezvous, giving it a
> size. Using the wait on rendezvous vi, a function will not continue until
> all rendezvous have reached that point. Using this method, you can synchronize
> your 2 while loops.
>
> Jared
>
> Guangde Wang wrote:
> >I tried two ways to control the tempo of my program.>>One is to use the
> While Loop's counter and a wait. The drawback of this>method is the cycle
> length is dependent on the measuring load. So if the>program runs for days,
> it will be significent off the real time.>>The other way is to use the difference
> of the Tick Count. It provides>accurate timing but the problem is the sychronization
> of the clock cycle>and the While Loop cycle. I can try to put a little bit
> wait but still>can not sychronize them very well. So after a while, there
> will be two>measures get together.>>I don't know whether there are some better
> ways to control the program>or whether we have some ways to improve either
> or both of the above
two>methods to make them work better. Please let me
> know if you have any>suggestion.>>Thank you in advance,>>Guangde Wang> -
A better way to manage Notes?
We are a small team in collaboration on a book-length manuscript.My editors are inserting hundred of Notes into the document that I must cycle through and resolve each one. But I find the Note icon soooo tiny. When I'm at full page I can barely see those little guys. Is there any way to make the Note indicators bigger or something? In general. I don't see this Notes tool as very robust compared to change tracking type features found in word processors.
I just want a better way to manage the Notes flow.Eugene Tyson wrote:
I find using Notes in Story Editor to be way better.
CTRL Y or CMD Y
Then you can Expand/Collapse notes in Story Editor.
Far easier to read and implement there, or if you need to switch back to layout just hit the shortcut again.
It's also useful to tile a Story Editor window and the corresponding document's window, to have both views of the content.
HTH
Regards,
Peter
Peter Gold
KnowHow ProServices -
Must be a better way...
Hello Flash Community!
Thanks in advance for any help/advice.
So, what I'm looking for here is some high level advice as far as a better way to do things. I feel like so often with programming I'm just breaking my neck to get things working when I know there is a better way (presumably based in OOP) to go about things. I just need someone to look at what I've done and point it out to me.
So, here's what I've done so far: http://www.catherinemix.com
And it works pretty well as far as I'm concerned! The app dynamically loads as many images as my client (my mom ) puts on the server, resizes them dynamically, adds L/R arrow buttons dynamically based on how many images are involved, etc... But the downside to all that dynamic flexibility is that I haven't found a way to load the thumbnail images (and their respective full size images) one by one. Instead, I have to load them all together and keeping the user waiting that long is unacceptable to my mom. What I would love is for each thumbnail/full size combo to get its own preloader bar in the location it will eventually be embedded, but I haven't found a way to do that and account for an unknown number of images (as it is determined dynamically.)
Any ideas here? I would specifically like to know which functions y'all use when you need to load multiple files simultaenously (AttachMovie?)
I have posted the kluge-y code which handles all of the image gallery functions below.
Thanks! and Be Well
Graham
import fl.transitions.Tween;
import fl.transitions.easing.*;
var wait:PleaseWait = new PleaseWait();
wait.x = 400;
wait.y = 50;
addChild(wait);
var waitFadeIn:Tween = new Tween(wait, "alpha", Regular.easeOut, 0, 1, 1, true);
var titleText:TextField;
var textSprite:Sprite;
//thumbH is the ideal height for our thumbnails, and thumbW the ideal width
var thumbH = 120;
var thumbW = 170;
//loadH is the ideal height for our fullsize images, and loadW the ideal width
var loadH = 500;
var loadW = 600;
//some counter numbers
var thumbNum = 1;
var loadNum = 1;
//some Sprites which need to be accessed by more than one function
var darkStage:Sprite;
var loadSprite:Sprite;
//Let's instantiate some Arrays that we can load the images into.
//Since Arrays of Loaders can't be copied, we have to go through the process twice.
var thumbArray:Array = new Array();
var loadArray:Array = new Array();
firstLoad();
firstThumb();
function firstLoad():void {
trace("firstLoad");
var loadski = new Loader();
loadski.load(new URLRequest("images/fulls/0.png"));
loadski.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
loadArray.push(loadski);
//Starting with the above Loader, this function will execute every time the Loader completes
function loadComplete(e:Event):void {
trace("loadComplete");
var loadski = new Loader();
loadski.load(new URLRequest("images/fulls/" + loadNum + ".png"));
loadArray.push(loadski);
loadski.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
loadski.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadError);
loadNum++;
//Once the Loader goes too far by attempting to load an image that doesn't exist on the computer,
//it will thorw an IOError Event at which point the following function will execute.
function loadError(e:IOErrorEvent):void {
trace("loadError");
loadArray.pop();
loadNum = 0;
loadResize();
//We use the pop function to remove the most recently added Loader instance, since we know it
//contains a null reference (beacuse the IOError Event is asynchronous.)
thumbArray.pop();
//We reset the counter variable.
thumbNum = 0;
//Add the little arrows that allow the user to click to see more thumbnails (if there are more
//than 8 images on the server.)
removeChild(wait);
addArrows();
//Let's resize the images to thumbnail size and add them to the display list.
thumbResize();
addClickOnThumb();
function loadResize():void {
trace("loadResize");
for (var ex = 0; ex < loadArray.length; ex++) {
//If the width of the image is greater than the ideal width, OR the height is greater than the ideal height...
if ( loadArray[loadNum].content.width > loadW || loadArray[loadNum].content.height > loadH) {
//And if the width of the image is greater than the height, apply Scaler 1...
if ( loadArray[loadNum].content.width > loadArray[loadNum].content.height ) {
//Scaler 1 is the ratio of the ideal width to the image width
var scaler1 = loadW / loadArray[loadNum].content.width;
trace(loadNum + " load scaler 1: " + scaler1);
//Apply Scaler 1 to both the width and height of the image
loadArray[loadNum].content.scaleX = loadArray[loadNum].content.scaleY = scaler1;
//Otherwise, apply Scaler 2
} else {
//Scaler 2 is the ratio of the ideal width to the image height
var scaler2 = loadH / loadArray[loadNum].content.height;
trace(loadNum + " load scaler 2: " + scaler2);
//Apply Scaler 2 to both the width and height of the image
loadArray[loadNum].content.scaleX = loadArray[loadNum].content.scaleY = scaler2;
trace("loadArray[loadNum].content.height = " + loadArray[loadNum].content.height);
trace("loadArray[loadNum].content.width = " + loadArray[loadNum].content.width);
//Otherwise... (that is, the image width and height are in both cases less than the ideal)
} else {
//And if the width of the image is greater than the heigh, apply Scaler 3
if ( loadArray[loadNum].content.width > loadArray[loadNum].content.height ) {
//Scaler 3 is the ratio of the ideal width to the image width
var scaler3 = loadW / loadArray[loadNum].content.width;
trace(loadNum + " load scaler 3: " + scaler3);
//Apply Scaler 3 to both the width and height of the image
loadArray[loadNum].content.scaleX = loadArray[loadNum].content.scaleY = scaler3;
} else {
//Scaler 4 is the ratio of the ideal width to the image height
var scaler4 = loadH / loadArray[loadNum].content.height;
trace(loadNum + " load scaler 4: " + scaler4);
//Apply Scaler 4 to both the width and height of the image
loadArray[loadNum].content.scaleX = loadArray[loadNum].content.scaleY = scaler4;
loadArray[loadNum].content.x = - (loadArray[loadNum].content.width / 2);
loadArray[loadNum].content.y = - (loadArray[loadNum].content.height / 2);
loadNum++;
function firstThumb():void {
trace("firstThumb");
//Let's populate the first Array with Loaders that load the images Mom has put on the server.
//We have to do this first Loader object by hand to get the Event.COMPLETE-based-loop going.
var thumbski = new Loader();
thumbski.load(new URLRequest("images/thumbs/0.png"));
thumbski.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbComplete);
//We add the MouseEvent.CLICK listener to the actual Loader instance so that, later on, in the
//function enLarge, we can make use of the currentTarget parameter to correlate the Array index of
//the thumbnail that the user is clicking on with that of the loadArray.
thumbski.addEventListener(MouseEvent.CLICK, enLarge);
thumbArray.push(thumbski);
//Starting with the above Loader, this function will execute every time the Loader completes
function thumbComplete(event:Event):void {
trace("thumbComplete");
var thumbski = new Loader();
thumbski.load(new URLRequest("images/thumbs/" + thumbNum + ".png"));
thumbski.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbComplete);
//We add the IOErrorEvent listener so that as soon as this error is thrown, we will exit this loop
//and proceed to the next logical step in the program can be taken.
thumbski.addEventListener(MouseEvent.CLICK, enLarge);
thumbArray.push(thumbski);
thumbNum++;
function addArrows():void {
//Let's determine how many batches there are. A batch is the minimum amount of thumbnail images
//mom wants to show up onscreen at a time. In this case, she has decided on 8.
var batches = Math.ceil(thumbArray.length / 8);
//The variable m is part of a kluge fix related to the calculation of startX (explained below.)
var m = 0;
//Pseudocode for this loop: If there are at least two batches, then...
//We do this because less than 2 batches doesn't warrant arrows
if (batches > 1) {
for (var k = 1; k < batches; k++) {
//triW is the desired width of our arrows
var triW = 20;
//startX is the x position of the start of our rightward facing triangle(s)
//The formula says: Our x starting position should be a triangle width shy of the
//far edge of the stage (multiplying it by k ensures it happens as many times
//as there are batches, which is why we intialize k = 1.) Every subsequent iteration
//of the formula has to add a triangle's width worth of distance, except for the
//very first one, which is why it is multiplied by m, which is initially set to 0.
var startX = (((stage.stageWidth - triW) * k) + (triW * m));
//We want the arrows to sit perfectly between the two rows of thumbnails. Since the
//max height of every thumbnail is thumbW, that would seem to be the natural choice
//for the starting y position of the arrows. But, we actually have to use thumbW/2
//because the thumbnails have already been offset by half of thumbW due to being
//aligned vertically with each other.
var startY = (thumbW / 2);
//This is the rightward facing triangle
var tri:Sprite = new Sprite();
tri.graphics.beginFill(0xFFFFFF);
tri.graphics.moveTo(startX, startY);
tri.graphics.lineTo(startX, (startY + triW));
tri.graphics.lineTo((startX + triW), (startY + (triW/2)));
tri.graphics.lineTo(startX, startY);
tri.graphics.endFill();
tri.buttonMode = true;
tri.useHandCursor = true;
tri.addEventListener(MouseEvent.CLICK, moveLeft);
addChild(tri);
//This is the leftward facing triangle
var tri2:Sprite = new Sprite();
var startX2 = (startX + (triW * 2));
tri2.graphics.beginFill(0xFFFFFF);
tri2.graphics.moveTo(startX2, startY);
tri2.graphics.lineTo(startX2, (startY + triW));
tri2.graphics.lineTo((startX2 - triW), (startY + (triW / 2)));
tri2.graphics.lineTo(startX2, startY);
tri2.graphics.endFill();
tri2.buttonMode = true;
tri2.useHandCursor = true;
tri2.addEventListener(MouseEvent.CLICK, moveRight);
addChild(tri2);
//Increase m (see above)
m++;
//This function moves the entire Gallery MovieClip to the left 800 pixels.
function moveLeft(event:MouseEvent):void {
var leftTween:Tween = new Tween(this, "x", Regular.easeOut, this.x, (this.x - 800), .5, true);
//This function moves the entire Gallery MovieClip to the right 800 pixels.
function moveRight(event:MouseEvent):void {
var rightTween:Tween = new Tween(this, "x", Regular.easeOut, this.x, (this.x + 800), .5, true);
//This function resizes the loaded images to the desired thumbnail dimensions and adds them
//to the display list.
function thumbResize():void {
//The highest level of organization of thumbnails is the batch. There are only as many batches
//as the length of the thumbArray divided by 8 (the max amount of thumbnails in a batch, as determined
//by mom.)
for (var batch = 0; batch < Math.ceil(thumbArray.length / 8); batch++) {
trace("batch " + batch);
//This Sprite serves as the container that we use to position entire batches
var batchSprite: Sprite = new Sprite();
//The logic behind setting the x position of the batchSprite to 800 x batch should be self-evident --
//we want each new batch to be 800 pixels to the right of the former one -- but the addition of (thumbW
//divided by 1.5) is a kluge fix for how much space to give the batches on left margin.
batchSprite.x = (thumbW / 1.5) + (batch * 800);
addChild(batchSprite);
//The second highest level of organization for our thumbnails is the row. Our grid of thumbnails is
//two rows deep.
for (var row = 0; row < 2; row++) {
trace(" row " + row);
//The third highest level of organization for our thumbnails is the column. Our grid of thumbnails is
//four columns deep.
for (var col = 0; col < 4; col++) {
trace(" col " + col);
trace(" thumb " + thumbNum);
if (thumbNum < thumbArray.length) {
//The following is the logic structure for handling the resizing of images. The goal was to develop
//a system robust enough to allow my mom to put whatever size images she wanted on the server and the
//app would use them. The logic is explained at each step...
//If the width of the image is greater than the ideal width, OR the height is greater than the ideal height...
if ( thumbArray[thumbNum].content.width > thumbW || thumbArray[thumbNum].content.height > thumbH) {
//And if the width of the image is greater than the height, apply Scaler 1...
if ( thumbArray[thumbNum].content.width > thumbArray[thumbNum].content.height ) {
//Scaler 1 is the ratio of the ideal width to the image width
var scaler1 = thumbW / thumbArray[thumbNum].content.width;
trace(" scaler1 = " + scaler1);
//Apply Scaler 1 to both the width and height of the image
thumbArray[thumbNum].content.scaleX = thumbArray[thumbNum].content.scaleY = scaler1;
trace(" image width:" + thumbArray[thumbNum].content.width);
trace(" image height:" + thumbArray[thumbNum].content.height);
//Otherwise, apply Scaler 2
} else {
//Scaler 2 is the ratio of the ideal width to the image height
var scaler2 = thumbW / thumbArray[thumbNum].content.height;
trace(" scaler2 = " + scaler2);
//Apply Scaler 2 to both the width and height of the image
thumbArray[thumbNum].content.scaleX = thumbArray[thumbNum].content.scaleY = scaler2;
trace(" image width:" + thumbArray[thumbNum].content.width);
trace(" image height:" + thumbArray[thumbNum].content.height);
//Otherwise... (that is, the image width and height are in both cases less than the ideal)
} else {
//And if the width of the image is greater than the heigh, apply Scaler 3
if ( thumbArray[thumbNum].content.width > thumbArray[thumbNum].content.height ) {
//Scaler 3 is the ratio of the ideal width to the image width
var scaler3 = thumbW / thumbArray[thumbNum].content.width;
trace(" scaler3 = " + scaler3);
//Apply Scaler 3 to both the width and height of the image
thumbArray[thumbNum].content.scaleX = thumbArray[thumbNum].content.scaleY = scaler3;
trace(" image width:" + thumbArray[thumbNum].content.width);
trace(" image height:" + thumbArray[thumbNum].content.height);
} else {
//Scaler 4 is the ratio of the ideal width to the image height
var scaler4 = thumbW / thumbArray[thumbNum].content.height;
trace(" scaler4 = " + scaler4);
//Apply Scaler 4 to both the width and height of the image
thumbArray[thumbNum].content.scaleX = thumbArray[thumbNum].content.scaleY = scaler4;
trace(" image width:" + thumbArray[thumbNum].content.width);
trace(" image height:" + thumbArray[thumbNum].content.height);
//Here is where we center the images vertically...
thumbArray[thumbNum].content.x = - (thumbArray[thumbNum].content.width / 2);
//Here is where we center the images horizontally...
thumbArray[thumbNum].content.y = - (thumbArray[thumbNum].content.height / 2);
//Before placing them in their own container Sprite, so that their relative positions can be
//determined accurately (a task that would've been otherwise impossible after the
//adjustments to position made above.)
var thumby = new MovieClip();
thumby.addChild(thumbArray[thumbNum]);
//thumbW being the max possible length or width of any one thumbnail (this was done for visual
//consistency and codified in the logic tree above), placing two thumbnails thumbW
//apart (measuring from center point in either case) will put them edge to edge at best. This is why
//we add (thumbW / 8) as additional spacing.
thumby.y = (row * (thumbW + (thumbW / 8)));
thumby.x = (col * (thumbW + (thumbW / 8)));
thumby.buttonMode = true;
thumby.useHandCursor = true;
var fA:Array = new Array();
var dS:DropShadowFilter = new DropShadowFilter(5, 45, 0x000000, 0.33, 5, 5, 1, 1);
fA.push(dS);
thumby.filters = fA;
trace("thumby.width = " + thumby.width);
trace("thumby.height = " + thumby.height);
batchSprite.addChild(thumby);
thumbNum++;
function enLarge(event:MouseEvent):void {
var indexNum:Number = new Number();
indexNum = thumbArray.indexOf(event.currentTarget);
trace("indexNum = " + indexNum);
darkStage = new Sprite();
darkStage.graphics.beginFill(0x333333, .9);
darkStage.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
darkStage.addEventListener(MouseEvent.CLICK, reMove);
darkStage.buttonMode = true;
darkStage.useHandCursor = true;
(parent as MovieClip).addChild(darkStage);
loadSprite = new Sprite();
loadSprite.addChild(loadArray[indexNum]);
loadSprite.x = (stage.stageWidth / 2);
loadSprite.y = (stage.stageHeight / 2);
loadSprite.addEventListener(MouseEvent.CLICK, reMove);
loadSprite.buttonMode = true;
loadSprite.useHandCursor = true;
loadSprite.mouseEnabled = false;
(parent as MovieClip).addChild(loadSprite);
var urlRequest:URLRequest = new URLRequest("xmls/" + indexNum + ".xml");
var titleURL:URLLoader = new URLLoader();
titleURL.addEventListener(Event.COMPLETE, completeListener);
titleURL.load(urlRequest);
function completeListener(event:Event):void {
titleText = new TextField();
titleText.autoSize = TextFieldAutoSize.LEFT;
var myFont:Font = new BOF();
var ttFormat:TextFormat = new TextFormat();
ttFormat.color = 0xFFFFFF;
ttFormat.size = 18;
ttFormat.font = myFont.fontName;
textSprite = new Sprite();
textSprite.addChild(titleText);
(parent as MovieClip).addChild(textSprite);
var titleXML:XML = new XML(titleURL.data);
titleText.text = titleXML.toXMLString();
titleText.setTextFormat(ttFormat);
titleText.embedFonts = true;
textSprite.y = 570;
textSprite.x = ((stage.stageWidth / 2) - (titleText.textWidth / 2));
textSprite.mouseEnabled = false;
titleText.mouseEnabled = false;
function reMove(event:MouseEvent):void {
(parent as MovieClip).removeChild(textSprite);
(parent as MovieClip).removeChild(loadSprite);
(parent as MovieClip).removeChild(darkStage);
function addClickOnThumb():void {
var cot:ClickOnThumbnail = new ClickOnThumbnail();
cot.x = 400;
cot.y = 583;
(parent as MovieClip).addChild(cot);Hey Jim
Wow, that's great; thanks! Can I ask what settings you used to get the files so small?
Yes, I am familiar with Photoshop and image optimization issues, but I didn't realize that PNG was so much bigger than JPG and that I had so much file size I could shed before I would notice a degradation in image quality. Your advice will certainly help greatly, and I will certainly apply it to the thumbs as well. I think my mom will be very pleased. : )
I look forward to hearing what collection of settings you used.
Thanks and Be Well
Graham -
Looking for a better way to determine string variable from multiple options
Hi,
I trying to figure out a better way to determine a string variable from multiple options.
Say i have five pictures each with a different filename: img1 - img5...these file names could be named anything really but for this example i will keep them as img1, img2, img3, img4 and img5.
I want to display a messagebox with the string depending on what a certain variable is.
So for example, we have the number X, if X = 1 then i want the messagebox to show "img1" as the message
Essentially the way I have been doing it so far is:
Private Sub WhichImage()
Dim ImageName As String = ""
Dim i as integer
If i = 0 Then
ImageName = "img1"
End If
If i = 1 Then
ImageName = "img2"
End If
If i = 2 Then
ImageName = "img3"
End If
If i = 3 Then
ImageName = "img4"
End If
If i = 4 Then
ImageName = "img5"
End If
MessageBox.show(imagename, "Name of image", MsgBox.Style.OkOnly, MsgBoxResult.Ok)
end
Up until now, this has been fine, but what if I have 50 images, do I have to do this for all 50 images? or is there an easier way like putting the image names into a text file and have it read from the file depending on what the variable i equals? If so,
how do I go about this? Does each image name go on a separate line? can it just be separated by a comma instead? or is there a better way?
Please note that i know that i have declared "i" above in my code and not intialised it with anything, in reality "i" comes from somewhere else in the program so please ignore that part, it is not what I am concerned with.
Thanks
MersecDoes each image name go on a separate line? can it just be separated by a comma instead? or is there a better way?
Arrays are useful for this.
Dim imagenames() As String = {"img1", "img2", "img3", "img4", "img5"}
Dim imagename As String = imagenames(i)
MessageBox.Show(imagename, "Name of image")
Any sort of collection will do instead of an array, and may be simpler to manage. There are many other options - the most suitable one probably depends on where the names originally come from. For instance, if you are getting them from a folder
using the FileSystem.GetFiles method, then they are already in a collection.
If the files names never change then you may as well include them in the program code, using something like the code above. If they can change, then you could use a text file, but that means you need a file update routine. If that is required
then the way you store the names will dictate how you access them. -
Better Way To Do This? Selector Operator...
I'm currently writing the selection operator for the algorithm. The aim of it is
to rate how the coursework block have been allocated and give there allocation
a rating...
How I have done it is have a method that searches through the one of the parent
timetables. It looks for coursework time blocks. Once it finds one it notes
this and looks at the next block along. If this is a coursework time block it
notes this as well. I then perform an operation comparing these two coursework
time blocks to find out if they are for the same Module. If they are not this
is not a very effective coursework timetable strategy.
Because of this I note in an array the the position of these two coursework time
block and give them a fitness rating of 1000. I then go on to see if the next
block is a coursework time block. If it is and its not of the same Module ID of
the two previous then I not these 3 block down in an array and give them a
fitness rating of 2000.
My concern is that I am using allot of if and for loop's and the code is
starting to look untidy at best. Is there any better way of doing this?
Below Is my code:
* @param parentOne
* @param parentTwo
public void selectionOperator(ArrayList parentOne, ArrayList parentTwo){
// Store's the fitness rating of sections of the timetable...
ArrayList parentOneBlockFitnessRating = new ArrayList ();
ArrayList parentTwoBlockFitnessRating = new ArrayList ();
//Loops through the timetable's timeblocks...
for (int i = 0; i < parentOne.size(); i++) {
//Checks to see if the current time block is of the class: CourseworkTimeBlock,
//if so it enters this statement...
if(parentOne.get(i).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
//A temp store for the current CourseworkTimeBlock...
CourseworkTimeBlock tempBlockOne = (CourseworkTimeBlock) parentOne.get(i);
System.out.println("Got Here!, Module ID...: " + tempBlockOne.getModuleId());
//Checks to see if the next time block along is of the class: CourseworkTimeBlock,
//if so it enters this statement...
if(parentOne.get(i+1).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
//A temp store for the next CourseworkTimeBlock...
CourseworkTimeBlock tempBlockTwo = (CourseworkTimeBlock) parentOne.get(i+1);
System.out.println("Got Here Aswell!");
//Checks to see if the current and next CourseworkTimeBlock module Id's
//are the same, if there arn't then this section is entered...
if(!tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId())){
//Checks to see if the second time block along is of the class: CourseworkTimeBlock,
//if so it enters this statement...
if(parentTwo.get(i+2).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
//A temp store for the second CourseworkTimeBlock along...
CourseworkTimeBlock tempBlockThree = (CourseworkTimeBlock) parentTwo.get(i+2);
//Checks to see if all 3 of the Module Id's of the CourseworkTimeBlocks match,
//if they don't match this statement is entered...
if(! tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId()) && (tempBlockTwo.getModuleId().equals(tempBlockThree.getModuleId()))) {
//ArrayList to store the fitness rating of the current block
//selection...
ArrayList <Integer> blockFitness = new ArrayList<Integer>();
//Position of first block.
blockFitness.add(i);
//Position of second block.
blockFitness.add(i+1);
//Position of second block.
blockFitness.add(i+2);
//Fitness Value
blockFitness.add(2000);
//Add block rating to main rating ArrayList...
parentOneBlockFitnessRating.add(blockFitness);
else{
//ArrayList to store the fitness rating of the current block
//selection...
ArrayList <Integer> blockFitness = new ArrayList<Integer>();
//Position of first block.
blockFitness.add(i);
//Position of second block.
blockFitness.add(i+1);
//Fitness Value
blockFitness.add(1000);
//Add block rating to main rating ArrayList...
parentOneBlockFitnessRating.add(blockFitness);
for (int o = 0; o < parentTwo.size(); o++) {
if(parentTwo.get(o).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
CourseworkTimeBlock tempBlockOne = (CourseworkTimeBlock) parentTwo.get(o);
System.out.println("Got Here!, Module ID...: " + tempBlockOne.getModuleId());
if(parentTwo.get(o+1).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
CourseworkTimeBlock tempBlockTwo = (CourseworkTimeBlock) parentTwo.get(o+1);
System.out.println("Got Here Aswell!");
if(!tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId())){
if(parentTwo.get(o+2).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
CourseworkTimeBlock tempBlockThree = (CourseworkTimeBlock) parentTwo.get(o+2);
if(! tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId()) && (tempBlockTwo.getModuleId().equals(tempBlockThree.getModuleId()))) {
ArrayList <Integer> blockFitness = new ArrayList<Integer>();
//Position of first block.
blockFitness.add(o);
//Position of second block.
blockFitness.add(o+1);
//Position of second block.
blockFitness.add(o+2);
//Fitness Value
blockFitness.add(2000);
//Add block rating to main rating ArrayList...
parentTwoBlockFitnessRating.add(blockFitness);
else{
ArrayList <Integer> blockFitness = new ArrayList<Integer>();
//Position of first block.
blockFitness.add(o);
//Position of second block.
blockFitness.add(o+1);
//Fitness Value
blockFitness.add(1000);
//Add block rating to main rating ArrayList...
parentTwoBlockFitnessRating.add(blockFitness);
}As you can see there are allot if statements and some bad coding practice to boot. But I don't know what other ways to do it....
Any directions of other ways how to do this?
Many Thanks
ChrisUnfortunately, I think you're stuck with a bunch of if-statements.
Fortunately, I have some things that may help you.
First, I usually make sure something is of x class via this
if (someObject instanceof SomeClass) {So, I'd adjust your 'class checking' conditionals from this
if(parentOne.get(i).getClass().toString().equals("class Timetable.CourseworkTimeBlock"))to this
if (parentOne.get(i) instanceof Timetable.CourseworkTimeBlock) {Secondly, your code logic is kind of confusing.
Why do you have a for-loop that iterates through every CourseworkTimeBlock, if you then (within each possible iteration) check iteration+1 and iteration+2? What happens if those throw an ArrayIndexOutOfBoundsException, or are null? -
Better Way to do this loop.
I know there is better ways to do this so that I can merely have it loop infinitely until it hits the max password. I would also like to keep the spot where it has the print Statements because I tend to set some other code in front of it.
If anyone also has some Ideas so I can have it stop and start in particular positions.
Like lets say ?!!!!? to ?~~~~?
Thanks a ton. Below is the code.
char[] password = new char[20];
int current_last_letter = 0;
int max_password = 3;
while(current_last_letter < max_password)
for(int counter_gamma = 32; counter_gamma <= 126; counter_gamma++)
for(int counter_beta = 32; counter_beta <= 126; counter_beta++)
for(int counter_alpha = 32; counter_alpha <= 126; counter_alpha++) //alpha = increase last character by one
password[current_last_letter] = (char)counter_alpha;
System.out.print(password);
System.out.println("::null");
if(current_last_letter > 0)
password[current_last_letter-1] = (char)counter_beta;
else
counter_beta = 127;
if(current_last_letter > 1)
password[current_last_letter-2] = (char)counter_gamma;
else
counter_gamma = 127;
current_last_letter++;
If I interpreted your code right, you simply want to count in radix '~'-' '+1 (read this carefully).
Given a password, and a lo/hi value for the character range, the following method returns the
lexicographically next password. The method returns null if no such password exists -- char[] nextPassword(char[] pw, char lo, char hi) {
for (int i= pw.lenght; --i >= 0;)
if (pw[i] < hi) { // next character possible here?
pw[i]++;
return pw;
else // * no, reset to first value and continue;
pw= lo;
return null; // all pw-chars reached their hi value
So, if you initialize a password char array as follows -- char[] pw= new char[20];
Arrays.fill(pw, ' '); the following fragment handles every possible password -- do {
handlePassword(pw); // do something with pw
pw= nextPassword(pw, ' ', '~');
} while (pw != null); kind regards,
Jos -
Multi-plot Graphs, is there a better way?
I am still not good at graphs in LabView but I think I am making some programs and I can usually get a graph to show with I want it to show with only a few hours of dinking around with it...
Anyway using graphs certainly makes for messy code unless there is a better way to wire this. Basically this graph shows four temperature probes and is updated every minute. Every 15 minutes a check for stabilization is run. Seemingly the only way I have been able to get multiple plots with Time as the X-Axis is to use an X-Y chart, but I have to index my readings out individually and put each in it's own shift register, and add it to the graph separately.
There must be a better way?
Solved!
Go to Solution.
Attachments:
G2.jpg 258 KBI think part of your problem is you are not aware of the "concatenate inputs" option for build array. You don't need multiple build arrays for the array of clusters you are wiring into the graph (pink wire). Just expand the build array, wire in all your clusters, then right click the build array and choose "concatenate inputs". Next, you can use a cluster to store all your graph arrays (orange wires) which will greatly clean up your diagram.
CLA, LabVIEW Versions 2010-2013 -
Need help to get alternate or better way to write query
Hi,
I am on Oracle 11.2
DDL and sample data
create table tab1 -- 1 millions rows at any given time
id number not null,
ref_cd varchar2(64) not null,
key varchar2(44) not null,
ctrl_flg varchar2(1),
ins_date date
create table tab2 -- close to 100 million rows
id number not null,
ref_cd varchar2(64) not null,
key varchar2(44) not null,
ctrl_flg varchar2(1),
ins_date date,
upd_date date
insert into tab1 values (1,'ABCDEFG', 'XYZ','Y',sysdate);
insert into tab1 values (2,'XYZABC', 'DEF','Y',sysdate);
insert into tab1 values (3,'PORSTUVW', 'ABC','Y',sysdate);
insert into tab2 values (1,'ABCDEFG', 'WYZ','Y',sysdate);
insert into tab2 values (2,'tbVCCmphEbOEUWbxRKczvsgmzjhROXOwNkkdxWiPqDgPXtJhVl', 'ABLIOWNdj','Y',sysdate);
insert into tab2 values (3,'tbBCFkphEbOEUWbxATczvsgmzjhRQWOwNkkdxWiPqDgPXtJhVl', 'MQLIOWNdj','Y',sysdate);I need to get all rows from tab1 that does not match tab2 and any row from tab1 that matches ref_cd in tab2 but key is different.
Expected Query output
'ABCDEFG', 'WYZ'
'XYZABC', 'DEF'
'PORSTUVW', 'ABC'Existing Query
select
ref_cd,
key
from
select
ref_cd,
key
from
tab1, tab2
where
tab1.ref_cd = tab2.ref_cd and
tab1.key <> tab2.key
union
select
ref_cd,
key
from
tab1
where
not exists
select 1
from
tab2
where
tab2.ref_cd = tab1.ref_cd
);I am sure there will be an alternate way to write this query in better way. Appreciate if any of you gurus suggest alternative solution.
Thanks in advance.Hi,
user572194 wrote:
... DDL and sample data ...
create table tab2 -- close to 100 million rows
id number not null,
ref_cd varchar2(64) not null,
key varchar2(44) not null,
ctrl_flg varchar2(1),
ins_date date,
upd_date date
insert into tab2 values (1,'ABCDEFG', 'WYZ','Y',sysdate);
insert into tab2 values (2,'tbVCCmphEbOEUWbxRKczvsgmzjhROXOwNkkdxWiPqDgPXtJhVl', 'ABLIOWNdj','Y',sysdate);
insert into tab2 values (3,'tbBCFkphEbOEUWbxATczvsgmzjhRQWOwNkkdxWiPqDgPXtJhVl', 'MQLIOWNdj','Y',sysdate);
Thanks for posting the CREATE TABLE and INSERT statments. Remember why you go to all that trouble: so the people whop want to help you can re-create the problem and test their ideas. When you post statemets that don't work, it's just a waste of time.
None of the INSERT statements for tab2 work. Tab2 has 6 columns, but the INSERT statements only have 5 values.
Please test your code before you post it.
I need to get all rows from tab1 that does not match tab2 WHat does "match" mean in this case? Does it mean that tab1.ref_cd = tab2.ref_cd?
and any row from tab1 that matches ref_cd in tab2 but key is different.
Existing Query
select
ref_cd,
key
from
select
ref_cd,
key
from
tab1, tab2
where
tab1.ref_cd = tab2.ref_cd and
tab1.key <> tab2.key
union
select
ref_cd,
key
from
tab1
where
not exists
select 1
from
tab2
where
tab2.ref_cd = tab1.ref_cd
Does that really work? In the first branch of the UNION, you're referencing a column called key, but both tables involved have columns called key. I would expect that to cause an error.
Please test your code before you post it.
Right before UNION, did you mean
tab1.key != tab2.key? As you may have noticed, this site doesn't like to display the <> inequality operator. Always use the other (equivalent) inequality operator, !=, when posting here.
I am sure there will be an alternate way to write this query in better way. Appreciate if any of you gurus suggest alternative solution.Avoid UNION; it can be very inefficient.
Maybe you want something like this:
SELECT tab1.ref_cd
, tab1.key
FROM tab1
LEFT OUTER JOIN tab2 ON tab2.ref_cd = tab1.ref_cd
WHERE tab2.ref_cd IS NULL
OR tab2.key != tab1.key
; -
Can some one tell me a better way...
Hi All..
I work on a web application. I create user ids for people logging into my application. here I have a small problem.. This is what I am currently doing...
When I create a new user, I assign a new user id to the user and store all hi info.
All our user ids are stored in User_ID table and user info in User_Info table.
First I get the max user id from the User_Id table.
int iuserid = select max(User_ID) from User_ID;
Then I add ' 1 ' to this and assign it to new user.
iuserid = iuserid+1;
insert into User_id values(iuserid, <ssn> );
Then I store all user info in User_info table..
insert into User_info(iuserid, <first_name>, <last_name>,...);
Both these SQLs are executed as a transaction.
The problem that I have...
It works fine in a normal environment and in my testing.
But when the load inceases, before I insert into the User_info, another user tries to get the max User_id from User_ID table, then it conflicts..
I have seen occurences of User_Info storing the info of a different user against the User_id when many people are accessing the app at the same time.
Can some one tell me a better way to handle this scenario..
Appreciate all you help..
TIA..
CKHi,
assuming that the requirement for user_id is only for uniqueness (primary key requirement) not continuosly.
perhaps can try this,
1) create a table to keep the max id for each table's key.
e.g.
create table key_id_lookup
key_name char(n),
current_value number(m)
where n & m is the size of the field
2) for each creation of entry in the user_id table, lookup the value in the key_id_table and increment it after retrieval.
e.g. current_id = select current_value from key_id_lookup where key_name = 'user_id_key';
current_id+=1;
update key_id_lookup set current_value = current_id where key_name = 'user_id_key';
something similar to use of sequence if your database support it.
3) continue with the creation of record in other tables. now obtain the time stamp of creation and append with the current_id obtained. e.g. timestamp = 132456872; size of m is 5, user_id = 132456872 x 100000 + current_id;
this should give you a unique key at creation time.
There should be other better ways of resolving this(like locking the table for the update operation but affect performance, etc), depending on the feature supported by the database in use.
Hope this can help as last resort if other options not available. -
A better way to activate an LOV
I want to allow users to activate the LOVs and run queries from them without having to press the enter query button, then move their cursor to the appropriate text box, then press Ctrl+L, then press the execute query button. Is there some way to fire an LOV from a button press or some simpler way than I have right now?
Thats really a good way.
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Steven Lietuvnikas ([email protected]):
i follow what you're saying but i think i found a better way to do it
i made a button that says search on it and the whenbuttonpressed trigger is simply enter_query
this then moves the focus to the first item in the record block
i then made a whennewiteminstance trigger on the first item in the record block that says:
DECLARE
DUMMY BOOLEAN;
BEGIN
If (:system.Mode = 'ENTER-QUERY') Then
DUMMY := SHOW_LOV('LOV_PERSONS',15,10);
EXECUTE_QUERY;
END IF;
END;
this works good<HR></BLOCKQUOTE>
null -
When my Start button is clicked it changes a member variable from false to true.
Here is a simplified version of my code:
public class gdvdhomevideo
private boolean blnBegin;
public static void main(String[] args)
while(blnBegin == false){}
//perform operations
public void actionPerformed(ActionEvent e)
String command = e.getActionCommand();
if(command.equals("Start"))
blnBegin = true;
}So when the user clicks start it exits the while loop and the program starts performing other functions. The problem is that this approach is 100% CPU intensive and I know that there must be a better way?1) Code executed in the main() is NOT running on the event thread. Don't do any GUI code from the main thread... You know, stuff like showing windows, attaching event listeners etc.. You need to wrap all that stuff in a Runnable and pass that Runnable to SwingUtilities.invokeLater().
2) Assuming the stuff you're doing in the main() is actually thread safe and doesn't touch the GUI, you can simply startup a new Thread and put your code in there. (see below)
3) You class name is named badly. Please check out sun's java coding conventions. It is very nice to have coding conventions. Use them! ;-)
4) if you want to setup your program as a loop rather than simply relying on user actions to fire events, then I'd suggest you use a timer that notifies on the event thread every X where X is a non-zero polling interval. I think there's a class is called SwingTimer that does this sort of thing for you.
What you're attempting to do is non-trivial.. so.. ummm.. have fun..
public class gdvdhomevideo
private boolean blnBegin;
public static void main(String[] args) throws Exception
SwingUtilities.invokeLater( new Runnable() {
public void run() {
//setup stuff in here.
public void actionPerformed(ActionEvent e)
String command = e.getActionCommand();
if(command.equals("Start"))
new Thread(new Runnable() {
public void run() {
//perform operations but don't touch the GUI.
}.start();
}
Maybe you are looking for
-
I got my iphone 5s last 2 months, and it's ios is 7.0.6, after a month i can't easily send SMS, i have several apps and games. I tried to update my ios but still the problem persist. What could be the possible reason and what are the solutions? Pleas
-
How to call a parametrized procedure from a htp.formsubmit
Hi there, i'm trying to call a procedure with parameters from my formsubmit. i would like to call that procedure once my submit button is pressed. I did this : HTP.formOpen(twbkwbis.f_cgibin||'MyPackage.MyProcedure(param1, param2, param3, param4)');
-
Fld selectn for mvmt type 543 / acct 6190030 differs for Asset retirement
Dear All, I create a Subcontracting PO and issue goods to vender against that PO. Suppose i issue two materials with Qty 50 Each to vender. again Vender gave me back 10 Qty each becoze there is only 40 Qty is ussed for that material in subcontracting
-
Hello experts, Need help on the below. For client we are using KRPO, content server. Hence in DC20, by mistake some one has defined data carrier type as PC in archive section instead of server front end section and have put default and sap system in
-
Hi All, I am getting below error, Please have a look. <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> - <!-- Call Adapter --> - <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/"