Loop events

plz explain about at end of? and give me nice example?diff at new and at end of..

Hi Ram,
This is the SAP documentation on AT END OF and AT NEW.
AT NEW f.
AT END OF f.
Effect
f is a sub-field of an internal table or extract dataset (EXTRACT) which is being processed with LOOP, i.e. the variants 1 and 2 only make sense within a LOOP.
Both "AT NEW f." and "AT END OF f. " introduce processing blocks which are concluded by " ENDAT.".
These processing blocks are processed whenever the contents of a field f or a sub-field defined before f change as a result of processing with LOOP. "AT NEW f." begins a new group of (table) lines with the same contents as the field f while "AT END OF f." concludes such a group.
Within the AT ... ENDAT processing of internal tables, all argument fields following f are filled with "*".
Examples
1. AT for sub-fields of an internal table
DATA: BEGIN OF COMPANIES OCCURS 20,
        NAME(30),
        PRODUCT(20),
        SALES TYPE I,
      END   OF COMPANIES.
LOOP AT COMPANIES.
  AT NEW NAME.
    NEW-PAGE.
    WRITE / COMPANIES-NAME.
  ENDAT.
  WRITE: / COMPANIES-PRODUCT, COMPANIES-SALES.
  AT END OF NAME.
    SUM.
    WRITE: / COMPANIES-NAME, COMPANIES-SALES.
  ENDAT.
ENDLOOP.
The AT statements refer to the field COMPANIES-NAME.
Examples
2. AT for the field of an extract dataset
DATA: NAME(30),
      SALES TYPE I.
FIELD-GROUPS: HEADER, INFOS.
INSERT: NAME  INTO HEADER,
        SALES INTO INFOS.
LOOP.
  AT NEW NAME.
    NEW-PAGE.
  ENDAT.
  AT END OF NAME.
    WRITE: / NAME, SUM(SALES).
  ENDAT.
ENDLOOP.
Notes
1.If the processing you want to perform on an internal table is fairly restricted (i.e. a WHERE addition with the LOOP statement), do not use the AT statements specified in variants 1 to 5, since the interaction of the WHERE addition and the AT statement is currently not defined.
2.When you use LOOP with an extract dataset, fields on hex zero are ignored during control level checking with AT NEW or AT END OF . This procedure is the same as the SORT statement. When sorting extracted datasets, this statement always sorts blank fields (i.e. fields on hex zero) regardless of the sequence (ascending or descending) before all fields that contain values.
3.Since fields addressed with AT are not set to an initial value when you enter a LOOP, the first new group of (table) lines in AT NEW f may not be processed, if f happens to be set to this value.
Regards
Anil Madhavan

