ARRAY constructor is slow

I am developing some code to call some stored procdures that have been developed by a customer. They require us to initialize an empty 2D array and send it into the procedure.
I noticed that the bigger I make the array, the slower the constructor takes to execute.
ARRAY[][] elems = new ARRAY[ 1 ][ 16 ]; => 1-2 seconds
ARRAY[][] elems = new ARRAY[ 10 ][ 16 ]; => 9-10 seconds
These aren't huge arrays, so I am wondering if there is anything I can do to increase performance?
ArrayDescriptor desc =
               ArrayDescriptor.createDescriptor( "APPS.L_CUSTOMER_ARRAY", conn.getConnection() );
ARRAY[][] elems = new ARRAY[ 1 ][ 16 ];
ARRAY newArray = new ARRAY( desc, conn.getConnection(), elems );=> this is really slow!
Thanks!

What language are you programming in? that doesn't look like PL/SQL.
cheers, APC

Similar Messages

  • Initializing array constructor to 0

    I have created a stats class, but I am not sure how to initialize the array constructor to be all zeros. It is a single interger array that can hold 50 values.

    int[] array = new int[50];Each array element will be initialized to zero.
    The Java� Tutorial - Arrays

  • Query with parameter as Array (UDT) very slow

    Hi.
    I have following Problem. I try to use Oracle Instant Client 11 and ODP.NET to pass Arrays in SELECT statements as Bind Parameters. I did it, but it runs very-very slow. Example:
    - Inittial Query:
    SELECT tbl1.field1, tbl1.field2, tbl2.field1, tbl2.field2 ... FROM tbl1
    LEFT JOIN tbl2 ON tbl1.field11=tbl2.field0
    LEFT JOIN tbl3 ON tbl2.field11=tbl3.field0 AND tbll1.field5=tbl3.field1
    ...and another LEFT JOINS
    WHERE
    tbl1.field0 IN ('id01', 'id02', 'id03'...)
    this query with 100 elements in "IN" on my database takes 3 seconds.
    - Query with Array bind:
    in Oracle I did UDT: create or replace type myschema.mytype as table of varchar2(1000)
    than, as described in Oracle Example I did few classes (Factory and implementing IOracleCustomType) and use it in Query,
    instead of IN ('id01', 'id02', 'id03'...) I have tbl1.field0 IN (select column_value from table(:prmTable)), and :prmTable is bound array.
    this query takes 190 seconds!!! Why? I works, but the HDD of Oracle server works very hard, and it takes too long.
    Oracle server we habe 10g.
    PS: I tried to use only 5 elements in array - the same result, it takes also 190 seconds...
    Please help!

    I did (some time ago and it was a packaged procedure) something like
    Procedure p(p_one in datatype,p_two in datatype,p_dataset out sys_refcursor) is
      the_sql varchar2(32000);
      the_cursor sys_refcursor;
    begin
      the_sql = 'WITH NOTIFICACAO AS( ' ||
                '      SELECT ' ||
                '       t1.cd_consultora, ' ||
                '                               where       t1.dt_notificacao_cn >= to_date(''01/09/2006'',''dd/mm/yyyy'') ' ||  -- note the ''
                '           where rownum <= :W_TO_REC) ' ||   -- parameter 1
                '         where r_linha >= :W_FROM_REC ';     -- parameter 2
      open the_cursor for the_sql using p_one,p_two;  -- just by the book
    end p;if I remember correctly
    Regards
    Etbin

  • Consumer loop very slow, queue size grows. How to speed up my consumer loop? As the array grows the slower it gets.

    LabView version: 2012
    OS: Windows XP SP3
    Hardware: USB NI cDAQ-9174 NI-9221
    Application: Oscilloscope
    I'm relatively new to LabView and I'm currently experiencing some performance issues with my project. I guess it has something to do with the way it's programmed. I'm hoping to get some tips from you guys.
    This is my producer loop. It should be capable of acquiring 100 000 Samples/s. I guess I've done this the right way and can't really be improved. Or am I mistaking?
    This is (part of) my consumer loop. It's too slow, the number of elements in the queue keeps getting bigger. I'm doing two types of calculations on the queue data. One for changing the scalling (a multiplication), one for changing the y-position (a summation). Because each time there are 10 000 samples acquired I have added an extra loop (inner loop). This loop splits the array into x samples when the requested samples are smaller than 10 000 or adds them when the requested samples are bigger than 10 000. This depends on the user input (time/dev).
    For example: when the user request 100 seconds of data to be plotted on a graph we get an array of 10 000 000 x 8. Is this considered big? Enlarging the array to that size is very very slow, the queue builds up rapidly.
    I don't know what really slows it down or how to 'debug' this properly. Transposing the array twice seems avoidable?
    Maybe I'm doing this in an inefficient way? Any thoughts that might help me?
    The VI's are attached.
    Thanks for your input.
    Attachments:
    Scope.zip ‏199 KB

    Thank you for your replies so far!
    LV_Pro,
    I agree it is a bit silly to plot more than 2000 points. I will change this. But even without a graph, the consumer loop seems to be unable to handle the speed.
    tst,
    1. Ok, I will change this
    2. Thank you for pointing this out. I implemented your technique and have some increased performance.
    Still not the speed I would expect from LabView. The system is 'stable' with a sample rate up to 100 Hz, increasing this makes my queue overflow.
    I must be doing something else wrong... Anymore ideas?
    Latest version of program in attachment.
    Attachments:
    Scope 1.zip ‏211 KB

  • Fill array is to slow

    hello,
    in the attachement there is an example.
    in this example i've got an array where i want to insert values at column 4.
    the attached vi works, but my array can contain 40000 rows.
    this takes minutes for the calculation.
    is there a way to make this vi faster?
    markus
    Attachments:
    Test.vi ‏24 KB

    Yes for speed purposes, you should initialize an array and index calculate and replace elements in a loop. This looks less elegent than just calculating and building an array but is much faster since you are not reallocating memory and copying the array as much. The downfall is that you will have to preallocate a known amount of memory for the array when initialized. You give up the nice dynamic nature of array processing but will get a speed boost in return. You also sometimes have to allocate large amounts of memory to make sure that you have enough room in your array to store all your points but memory is practically free (for most arrays you still only need a few MB at most). Also make sure you are optimized in your processing algorithms (ie move any calculations which are constant in respect to index outside of the calculation loop). One final trick which is possible on hyperthreaded systems (Newer CPU & LV 7.1+) is to split your array in to two parts and process each half in its own parallel loop. Warning that a non hyperthreaded complient system will take a speed hit (might be significant) since there will be a large amount of context switching added to your overhead. In the near future we will be seeing a greater degree of multithreaded and multi-core CPU becoming mainstream so you can keep this in mind if you are developing longterm applications. (if all else fails you can write the process algorithm in c++ and call the .dll from labview, but I will probably be ousted from the Labview community for suggesting such a 'stupid' fix).
    -Paul
    Paul Falkenstein
    Coleman Technologies Inc.
    CLA, CPI, AIA-Vision
    Labview 4.0- 2013, RT, Vision, FPGA

  • Two array objects compareTo:

    Have two arrays: ttt and ppp. I have to have a method to compare them.
    public int compareTo(object ob)
    both of the arrays are int type and both have super long numbers in them.
    Thanks

    Actually, the reflection api is pretty fast since
    JDK1.4.0...No. Reflection could not be fast. In J2SDK1.4 it seems to be faster then in previous releases. But improvments do not include array operations. So here are some results of simple benchmark:
    bash-2.05a$ /usr/java/jdk1.3.1_04/bin/java TestArray
    Result for reflect copiing (3 elements, 1000000 times): 4915ms
    Result for system copiing (3 elements, 1000000 times): 460ms
    Result for pure java copiing (3 elements, 1000000 times): 137ms
    bash-2.05a$
    bash-2.05a$ /usr/java/j2sdk1.4.0_01/bin/java TestArray
    Result for reflect copiing (3 elements, 1000000 times): 6082ms
    Result for system copiing (3 elements, 1000000 times): 491ms
    Result for pure java copiing (3 elements, 1000000 times): 115ms
    bash-2.05a$
    bash-2.05a$ /usr/java/j2sdk1.4.1/bin/java TestArray
    Result for reflect copiing (3 elements, 1000000 times): 5738ms
    Result for system copiing (3 elements, 1000000 times): 497ms
    Result for pure java copiing (3 elements, 1000000 times): 157ms
    bash-2.05a$
    As you can see, in new Java reflect operations on arrays are even slower then in jdk1.3.1. System copiing is good alternative for pure java (element by element) copiing, espetially for big arrays. And here is the code of this benchmark, test it on your PC also:
    import java.lang.reflect.*;
    public class TestArray {
        static void doNothing(){}
        static int field;
        public static void main(String[] args) throws Exception {
            final int COUNT = 3, TIMES = 1000*1000;
            final String[] arr1 = new String[COUNT];
            final String[] arr2 = new String[COUNT];
                long time = -System.currentTimeMillis();
                for(int i=TIMES; i-->0;)
                    copyReflect(arr1, arr2, COUNT);
                time += System.currentTimeMillis();
                System.out.println("Result for reflect copiing ("+COUNT+" elements, "+TIMES+" times): "+time+"ms");
                long time = -System.currentTimeMillis();
                for(int i=TIMES; i-->0;)
                    copySystem(arr1, arr2, COUNT);
                time += System.currentTimeMillis();
                System.out.println("Result for system copiing ("+COUNT+" elements, "+TIMES+" times): "+time+"ms");
                long time = -System.currentTimeMillis();
                for(int i=TIMES; i-->0;)
                    copyPureJava(arr1, arr2, COUNT);
                time += System.currentTimeMillis();
                System.out.println("Result for pure java copiing ("+COUNT+" elements, "+TIMES+" times): "+time+"ms");
        private static void copyReflect(Object src, Object dst, int count) {
            for(int i=count; i-->0; ) Array.set(dst, i, Array.get(src, i));
        private static void copySystem(Object src, Object dst, int count) {
            System.arraycopy(src, 0, dst, 0, count);
        private static void copyPureJava(String[] src, String[] dst, int count) {
            for(int i=count; i-->0; ) dst[i] = src;

  • What is the best way of dealing with an "implicit coercion" of an array to a sprite?

    Hello everyone!
         With continued help from this forum I am getting closer to having a working program. I look forward to being able to help others like myself once I finish learning the AS3 ropes.
         I will briefly explain what I am trying to achieve and then follow it up with my question.
    Background
         I have created a 12 x 9 random number grid that populates each cell with a corresponding image based on each cell's numeric value. I have also created a shuffle button that randomizes the numbers in the grid. The problem I am running into is getting my button-click event to clear the current images off the grid in order to assign new ones (i.e. deleting the display stack objects in order to place news ones in the same locations).
    Question
         My question is this: what is the best way to handle an implicit coercion from an array to a sprite? I have pasted my entire code below so that you can see how the functions are supposed to work together. My trouble apparently lies with not being able to use an array value with a sprite (the sprite represents the actual arrangement of the grid on the display stack while the array starts out as a number than gets assigned an image which should be passed to the sprite).
    ============================================================================
    package 
    import flash.display.MovieClip;
    import flash.display.DisplayObject;
    import flash.events.MouseEvent;
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFormat;
    import flash.utils.getDefinitionByName;
    public class Blanko extends MovieClip
          // Holds 12*9 grid of cells.
          var grid:Sprite;
          // Holds the shuffle button.
          var shuffleButton:Sprite;
          // Equals 12 columns, 9 rows.
          var cols:int = 12;
          var rows:int = 9;
          // Equals number of cells in grid (108).
          var cells:int = cols * rows;
          // Sets cell width and height to 40 pixels.
          var cellW:int = 40;
          var cellH:int = 40;
          // Holds 108 cell images.
          var imageArray:Array = [];
          // Holds 108 numerical values for the cells in the grid.
          var cellNumbers:Array = [];
          // Constructor calls "generateGrid" and "makeShuffleButton" functions.
          public function Blanko()
               generateGrid();
               makeShuffleButton();
      // Creates and displays the 12*9 grid.
      private function generateGrid():void
           grid = new Sprite;
           var i:int = 0;
           for (i = 0; i < cells; i++)
                cellNumbers.push(i % 9 + 1);
           trace("Before shuffle: ", cellNumbers);
           shuffleCells(cellNumbers);
           trace("After shuffle: ", cellNumbers);
           var _cell:Sprite;
           for (i = 0; i < cells; i++)
                // This next line is where the implicit coercion occurs. "_cell" is a sprite that tries
                   to temporarily equal an array value.
                _cell = drawCells(cellNumbers[i]);
                _cell.x = (i % cols) * cellW;
                _cell.y = (i / cols) * cellH;
                grid.addChild(_cell);
      // Creates a "shuffle" button and adds an on-click mouse event.
      private function makeShuffleButton():void
           var _label:TextField = new TextField();
           _label.autoSize = "center";
           TextField(_label).multiline = TextField(_label).wordWrap = false;
           TextField(_label).defaultTextFormat = new TextFormat("Arial", 11, 0xFFFFFF, "bold");
           _label.text = "SHUFFLE";
           _label.x = 4;
           _label.y = 2;
           shuffleButton = new Sprite();
           shuffleButton.graphics.beginFill(0x484848);
           shuffleButton.graphics.drawRoundRect(0, 0, _label.width + _label.x * 2, _label.height +
                                                _label.y * 2, 10);
           shuffleButton.addChild(_label);
           shuffleButton.buttonMode = shuffleButton.useHandCursor = true;
           shuffleButton.mouseChildren = false;
           shuffleButton.x = grid.x + 30 + grid.width - shuffleButton.width;
           shuffleButton.y = grid.y + grid.height + 10;
           this.addChild(shuffleButton);
           shuffleButton.addEventListener(MouseEvent.CLICK, onShuffleButtonClick);
      // Clears cell images, shuffles their numbers and then assigns them new images.
      private function onShuffleButtonClick():void
       eraseCells();
       shuffleCells(cellNumbers);
       trace("After shuffle: ", cellNumbers);
       for (var i:int = 0; i < cells; i++)
        drawCells(cellNumbers[i]);
      // Removes any existing cell images from the display stack.
      private function eraseCells(): void
       while (imageArray.numChildren > 0)
        imageArray.removeChildAt(0);
      // Shuffles cell numbers (randomizes array).
      private function shuffleCells(_array:Array):void
       var _number:int = 0;
       var _a:int = 0;
       var _b:int = 0;
       var _rand:int = 0;
       for (var i:int = _array.length - 1; i > 0; i--)
        _rand = Math.random() * (i - 1);
        _a = _array[i];
        _b = _array[_rand];
        _array[i] = _b;
        _array[_rand] = _a;
      // Retrieves and assigns a custom image to a cell based on its numerical value.
      private function drawCells(_numeral:int):Array
       var _classRef:Class = Class(getDefinitionByName("skin" + _numeral));
       _classRef.x = 30;
       imageArray.push(_classRef);
       imageArray.addChild(_classRef);
       return imageArray;
    ===========================================================================
         Any help with this is greatly appreciated. Thanks!

    Rothrock,
         Thank you for the reply. Let me address a few things here in the hopes of allowing you (and others) to better understand my reasoning for doing things in this manner (admittedly, there is probably a much better/easier approach to what I am trying to accomplish which is one of the things I hope to learn/discover from these posts).
         The elements inside my "imageArray" are all individual graphics that I had imported, changed their type to movie clips using .Sprite as their base class (instead of .MovieClip) and then saved as classes. The reason I did this was because the classes could then be referenced via "getDefinitionByName" by each cell value that was being passed to it. In this grid every number from 1 to 9 appears randomly 12 times each (making the 108 cells which populate the grid). I did not, at the time (nor do I now), know of a better method to implement for making sure that each image appears in the cell that has the corresponding value (i.e. every time a cell has the value of 8 then the custom graphic/class "skin8" will be assigned to it so that the viewer will be able to see a more aesthetically pleasing numerical representation, that is to say a slightly more fancy looking number with a picture behind it). I was advised to store these images in an array so that I could destroy them when I reshuffle the grid in order to make room for the new images (but I probably messed up the instructions).
         If the "drawCell" function only returns a sprite rather than the image array itself, doesn't that mean that my "eraseCells" function won't be able to delete the array's children as their values weren't first returned to the global variable which my erasing function is accessing?
         As for the function name "drawCells," you have to keep in mind that a) my program has been redesigned in stages as I add new functionality/remove old functionality (such as removing text labels and formatting which were originally in this function) and b) that my program is called "Blanko."
         I will try and attach an Illustrator exported JPG file that contains the image I am using as the class "skin7" just to give you an example of what I'm trying to use as labels (although it won't let me insert it here in this post, so I will try it in the next post).
    Thank you for your help!

  • Using arrays as type for bind variable

    Hi all,
    I have this stored procedures that takes an array of strings as an argument:
    CREATE OR REPLACE PACKAGE mypackage AS
    TYPE StringArray IS VARRAY(100) OF VARCHAR2(16);
    PROCEDURE doSomething(v_strings IN StringArray);
    END;
    My java code looks something like:
    String[] strings = ...;
    CallableStatement cs = connection.prepareCall("CALL mypackage.doSomething(?)");
    cs.setObject(1, strings, java.sql.Types.ARRAY);
    calling the setObject method throws a SQLException: invalid column type.
    I have tried to change the call to:
    cs.setArray(1, new SqlStringArray(strings))
    where SqlStringArray is a wrapper around String[] that implements the java.sql.Array interface. This however throws a ClassCastException in oracle.jdbc.driver.OraclePreparedStatement. The latter is assuming it is receiving a class that implements yet another interface I guess.
    I also tried:
    cs.setObject(1, strings, java.sql.Types.VARCHAR);
    but that also throws a SqlException: invalid conversion requested
    Does anybody know how to bind String[] into a PreparedStatement?
    Any help is appreciated.
    Rudi.

    Made some progress. I am getting the OracleConnection from the WrappedConnection. This is a temporary solution for me so I would appreciate a final solution from anybody.
    I am now constructing a oracle.sql.ARRAY with an appropriate oracle.sql.ArrayDescriptor. I have found out that the type must be defined on a global level rather than in the scope of the package. Would be good if an Oracle expert could confirm that but I am happy to live with that.
    The IN parameter is correctly bound using the ARRAY instance but I am getting the following error when actually executing the statement:
    ORA-06512: Reference to uninitialized collection: at "BLUETEST_MYPACKAGE", line 57
    Now I have found quite some problem descriptions with that ORA error but all are dealing with OUT parameters that were not correctly initialized, i.e. the array constructor had not been called. In my case however, the array is initialized at by the java code and then bount to the sql statement. You would expect that the jdbc driver takes care of correctly initializing the PL/SQL collection wouldn't you.
    Does anybody know if I need to do anything extra?
    Many thanks,
    Rudi.

  • Object in array list

    Is it possible that object can be store in array list.
    package{
    // Importing object from flash libary
        import flash.text.TextField;
        import flash.display.Sprite;
    // Creating class
         public class Show extends Sprite {
         //Attribute
        private var txt:Array = new Array();
         // Constructor 
           function Show()
                   txt[0]:TextField =  new TextField();
                     addChild(txt[0]);
                     txt[0].width=320;
                     txt[0].height=25;
                     txt[0].x=0;
                     txt[0].y=0;
                     txt[0].border=true;
                   txt[0].text="nepalikto";
    Error
    Description : Label must be a simple identifier
    Location : Above orange textcolor line

    Not sure if this all is 100% technically correct but:
    You only use datatyping if you actually create a variable. Like:
    var myArray:Array = new Array();
    if you do not declare the var with the var keyword, you can't use datatyping either.
    // this is wrong
    myArray:Array = new Array()
    It is good practice to use datatyping whenever possible since it can help you debug an application:
    Flash finds the possible errors in code where one variable contains different datatypes at different times which can be confusing
    Flash helps with the codecompletion feature once a variable is typed so there's less chance of typos.
    The items in the array, unlike CS4's new Vector datatype aren't typed. Probably has some memory usage reason in the onderlying C++ code but I'm not sure. If you have CS4 you could possibly use:
    var txt:Vector.<TextField> = new Vector.<TextField>();
    To tell you the truth I haven't used the CS4 Vector Datatype so I'm not sure if aside from faster code execution there's errorcheckings on it's contents like mentioned above.
    Hope this helps some

  • Passing Array of java objects to and from oracle database-Complete Example

    Hi all ,
    I am posting a working example of Passing Array of java objects to and from oracle database . I have struggled a lot to get it working and since finally its working , postinmg it here so that it coudl be helpful to the rest of the folks.
    First thinsg first
    i) Create a Java Value Object which you want to pass .
    create or replace and compile java source named Person as
    import java.sql.*;
    import java.io.*;
    public class Person implements SQLData
    private String sql_type = "PERSON_T";
    public int person_id;
    public String person_name;
    public Person () {}
    public String getSQLTypeName() throws SQLException { return sql_type; }
    public void readSQL(SQLInput stream, String typeName) throws SQLException
    sql_type = typeName;
    person_id = stream.readInt();
    person_name = stream.readString();
    public void writeSQL(SQLOutput stream) throws SQLException
    stream.writeInt (person_id);
    stream.writeString (person_name);
    ii) Once you created a Java class compile this class in sql plus. Just Copy paste and run it in SQL .
    you should see a message called "Java created."
    iii) Now create your object Types
    CREATE TYPE person_t AS OBJECT
    EXTERNAL NAME 'Person' LANGUAGE JAVA
    USING SQLData (
    person_id NUMBER(9) EXTERNAL NAME 'person_id',
    person_name VARCHAR2(30) EXTERNAL NAME 'person_name'
    iv) Now create a table of Objects
    CREATE TYPE person_tab IS TABLE OF person_t;
    v) Now create your procedure . Ensure that you create dummy table called "person_test" for loggiing values.
    create or replace
    procedure give_me_an_array( p_array in person_tab,p_arrayout out person_tab)
    as
    l_person_id Number;
    l_person_name Varchar2(200);
    l_person person_t;
    l_p_arrayout person_tab;
    errm Varchar2(2000);
    begin
         l_p_arrayout := person_tab();
    for i in 1 .. p_array.count
    loop
         l_p_arrayout.extend;
         insert into person_test values(p_array(i).person_id, 'in Record '||p_array(i).person_name);
         l_person_id := p_array(i).person_id;
         l_person_name := p_array(i).person_name;
         l_person := person_t(null,null);
         l_person.person_id := l_person_id + 5;
         l_person.person_name := 'Out Record ' ||l_person_name ;
         l_p_arrayout(i) := l_person;
    end loop;
    p_arrayout := l_p_arrayout;
         l_person_id := p_arrayout.count;
    for i in 1 .. p_arrayout.count
    loop
    insert into person_test values(l_person_id, p_arrayout(i).person_name);
    end loop;
    commit;
    EXCEPTION WHEN OTHERS THEN
         errm := SQLERRM;
         insert into person_test values(-1, errm);
         commit;
    end;
    vi) Now finally create your java class which will invoke the pl/sql procedure and get the updated value array and then display it on your screen>Alternatively you can also check the "person_test" tbale
    import java.util.Date;
    import java.io.*;
    import java.sql.*;
    import oracle.sql.*;
    import oracle.jdbc.driver.*;
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    public class ArrayDemo
    public static void passArray() throws SQLException
    Connection conn = getConnection();
    ArrayDemo a = new ArrayDemo();
    Person pn1 = new Person();
    pn1.person_id = 1;
    pn1.person_name = "SunilKumar";
    Person pn2 = new Person();
    pn2.person_id = 2;
    pn2.person_name = "Superb";
    Person pn3 = new Person();
    pn3.person_id = 31;
    pn3.person_name = "Outstanding";
    Person[] P_arr = {pn1, pn2, pn3};
    Person[] P_arr_out = new Person[3];
    ArrayDescriptor descriptor =
    ArrayDescriptor.createDescriptor( "PERSON_TAB", conn );
    ARRAY array_to_pass =
    new ARRAY( descriptor, conn, P_arr);
    OracleCallableStatement ps =
    (OracleCallableStatement )conn.prepareCall
    ( "begin give_me_an_array(?,?); end;" );
    ps.setARRAY( 1, array_to_pass );
         ps.registerOutParameter( 2, OracleTypes.ARRAY,"PERSON_TAB" );
         ps.execute();
         oracle.sql.ARRAY returnArray = (oracle.sql.ARRAY)ps.getArray(2);
    Object[] personDetails = (Object[]) returnArray.getArray();
    Person person_record = new Person();
    for (int i = 0; i < personDetails.length; i++) {
              person_record = (Person)personDetails;
              System.out.println( "row " + i + " = '" + person_record.person_name +"'" );
                        public static void main (String args[]){
         try
                             ArrayDemo tfc = new ArrayDemo();
                             tfc.passArray();
         catch(Exception e) {
                        e.printStackTrace();
              public static Connection getConnection() {
         try
                             Class.forName ("oracle.jdbc.OracleDriver");
                             return DriverManager.getConnection("jdbc:oracle:thin:@<<HostNanem>>:1523:VIS",
                             "username", "password");
         catch(Exception SQLe) {
                        System.out.println("IN EXCEPTION BLOCK ");
                        return null;
    and thats it. you are done.
    Hope it atleast helps people to get started. Comments are appreciated. I can be reached at ([email protected]) or [email protected]
    Thanks
    Sunil.s

    Hi Sunil,
    I've a similar situation where I'm trying to insert Java objects in db using bulk insert. My issue is with performance for which I've created a new thread.
    http://forum.java.sun.com/thread.jspa?threadID=5270260&tstart=30
    I ran into your code and looked into it. You've used the Person object array and directly passing it to the oracle.sql.ARRAY constructor. Just curios if this works, cos my understanding is that you need to create a oracle.sql.STRUCT out of ur java object collection and pass it to the ARRAY constructor. I tried ur way but got this runtime exception.
    java.sql.SQLException: Fail to convert to internal representation: JavaBulkInsertNew$Option@10bbf9e
                        at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
                        at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
                        at oracle.jdbc.oracore.OracleTypeADT.toDatum(OracleTypeADT.java:239)
                        at oracle.jdbc.oracore.OracleTypeADT.toDatumArray(OracleTypeADT.java:274)
                        at oracle.jdbc.oracore.OracleTypeUPT.toDatumArray(OracleTypeUPT.java:115)
                        at oracle.sql.ArrayDescriptor.toOracleArray(ArrayDescriptor.java:1314)
                        at oracle.sql.ARRAY.<init>(ARRAY.java:152)
                        at JavaBulkInsertNew.main(JavaBulkInsertNew.java:76)
    Here's a code snippet I used :
    Object optionVal[] =   {optionArr[0]};   // optionArr[0] is an Option object which has three properties
    oracle.sql.ArrayDescriptor empArrayDescriptor = oracle.sql.ArrayDescriptor.createDescriptor("TT_EMP_TEST",conn);
    ARRAY empArray = new ARRAY(empArrayDescriptor,conn,optionVal);If you visit my thread, u'll see that I'm using STRUCT and then pass it to the ARRAY constructor, which works well, except for the performance issue.
    I'll appreciate if you can provide some information.
    Regards,
    Shamik

  • Problems creating an array and mixing them up

    I am trying to create an array (1-35), mix that array and display the results with a trace. I am getting an error withthe following code.
    public function generateArray(toNumber : int) : Array {
            var result : Array = [];
            for (var i : int = toNumber; i != 0; i--) {
            result.push(i);
            return result;
            public function shuffle (a:Array,i:int):Array
            {var rndm:int;
            var b:Array = a.slice();
            var c:Array = [];
            while (i) {
            rndm = Math.random() * b.length;
            c.push(b.splice(rndm,1)[0]);
            i--;
            return c;
             /*limit question display to 35*/
             generateArray(35);
             trace(generateArrays);
    the error(s) are:
    1180: Call to a possibly undefined method generateArray.
    1120: Access of undefined property generateArrays.
    please assist with resolving these problems.
    thanks in advance!

    generateArray(35) and that trace() must be inside a method (or methods).  for example,
        internal class Mixer {
            //retains the array that is consulted for random question numbers
            private var randomizedOrder:Array;
            //CONSTRUCTOR - passed total number of questions in section
            public function Mixer (questnsTotal:Number) {
                randomizedOrder = new Array();
                randomizedOrder[0] = Math.floor(Math.random()*questnsTotal);
                for (var i:Number=1; i<questnsTotal; i++) {
                    randomizedOrder[i] = newNumber(questnsTotal, i);
                for (var k:Number=0; k<questnsTotal; k++) {
                    trace(""+k+": "+randomizedOrder[k]);
      /*limit question display to 35*/
             generateArray(35);
             trace(generateArray);
            //recursive function that creates a new number until it creates one that isn't already in use
            private function newNumber (qTotal:Number, curNum:Number):Number {
                var newNum:Number = Math.floor(Math.random()*qTotal);
                for (var j:Number=0; j<curNum; j++) {
                    if (randomizedOrder[j] == newNum) {
                        return newNumber(qTotal, curNum);
                return newNum;
            public function generateArray(toNumber : int) : Array {
            var result : Array = [];
            for (var i : int = toNumber; i != 0; i--) {
            result.push(i);
            return result;
            public function shuffle (a:Array,i:int):Array
            {var rndm:int;
            var b:Array = a.slice();
            var c:Array = [];
            while (i) {
            rndm = Math.random() * b.length;
            c.push(b.splice(rndm,1)[0]);
            i--;
            return c;
            //This is how external classes acquire a random number from this class's array
            //(programNum = the question the program wants to ask next, based on sequential order, or user selection)
            internal function getRandomNumber(programNum:Number):Number {
                return randomizedOrder[programNum];

  • Newbie: Array killing function ?

    Hi all,
    This very simple & "out-of-the-book" Array declaration
    and - initialisation kills the function underneath.
    If I take out the Array-piece the function works again.
    Even in strict mode the compiler reports no errors.
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="vertical">
    <mx:Panel>
    <mx:VBox >
    <mx:TextInput id="zone1" text="zone" />
    <mx:Button id="button1" label="click!"
    click="myEventHandler(event)" />
    </mx:VBox>
    </mx:Panel>
    <mx:Script>
    <![CDATA[
    import mx.controls.Alert;
    // Array constructor
    public var myArray:Array = new Array();
    myArray[0]= 1;
    myArray[1]= 2;
    myArray[2]= 3;
    public function myEventHandler(event:Event):void {
    zone1.text = ("hello");
    Alert.show("An event occurred");
    ]]>
    </mx:Script>
    </mx:Application>
    Being new tot AS3 I'm probably doing something very wrong,
    but I'm really mystified.
    So can someone out here please tell me what is going wrong
    here ?
    And perhaps what the correct code should look like?
    Thx a lot.
    Rgds from Rotterdam in Holland,
    Borizz

    Remember, when writing an mxml file you are essentially
    writing a class.

  • Performance of System.arraycopy and Arrays.fill

    I have some code where I call a function about 1,000,000 times. That function has to allocate a small array (around 15 elements). It would be much cheaper if the client could just allocate the array one single time outside of the function.
    Unfortunately, the function requires the array to have all of its elements set to null. With C++, I would be able to memset the contents of the array to null. In Java, the only methods I have available to me are System.arraycopy() and Arrays.fill().
    Apparently, Arrays.fill() is just a brain-dead loop. It costs more for Arrays.fill() to set the elements to null than it does to allocate a new array. (I'm ignoring possible garbage collection overhead).
    System.arraycopy is a native call (that apparently uses memcpy). Even with the JNI overhead, System.arraycopy runs faster than Arrays.fill(). Unfortunately, it's still slower to call System.arraycopy() than it is to just allocate a new array.
    So, the crux of the problem is that the heap allocations are too slow, and the existing means for bulk setting the elements of an array are even slower. Why doesn't the virtual machine have explicit support for both System.arraycopy() and Arrays.fill() so that they are performed with ultra-efficient memsets and memcpys and sans the method call and JNI overhead? I.E. something along the lines of two new JVM instructions - aarraycpy/aarrayset (and all of their primitive brethern).
    God bless,
    -Toby Reyelts

    A newly allocated array begins its life with null in its elements. There is no need to fill it with null.
    As Michael already stated, I'm not redundantly resetting all of the elements to null. Here's some code that demonstrates my point. You'll have to replace my PerfTimer with your own high performance timer. (i.e. sun.misc.Perf or whatever) Also note that the reason I'm only allocating half the array size in allocTest is to more accurately model my problem. The size of the array I need to allocate is variable. If I allocate the array outside of the function, I'll have to allocate it at a maximum. If I allocate inside the function, I can allocate it at exactly the right size.import java.util.*;
    public class AllocTest {
      private static final int count = 100000;
      public static void main( String[] args ) {
        for ( int i = 0; i < 10; ++i ) {
          allocTest();
        double allocStartTime = PerfTimer.time();
        allocTest();
        double allocTime = PerfTimer.time() - allocStartTime;
        for ( int i = 0; i < 10; ++i ) {
          copyTest();
        double copyStartTime = PerfTimer.time();
        copyTest();
        double copyTime = PerfTimer.time() - copyStartTime;
        for ( int i = 0; i < 10; ++i ) {
          fillTest();
        double fillStartTime = PerfTimer.time();
        fillTest();
        double fillTime = PerfTimer.time() - fillStartTime;
        System.out.println( "AllocTime (ms): " + allocTime / PerfTimer.freq() * 1000 );
        System.out.println( "CopyTime (ms): " + copyTime / PerfTimer.freq() * 1000 );
        System.out.println( "FillTime (ms): " + fillTime / PerfTimer.freq() * 1000 );
      private static void allocTest() {
        for ( int i = 0; i < count; ++i ) {
          Object[] objects = new Object[ 8 ];
      private static void copyTest() {
        Object[] objects = new Object[ 15 ];
        Object[] emptyArray = new Object[ 15 ];
        for ( int i = 0; i < count; ++i ) {
          System.arraycopy( emptyArray, 0, objects, 0, emptyArray.length );
      private static void fillTest() {
        Object[] objects = new Object[ 15 ];
        for ( int i = 0; i < count; ++i ) {
          Arrays.fill( objects, null );
    }I getH:\>java -cp . AllocTest
    AllocTime (ms): 9.749283777686829
    CopyTime (ms): 13.276827082771694
    FillTime (ms): 16.581995756443906So, to restate my point, all of these times are too slow just to perform a reset of all of the elements of an array. Since AllocTime actually represents dynamic heap allocation its number is good for what it does, but it's far too slow for simply resetting the elements of the array.
    CopyTime is far too slow for what it does. It should be much faster, because it should essentially resolve to an inline memmove. The reason it is so slow is because there is a lot of call overhead to get to the function that does the actual copy, and that function ends up not being an optimized memmove. Even so, one on one, System.arraycopy() still beats heap allocation. (Not reflected directly in the times above, but if you rerun the test with equal array sizes, CopyTime will be lower than AllocTime).
    FillTime is unbelievably slow, because it is a simple Java loop. FillTime should be the fastest, because it is the simplest operation and should resolve to an inline memset. Fills should run in single-digit nanosecond times.
    God bless,
    -Toby Reyelts

  • Build Array Question

    Hi,
    I am wondering how to build a selective array from a continually changing stream of data. For example in the attached picture, I wish to append to the array only even numbers. So the resulting array should be [2 4 6...]. However, I am aware that for a case structure, an output terminal is required, so instead my output reads [0 2 0 4 0 6...], since the default value in the false case is zero. Is there a way to build an array that will only append new elements when certain conditions are met? (in this case, the condition being if the number is even).
    I am aware that you can use a sort array function block, then remove the zeros. Is there a better way to perform this task that I need? In my actual program, I need to record the value of the time at a couple values at the turn of the hour when certain conditions are met, then feed the new array to a graph. Thanks,
    Adam
    Attachments:
    Build an Array.JPG ‏31 KB

    You can just put the build array part into the case statement.
    You can also switch the build array to concatenate inputs mode (right
    click on it), and use arrays to output from your case statement (using empty
    arrays when you don't want to add anything)
    Ideally you avoid puting build array into a loop, since reallocating large arrays can really slow down a program (shouldn't be a problem for small arrays).
    Message Edited by Matt W on 11-21-2006 08:27 PM
    Message Edited by Matt W on 11-21-2006 08:28 PM
    Attachments:
    build array 1.PNG ‏15 KB
    build array 2.PNG ‏15 KB

  • Trying to create a flash gallery

    trying to create a simple clickable slideshow.
    my problem i think is in the math. but i clickable picture buttons on right and left. the center clickable too.
    i wanna know how can i increment decrement a variable depending on direction.
    currently it seems to go in one direction which is to the right.
    also can i make an array of functions: ex- function animate[count](e:event):void
    or do functions handle arrays differently.
    sorry if i sound stupid but its been awhile doing flash.
    heres little code:
    var picture:Array = new Array();
    picture[1] = new pic1();
    addChild(picture[1]);
    picture[1].x =50;
    picture[1].y =384;
    picture[2] = new pic2();
    addChild(picture[2]);
    picture[2].x =512;
    picture[2].y =384;
    picture[2].scaleX =10;
    picture[2].scaleY =10;
    picture[3] = new pic3();
    addChild(picture[3]);
    picture[3].x =974;
    picture[3].y =384;
    var counter = 1;
        picture[1].addEventListener(MouseEvent.CLICK, animate1)
        function animate1(e:MouseEvent):void
            trace(counter);
            picture[counter+1].x =50;
            picture[counter+1].y =384;
            picture[counter + 2].x =512;
            picture[counter + 2].y =384;
            picture[counter + 2].scaleX =10;
            picture[counter + 2].scaleY =10;
            picture[counter + 3].x =974;
            picture[counter + 3].y =384;
            counter++;
    5 more similar eventlisteners and function

    Sorry I think I misread your code before when I responded. Well I think I have a working version of what you are trying to do. You can view what I made at http://www.jeremyseverson.com/as3/flash_gallery/index.html . I created this all in straight AS3 but it should give you an idea of what I did and give you some direction to achieve what you want.
    package
         import caurina.transitions.*;
         import flash.display.Bitmap;
         import flash.display.SimpleButton;
         import flash.display.Sprite;
         import flash.events.MouseEvent;
         [SWF(backgroundColor="#000000", frameRate="31", width="800", height="300")]
         public class Main2 extends Sprite
              //  EMBED ASSETS
              [Embed(source='assets/rightArrow.png')]
              private var rightArrowClass:Class;
              [Embed(source='assets/leftArrow.png')]
              private var leftArrowClass:Class;
              [Embed(source='assets/IMG_0001.JPG')]
              private var img0001Class:Class;
              [Embed(source='assets/IMG_0002.JPG')]
              private var img0002Class:Class;
              [Embed(source='assets/IMG_0003.JPG')]
              private var img0003Class:Class;
              [Embed(source='assets/IMG_0004.JPG')]
              private var img0004Class:Class;
              [Embed(source='assets/IMG_0005.JPG')]
              private var img0005Class:Class;
              [Embed(source='assets/IMG_0006.JPG')]
              private var img0006Class:Class;
              [Embed(source='assets/IMG_0007.JPG')]
              private var img0007Class:Class;
              //  PRIVATE VARIABLES
              // Layout Properties
              private var imgPad:Number = 5;
              private var imgScale:Number = 2.5;
              private var btnSize:Number = 25;
              private var imgCounter:Number = 0;
              private var middleImgX:Number = 400;
              private var leftImgX:Number = 100;
              private var rightImgX:Number = 700;
              private var leftImgTransX:Number = leftImgX - (middleImgX - leftImgX);
              private var rightImgTransX:Number = rightImgX + (rightImgX - middleImgX);
              private var imgY:Number = 150;
              private var imgLeft:Sprite;
              private var imgMid:Sprite;
              private var imgRight:Sprite;
              private var imgTransIn:Sprite;
              private var imgTransOut:Sprite;
              // Image Array
              private var classList:Array = new Array(img0001Class,img0002Class,img0003Class,img0004Class,img0005Class,img0006Class,img0007Class);
              private var spriteList:Array;
              private var currImages:Array;
              //  CONSTRUCTOR
              public function Main2()
                   init();
              //  PRIVATE METHODS
              private function init():void
                   initSpriteList();              
                   updateInterface(imgCounter);
               * Creating an array of sprites so that my registration point
               * will be in the center of the image instead of the upper left
              private function initSpriteList():void
                   spriteList = new Array();
                   var tSprite:Sprite;
                   var tBmp:Bitmap;
                   for (var i:uint=0; i<classList.length; i++)
                        tBmp = new classList[i] as Bitmap;
                        tSprite = new Sprite;
                        tSprite.addChild(tBmp);
                        tBmp.x = (-tBmp.width / 2);
                        tBmp.y = (-tBmp.height / 2);
                        spriteList.push(tSprite);
              private function updateInterface(newPos:Number,direction:String=null):void
                   var maxPos:Number = spriteList.length - 1;
                   var minPos:Number = 0;
                   var midPos:Number;
                   var leftPos:Number;
                   var rightPos:Number;
                   var transInSprite:Sprite;
                   // Set center array position
                   midPos = newPos;
                   if (midPos > maxPos) midPos = minPos;
                   if (midPos < minPos) midPos = maxPos;
                   // Update Image Counter
                   imgCounter = midPos;
                   // Set left array position
                   leftPos = midPos - 1;
                   if (leftPos < minPos) leftPos = maxPos;
                   // Set right array position
                   rightPos = midPos + 1;
                   if (rightPos > maxPos) rightPos = minPos;
                   switch(direction)
                        case "L":
                             currImages[0].removeEventListener(MouseEvent.MOUSE_DOWN, moveRight);
                             currImages[2].removeEventListener(MouseEvent.MOUSE_DOWN, moveLeft);
                             // Add transition in img
                             transInSprite = spriteList[rightPos];
                             transInSprite.x = rightImgTransX;
                             transInSprite.y = imgY;
                             transInSprite.scaleX = transInSprite.scaleY = .05;
                             transInSprite.alpha = 0;
                             addChild(transInSprite);    
                             Tweener.addTween(transInSprite, {x:rightImgX, alpha:1, scaleX:1, scaleY:1, time:0.5});
                             Tweener.addTween(currImages[0], {x:leftImgTransX, scaleX:.5, scaleY:.5, alpha:0, time:0.5, onComplete:removeImage, onCompleteParams:[currImages[0]]});
                             Tweener.addTween(currImages[1], {x:leftImgX, scaleX:1, scaleY:1, alpha:1, time:0.5});
                             Tweener.addTween(currImages[2], {x:middleImgX, scaleX:imgScale, scaleY:imgScale, alpha:1, time:0.5});
                             break;
                        case "R":
                             currImages[0].removeEventListener(MouseEvent.MOUSE_DOWN, moveRight);
                             currImages[2].removeEventListener(MouseEvent.MOUSE_DOWN, moveLeft);
                             // Add transition in img
                             transInSprite = spriteList[leftPos];
                             transInSprite.x = leftImgTransX;
                             transInSprite.y = imgY;
                             transInSprite.scaleX = transInSprite.scaleY = .05;
                             transInSprite.alpha = 0;
                             addChild(transInSprite);    
                             Tweener.addTween(transInSprite, {x:leftImgX, alpha:1, scaleX:1, scaleY:1, time:0.5});
                             Tweener.addTween(currImages[2], {x:rightImgTransX, scaleX:.5, scaleY:.5, alpha:0, time:0.5, onComplete:removeImage, onCompleteParams:[currImages[2]]});
                             Tweener.addTween(currImages[1], {x:rightImgX, scaleX:1, scaleY:1, alpha:1, time:0.5});
                             Tweener.addTween(currImages[0], {x:middleImgX, scaleX:imgScale, scaleY:imgScale, alpha:1, time:0.5});
                             break;
                        default:
                             // Add left img
                             spriteList[leftPos].x = leftImgX;
                             spriteList[leftPos].y = imgY;
                             spriteList[leftPos].scaleX = spriteList[leftPos].scaleY = 1;
                             addChild(spriteList[leftPos]);                        
                             // Add middle img
                             imgMid = spriteList[midPos];
                             spriteList[midPos].x = middleImgX;
                             spriteList[midPos].y = imgY;
                             spriteList[midPos].scaleX = spriteList[midPos].scaleY = imgScale;
                             addChild(spriteList[midPos]);
                             // Add right img
                             spriteList[rightPos].x = rightImgX;
                             spriteList[rightPos].y = imgY;
                             spriteList[rightPos].scaleX = spriteList[rightPos].scaleY = 1;
                             addChild(spriteList[rightPos]);         
                   spriteList[leftPos].addEventListener(MouseEvent.MOUSE_DOWN, moveRight);
                   spriteList[rightPos].addEventListener(MouseEvent.MOUSE_DOWN, moveLeft);
                   currImages = [spriteList[leftPos], spriteList[midPos], spriteList[rightPos]];
              private function removeImage(spriteRef:Sprite):void
                   removeChild(spriteRef);
              //  EVENT HANDLERS
              private function moveRight(e:MouseEvent):void
                   imgCounter--;
                   updateInterface(imgCounter,"R");
              private function moveLeft(e:MouseEvent):void
                   imgCounter++;
                   updateInterface(imgCounter,"L");

Maybe you are looking for

  • ITunes wont start Error report.

    A while back, I had to do a system restore. I reinstalled both quicktime and iTunes, but whenever I open iTunes, one of those "iTunes has encountered an error," messages appears. I have tried everything, including reinstalling several times. I have a

  • How to preserve jagged (without anti-aliasing) when exporting to PDF?

    I created a jagged line drawing in Processing, than exported it to PDF. When I opened it in Illustrator it was fine (I turned anti-aliasing off). But after saving it to PDF and reviewing in Adobe Acrobat the anti-aliasing was back on. Is there any wa

  • Over saturated images when monitor resumes from sleep

    Lately I started to get this weird beheviour from LR 2.7. each time my monitor resumes from sleep all image colors become extremely over saturated. All other apps and computer desktop are just the same so it's only LR. I use a wide gamut LCD (HP LP24

  • How do I get movies off my ipad to my computer?

    I have a video on my iPad that appears in the Movies section. It is a home video not one I purchased. How do I get this onto my iMac or PC? It does not show up in iTunes on my computer in Movies, Videos or anywhere else, but is playable only on my iP

  • Change font in Document

    Hi there. I have a rtf file in which I am inserting string using Java: FileInputStream fis= new FileInputStream(exampleFile); RTFEditorKit rtf = new RTFEditorKit(); Document doc = rtf.createDefaultDocument(); rtf.read(fis, doc, 0); doc.insertString(5