Making code more efficient

I am having a lot of trouble getting my code to work fast enough. I have 4 sonic anemometers and currently my code is only efficient enough to collect data from one. I have programs that run 2 sonic anemometers and save the data, but bites pile up at the port. The instruments are in unprompted mode and send data at 10hz. I find that using the wait command dose not work well for some reason so I have the loop continuously running. The first version of my code (V3a) worked for one sonic and bites did not pile up at the port. So I made (V3b) and tried to make a more efficient program. I tried separating things into multiple loops but, it still does not work well and was hoping to get some ideas to make things work better.
I attached the 2 versions of my code. I am not sure if I should attach the subVIs, let me know.
Thanks!
Attachments:
fo3csat_unprompted_v3a.vi ‏23 KB
fo3csat_unprompted_v3b.vi ‏27 KB

I'm going to ask you a very important question about that occurrence in the top loop: by using the occurrence the way you have, have you eliminated the possibility of a race condition? The answer is NO... study it, and you'll see why. If you can't figure it out, post back and I'll tell you why the race condition is still present.
Also, if you ever are coding and thinking to yourself, "WOW, I can't believe the guys who developed LabVIEW made it so hard to do this simple task!", odds are, you're making it hard yourself! Rather than making 4 parallel branches of a numeric, converting to an ASCII string, then reinterpreting as 4 separate numerics, consider the following code. It's nearly equivalent, except my seconds has more significant digits (maybe good, maybe not):
I'm going to argue that even splitting the discrete components of time is unnecessary, unless your logging protocol specifically requires that format. Instead, simply write the timestamp directly to file with the data points.
Also, remember to use a standard 4x2x2x4 connector pane on your SubVIs. Refer to the LabVIEW Style Guide (search, and you will find it).
Finally, I'm going to disagree with the other guys, it's not evident why you split the one loop into three loops. The only "producer/consumer" architecture has the top loop as the "producer", and all it's producing is a timestamp! This is not a typical or intended use of the producer/consumer architecture. Your VI is intended to only save a data point once every 30 minutes (presumably), so it's no big deal of both of your serial devices are in the same loop.
The single biggest problem why your VI is completely railing out a CPU core (you didn't state this, but I'm guessing the reason you posting is because you noticed a core running at 100%!) is the unmetered loop rate... like the other guys say, drop a "Wait Until Next ms Multiple" and slow the loop rate down significantly. 10msec is probably too fast for your application.... actually, a loop rate of once every 30 minutes (that's 1800000msec) might be best.
Let us know how it goes!
a.lia-user-name-link[href="/t5/user/viewprofilepage/user-id/88938"] {color: black;} a.lia-user-name-link[href="/t5/user/viewprofilepage/user-id/88938"]:after {content: '';} .jrd-sig {height: 80px; overflow: visible;} .jrd-sig-deploy {float:left; opacity:0.2;} .jrd-sig-img {float:right; opacity:0.2;} .jrd-sig-img:hover {opacity:0.8;} .jrd-sig-deploy:hover {opacity:0.8;}

Similar Messages

  • Make Code More Efficient

    I got this code to play some audio clips and it works alright. The only issue is that when I call the play method it lags the rest of my game pretty badly. Is there anything in the play method you guys think could be moved to the constructor to make it more efficient?
    package main;
    import java.io.*;
    import javax.sound.sampled.*;
    public class Sound
         private AudioFormat format;
        private byte[] samples;
        private String name;
         public Sound(String filename)
              name=filename;
              try
                AudioInputStream stream =AudioSystem.getAudioInputStream(new File("sounds/"+filename));
                format = stream.getFormat();
                samples = getSamples(stream);
            }catch (Exception e){System.out.println(e);}
         public byte[] getSamples()
            return samples;
        private byte[] getSamples(AudioInputStream audioStream)
            int length=(int)(audioStream.getFrameLength()*format.getFrameSize());
            byte[] samples = new byte[length];
            DataInputStream is = new DataInputStream(audioStream);
            try
                is.readFully(samples);
            }catch (Exception e){System.out.println(e);}
            return samples;
        public void play()
             InputStream stream =new ByteArrayInputStream(getSamples());
            int bufferSize = format.getFrameSize()*Math.round(format.getSampleRate() / 10);
            byte[] buffer = new byte[bufferSize];
            SourceDataLine line;
            try
                DataLine.Info info=new DataLine.Info(SourceDataLine.class, format);
                line=(SourceDataLine)AudioSystem.getLine(info);
                line.open(format, bufferSize);
            }catch (Exception e){System.out.println(e);return;}
            line.start();
            try
                int numBytesRead = 0;
                while (numBytesRead != -1)
                    numBytesRead =
                        stream.read(buffer, 0, buffer.length);
                    if (numBytesRead != -1)
                       line.write(buffer, 0, numBytesRead);
            }catch (Exception e){System.out.println(e);}
            line.drain();
            line.close();
        public String getName()
             return name;
    }

    I don't know much about the guts of flex, but I assume it's
    based on Java's design etc.
    Storing event.target.selectedItem in an objet should not be
    anymore efficient than calling event.target.selectedItem. The objet
    will simply be a pointer of sorts to event.target.selectedItem. At
    no point in the event.target.selectedItem call are you doing a
    search or something, so storing the result will not result in any
    big savings.
    Now, if you were doing something like
    array.findItem(something) 4 times, then yes, it would be to your
    advantage to store the data.
    Keep in mind that storing event.target.selectedItem in an
    object will probably break bindings....that may or may not be a
    problem. Objet doesn't support binding. There is a subclass of
    Object that does, but I forget which.
    Just a suggestion based on my knowledge of how data is stored
    in an object oriented language...this may not be the case in
    flex.

  • Making Sound More Efficient

    I got this code to play some audio clips and it works alright. The only issue is that when I call the play method it lags the rest of my game pretty badly. Is there anything in the play method you guys think could be moved to the constructor to make it more efficient?
    btw I know I posted this in the sound section already but it had like 17 views there and no responses after like a week on the front page so I decided to bring it here.
    package main;
    import java.io.*;
    import javax.sound.sampled.*;
    public class Sound
         private AudioFormat format;
        private byte[] samples;
        private String name;
         public Sound(String filename)
              name=filename;
              try
                AudioInputStream stream =AudioSystem.getAudioInputStream(new File("sounds/"+filename));
                format = stream.getFormat();
                samples = getSamples(stream);
            }catch (Exception e){System.out.println(e);}
         public byte[] getSamples()
            return samples;
        private byte[] getSamples(AudioInputStream audioStream)
            int length=(int)(audioStream.getFrameLength()*format.getFrameSize());
            byte[] samples = new byte[length];
            DataInputStream is = new DataInputStream(audioStream);
            try
                is.readFully(samples);
            }catch (Exception e){System.out.println(e);}
            return samples;
        public void play()
             InputStream stream =new ByteArrayInputStream(getSamples());
            int bufferSize = format.getFrameSize()*Math.round(format.getSampleRate() / 10);
            byte[] buffer = new byte[bufferSize];
            SourceDataLine line;
            try
                DataLine.Info info=new DataLine.Info(SourceDataLine.class, format);
                line=(SourceDataLine)AudioSystem.getLine(info);
                line.open(format, bufferSize);
            }catch (Exception e){System.out.println(e);return;}
            line.start();
            try
                int numBytesRead = 0;
                while (numBytesRead != -1)
                    numBytesRead =
                        stream.read(buffer, 0, buffer.length);
                    if (numBytesRead != -1)
                       line.write(buffer, 0, numBytesRead);
            }catch (Exception e){System.out.println(e);}
            line.drain();
            line.close();
        public String getName()
             return name;
    }

    BammRocket wrote:
    I got this code to play some audio clips and it works alright. The only issue is that when I call the play method it lags the rest of my game pretty badly. Is there anything in the play method you guys think could be moved to the constructor to make it more efficient?you got this code from chapter 4 of [Developing Games in Java|http://www.brackeen.com/javagamebook/] right?
    are you playing the sounds in a different thread?
    if not, your program will just freeze until the sound is finished.

  • Making it more efficient

    I will be using this function
                   private function inter_1a(evt:MouseEvent):void {
                    var popUpInterDisplay:interactionexporter;
                    popUpInterDisplay = new interactionexporter();
                    popUpInterDisplay.source = "lessons/lessonone/interactions/inter1a.swf";
                    PopUpManager.addPopUp(popUpInterDisplay, this, true);
    But will use it at least 30 times. For example:
                   private function inter_1b(evt:MouseEvent):void {
                    var popUpInterDisplay:interactionexporter;
                    popUpInterDisplay = new interactionexporter();
                    popUpInterDisplay.source = "lessons/lessonone/interactions/inter1b.swf";
                    PopUpManager.addPopUp(popUpInterDisplay, this, true);
               private function inter_1c(evt:MouseEvent):void {
                     var popUpInterDisplay:interactionexporter;
                     popUpInterDisplay = new interactionexporter();
                     popUpInterDisplay.source = "lessons/lessonone/interactions/inter1c.swf";
                     PopUpManager.addPopUp(popUpInterDisplay, this, true);
        ETC......
    Any ideas as to make this more efficient?
    Thanks

    This can be written more efficient indeed. How are these functions called, by Buttons or by an item in a datagrid?
    In case it are buttons, you can store the name of the swf in their id properties:
    private function inter(evt:MouseEvent):void
          var popUpInterDisplay:interactionexporter = new interactionexporter();
          popUpInterDisplay.source = "lessons/lessonone/interactions/" + evt.target.id + ".swf";
          PopUpManager.addPopUp(popUpInterDisplay, this, true);
    In case of a datagrid, you can use a property of the selectedItem:
    private function inter(evt:MouseEvent):void
           var popUpInterDisplay:interactionexporter = new interactionexporter();
           popUpInterDisplay.source = "lessons/lessonone/interactions/" + evt.currentTarget.selectedItem.propName + ".swf";
           PopUpManager.addPopUp(popUpInterDisplay, this, true);
    Dany

  • Need a 'Time' Code More Efficient

    Hi,
    I have a script here that I have written to basically calculate a 'turn around time' using two number fields (arrival_time and departure_time). The script functions perfectly and succesfully uses a decode and sign function to make sure that none of the hours exceed 24.
    However, as you will notice - the code is huge for something so simple - it really couldn't be more less efficient.
    I am new (ish) to SQL so I'm happy that it works for now but the amount of code I have copied and pasted is silly - it takes longer than necessary to implement on an existing table.
    Thanks in advance for any ways you can come up with to cut the code down:
    UPDATE dw_dmcn.time_tester
    UPDATE dw_dmcn.time_tester
    SET TURN_AROUND = DECODE(SIGN(floor(((to_date('2008-01-01 '||lpad(departure_time, 4, '0'), 'yyyy-mm-dd hh24,mi') - to_date('2008-01-01 '||lpad(arrival_time, 4, '0'), 'yyyy-mm-dd hh24,mi'))*24*60*60)/3600)), -1, (floor(((to_date('2008-01-01 '||lpad(departure_time, 4, '0'), 'yyyy-mm-dd hh24,mi') - to_date('2008-01-01 '||lpad(arrival_time, 4, '0'), 'yyyy-mm-dd hh24,mi'))*24*60*60)/3600) + 24), 1, (floor(((to_date('2008-01-01 '||lpad(departure_time, 4, '0'), 'yyyy-mm-dd hh24,mi') - to_date('2008-01-01 '||lpad(arrival_time, 4, '0'), 'yyyy-mm-dd hh24,mi'))*24*60*60)/3600)), 0, (floor(((to_date('2008-01-01 '||lpad(departure_time, 4, '0'), 'yyyy-mm-dd hh24,mi') - to_date('2008-01-01 '||lpad(arrival_time, 4, '0'), 'yyyy-mm-dd hh24,mi'))*24*60*60)/3600))) ||
    DECODE(round((((to_date('2008-01-01 '||lpad(departure_time, 4, '0'), 'yyyy-mm-dd hh24,mi') - to_date('2008-01-01 '||lpad(arrival_time, 4, '0'), 'yyyy-mm-dd hh24,mi'))*24*60*60) -
    floor(((to_date('2008-01-01 '||lpad(departure_time, 4, '0'), 'yyyy-mm-dd hh24,mi') - to_date('2008-01-01 '||lpad(arrival_time, 4, '0'), 'yyyy-mm-dd hh24,mi'))*24*60*60)/3600)*3600 -
    (floor((((to_date('2008-01-01 '||lpad(departure_time, 4, '0'), 'yyyy-mm-dd hh24,mi') - to_date('2008-01-01 '||lpad(arrival_time, 4, '0'), 'yyyy-mm-dd hh24,mi'))*24*60*60) -
    floor(((to_date('2008-01-01 '||lpad(departure_time, 4, '0'), 'yyyy-mm-dd hh24,mi') - to_date('2008-01-01 '||lpad(arrival_time, 4, '0'), 'yyyy-mm-dd hh24,mi'))*24*60*60)/3600)*3600)/60)*60) )), 60, (floor((((to_date('2008-01-01 '||lpad(departure_time, 4, '0'), 'yyyy-mm-dd hh24,mi') - to_date('2008-01-01 '||lpad(arrival_time, 4, '0'), 'yyyy-mm-dd hh24,mi'))*24*60*60) -
    floor(((to_date('2008-01-01 '||lpad(departure_time, 4, '0'), 'yyyy-mm-dd hh24,mi') - to_date('2008-01-01 '||lpad(arrival_time, 4, '0'), 'yyyy-mm-dd hh24,mi'))*24*60*60)/3600)*3600)/60) + 1), 0, floor((((to_date('2008-01-01 '||lpad(departure_time, 4, '0'), 'yyyy-mm-dd hh24,mi') - to_date('2008-01-01 '||lpad(arrival_time, 4, '0'), 'yyyy-mm-dd hh24,mi'))*24*60*60) -
    floor(((to_date('2008-01-01 '||lpad(departure_time, 4, '0'), 'yyyy-mm-dd hh24,mi') - to_date('2008-01-01 '||lpad(arrival_time, 4, '0'), 'yyyy-mm-dd hh24,mi'))*24*60*60)/3600)*3600)/60))
    btw - i've forgot how to use the code tags in here, doesn't seem to work!?
    Thanks again,
    Dan
    Edited by: Dan Mc on 16-Feb-2009 07:11                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Try Timestamp:
    declare
    ts1 timestamp;
    ts2 timestamp;
    tsResult VARCHAR2(30);
    BEGIN
    ts1 := to_timestamp('04-JUL-2008','DD-MON-YYYY');
    ts2 := to_timestamp('20-OCT-2008 15:30:00','DD-MON-YYYY HH24:MI:SS');
    tsResult :=  SUBSTR((ts2-ts1),1,30) ;
    dbms_output.put_line('Time diff is ' || tsResult);
    END;
    Time diff is +000000108 15:30:00.000000000
    PL/SQL procedure successfully completed.108 day, 15 hours, 30 minutes...
    or if you need it in a select [from this site|http://www.akadia.com/services/ora_date_time.html]
    SELECT SUBSTR(time1,1,30) "Time1",
           SUBSTR(time2,1,30) "Time2",
           SUBSTR((time2-time1),1,30) "Time1 - Time2"
    FROM date_table;
    Time1                          Time2                          Time1 - Time2
    17-DEC-80 12.00.00.000000 AM   03-DEC-04 10.34.24.000000 AM   +000008752 10:34:24.000000 Either way, you can pick off whatever pieces you want with SUBSTR or REGEXP.

  • Making code more precise

    Hi my name is vicente and i was wondering if the following code is as precise as it could be. I made the program in the course of 1 hour during class and it is quite simple. Let me know if there are things i can clean up. thanks
    import java.io.*;
    class Program49A1
         public static void main ( String[] args ) throws IOException
              EasyReader indata = new EasyReader ("testscores.dat");
              //initialize the variables
              int num=0,index,count, count2,newsize;
              String input,fName,lName,input2;
              double total=0, average,min=0,max=0;
              //read the first piece of data and save it to some variables for later          
              input = indata.readLine();
              count = Integer.parseInt(  input );
              index=count;
              count2=index;
              double testScores[] = new double[index+1];     
              //get the student's name and begin output.
              fName = indata.readLine();
              lName = indata.readLine();
              System.out.println(fName+ " " +lName+"'s test scores:");
              //read the first test score.
              input2 = indata.readLine();
              testScores[index] = Double.parseDouble(  input2 );
              total = total + testScores[index];
              //initializing the first element of the array as both the largest and the smallest number
              min=testScores[index];
              max=testScores[index];
              for( count=count-1; count != 0; count--)
                   //begin the for loop by printing the test score and a comma.
                   System.out.print( testScores[index] + ", ");
                   input2 = indata.readLine();
                   testScores[index] = Double.parseDouble(  input2 );
                   //find the max and the min
                   if ( testScores[index] <= min)
                        min = testScores[index];
                   if (testScores[index] >= max)
                        max = testScores[index];
                   //calculate average
                   total = total + testScores[index];
              //print out the last testscore of the array.
              System.out.print(testScores[index]);
              //if the max and the min are the same number (unlikely)
              //this will make sure the new average is correctly calculated
              if(max==min)
                   newsize =index-1;
              else
                   newsize=index-2;
              //calculations and final output
              average = (total/count2);
              System.out.println("\n\naverage: "+average);
              System.out.println("\nmin:" +min+"\n\nmax: "+max);
              //subtract the sum of the max number and the lowest number from the total.
              total =total -(min+max);
              //average is now equal to the new total divided by the new number of numbers.
              average=total/(newsize);
              //final output
              System.out.println("\n\naverage: "+average);
              System.out.println("\n\n");               
    }im using easy reader which you can find here: http://www.skylit.com/javamethods-old/EasyReader.java

    Any place you have a comment could potentially be re-factored into a private method with a descriptive name. When you see 'blocks' in your code delineated by comments, always consider breaking up the larger method into smaller ones. Blocks within loops are also excellent candidates for a private method.
    Consider making all string literals in your class into constants that are static and final. (Don't bother doing this for logging message or System.out.println(), it's overkill).
    Consider catching the IOException rather than letting it propogate out of the main() method. You should instead display a meaningul message to the user. Stack traces are not that friendly on the eyes to ordinary users.
    - Saish

  • How can I make my code more efficient?

    Hello Everyone,
    I have a problem that is something like this:
    Say you have a database and inside that database you have a table called 'books' which has only 3 columns: id, title, author.
    Now let's say you have a servlet/jsp (servlet1) that expects a parameter called 'author' and it will display a list of all books by a certain author to the client. It will display this list such that each book is a link to another servlet/jsp (servlet 2)that accepts the book 'id' [primary key] as a parameter. Servlet 2 will display all the information about that book to the client.
    Servlet1 works by querying the database and building a list of beans, one of which will contain the same data as servlet 2 is going to need to display the book information. But I don't know how to make so that servlet2 can see the bean used in servlet 1. Right now servlet2 gets the primary key as a parameter and queries the database again. This can't be the right way to being going about this. Can anyone offer me some insight as to a better way to approach this problem?
    Thanks v. much.
    Chris Latimer

    put all the data you wish the 2nd servlet to recieve from the first servlet in a bean or object and pass it to the second. This works great with small amounts of data, but if you are going to have huge beans there are other ways of doing it.
    If you have huge beans, then you may consider updating/inserting into a table in the database and then reading the data from the table into the 2nd servlet.
    tnx,
    Les

  • Can we replace this SELECT query by more efficient code

    can we replace this SELECT query by more efficient code ?:-
    SELECT * FROM zv7_custord
         INTO TABLE G_T_ZV7_CUSTORD
         WHERE ( SENDER in S_SENDER and
                 ORDNUM in S_ORDER  and
                 ZDATE   in S_DATE ) OR
               ( SENDER in S_SENDER AND
                 STATUS = SPACE )
         ORDER BY IDOCNUM.

    Hi
    U can leave ORDER BY option and sort the table by yourself and try to split the query:
    SELECT * FROM zv7_custord
         INTO TABLE G_T_ZV7_CUSTORD
         WHERE  SENDER in S_SENDER and
                       ORDNUM in S_ORDER  and
                       ZDATE   in S_DATE .
    SELECT * FROM zv7_custord
         APPENDING TABLE G_T_ZV7_CUSTORD
         WHERE  SENDER in S_SENDER        and
                       NOT ORDNUM in S_ORDER  and
                       NOT ZDATE   in S_DATE       and
                       STATUS = SPACE
    or
    SELECT * FROM zv7_custord
         INTO TABLE G_T_ZV7_CUSTORD
         WHERE  SENDER in S_SENDER and
                       ORDNUM in S_ORDER  and
                       ZDATE   in S_DATE .
    SELECT * FROM zv7_custord
         APPENDING TABLE G_T_ZV7_CUSTORD
         WHERE  SENDER in S_SENDER        and
                       STATUS = SPACE.
    * Sort the table key fields
    SORT G_T_ZV7_CUSTORD BY <KEY1> <KEY2> .....
    DELETE ADJACENT DUPLICATES FROM G_T_ZV7_CUSTORD COMPARING <KEY1> .....
    Max

  • Pointers: more efficient method(s), styles for making unconventional UI's

    i currently use mages on my custom panels to give the customized look i want for my apps. But i just can shake the feeling that there are more efficient ways to do it. i just need pointers to some materials (books, articles, documentation, etc) for some technology i can use.
    thanks!

    i currently use mages on my custom panels to give the customized look i want for my apps. But i just can shake the feeling that there are more efficient ways to do it. i just need pointers to some materials (books, articles, documentation, etc) for some technology i can use.
    thanks!

  • Making code faster smaller and more elegant

    hi just like yesterday I�m new to java. first of all I want to get familiar with the basics. I wrote a little game therefore. with some help. within the code are no mistakes, compiling errors or such. but now my question is why is my CPU usage nearly 75% when I run it. when the �h� ( Thread.sleep(h); ) is about 5 which makes the game faster but the CPU usage is 100%. Are there any possibilities to make the code faster? next question. are there any tricks to make the code more elegant or smaller? you know what I mean? it�s quite difficult for me to express what I want cause my English isn�t the best�
    what ever here is the code
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class BricksGame extends JFrame implements MouseListener, MouseMotionListener{
         private int mouseX, mouseY;
         double a = -3;
         int delta = 1;
         int beta = -3;
         int x_max = 288;
         int y_max = 320;
         int x_min = 0;
         int y_min = 0;          
         int x = 5;
         int y = 5;
         int b = y_max;
         int h = 15;
         int y_block = 80;
         int i;
         int x_point;
         int y_point =0;
         int punkte = 0;
         double k ;
         double r;
         int zahl = 1;
         boolean changed = true;     
         boolean gameNotOver = true;
         JPanel panelOben = new MyPanel();
         JPanel panelUnten = new JPanel();
         JLabel labelU1 = new JLabel();
         JLabel labelU2 = new JLabel("Punktestand: 0");
           JButton b1 = new JButton("restart");
         public  BricksGame(){
              setSize(400,600);
              setLocation(100,200);
              Dimension full = getSize();
              mouseX = full.width/2;
              mouseY = full.height/2;
              addMouseMotionListener(this);
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {System.exit(0);}
              panelOben.setLayout(null);
              //Ausrichtung der Elemente
              panelOben.setBounds(50, 50, 400, 500);
              panelUnten.addMouseMotionListener(this);
              panelUnten.setLayout(null);
                   //Ausrichtung der Elemente
              panelUnten.setSize(300, 100);          
              panelUnten.setBounds(50, 500, 300, 100);
              labelU1.setBounds(100,380,130,25);
              labelU2.setBounds(150,430,130,25);
              b1.setBounds(150,500, 80, 30);
              b1.addMouseListener(this);
              ImageIcon ii2 = new ImageIcon(getClass().getResource("TW1.gif"));
              labelU1.setIcon(ii2);
                   //Hinzuf�gen der Elemente
              panelUnten.add(labelU1);
              panelUnten.add(labelU2);
              panelUnten.add(b1);
              getContentPane().add(panelOben);
              getContentPane().add(panelUnten);
              setResizable(false);
              (new Mover()).start();
              setVisible(true);          
              validate();     
         public static void main (String[]args){
              BricksGame object = new BricksGame();     
         public void mousePressed (MouseEvent e) {}
         public void mouseReleased (MouseEvent e) {}
         public void mouseClicked (MouseEvent e) {
              restart();
         public void mouseEntered (MouseEvent e) {}
         public void mouseExited (MouseEvent e) {}
         public void mouseDragged (MouseEvent e) { }
         public void mouseMoved (MouseEvent e) {
              mouseX = e.getX();
              if (mouseX <= 85){
                   mouseX = 85;
              }else if (mouseX >= 319){
                   mouseX = 319;
              labelU1.setBounds(mouseX -35 ,380,70,25);
          * @author Haferberger
          * To change the template for this generated type comment go to
          * Window>Preferences>Java>Code Generation>Code and Comments
         class Mover extends Thread{
              public void run(){
                   while (gameNotOver){
                        try {Thread.sleep(h);}
                        catch (Exception e) {
    //                     TODO: handle exception
                        repaint();
          * @author Haferberger
          * To change the template for this generated type comment go to
          * Window>Preferences>Java>Code Generation>Code and Comments
         class MyPanel extends JPanel{
              public void paint(Graphics g){
                   if (y <= y_min && !changed){
    //                    System.out.println("up");     
                        //wie oft oben gegen     
                        i++;
                        //Koordinaten des G�nen Punktes
                        x_point =x_max -x;
                        y_point =0;
                        //Nach 5 mal oben gegen wird der Winkel ge�ndert
                        if (i%5==0){
                             zZahl();
                             alpha();
                        //Richtungs�nderung
                        a = -a;
                        b = (int)(y_min - a*x);
                        changed = true;     
                   }else if (y >= y_max && !changed){
    //                    System.out.println("down");                    
                        //Bei Ber�hrung unten wird der Block verschoben
                        if (y_block == 221){
                             beta = -beta;
                        }else if (y_block == 80){
                             beta = -beta;
                        y_block+= beta;
                        //Betimmen wo der Ball aufkommt
                        if (x + 5 >= mouseX - 84 && x + 5 <= mouseX -27 ){
    //                         System.out.println("Mitte");
                        }else if(x + 5 >= mouseX - 95 && x + 5 <= mouseX -85 ){
    //                         System.out.println("au�en links");
                             if(delta > 0){
                                  delta = -delta;
                                  a = -a;
                                  b = (int)(y_min - a*x);
                        }else if(x + 5 <= mouseX -16 && x + 5 >= mouseX -26 ){
    //                         System.out.println("au�en rechts");
                             if(delta < 0){
                                  delta = -delta;
                                  a = -a;
                                  b =(int)(y_min - a*x);
                        }else{
                             System.out.println("daneben");
                             gameNotOver=false;
                             a = -a;
                             b = (int)(y_max - a*x);
                        changed = true;
                   }else if (x >= x_max && !changed){
    //                    System.out.println("right");                                        
                        a = -a;
                        b = (int)(y - a*x_max);
                        delta = -delta;
                        changed = true;
                   }else if (x <= x_min && !changed){
    //                    System.out.println("left");
                        a = -a;
                        b = (int)(y - a*x_min);
                        delta = -delta;
                        changed = true;               
                   }else if (y == y_block && x>72 && x<216 && !changed){
    //                    System.out.println("Balken unten");
                        a = -a;
                        b = (int)(y - a*x);
                        changed = true;               
                   }else if (y == y_block+20 && x>72 && x<216 && !changed){
    //                    System.out.println("Balken oben");
                        a = -a;
                        b = (int)(y - a*x);
                        changed = true;               
                   }else{
                        changed = false;                    
                   g.setColor(Color.cyan);
                   g.fillRect(0, 0, 300, 330);
                   x+= delta;               
                   y = (int)(a*x + b);
                   g.setColor(Color.red);               
                   g.fillOval(x,y+5,10,10);
                   g.setColor(Color.magenta);
                   g.fillRect(72, y_block,144,20);
                   y_point+=2;
                   if(y_point==310){
                        y_point=500;
                        if(x_point + 5 >= mouseX - 94 && x_point + 5 <= mouseX -20 ){
                             punkte+=50;
                   g.setColor(Color.green);               
                   g.fillOval(x_point,y_point,20,20);
                   labelU2.setText("Punktestand: " + punkte);
                   labelU2.validate();
         public void zZahl(){
                   r = (Math.random() * 10);
                   zahl = (int)r%5 + 1;
         public void alpha(){
              switch(zahl){
                   case 4:
                        if (a<0){
                             a=-1;
                        }else if (a>0){
                             a=1;
                        if (delta<0){
                             delta=-4;
                        }else if (delta>0){
                             delta=4;
                        break;
                   case 3:
                        if (a<0){
                             a=-2;
                        }else if(a>0){
                             a=2;
                        if (delta<0){
                             delta=-4;
                        }else if(delta>0){
                             delta=4;
                        break;
                   case 5:
                        if (a<0){
                             a=-3;
                        }else if (a>0){
                             a=3;
                        if (delta<0){
                             delta=-1;
                        }else if (delta>0){
                             delta=1;
                        break;
                   case 2:
                        if (a<0){
                             a=-0.5;
                        }else if (a>0){
                             a=0.5;
                        if (delta<0){
                             delta=-4;
                        }else if (delta>0){
                             delta=4;
                        break;
                   case 1:
                        if (a<0){
                             a=-0.2;
                        }else if (a>0){
                             a=0.2;
                        if (delta<0){
                             delta=-5;
                        }else if (delta>0){
                             delta=5;
                        break;
         public void restart(){
              gameNotOver=true;
              y_block=80;
              beta = -3;
              x=mouseX;
              (new Mover()).start();
              punkte = 0;
              labelU2.validate();
    }thanks

    First of all, big friendly advice: split your code into few classes and methods. Currently your code looks very ugly.
    And one simple question: what is happening with Mover instance after restart? I don't see anything that stops old Mover thread instance before starting a new one...
    And so on...
    It is much simpler to answer your question when code is splited in small parts - problems then are located in small pieces of code.

  • Linking from one PDF to another: Is there a more efficient way?

    Some background first:
    We make a large catalog (400pages) in Indesign and it's updated every year. We are a wholesale distributor and our pricing changes so we also make a price list with price ref # that corresponded with #s printed in the main catalogue.  Last year we also made this catalog interactive so that a pdf of it could be browsed using links and bookmarks. This is not too difficult using Indesign and making any adjustments in the exported PDF. Here is the part that becomes tedious and is especially so this year:
    We also set up links in the main catalog that go to the price list pdf - opening the page with the item's price ref # and prices... Here's my biggest issue - I have not found any way to do this except making links one at a time in Acrobat Pro (and setting various specifications like focus and action and which page (in the price list) to open) Last year this wasn't too bad because we used only one price list. It still took some time to go through and set up 400-500 links individually.
    This year we've simplified our linking a little by putting only one link per page but that is still 400 links. And this year I have 6 different price lists (price tiers...) to link to the main catalogue pdf. (That's in the neighborhood of 1200-1500 double clicking the link(button) to open Button Properties, click Actions tab, click Add..."Go to page view" , set link to other pdf page, click edit, change Open in to "New Window" and set Zoom.  This isn't a big deal if you only have a few Next, Previous, Home kind of buttons....but it's huge when you have hundreds of links. Surely there's a better way?
    Is there anyway in Acrobat or Indesign to more efficiently create and edit hundreds of links from one pdf to another?
    If anything is unclear and my question doesn't make sense please ask. I will do my best to help you answer my questions.
    Thanks

    George, I looked at the article talking about the fdf files and it sounds interesting. I've gathered that I could manipulate the pdf links by making an fdf file and importing that into the PDF, correct?
    Now, I wondered - can I export an fdf from the current pdf and then change what is in there and import it back into the pdf.  I've tried this (Forms>More Form Options>Manage Form Data>Export Data) and then opened the fdf in a text editor but I see nothing related to the documents links... I assume this is because the links are 'form' data to begin with - but is there away to export something with link data like that described in the article link you provided?
    Thanks

  • More efficient way to extract number from string

    Hello guys,
    I am using this Regexp to extract numbers from a string, and I doubt that there is a more efficient way to get this done:
    SELECT  regexp_replace (regexp_replace ( REGEXp_REPLACE ('  !@#$%^&*()_+= '' + 00 SDFKA 324 000 8702 234 |  " ' , '[[:punct:]]',''), '[[:space:]]',''), '[[:alpha:]]','')  FROM dual
    {code}
    Is there a more efficient way to get this done ?
    Regards,
    Fateh                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Or, with less writing, using Perl syntax \D (non-digit):
    SELECT  regexp_replace('  !@#$%^&*()_+= '' + 00 SDFKA 324 000 8702 234 |  " ','\D')
      FROM  dual
    REGEXP_REPLACE(
    003240008702234
    SQL>
    {code}
    SY.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to make it more efficient

    Hi,
    I am working on AQ where I am just sending and receiving simple messages. But the performance is very poor. It takes around 35 seconds to send (enqueue) just 100 messages which is not acceptable for our project. Can someone help me how to make it more efficient. I am using JMS for sending and receiving messages.
    Thanks,
    Sateesh

    Bhagath,
    Thanks for your help.
    Oracle server we are using is 8.1.7. We are using JDBC client that ships with Oracle client (classes12.zip).
    Right now we are working on point to point messages.
    I am just wondering whether I need to do any tuning on server.
    Your help is greately appreciated.
    Here I am pasting sample code that I wrote which may help in finding the problem.
    Thank you so much once again for your help.
    -Sateesh
    import java.sql.*;
    import javax.jms.*;
    import java.io.*;
    import java.util.Properties;
    import oracle.AQ.*;
    import oracle.jms.*;
    public class CDRQueueSender {
    private final String DB_CONNECTION = "jdbc:oracle:thin:@dev1:1521:dev";
    protected final String DB_AQ_ADMIN_NAME = "dev78";
    private final String DB_AQ_ADMIN_PASSWORD = "dev78";
    /** DB AQ user agent name and password */
    private final String DB_AQ_USER_NAME = "dev78";
    private final String DB_AQ_USER_PASSWORD = "dev78";
    private QueueConnectionFactory queueConnectionFactory = null;
    private QueueConnection connection = null;
    private QueueSession session = null;
    private Queue sendQueue;
    private QueueSender qSender;
    public CDRQueueSender() {
    try {
    Properties info = new Properties();
    info.put(DB_AQ_USER_NAME, DB_AQ_USER_PASSWORD);
    queueConnectionFactory = AQjmsFactory
    .getQueueConnectionFactory(DB_CONNECTION, info);
    connection = queueConnectionFactory.
    createQueueConnection(DB_AQ_USER_NAME,
    DB_AQ_USER_PASSWORD);
    session = connection.createQueueSession(
    true, Session.AUTO_ACKNOWLEDGE);
    connection.start();
    sendQueue = ((AQjmsSession) session).getQueue (DB_AQ_ADMIN_NAME,"CDR_QUEUE");
    qSender = session.createSender(sendQueue);
    catch (Exception ex) {
    ex.printStackTrace();
    public boolean sendCDRMessage(CDRMessage messageData)
    throws JMSException, SQLException {
    ObjectMessage objectMessage = session.createObjectMessage(messageData);
    try {
    qSender.send(objectMessage);
    session.commit();
    catch (Exception e) {
    System.out.println(e.getMessage());
    e.printStackTrace();
    return true;
    public void close() throws JMSException {
    session.close();
    connection.close();
    public static void main(String[] args) throws SQLException, JMSException {
    int count = 0;
    CDRQueueSender qSender = new CDRQueueSender();
    long startTime = System.currentTimeMillis();
    long endTime;
    CDRMessage message;
    while(count < 100) {
    message = new CDRMessage("filename", 20, "This is testing", count);
    qSender.sendCDRMessage(message);
    count++;
    //qSender.sessionCommit();
    endTime = System.currentTimeMillis();
    System.out.println("time taken to process 100 records is " +
    ((endTime - startTime)/1000) + " seconds");
    qSender.close();

  • Can you write this program more efficiently?

    Hello :)
    I am trying to write a program that does the following:
    "The prime factors of 13195 are 5, 7, 13 and 29.
    What is the largest prime factor of the number 317584931803?"
    Since we are dealing with such a huge number, I've used the BigInteger class to handle it. But the problem is, the following code is inefficient..... I mean, its been calculating for the past 2.5 hours ;( I its still only on the 8th digit. I was wondering if someone could write this more efficiently?
    import java.math.*;
    public class euler6 {
         public static void main (String arhs[]){
               BigInteger a[]=new BigInteger[999];
               int j=0;
               BigInteger bi = new BigInteger("317584931803"); //*********
               BigInteger i=new BigInteger("2");
               final BigInteger one=new BigInteger("1");     
               final BigInteger zero=new BigInteger("0");     
               boolean state     ;
         for(;i.compareTo(bi)==-1;i=i.add(one))
              { //System.out.println(i);
                //System.out.println(bi.mod(i)+"*");
                //System.out.println(bi.mod(i).equals(zero)+"**");
                   if ((bi.mod(i).equals(zero))&& (findPrime(i)))
                        {a[j]=i;
                         j++;}
         for(int f=0;f<a.length;f++)
              System.out.print(a[f]+" ");
         public static boolean findPrime(BigInteger n){
                   final BigInteger one=new BigInteger("1");
                   final BigInteger zero=new BigInteger("0");
                   BigInteger x=new BigInteger("2");
                   for(;n.divide(x).compareTo(one)==1;x=x.add(one))
                        if (n.mod(x).equals(zero))          
                             return false;
                        return true;

    Hi,
    I agree with prev poster, you don't have to use BigInteger since long is sufficient.
    Try this, more optimized than initial version, yet still using brute force ... The drawback is, if the given number 317584931803 is a prime number .. then ... it will also take 24 hours to compute ... can't help that.
    My idea is, let's say I have number 30.
    So, I will search all possibility between 2 to 15. My reason is the factor will not exceed from 30 div 2 which is 15.
    While doing brute, I will decrease the iteration boundary.
    Eg:
    - 30 is succesfully devided by 2, then iteration will stop bruting force up to iteration #15.
    - next iteration, 30 is succesfully devided by 3, then iteration will stop bruting force up to iteration #10.
    - next iteration, 30 is succesfully devided by 5, then iteration will stop bruting force up to iteration #6.
    So, total there is only 4 iterations to check the factor of 30. And I get these number: 2, 15, 3, 10, 5, 6
    The next step would be checking which of the numbers are prime, and we get 2, 3, and 5.
    My algorithm is something like this:
    import java.util.*;
    public class PF // stands from Prime Factors ..
    public static void main(String s[]) throws Exception {
            long num = 317584931803l;
            List factors = new ArrayList(255);
            long div2 = (long) (num / 2);
            for (int i=2; i<=div2; i++) {
                    if (num % i == 0) {
                            div2 = (int) (num / i);
                            factors.add(new Long(i));
                            factors.add(new Long(div2));
                    Thread.yield();
            Iterator iter = factors.iterator();
            while (iter.hasNext()) {
                    long factor =  ((Long) iter.next()).longValue();
                    if (isPrime(factor)) {
                            System.out.println(factor);
    static boolean isPrime(long num) throws Exception {
            long div2 = (long) (num / 2);
            for (int i=2; i<div2; i++)  {
                    if (num % i == 0) return false;
                    Thread.yield();
            return true;
    }The reason I put Thread.yield() is so it won't hang your machine ... this happens if the big number you test is a prime number...
    My machine (Intel pentium III 700 MHz, 512 MB SDRAM) takes less than 1 second to compute ... ;-)
    Alex

  • MDX - More efficient way?

    Hi
    I am still learning MDX and have written this code. It needs to recalculate all employees in a cost center (COSTCENTER is a property of the DIM EMPLOYEE) when one of the assumptions (e.g P00205 etc) change. These assumptions are planned on cost center level and planned against employee DUMMY. Is there a more efficient way to write this code as there are lots of accounts that needs to be posted to::
    *SELECT (%EMPLOYEE%, ID, EMPLOYEE, [COSTCENTER]  = %COSTCENTER_SET%)
    //Workmens Comp
    *XDIM_MEMBERSET P_ACCT = "IKR0000642000"
    *FOR %EMP% = %EMPLOYEE%   
             [EMPLOYEE].[#%EMP%] = ( [P_ACCT].[P00205],[EMPLOYEE].[DUMMY ]) * ( [P_ACCT].[P00400],[EMPLOYEE].[%EMP%] )
    *NEXT
    *COMMIT
    //Fringe Benefits Employer
    *XDIM_MEMBERSET P_ACCT = "IKR0000628100" 
    *FOR %EMP% = %EMPLOYEE%
             [EMPLOYEE].[#%EMP%] = ( [P_ACCT].[P00210],[EMPLOYEE].[DUMMY ]) * ( [P_ACCT].[P00400],[EMPLOYEE].[%EMP%] )
    *NEXT
    *COMMIT
    //Fringe Benefits Other
    *XDIM_MEMBERSET P_ACCT = "IKR0000626100" 
    *FOR %EMP% = %EMPLOYEE%
             [EMPLOYEE].[#%EMP%] = ( [P_ACCT].[P00209],[EMPLOYEE].[DUMMY ]) * ( [P_ACCT].[P00400],[EMPLOYEE].[%EMP%] )
    *NEXT
    *COMMIT

    Maybe the following?
    *SELECT (%EMPLOYEE%, ID, EMPLOYEE, [COSTCENTER]  = %COSTCENTER_SET%)
    *XDIM_MEMBERSET EMPLOYEE = %EMPLOYEE%
    *XDIM_MEMBERSET P_ACCT = IKR0000642000,IKR0000628100,IKR0000626100
    //Workmens Comp
    [P_ACCT].[#IKR0000642000] = ( [P_ACCT].[P00205],[EMPLOYEE].[DUMMY] ) * ( [P_ACCT].[P00400] )
    //Fringe Benefits Employer
    [P_ACCT].[#IKR0000628100] = ( [P_ACCT].[P00210],[EMPLOYEE].[DUMMY] ) * ( [P_ACCT].[P00400] )
    //Fringe Benefits Other
    [P_ACCT].[#IKR0000626100] = ( [P_ACCT].[P00209],[EMPLOYEE].[DUMMY] ) * ( [P_ACCT].[P00400] )
    *COMMIT
    You should probably also restrict explicitly on all other dimensions in your applications so that none are accidentally left open that don't need to be.
    Ethan

Maybe you are looking for

  • Multiple admin accounts, need to delete one of them ... what happens?

    Ok, short story shorter - broke up with my GF and she has an account on my laptop. She has saved all her stuff, so I'm not worried about loosing personal files/documents. My question is though, what else may be lost that I should be careful of. • Wil

  • How to hide the cursor in text entry boxes

    I didn't see this answer in the forum, and it took a while to figure this out so I thought I'd post my solution. The issue is that a question requires that the user know where to click before typing, then type the correct value. The problem is that a

  • Intercompany Sales for 3 companies

    Hi All Expert, I am now facing big problem in setting of Intercompany sales. Now I want to set a new Company C, with Sales and Bill to Oversea customer, but goods are purchased from Company B, and the goods are produced by Company A and Ship to Custo

  • SRM 7.0 / NW 7.01 SR1 upgrade SP levels - Note 819722

    Hi, I'm preparing for an upgrade to SRM 7.0 / NW 7.01 SR1, and I want to include the latest SP Stack.  I need to know what SP level the upgrade delivers, so I can download just the delta SP Stacks rather than all of them. The upgrade guide states tha

  • I am unable to change my id successfully -

    I have had to change my id repeatedly. Maybe it is because the computer is registered under my husband's name? It keeps rejecting the id and password. It becomes a stalemate for me in shifting to icloud, ordering from itunes, etc. I have to keep an o