Similar Messages

  • SubVI with while loop + event structure not working in multi tab VI

    Hello Everyone,
    I am developing an interface for the control of a prober using Labview 2012, and I am stuck with some issue.
    To start with I provide you with a simplified version of my control interface VI, and with the sub-VI used to build and manage the wafer maps.
    The VI consists of several tabs: Prober Initialization, Wafer Handling, Wafer Map, Status, Error.
    The sub-VI can:
    1/ initialize the grid to display the map (sub VI Init Grid not provided here)
    2/ import XY coordinates from a txt file (sub VI Wafer Map Import)
    3/ display the coordinates and index of the die below the cursor
    4/ and when a die position is double clicked, and the boolean "Edit Wafer Map" is true, then the user can change the state (color) of the die between On-wafer die and Selected Die
    My issue:
    If I use the sub-VI by itself, it works fine. However when I use it as a sub-VI in the tab "Wafer Map", the map does not build up and I can no further use the embedded functionalities in the sub-VI.
    I suspect the while loop + event structure of the sub-VI to be the bottleneck here.
    However I don't know which way to go, that's why I'd be glad to have some advice and help here.
    Thank you.
    Florian
    Solved!
    Go to Solution.
    Attachments:
    Control Interface.zip ‏61 KB

    Hi NitzZ,
    Thank you for your reply.
    I tried to save the VIs in LV10, please tell me if you can open them now.
    Inside he event structure there is quite some code, and since I don't want to make the main vi too bulky, I would like to keep it as a sub-VI. 
    As you can see from the sub-VI, the event structure is used for extracting cursor position and tracking the double click action. These events are linked, through a property node, to the image "Wafer Map" which is passed to the main vi through connector pane.
    All values are passed this way as well (through connector pane). Is there another way?
    Maybe "refnum", but I don't really understand how to use them...
    If I use the event structure in the main vi, the wafer map is still not working. I tried it earlier.
    To implement the multi tab front panel, I used a tab control, and a for loop + case structure. For each element of the case structure, there is a corresponding action.
    For the case where I put the code (element=2) for Wafer Map, I also control the execution of the code with a case structure activated by the button "REFRESH". Otherwise I end up with a freezing of the panel right after the start.
    I hope these comments help you understand better.
    Regards,
    Florian
    Attachments:
    Control Interface.zip ‏104 KB

  • 1ms Time Loop / Event Trigger from Counter

    Hi.  I'm pretty new to LabView so I'm am hoping this is an easy question:
    I need to read the pulse signal from some reluctors (toothed wheels that pulse a signal with each passing tooth).  The amplitude of each pulse is above 2.2V so I was planning on using TTL counters.
    I need to record the status of 5 counters with each increment of one of the counters  For the RPM and tooth count, I can do this with a 1ms timed loop.
    Question:  Can windows successfully give a 1ms (accurate) timed loop?  I know this depends on how much I am doing inside the loop but, for now, I just need to read 5 counters and store the data with a timestamp.
    Is it possible to make a counter throw an event?  If the counter is incrememented, can LabView be notified to then go off and handle a block of code?
    Thanks for any help you can offer!

    I assume you also have an analog input card for the chasis?
    So, it's probably possible to get 1ms timing with software timed loops, however based on my quick check of the manual for your chasis
    http://www.ni.com/pdf/manuals/372780c.pdf (see section 2-2 for example)
    You can use an Analog Comparison Event or a PFI channel to trigger a sample (i.e. your generated pulse is the sample clock). This could allow you to use your pulse to trigger an analog sample. Now, this doesn't get you timing information (it just gets you the value of the analog input at the time the event occurs). To get a time, you can use the counters on the digital card in the same way. You have the counters be driven by a fast sample, on-board clock. Then you can use your pulse events again to sample that clock. So each pulse, you get one analog voltage sample and one time sample from the counter. The resolution on this counter will be great, depending on how fast your counters can be driven (sometimes NI counters can actually be driven faster than the fastest available clock on the card or chasis). 
    Or you can just do the software loop.

  • Diff between at-new and on-change of in loop events

    diff between <b>at-new</b> and <b>on-change of</b> in loop events

    Hello,
    <b>ON CHANGE OF f.
    Normally, you use the statement to manipulate database fields during GET events or SELECT/ENDSELECT processing.
    AT NEW
    There are special control structures for processing control breaks in LOOP s on internal tables or extract datasets (AT).</b>
    ON CHANGE OF f.
    Executes the processing block enclosed by the "ON CHANGE OF f" and "ENDON" statements whenever the contents of the field f change (control break processing).
    Normally, you use the statement to manipulate database fields during GET events or SELECT/ENDSELECT processing.
    ON CHANGE OF is unsuitable for recognizing control levels in loops of this type because it always creates a global auxiliary field which is used to check for changes. This global auxiliary field is only changed in the relevant ON CHANGE OF statement. It is not reset when the processing enters loops or subroutines, so unwanted effects can occur if the loop or subroutine is executed again. Also, since it is set to its initial value when created (like any other field), any ON CHANGE OF processing will be executed after the first test, unless the contents of the field concerned happen to be identical to the initial value.
    Example
    TABLES T100.
    SELECT * FROM T100 WHERE SPRSL = SY-LANGU AND
                             MSGNR < '010'
                       ORDER BY PRIMARY KEY.
      ON CHANGE OF T100-ARBGB.
        ULINE.
        WRITE: / '**', T100-ARBGB, '**'.
      ENDON.
      WRITE: / T100-MSGNR, T100-TEXT.
    ENDSELECT.
    Displays all messages with their numbers in the logon language, provided the number is less than '010'.
    Each time the message class changes, it is output.
    AT NEW f.
    f is a field from the field group HEADER. The enclosed sequence of statements is executed if the field f occurs in the sort key of the extract dataset (and thus also in the field group HEADER) and the field f or a superior sort criterion has a different value in the current LOOP line than in the preceding (AT NEW) or subsequent (AT END OF) record of the extract dataset.
    If f is not an assigned field symbol, the control break criterion is ignored, and the subsequent sequence of statements is not executed. If a field symbol is assigned, but does not point to the HEADER field group, the system triggers a runtime error.
    Example
    DATA: NAME(30),
          SALES TYPE I.
    FIELD-GROUPS: HEADER, INFOS.
    INSERT: NAME  INTO HEADER,
            SALES INTO INFOS.
    LOOP.
      AT NEW NAME.
        NEW-PAGE.
      ENDAT.
      AT END OF NAME.
        WRITE: / NAME, SUM(SALES).
      ENDAT.
    ENDLOOP.
    Notes
    If the extract dataset is not sorted before processing with LOOP, no control level structure is defined and the statements following AT NEW or AT END OF are not executed.
    Reward if helpful,
    Regards,
    LIJO

  • How to detect the key enter with a numerical control without using loop event?

    I want to accept a numerical value only when the key enter is pressed, but without using the event. How to detect the char "enter" with a numerical control?
    Thanks!

    When the user edits a numeric control with a keyboard, its property "key focus" is true. When the user hits enter, key focus becomes false. Poll the property to latch the control valuse at the true-false transition. That won't work if the user modify the control using up and down arrows.
    LabVIEW, C'est LabVIEW

  • Looping, Clickable FLV Preview - Click Event not being recognized

    I have tried the following code to create a thumbnail preview that loops and is clickable to go to a new page with a video gallery... The video plays anbd loops, but, it does not seem to recognize the mouse click -- i have a trace that isn't being triggered an nothing happens... code is below. any help appreciated...
    import fl.video.VideoEvent;
    import flash.events.MouseEvent;
    player.fullScreenTakeOver = false;
    player.source =
    "YadWebPreview.flv";
    player.autoRewind = true;
    player.autoPlay = true;
    function Loop(event:VideoEvent):void
    player.play();
    function Link(event:MouseEvent):void
    trace("Clicked");
    navigateToURL(
    new URLRequest(
    "http://yad.nyckatz.com/index.php/about-us/meet-our-people"),
    "_blank");
    player.addEventListener(VideoEvent.AUTO_REWOUND, Loop);
    player.addEventListener(MouseEvent.CLICK, Link);

    I added a button on top of the video and made it transparent.  added the  following code to the button:
    import flash.events.MouseEvent;
    function Link(event:MouseEvent):void
    trace("Clicked");
    navigateToURL(
    new URLRequest(
    "http://yad.nyckatz.com/index.php/about-us/meet-our-people"),
    "_blank");
    myButton.addEventListener(MouseEvent.CLICK,Link);
    getting the following compler errors:
    5000: The class 'fl.controls.Button' must subclass 'flash.display.SimpleButton' since it is linked to a library symbol of that type.
    and the following in the output tab
    ReferenceError: Error #1065: Variable Icon is not defined.
    ReferenceError: Error #1065: Variable FLVPlayback is not defined.
    ReferenceError: Error #1065: Variable ComponentShim is not defined.
    have the following code on the video:
    import fl.video.VideoEvent;
    player.fullScreenTakeOver = false;
    player.source =
    "YadWebPreview.flv";
    player.autoRewind = true;
    player.autoPlay = true;
    function Loop(event:VideoEvent):void
    player.play();
    player.addEventListener(VideoEvent.AUTO_REWOUND, Loop);
    Can't find anything to help figure out how to correct these...  Any help much appreciated.

  • Event from an Event in a while loop

    Let's say I am in a while loop in an event. During this time, I would like to trigger another event. Is this possible?

    Herny,
    you are running into caveats of the event structure. Esp. this caveat is the one you have implemented.
    I recommend you not to use more than a single event structure in your whole project. That is, of course, not suitable for certain projects, but in general a very good advice since it reduces the chances to run into issues very much.
    Furthermore, please note that events lock the frontpanel by default. See here for more information.
    hope this helps,
    Norbert 
    [EDIT] Taking a closer look into your right loop/event structure/loop - construct: your vi creates an infinite loop eating up 100% CPU load when pressing Boolean 3. Never ever do that!
    Message Edited by Norbert B on 01-13-2009 02:18 AM
    CEO: What exactly is stopping us from doing this?
    Expert: Geometry
    Marketing Manager: Just ignore it.

  • Change the condition in event structures

    Hi all,
    I am a student, currently doing a project. I'm very new to labview and I don't really know much of the function in labview. Anyway, I have this timer made using event structure if I'm not mistaken (I downloaded this timer from one of the post in this forum). This timer will start at 0s, count to 20s, then stop. So what can I do to change the end time of this timer?? Let's say stop at 50s??
    Attached is the program. Kindly please explain to me or modify the program and attached back as a reply. I've been trying to figure it out from the help function, but still don't understand.
    Thank you very much in advance!!!
    Solved!
    Go to Solution.
    Attachments:
    TIMER s.vi ‏13 KB

    Hi,
    Thanks for your inquiry. The VI attached uses a couple of programming structures: While loop, Event structure and Case structure. What you would have to change is actually the case structure. Before we go to that, let us go through the different structures. Open up the block diagram by going to the Menu bar of the front panel and navigate to Window->Open block diagram.
    The While loop is like a Do Loop in text based programming. It will execute until a condition is met. From the attached VI, it stops running when you click the exit button.
    The Event structure is a structure which consists of subdiagrams. The structure responds to interactions with front panel objects. For example, if you click the start or stop button in the front panel, the event structure will switch to a case which corresponds to this interation. In the attached VI, the case, which corresponds to intreaction with the start or stop button, is called  "Start", "Stop": Value Change. Each case will contain an event-handling routine.
    Case structures are like switch statements in text programming. Take a look at the "Start", "Stop": Value Change event. It contains a routine which consists of a case structure. The case structure responds to the input terminal called Start (which is actually the start button on the front panel). The case structure switches between cases according to this input. To view the different cases just cycle through the case structure by clicking the left and right buttons. There are only two cases: True or False as the input is a boolean.
    Now lets take a look at the VI. Take a look at the "Timeout" case of the event structure. This is where the modification needs to be made. Modify the case structure by editing the cases. Change the numbers in case structures: ..20000 to ..50000  and 20001.. to 50001.. This should do the trick.
    Regards,
    Alan Bong

  • How to treat error handling in the consumer loop in the queue message handler structure?

    Hi,
    I'd like to know how to stop the producer loop(event loop) in the QMH structure when the error happened in the consumer loop.
    I've construct a demo code by myself as the attached image, but it's a pity that I have to create a recdundant indicator "End" to trigger the value change event to stop the program. This is not a good way to do it. Could someone give me some better idea how to deal with it? Very appreciated to you sharing ideas.

    Concerning your doubts about the "traditional" implementation of this pattern, I hear you. As I have written many times before, its main benefit is that it is easy to explain in a training class. It unfortunately has a lot of drawbacks.
    Tim's suggestion about User Events, is a good one. But to use it to the best advantage, you will need to get away from having everything on one block diagram. If you think about it there is no real need for the two loops to be on the same block diagram and a lot of really good reasons for them not to be. For example, if they are in separate VIs, they can both be event driven and any communication problems between loops evaporates.
    Its also more modular, easier to maintain, more reusable, etc...
    Check the link in my signature.
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • Windows Server 2008 X64 - gpupdate takes 10min - svchost.exe (gpsvc) pid logs 8.5 million events in procmon

    Hello,
    We've seen that on our 2008 x64 servers the svchost.exe that holds gpsvc in it takes up alot of CPU-time. Upon further investigation I saw that when it refreshes policies it holds 1 core for 10 minutes. I setup a procmon and filtered it on the pid off the gpsvc-svchost and saw that it logged 8.5 million events.
    It keeps looping events where it seems to be checking history-data under "C:\ProgramData\Microsoft\Group Policy\History\<GUIDS>".
    We are using GPPreferences. Has anyone seen anything like this before?
    I have the .PML-file from procmon, however its 350MB zipped so I dont know how to attach it to case.

    Hi,
    To better understand the issue, please help confirm the following:
    1.    Do all computers encounter this issue?
    2.    When did this issue begin to occur? Did it coincide with any events, such as the installation of some software?
    Meanwhile, please perform the steps below to see if the issue goes away:
    1.    Delete the contents in the "C:\ProgramData\Microsoft\Group Policy\History\" folder.
    2.    Please perform a clean boot on the server:
    1)    Click Start, type msconfig in the Start Search box, and then press ENTER.
    2)    On the General tab, click Selective Startup.
    3)    Under Selective Startup, click to clear the Load Startup Items check box.
    4)    Click the Services tab, click to select the Hide All Microsoft Services check box, and then click Disable All.
    5)    Click OK.
    6)    When you are prompted, click Restart.
    If the issue continues, please help collect the following information for further research:
    1.    Enable gpsvc.log:
    Please create the following key in Registry Editor:
    HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Diagnostics
    Type: DWORD
    Value: GPSvcDebugLevel
    Data: 0x30002 (hexadecimal)
    2.    Please run gpupdate /force to reproduce the issue and then collect MPSReport on the server:
    1) Download the MPSReport from the website below:
    http://www.microsoft.com/downloads/details.aspx?FamilyID=CEBF3C7C-7CA5-408F-88B7-F9C79B7306C0&displaylang=en
    2) Double-click the executable to launch the report gathering tool on the computer.
    3) Follow the steps as guided by the Wizard.
    4) On the Select the diagnostics you want to run page, select General, Internet and Networking, Business Networks, and Server Components.     
    3.    After that, please zip the gpsvc.log (%windir%\debug\usermode\gpsvc.log), MPSReport and the PML.file and upload to the following space:
    https://sftasia.one.microsoft.com/choosetransfer.aspx?key=ef4b8b4e-0e6c-4774-a132-2d072f8b77b0
    Password: fQxbhTjUV
    More Information about MPSReport:
    http://blogs.technet.com/askperf/archive/2009/05/01/two-minute-drill-the-new-mps-reports.aspx
    This posting is provided "AS IS" with no warranties, and confers no rights.

  • Event structure and waveform graph cursor

    I am utilizing a waveform graph and I need to programatically manipulate multiple cursors based upon the movement of a primary cursor.  I would like to use the event structure to avoid processor usesage. 
    My approach is to create an While Loop/event structure where it goes into a it when there is a "mouse down" on the waveform graph.  Once in it, there is another While Loop/event structure that has two cases: Time Out (set to 25) and a "Mouse Up" on the waveform graph.  In the Time Out case, the primary cursor is read and modifies the location of the secondary cursors.  In the "Mouse Up" case, the primary cursor location is read, other cursors are manipulated, and the While Loop is exited.
    When I code this up and perform a "mouse down" on the waveform graph, the index on the inner While Loop/Event Structure is advancing but there is no control (can't move it) of the primary cursor on the waveform graph.  When I "Mouse Up", the inner While Loop exits.
    Obviously, my approach is flawed here based on my lack of understanding of the characteristics of the waveform graph and cursor manipulation.  Has somebody come up with a way to achieve what I am trying to do?

    This is basically the method I typically used in LabVIEW 7.1 and below as described in this old post.
    Of course you could upgrade to LabVIEW 8.0 and none of this is necessary! LabVIEW 8.0 has events for "Cursor Move".
    Now you only need the "cursor move" and "stop" cases. Isn't that cool!
    Message Edited by altenbach on 12-12-2005 07:05 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    LV8CursorMove.png ‏6 KB

  • How to add new increase the pool rather then trowing a error.

    Im trying to build a game and after many attempts and hours of thinking i did manage to create something that looks like a game.The problem now is that there are so many objects that are constantly creating and removing from the stage. that the game is starting to slow down(it is laggy.).So i have searched the net and understood that i will have to use a "Object pooling Method" rather than creating and removing the objects after i dont have any use of them any more, if i want to make the game more memory friendly.
    At first i didnt want to use this method (object pooling) ,but after a while i understood that i dont have a lot of options.So i started to search how and why and how.
    Yet in this example im just trying this for the bullets (for now) cause if i can do it for them, i can manage to do it for other objects and projects (it will be simple for me to understand what is happening ., what am i doing , when do i add an existing object from the pool and when im creating a new one(when there are non left, things like this)
    i did copy some part of this code from a tutorial that i found in the net but , from then i dont know how to increase the pool rather than throwing this error. I did try to create a new object or to increase the pool length but .... it is not working so im sure that im not doing something the way it must be done.
    so i have this so far :
    its a "simple" pool that calls a simple shape class (circle dot) and gives that to the main stage when the "SPACE" button is pressed
    package
              import flash.display.Sprite;
              import flash.events.Event;
              import flash.display.Bitmap;
              import flash.display.BitmapData;
              import flash.display.Shape;
              public class Bullet extends Sprite{
                        public var  rectangle:Shape = new Shape();
                        public function Bullet(){
                                  super();
                                  addEventListener(Event.ADDED_TO_STAGE, init);
                                  graphics.beginFill(0xFF0000);
                                  graphics.drawRect(-5, -5, 10,10);
                                  graphics.endFill();
                        private function init(event:Event):void{
    the SpritePool where i cant figure out how to replace the throw new error with some new code that will increase the pool
    package {
              import flash.display.DisplayObject;
              public class SpritePool {
                        private var pool:Array;
                        private var counter:int;
                        public function SpritePool(type:Class, len:int) {
                                  pool = new Array();
                                  counter = len;
                                  var i:int = len;
                                  while (--i > -1) {
                                            pool[i] = new type();
                        public function getSprite():DisplayObject {
                                  if (counter > 0) {
                                            return pool[--counter];
                                  } else {
                                            throw new Error("You exhausted the pool!");
                        public function returnSprite(s:DisplayObject):void {
                                  pool[counter++] = s;
    and the Game class (the documents class)
    package {
              import flash.ui.Keyboard;
              import flash.display.Sprite;
              import flash.events.Event;
              import flash.events.KeyboardEvent;
              import flash.display.Bitmap;
              import flash.display.BitmapData;
              import flash.display.Shape;
              public class Game extends Sprite {
                        private var ship:Shape;
                        private var bullets:Array;
                        private var pool:SpritePool;
                        public function Game() {
                                  Assets.init();
                                  addEventListener(Event.ADDED_TO_STAGE, init);
                        private function init(event:Event):void {
                                  pool = new SpritePool(Bullet,10);
                                  bullets = new Array();
                                  ship = new Shape();
                                  ship.graphics.beginFill(0xFF00FF);
                                  ship.graphics.drawRect(0,0, 60, 60);
                                  ship.graphics.endFill();
                                  ship.x = stage.stageWidth / 2 - ship.width / 2;
                                  ship.y = stage.stageHeight - ship.height;
                                  addChild(ship);
                                  stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
                                  addEventListener(Event.ENTER_FRAME, loop);
                        private function onDown(event:KeyboardEvent):void {
                                  if (event.keyCode == Keyboard.SPACE) {
                                            var b:Bullet = pool.getSprite() as Bullet;
                                            b.x = ship.x + ship.width / 2;
                                            b.y = ship.y;
                                            addChild(b);
                                            bullets.push(b);
                                            trace("Bullet fired");
                        private function loop(event:Event):void {
                                  for (var i:int=bullets.length-1; i>=0; i--) {
                                            var b:Bullet = bullets[i];
                                            b.y -=  10;
                                            if (b.y < 0) {
                                                      bullets.splice(i, 1);
                                                      removeChild(b);
                                                      pool.returnSprite(b);
                                                      trace("Bullet disposed");
    any suggestions/help how to do it

    To put you on the path (the errors/events needs formalization), here would be a quick example. Your pool class:
    package
              import flash.display.DisplayObject;
              public class SpritePool
                        private var pool:Array;
                        private var counter:int;
                        private var classRef:Class;
                        // public get to know what's left in the pool
                        public function get availableObjects():int
                                  return counter;
                        public function SpritePool(type:Class, len:int)
                                  classRef = type;
                                  pool = new Array();
                                  counter = len;
                                  var i:int = len;
                                  while (--i > -1)
                                            pool[i] = new classRef();
                        public function getSprite():DisplayObject
                                  if (counter > 0)
                                            return pool[--counter];
                                  else
                                            throw new Error("PoolExhausted");
                        public function returnSprite(s:DisplayObject):void
                                  pool[counter++] = s;
                        public function increasePool(amount:int):void
                                  counter += amount;
                                  while (--amount > -1)
                                            pool.push(new classRef());
                        public function decreasePool(amount:int):void
                                  if (counter >= amount)
                                            counter -= amount;
                                            pool.splice(counter - amount,amount);
                                  else
                                            throw new Error("PoolDecreaseFail");
    Now you'd need to be catching those errors. Again, the errors should be formalized or you could use events by extending IEventDispatcher. I kept it simple.
    Here would be the simple Bullet class I'm using:
    package
              import flash.display.Sprite;
              public class Bullet extends Sprite
                        private var bullet:Sprite;
                        public function Bullet():void
                                  var bullet:Sprite = new Sprite();
                                  bullet.graphics.beginFill(0xFF0000,1);
                                  bullet.graphics.drawCircle(-5,-5,10);
                                  bullet.graphics.endFill();
                                  addChild(bullet);
    Just draws a red circle just to visualize it..
    Here would be a full example of using it. It will import both of these classes (saved as SpritePool.as and Bullet.as in the same folder). Paste this in the actions panel on frame 1:
    import SpritePool;
    import Bullet; // a simple red 10px circle
    import flash.display.Sprite;
    import flash.utils.setTimeout;
    // fill the pool, swim trunks optional
    var pool:SpritePool = new SpritePool(Bullet, 10);
    // grab some objects from the pool
    // array of currently held objects
    var myBullets:Array = new Array();
    while (pool.availableObjects > 0)
              myBullets.push(pool.getSprite());
    // display in random positions
    for (var i:int = 0; i < myBullets.length; i++)
              addChild(myBullets[i]);
              // position
              myBullets[i].x = int(Math.random()*stage.stageWidth);
              myBullets[i].y = int(Math.random()*stage.stageHeight);
    trace("myBullets has " + myBullets.length + " bullets! pool has " + pool.availableObjects + " left.");
    // now I want one more, but I should check for errors
    try
              // fail, none left!
              myBullets.push(pool.getSprite());
    catch (e:*)
              // this should be a custom event, but for speed, quick and dirty
              if (e == 'Error: PoolExhausted')
                        trace("D'oh no more bullets! I need more!");
                        pool.increasePool(10);
                        trace("Added 10 more, now available in pool " + pool.availableObjects);
    // try to reduce the pool by 15, which should error
    try
              pool.decreasePool(15);
    catch (e:*)
              // again should be a formal error
              if (e == 'Error: PoolDecreaseFail')
                        trace("Oops, can't reduce pool by 15! Let's trim all extras, available is " + pool.availableObjects);
                        // we know it'll work, no error checking
                        pool.decreasePool(pool.availableObjects);
                        trace("Left in pool: " + pool.availableObjects);
    // now lets wait 5 seconds and remove it all back to the pool
    setTimeout(ReturnToPool,5000);
    function ReturnToPool():void
              // now let's just return all the objects to the pool
              while (myBullets.length > 0)
                        removeChild(myBullets[myBullets.length - 1]);
                        pool.returnSprite(myBullets.pop());
              // now check the pool, should have 10
              trace("Amount of bullets in use " + myBullets.length + ", in pool " + pool.availableObjects);
    For ease you can just download my example source (saved down to CS5).
    Anything from here is just symantics. For example instead of throwing an error because the pool is too small you could simply increase the pool by a fixed amount yourself and return the objects requested.
    To keep objects as low as possible you could use a timer to measure the amount of objects in use over a duration and reduce the pool appropriately, knowing the pool will grow as it needs.
    All of this is just to avoid unnecessary object creation.
    BTW here's my trace which should match yours:
    myBullets has 10 bullets! pool has 0 left.
    D'oh no more bullets! I need more!
    Added 10 more, now available in pool 10
    Oops, can't reduce pool by 15! Let's trim all extras, available is 10
    Left in pool: 0
    (after 5 seconds)
    Amount of bullets in use 0, in pool 10

  • Program runs fine then takes a long time to close

    Hi Everyone,
    I have written a mid sized application, which is running fine until it comes to closing, then it takes an age to close. If it has only been running for a short time it closes fine, but after some time running it takes longer and longer to close. Until you try to close, it remains fully responsive and performing well.
    I have heard the phrase 'memory leak' banded around, but am not 100% sure how I would have created one of these. I am also looking into my queues accidentally getting too big.
    If you had this a problem like this, where would you look first?
    I could do with some advice around common places that this kind of thing happens.
    I don't really want to post my whole application on here, but it includes:
    Multiple loop event based producer consumer
    Camera acquisisition and image processing
    DAQ for some simple digital I/O
    Reading and writing to text and image files
    Error handling
    Compiled as an executable
    No local variable abuse
    Any advice would be appreciated.
    Thanks.

    Any building of arrays?  If those get large, the application can start to get sluggish.
    P@Anand is probably on the right track.  Make sure you check your closing operations and make sure a loop isn't left sitting there for a long time.
    I have also seen file handling take a lot of time to delete temporary files or close large files.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • How would you approach this?

    Hello All,
    I am writing a simple GUI that will allow me to choose a file and then transmit that file to a device.  Attached what my GUI (front panel) will look like.  This is my approach:
    -Two 'while loops'
    -One loop (event loop) contains an event structure to handle button presses as well as window close (I want to release a semaphore before the program terminates).
    -The other loop (main loop) takes care of communication with the device.
    -The event loop uses a notifier to relay start/stop commands to the main loop
    -The main loop triggers an event signaling that it has completed transmitting
    -*When one button is pressed, it is disabled and greyed until that action can be performed again*
    (ex. 'Download' is diabled until 'Cancel' is pressed or transmission completes)
    Does anyone see where this VI could get 'stuck' (in a state that it can't recover from)?  Does anyone have another approach that may be simpler yet do the same?
    Thanks!!
    Jorge

    Using a notifier might be problematic, I only use those to interchange static values (write once, read many).
    You could get stuck if you don't have a time-out on the hardware interfacing values.
    Ton
    Free Code Capture Tool! Version 2.1.3 with comments, web-upload, back-save and snippets!
    Nederlandse LabVIEW user groep www.lvug.nl
    My LabVIEW Ideas
    LabVIEW, programming like it should be!

  • Javascript needed for multiple lines of the same calculations: price x quantity = total

    I have received some help already but I need more details - like exactly where to place the code - and - do I place the code before using "Place Multiple Fields?  Also, does the first Total1.0 field need any calculation in it or does the area under the "Calculate" tab need to be blank?
    The fields in the example below were placed using "Place Multiple Fields".  Instead of going into the Total fields one at a time and telling it to pick up the correct field names for Price and Qty for that row, I'd love a formula that was able to figure out the totals for each row.   The only thing is that when you use "Place Multiple Fields" the field names change (e.g. Price1.0, Price1.1, Price1.2, etc.)
    I really need this spelled out step by step for me, if someone has time time.
    Thank you x 1,000,000.

    With Hierarchical field names one can create an array of the lower field objects below a one of the levels in the hierarchy.
    // Custom JavaSCript for the subtotal field;
    var oHFieldTotal = this.getField("Total1");
    var aHFieldTotal = oHField.getArray(); // Total field objects in an array;
    var aHFieldPrice = this.getField("Price1").getArray(); // Price field objects in an array;
    var aHFieldQty = this.getField("Qty1").getArray(); // Qty field objects in an array;
    var nSum = 0; // sum of extended price * qty;
    // process each row of fields;
    for(i = 0; i < aHField.length; i++) {
    aHFieldTotal[i].value = aHFieldPrice[i].value * aHFieldQty[i].value; // compute the extended value;
    nSum += aHFieldTotal[i].value; // add the extended value to the running sum;
    } // end for loop;
    event.value = nSum; // set the field value to the running sum;

Maybe you are looking for