A better way to code ?

There was this select statement and will return lines along with its flag (status). Though I don't like the query itself, it uses MIN on a CHAR field. But it works. the open_flag value on both table will only be 'Y', 'N' or NULL. It's a CHAR(1).
SELECT (SELECT DECODE(l.open_flag, 'N', 'N', NVL(MIN(s.open_flag), 'Y'))
FROM my_shipping_v s
WHERE s.order_line_id = l.line_id) update_flag, l.LINE_NUMBER
FROM my_order_line_v l
WHERE order_id = variable_order_id
AND link_to_line_id IS NULL;
ORDER BY line_number;
Is there a simple modification to the query to find out if any update_flag = 'N' ? (from both table).
Will exists works? I tried couple of ways, no luck yet.

This?
SELECT update_flag, line_number
FROM   (SELECT DECODE(l.open_flag, 'N', 'N', NVL(MIN(s.open_flag), 'Y')) update_flag,
               l.line_number
        FROM   my_order_line_v l, my_shipping_v s
        WHERE  s.order_line_id = l.line_id
        AND    order_id = variable_order_id
        AND    link_to_line_id IS NULL)
WHERE  update_flag = 'N'
ORDER BY line_number;NB. I took the correlated subquery out of the select clause and incorporated it as a join in the main query - looks neater that way. I think the performance will be the same, but you'd need to check. My gut feel is that Oracle would rewrite your query into a join.
Message was edited by:
Boneist
Or by the same token, if you'd prefer not to have the query wrapped in an outer select, you could do:
SELECT DECODE(l.open_flag, 'N', 'N', NVL(MIN(s.open_flag), 'Y')) update_flag,
       l.line_number
FROM   my_order_line_v l, my_shipping_v s
WHERE  s.order_line_id = l.line_id
AND    order_id = variable_order_id
AND    link_to_line_id IS NULL
AND    DECODE(l.open_flag, 'N', 'N', NVL(MIN(s.open_flag), 'Y')) = 'N'
ORDER BY l.line_number;

Similar Messages

  • Need help to get alternate or better way to write query

    Hi,
    I am on Oracle 11.2
    DDL and sample data
    create table tab1 -- 1 millions rows at any given time
    id       number       not null,
    ref_cd   varchar2(64) not null,
    key      varchar2(44) not null,
    ctrl_flg varchar2(1),
    ins_date date
    create table tab2 -- close to 100 million rows
    id       number       not null,
    ref_cd   varchar2(64) not null,
    key      varchar2(44) not null,
    ctrl_flg varchar2(1),
    ins_date date,
    upd_date date
    insert into tab1 values (1,'ABCDEFG', 'XYZ','Y',sysdate);
    insert into tab1 values (2,'XYZABC', 'DEF','Y',sysdate);
    insert into tab1 values (3,'PORSTUVW', 'ABC','Y',sysdate);
    insert into tab2 values (1,'ABCDEFG', 'WYZ','Y',sysdate);
    insert into tab2 values (2,'tbVCCmphEbOEUWbxRKczvsgmzjhROXOwNkkdxWiPqDgPXtJhVl', 'ABLIOWNdj','Y',sysdate);
    insert into tab2 values (3,'tbBCFkphEbOEUWbxATczvsgmzjhRQWOwNkkdxWiPqDgPXtJhVl', 'MQLIOWNdj','Y',sysdate);I need to get all rows from tab1 that does not match tab2 and any row from tab1 that matches ref_cd in tab2 but key is different.
    Expected Query output
    'ABCDEFG',  'WYZ'
    'XYZABC',   'DEF'
    'PORSTUVW', 'ABC'Existing Query
    select
       ref_cd,
       key
    from
        select
            ref_cd,
            key
        from
            tab1, tab2
        where
            tab1.ref_cd = tab2.ref_cd and
            tab1.key    <> tab2.key
        union
        select
            ref_cd,
            key
        from
            tab1
        where
            not exists
               select 1
               from
                   tab2
               where
                   tab2.ref_cd = tab1.ref_cd
        );I am sure there will be an alternate way to write this query in better way. Appreciate if any of you gurus suggest alternative solution.
    Thanks in advance.

    Hi,
    user572194 wrote:
    ... DDL and sample data ...
    create table tab2 -- close to 100 million rows
    id       number       not null,
    ref_cd   varchar2(64) not null,
    key      varchar2(44) not null,
    ctrl_flg varchar2(1),
    ins_date date,
    upd_date date
    insert into tab2 values (1,'ABCDEFG', 'WYZ','Y',sysdate);
    insert into tab2 values (2,'tbVCCmphEbOEUWbxRKczvsgmzjhROXOwNkkdxWiPqDgPXtJhVl', 'ABLIOWNdj','Y',sysdate);
    insert into tab2 values (3,'tbBCFkphEbOEUWbxATczvsgmzjhRQWOwNkkdxWiPqDgPXtJhVl', 'MQLIOWNdj','Y',sysdate);
    Thanks for posting the CREATE TABLE and INSERT statments. Remember why you go to all that trouble: so the people whop want to help you can re-create the problem and test their ideas. When you post statemets that don't work, it's just a waste of time.
    None of the INSERT statements for tab2 work. Tab2 has 6 columns, but the INSERT statements only have 5 values.
    Please test your code before you post it.
    I need to get all rows from tab1 that does not match tab2 WHat does "match" mean in this case? Does it mean that tab1.ref_cd = tab2.ref_cd?
    and any row from tab1 that matches ref_cd in tab2 but key is different.
    Existing Query
    select
    ref_cd,
    key
    from
    select
    ref_cd,
    key
    from
    tab1, tab2
    where
    tab1.ref_cd = tab2.ref_cd and
    tab1.key    <> tab2.key
    union
    select
    ref_cd,
    key
    from
    tab1
    where
    not exists
    select 1
    from
    tab2
    where
    tab2.ref_cd = tab1.ref_cd
    Does that really work? In the first branch of the UNION, you're referencing a column called key, but both tables involved have columns called key. I would expect that to cause an error.
    Please test your code before you post it.
    Right before UNION, did you mean
    tab1.key    != tab2.key? As you may have noticed, this site doesn't like to display the &lt;&gt; inequality operator. Always use the other (equivalent) inequality operator, !=, when posting here.
    I am sure there will be an alternate way to write this query in better way. Appreciate if any of you gurus suggest alternative solution.Avoid UNION; it can be very inefficient.
    Maybe you want something like this:
    SELECT       tab1.ref_cd
    ,       tab1.key
    FROM           tab1
    LEFT OUTER JOIN  tab2  ON  tab2.ref_cd     = tab1.ref_cd
    WHERE       tab2.ref_cd  IS NULL
    OR       tab2.key     != tab1.key
    ;

  • A better way to execute a series of external commands?

    Hi,
    Consider the code snippet...
    Process proc1 = rt.exec("Some external command");
    Vector vecOutput = outputGobbler.getOutput() ;
    String[] strAlterCmds = new String[vecOutput.size()];
    for ( int k = 0 ; k < vecOutput.size() ; k++ )
    strAlterCmds[k] = new String();
    strAlterCmds[k] = "cmd.exe /c blah.... " +(String) vecOutput.elementAt( k )+ " ;
    Process proc2 = rt.exec(strAlterCmds[k], null);
    StreamGobbler errorG = new
    StreamGobbler( proc2.getErrorStream(), "Error") ;
    StreamGobbler outputG = new
    StreamGobbler( proc2.getInputStream(), "Output") ;
    errorG.start() ;
    outputG.start() ;
    int exitVal1 = proc2.waitFor();
    The second part of the execution is taking AGES and I am not sure forking a new process for runtime execution is the best alternative here.
    I would be glad if someone can point me to a smarter solution.
    In short: I intend to execute a series of commands using RTE depending on the values I get in the loop.
    Thanks.

    Jared,
    Thank you for responding to my posted message. Rendezvous is a new concept to me, maybe
    it's the solution to my problem. I have been trying to read the on line manual and
    example VIs from National Instruments website. I still have a hard time to understand
    the concept.
    One of the example I saw is using rendezvous to run some sub VIs. But in my case, I have
    only one VI that is a while loop. Inside the while loop, there are a few tasks running
    simultaneously. I don't know whether it will serve my purpose.
    Guangde Wang
    Jared O'Mara wrote:
    > Guangde,
    >
    > Referring to your 2nd method, use rendezvous (under advanced>>synchronize
    > on function palette) to synchronize two processes. There are good examples
    > that come with labview. basically, you cre
    ate a rendezvous, giving it a
    > size. Using the wait on rendezvous vi, a function will not continue until
    > all rendezvous have reached that point. Using this method, you can synchronize
    > your 2 while loops.
    >
    > Jared
    >
    > Guangde Wang wrote:
    > >I tried two ways to control the tempo of my program.>>One is to use the
    > While Loop's counter and a wait. The drawback of this>method is the cycle
    > length is dependent on the measuring load. So if the>program runs for days,
    > it will be significent off the real time.>>The other way is to use the difference
    > of the Tick Count. It provides>accurate timing but the problem is the sychronization
    > of the clock cycle>and the While Loop cycle. I can try to put a little bit
    > wait but still>can not sychronize them very well. So after a while, there
    > will be two>measures get together.>>I don't know whether there are some better
    > ways to control the program>or whether we have some ways to improve either
    > or both of the above
    two>methods to make them work better. Please let me
    > know if you have any>suggestion.>>Thank you in advance,>>Guangde Wang>

  • A better way to poll

    When my Start button is clicked it changes a member variable from false to true.
    Here is a simplified version of my code:
    public class gdvdhomevideo
       private boolean blnBegin;
       public static void main(String[] args)
          while(blnBegin == false){}
          //perform operations
       public void actionPerformed(ActionEvent e)
          String command = e.getActionCommand();
          if(command.equals("Start"))
             blnBegin = true;
    }So when the user clicks start it exits the while loop and the program starts performing other functions. The problem is that this approach is 100% CPU intensive and I know that there must be a better way?

    1) Code executed in the main() is NOT running on the event thread. Don't do any GUI code from the main thread... You know, stuff like showing windows, attaching event listeners etc.. You need to wrap all that stuff in a Runnable and pass that Runnable to SwingUtilities.invokeLater().
    2) Assuming the stuff you're doing in the main() is actually thread safe and doesn't touch the GUI, you can simply startup a new Thread and put your code in there. (see below)
    3) You class name is named badly. Please check out sun's java coding conventions. It is very nice to have coding conventions. Use them! ;-)
    4) if you want to setup your program as a loop rather than simply relying on user actions to fire events, then I'd suggest you use a timer that notifies on the event thread every X where X is a non-zero polling interval. I think there's a class is called SwingTimer that does this sort of thing for you.
    What you're attempting to do is non-trivial.. so.. ummm.. have fun..
    public class gdvdhomevideo
       private boolean blnBegin;
       public static void main(String[] args) throws Exception
            SwingUtilities.invokeLater( new Runnable() {
                  public void run() {
                       //setup stuff in here.
       public void actionPerformed(ActionEvent e)
          String command = e.getActionCommand();
          if(command.equals("Start"))
             new Thread(new Runnable() {
                public void run() {
                     //perform operations but don't touch the GUI.
              }.start();
    }

  • A better way to do ChangeListeners?

    I find myself having to implement multiple change listeners in a single class, and I was wondering if there was a way to do this that wouldn't trigger compilation problems. For example, let's say you have a LineChart, and you want the chart to listen for changes to the data, but also changes to the user's smoothing algorithm selection. You might try declaring your class like this:
    public class MyGraph implements DataChangeListener, SmoothingChangeListener {....where you've declared DataChangeListener, and SmoothingChangeListener as
    DataChangeListener extends ChangeListener<SomeDataStructure>{...}
    SmoothingChangeListener extends ChangeListener<ISmoothable>{...}The compiler will tell you immediately that MyGraph can only implement one ChangeListener.
    In real life, I have classes that have to listen for multiple types of events, and both for the sake of semantic clarity and for the sake of feasibility, they need to implement those change listeners. I've used event buses in certain cases, but they tend to obscure what the class is actually listening to.
    Is there a better way of doing this?

    Event handling code is, almost by definition, controller code. So it makes sense (to me at least) to have event handling code in the controller. You can put the code I showed previously
    someDataSeries.dataProperty().addListener(new ChangeListener<...>() {
       public void changed(...) {
    someChart.animatedProperty().addListener(new ChangeListener<Boolean>() {
       public void changed(...) {
    });directly in your controller. (I suppose I thought "MyGraph" was your controller, though the name should have implied otherwise to me.)
    However, if you really want to have the event handlers defined elsewhere, you can still do so, while using anonymous inner classes (or lambdas when we all upgrade next September):
    public class MyGraph {
      private final ChangeListener<SomeDataType> dataListener = new ChangeListener<SomeDataType>() {
        @Override
        public void changed(...) { ... }
      private final ChangeListener<ISmoothable> smoothingListener = new ChangeListener<ISmoothable>() {
       @Override
       public void changed(...) { ... }
      public ChangeListener<SomeDataType> dataListener() { return dataListener ; }
      public ChangeListener<ISmoothable> smoothingListener() { return smoothingListener ; }
    }and you can then do
    dataSource.addListener(myGraph.dataListener());
    smoothingProperty.addListener(myGraph.smoothingListener());But I recommend the approach I first suggested: I use this all the time.

  • A better way to do this ?

    where does the sql stuff excute in the following stored procedure, directly in the database or it goes through the oracle VM first ?
    CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "CustomExport" AS
    import javax.sql.Connection;
    import oracle.jdbc.OracleDriver;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class CustomExport
    public void do() throws SQLException{
    OracleDriver oracle = new OracleDriver();
    DriverManager.registerDriver(oracle);
    Connection conn = oracle.defaultConnection();
    PreparedStatement st = conn.prepareStatement("select from table where col=?");
    st.setString(1,"value");
    ResultSet rs = st.execute();
    and is there a better way to read and parse an xml document with PL/SQL.what i've read about is the ability to parse an XML file to load its data directly into a database table.What i was looking for was just a way to parse XML without having to load any data into tables so i did it with java.
    CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "CustomParser" AS
    import javax.xml.prasers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.Attributes;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    public class CustomParser
    private static CustomParseHandler handler = new CustomParseHandler();
    public static void parseXMLFile(String fileName) throws FileNotFoundException,IOException,SAXException
    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    SAXParser parser=saxFactory.newSAXParser();
    parser.parse(new FileInputStream(fileName)),handler);
    private class CustomParseHandler extends DefaultHandler{
    StringBuffer buff;
    public CustomParseHandler()
    this.buff = new StringBuffer();
    public void startElement (String uri, String localName,
    String qName, Attributes attributes)
    throws SAXException
    buff.append("<").append(qName).append(">");
    public void endElement (String uri, String localName, String qName)
    throws SAXException
    buff.append("</").append(qName).append(">").append(newLine);
    public void characters (char ch[], int start, int length)
    throws SAXException
    String fieldName = new String(ch,start,length);
    if(fieldName==null || "".equals(fieldName.trim()))
    return;
    public void clearBuffer(){
    buff.delete(0, buff.length());
    public String getXMLString(){
    return buff.toString();
    }

    PLSQL does not go through Java to access the database. The actual access to the database is via the same mechanism for both, so in some sense, both perform about the same. However, PLSQL datatypes have the same representation as database datatypes so there is no conversion. Java datatypes have different representations than database datatypes so there is a conversion cost associated with moving data between Java and the database.
    If your processing is simple and you are moving a lot of data, PLSQL is likely the better choice. If your processing is more complex and you are moving less data, Java is likely the better choice. There are other things such as portability you should consider, but the amount of data and complexity of the code are the first considerations.
    Douglas

  • A better way to make Automator mount a volume?

    I made an Automator application, using the Record function, to mount a volume on a drive connected to my Mini. I also made a similar one to eject it. I use them as Calendar-triggered events as part of my backup scheme.
    They work well ... until I restart the Mini, when occasionally my two connected drives will mount in a different order. What happens then is that the sequence of mouse clicks recorded in Automator don’t find the correct volume.
    I wonder if there’s a better way to automate the mounting of a currently ejected disc (and later its ejection). Automator, as far as I can see, does not have the actions I need. It has Ask For/Connect to/Get specified Servers, but they seem only to be for network-connected stuff.
    Anyone know a better way?

    Welcome to Unix. 
    The key part of that shell script code is the test for the existence of the mount point (if [ -e /Volumes/dbamp ]), followed by a conditional block that — in the "else" section involved when the mount point wasn't found — creates it, and then mounts an AFP file system on that mount point.  Most of the rest of the baggage in that script is used to get the mysqldump database dumps over onto the target disk, once it's been mounted.
    Here's a very quick overview of the basics of scripting , Apple's introduction to the command line manual, there's a generic bash intro (which is good, but doesn't line up exactly with how bash is implemented on OS X) and O'Reilly has some reasonable books on bash and bash scripting.  Once you know and are comfortable with the basics, there are advanced bash guides available.

  • A better way to Double Click

    I have been wondering if there is a better way to detect single clicks Vs double clikcs than the model currently implemented. I am sure all of you have run into the problem of even though an event listener detects a double click eventually, it detects the single click first, so often you have to compromise the quality of your software to account for that. I have considered writing my own custom handler using threads and such, but it seems to me there must be a better way out there that I just have not been able to find. I need a way to detect double clicks, and fool the machine into believing no single click has occured. Must I re-invent the wheel?
    AC

    I agree that GUIs should have some uniformity to
    them..especially as we enter an age where computers
    are ubiquitous. But there are some situations where
    customized behavior is preferrable. If you have ever
    worked with movie special effects software, some art
    software, music software, especially, you know that to
    make a GUI intuitive, sometimes liberties must be
    taken with the 'standard' gui design.The application determines the standard not the OS nor the GUI.
    And to say 'Your code is not standard, therefore the
    fact that java cannont accurately distinguish between
    single and double clicks is your problem' smacks of
    nonsense to me.
    We all know that Java is a great
    language.Java is not just a language it is a platform and a philosophy.
    It is quicker and easier to program in,
    than c++, but it is not at full maturity. Every c++
    development environment I have ever used had the
    ability built in to distinguish between a true single
    click and a double click.As does Swing..
    I love Java, but most
    programmers could fill a page with the enhancements
    that it needs. Not all enhancements are practical.
    Like many I balked when I first started with Java at
    the fact that it did not have true multiple
    inheritence. I now realize that
    I never really needed it anyway. But some things, eg
    templates, I definitely could still use. That being,
    said, thanks for the dialog. Templates are a complicated horror, unless you really need your software to be truly adaptable you will never use them. Even MS, Sun and IBM disposed of that need a long time ago.

  • What is the better way to end a ajax request in JSF?

    Hi, i hav a question.
    Im working with AJAX inside JSF, using a phaseListener, when i finish my work i do:
    context.responseComplete( );But i want to save the view, i dont want lose the changes ive made in my backbeans, what can i do?
    tkz.

    Ok, ill try to explain in better way:
    AJAX goes to the server and update the model, server response xml and update the client, i hav tags in my jsp like saveState (save the state of object), its a tomahawk component, the jsf_sequence goes with AJAX, i need save the view state using that sequence, because another sequence will be back to the client.
    When client go with normal request (get, post), the server doenst restore my previous state (because i think ajax ended the lifecycle first).
    Some time ago, i did something like this:
              Map map = context.getExternalContext().getRequestMap();
              Integer sequence = (Integer) map.get(RendererUtils.SEQUENCE_PARAM);
              if (sequence == null || sequence == 1) {
                   logger.warn("JSF_SEQUENCE error");
              } else {
                   sequence--;
                   synchronized (context.getExternalContext().getSession(true)) {
                        context.getExternalContext().getSessionMap().put(
                                  RendererUtils.SEQUENCE_PARAM, sequence);
                   synchronized (map) {
                        map.put(RendererUtils.SEQUENCE_PARAM, sequence);
    context.getApplication().getStateManager().saveSerializedView(
                             context);The code back the jsf_sequence and i dont touch in the jsf_sequence on cliente, so when client post with normal away, everything is fine because faces saved the last view in that sequence. I dont wanna do that again, i wanna discover a soft way.
    tkz.
    Message was edited by:
    CasMeiron

  • Must be a better way...

    Hello Flash Community!
    Thanks in advance for any help/advice.
    So, what I'm looking for here is some high level advice as far as a better way to do things. I feel like so often with programming I'm just breaking my neck to get things working when I know there is a better way (presumably based in OOP) to go about things. I just need someone to look at what I've done and point it out to me.
    So, here's what I've done so far: http://www.catherinemix.com
    And it works pretty well as far as I'm concerned! The app dynamically loads as many images as my client (my mom ) puts on the server, resizes them dynamically, adds L/R arrow buttons dynamically based on how many images are involved, etc... But the downside to all that dynamic flexibility is that I haven't found a way to load the thumbnail images (and their respective full size images) one by one. Instead, I have to load them all together and keeping the user waiting that long is unacceptable to my mom. What I would love is for each thumbnail/full size combo to get its own preloader bar in the location it will eventually be embedded, but I haven't found a way to do that and account for an unknown number of images (as it is determined dynamically.)
    Any ideas here? I would specifically like to know which functions y'all use when you need to load multiple files simultaenously (AttachMovie?)
    I have posted the kluge-y code which handles all of the image gallery functions below.
    Thanks! and Be Well
    Graham
    import fl.transitions.Tween;
    import fl.transitions.easing.*;
    var wait:PleaseWait = new PleaseWait();
    wait.x = 400;
    wait.y = 50;
    addChild(wait);
    var waitFadeIn:Tween = new Tween(wait, "alpha", Regular.easeOut, 0, 1, 1, true);
    var titleText:TextField;
    var textSprite:Sprite;
    //thumbH is the ideal height for our thumbnails, and thumbW the ideal width
    var thumbH = 120;
    var thumbW = 170;
    //loadH is the ideal height for our fullsize images, and loadW the ideal width
    var loadH = 500;
    var loadW = 600;
    //some counter numbers
    var thumbNum = 1;
    var loadNum = 1;
    //some Sprites which need to be accessed by more than one function
    var darkStage:Sprite;
    var loadSprite:Sprite;
    //Let's instantiate some Arrays that we can load the images into.
    //Since Arrays of Loaders can't be copied, we have to go through the process twice.
    var thumbArray:Array = new Array();
    var loadArray:Array = new Array();
    firstLoad();
    firstThumb();
    function firstLoad():void {
        trace("firstLoad");
        var loadski = new Loader();
        loadski.load(new URLRequest("images/fulls/0.png"));
        loadski.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
        loadArray.push(loadski);
    //Starting with the above Loader, this function will execute every time the Loader completes
    function loadComplete(e:Event):void {
        trace("loadComplete");
        var loadski = new Loader();
        loadski.load(new URLRequest("images/fulls/" + loadNum + ".png"));
        loadArray.push(loadski);
        loadski.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
        loadski.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadError);
        loadNum++;
    //Once the Loader goes too far by attempting to load an image that doesn't exist on the computer,
    //it will thorw an IOError Event at which point the following function will execute.
    function loadError(e:IOErrorEvent):void {
        trace("loadError");
        loadArray.pop();
        loadNum = 0;
        loadResize();
        //We use the pop function to remove the most recently added Loader instance, since we know it
        //contains a null reference (beacuse the IOError Event is asynchronous.)
        thumbArray.pop();
        //We reset the counter variable.
        thumbNum = 0;
        //Add the little arrows that allow the user to click to see more thumbnails (if there are more
        //than 8 images on the server.)
        removeChild(wait);
        addArrows();
        //Let's resize the images to thumbnail size and add them to the display list.
        thumbResize();
        addClickOnThumb();
    function loadResize():void {
        trace("loadResize");
        for (var ex = 0; ex < loadArray.length; ex++) {
            //If the width of the image is greater than the ideal width, OR the height is greater than the ideal height...
            if ( loadArray[loadNum].content.width > loadW || loadArray[loadNum].content.height > loadH) {
                //And if the width of the image is greater than the height, apply Scaler 1...
                if ( loadArray[loadNum].content.width > loadArray[loadNum].content.height ) {
                    //Scaler 1 is the ratio of the ideal width to the image width
                    var scaler1 = loadW / loadArray[loadNum].content.width;
                    trace(loadNum + " load scaler 1: " + scaler1);
                    //Apply Scaler 1 to both the width and height of the image
                    loadArray[loadNum].content.scaleX = loadArray[loadNum].content.scaleY = scaler1;
                    //Otherwise, apply Scaler 2
                } else {
                    //Scaler 2 is the ratio of the ideal width to the image height
                    var scaler2 = loadH / loadArray[loadNum].content.height;
                    trace(loadNum + " load scaler 2: " + scaler2);
                    //Apply Scaler 2 to both the width and height of the image
                    loadArray[loadNum].content.scaleX = loadArray[loadNum].content.scaleY = scaler2;
                    trace("loadArray[loadNum].content.height = " + loadArray[loadNum].content.height);
                    trace("loadArray[loadNum].content.width = " + loadArray[loadNum].content.width);
                //Otherwise... (that is, the image width and height are in both cases less than the ideal)
            } else {
                //And if the width of the image is greater than the heigh, apply Scaler 3
                if ( loadArray[loadNum].content.width > loadArray[loadNum].content.height ) {
                    //Scaler 3 is the ratio of the ideal width to the image width
                    var scaler3 = loadW / loadArray[loadNum].content.width;
                    trace(loadNum + " load scaler 3: " + scaler3);
                    //Apply Scaler 3 to both the width and height of the image
                    loadArray[loadNum].content.scaleX = loadArray[loadNum].content.scaleY = scaler3;
                } else {
                    //Scaler 4 is the ratio of the ideal width to the image height
                    var scaler4 = loadH / loadArray[loadNum].content.height;
                    trace(loadNum + " load scaler 4: " + scaler4);
                    //Apply Scaler 4 to both the width and height of the image
                    loadArray[loadNum].content.scaleX = loadArray[loadNum].content.scaleY = scaler4;
            loadArray[loadNum].content.x = - (loadArray[loadNum].content.width / 2);
            loadArray[loadNum].content.y = - (loadArray[loadNum].content.height / 2);
            loadNum++;
    function firstThumb():void {
        trace("firstThumb");
        //Let's populate the first Array with Loaders that load the images Mom has put on the server.
        //We have to do this first Loader object by hand to get the Event.COMPLETE-based-loop going.
        var thumbski = new Loader();
        thumbski.load(new URLRequest("images/thumbs/0.png"));
        thumbski.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbComplete);
        //We add the MouseEvent.CLICK listener to the actual Loader instance so that, later on, in the
        //function enLarge, we can make use of the currentTarget parameter to correlate the Array index of
        //the thumbnail that the user is clicking on with that of the loadArray.
        thumbski.addEventListener(MouseEvent.CLICK, enLarge);
        thumbArray.push(thumbski);
    //Starting with the above Loader, this function will execute every time the Loader completes
    function thumbComplete(event:Event):void {
        trace("thumbComplete");
        var thumbski = new Loader();
        thumbski.load(new URLRequest("images/thumbs/" + thumbNum + ".png"));
        thumbski.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbComplete);
        //We add the IOErrorEvent listener so that as soon as this error is thrown, we will exit this loop
        //and proceed to the next logical step in the program can be taken.
        thumbski.addEventListener(MouseEvent.CLICK, enLarge);
        thumbArray.push(thumbski);
        thumbNum++;
    function addArrows():void {
        //Let's determine how many batches there are. A batch is the minimum amount of thumbnail images
        //mom wants to show up onscreen at a time. In this case, she has decided on 8.
        var batches =  Math.ceil(thumbArray.length / 8);
        //The variable m is part of a kluge fix related to the calculation of startX (explained below.)
        var m = 0;
        //Pseudocode for this loop: If there are at least two batches, then...
        //We do this because less than 2 batches doesn't warrant arrows
        if (batches > 1) {
            for (var k = 1; k < batches; k++) {
                //triW is the desired width of our arrows
                var triW = 20;
                //startX is the x position of the start of our rightward facing triangle(s)
                //The formula says: Our x starting position should be a triangle width shy of the
                //far edge of the stage (multiplying it by k ensures it happens as many times
                //as there are batches, which is why we intialize k = 1.) Every subsequent iteration
                //of the formula has to add a triangle's width worth of distance, except for the
                //very first one, which is why it is multiplied by m, which is initially set to 0.
                var startX = (((stage.stageWidth - triW) * k) + (triW * m));
                //We want the arrows to sit perfectly between the two rows of thumbnails. Since the
                //max height of every thumbnail is thumbW, that would seem to be the natural choice
                //for the starting y position of the arrows. But, we actually have to use thumbW/2
                //because the thumbnails have already been offset by half of thumbW due to being
                //aligned vertically with each other.
                var startY = (thumbW / 2);
                //This is the rightward facing triangle
                var tri:Sprite = new Sprite();
                tri.graphics.beginFill(0xFFFFFF);
                tri.graphics.moveTo(startX, startY);
                tri.graphics.lineTo(startX, (startY + triW));
                tri.graphics.lineTo((startX + triW), (startY + (triW/2)));
                tri.graphics.lineTo(startX, startY);
                tri.graphics.endFill();
                tri.buttonMode = true;
                tri.useHandCursor = true;
                tri.addEventListener(MouseEvent.CLICK, moveLeft);
                addChild(tri);
                //This is the leftward facing triangle
                var tri2:Sprite = new Sprite();
                var startX2 = (startX + (triW * 2));
                tri2.graphics.beginFill(0xFFFFFF);
                tri2.graphics.moveTo(startX2, startY);
                tri2.graphics.lineTo(startX2, (startY + triW));
                tri2.graphics.lineTo((startX2 - triW), (startY + (triW / 2)));
                tri2.graphics.lineTo(startX2, startY);
                tri2.graphics.endFill();
                tri2.buttonMode = true;
                tri2.useHandCursor = true;
                tri2.addEventListener(MouseEvent.CLICK, moveRight);
                addChild(tri2);
                //Increase m (see above)
                m++;
    //This function moves the entire Gallery MovieClip to the left 800 pixels.
    function moveLeft(event:MouseEvent):void {
        var leftTween:Tween = new Tween(this, "x", Regular.easeOut, this.x, (this.x - 800), .5, true);
    //This function moves the entire Gallery MovieClip to the right 800 pixels.
    function moveRight(event:MouseEvent):void {
        var rightTween:Tween = new Tween(this, "x", Regular.easeOut, this.x, (this.x + 800), .5, true);
    //This function resizes the loaded images to the desired thumbnail dimensions and adds them
    //to the display list.
    function thumbResize():void {
        //The highest level of organization of thumbnails is the batch. There are only as many batches
        //as the length of the thumbArray divided by 8 (the max amount of thumbnails in a batch, as determined
        //by mom.)
        for (var batch = 0; batch < Math.ceil(thumbArray.length / 8); batch++) {
            trace("batch " + batch);
            //This Sprite serves as the container that we use to position entire batches
            var batchSprite: Sprite = new Sprite();
            //The logic behind setting the x position of the batchSprite to 800 x batch should be self-evident --
            //we want each new batch to be 800 pixels to the right of the former one -- but the addition of (thumbW
            //divided by 1.5) is a kluge fix for how much space to give the batches on left margin.
            batchSprite.x = (thumbW / 1.5) + (batch * 800);
            addChild(batchSprite);
            //The second highest level of organization for our thumbnails is the row. Our grid of thumbnails is
            //two rows deep.
            for (var row = 0; row < 2; row++) {
                trace("     row " + row);
                //The third highest level of organization for our thumbnails is the column. Our grid of thumbnails is
                //four columns deep.
                for (var col = 0; col < 4; col++) {
                    trace("          col " + col);
                    trace("               thumb " + thumbNum);
                    if (thumbNum < thumbArray.length) {
                        //The following is the logic structure for handling the resizing of images. The goal was to develop
                        //a system robust enough to allow my mom to put whatever size images she wanted on the server and the
                        //app would use them. The logic is explained at each step...
                        //If the width of the image is greater than the ideal width, OR the height is greater than the ideal height...
                        if ( thumbArray[thumbNum].content.width > thumbW || thumbArray[thumbNum].content.height > thumbH) {
                            //And if the width of the image is greater than the height, apply Scaler 1...
                            if ( thumbArray[thumbNum].content.width > thumbArray[thumbNum].content.height ) {
                                //Scaler 1 is the ratio of the ideal width to the image width
                                var scaler1 = thumbW / thumbArray[thumbNum].content.width;
                                trace("               scaler1 = " + scaler1);
                                //Apply Scaler 1 to both the width and height of the image
                                thumbArray[thumbNum].content.scaleX = thumbArray[thumbNum].content.scaleY = scaler1;
                                trace("               image width:" + thumbArray[thumbNum].content.width);
                                trace("               image height:" + thumbArray[thumbNum].content.height);
                                //Otherwise, apply Scaler 2
                            } else {
                                //Scaler 2 is the ratio of the ideal width to the image height
                                var scaler2 = thumbW / thumbArray[thumbNum].content.height;
                                trace("               scaler2 = " + scaler2);
                                //Apply Scaler 2 to both the width and height of the image
                                thumbArray[thumbNum].content.scaleX = thumbArray[thumbNum].content.scaleY = scaler2;
                                trace("               image width:" + thumbArray[thumbNum].content.width);
                                trace("               image height:" + thumbArray[thumbNum].content.height);
                            //Otherwise... (that is, the image width and height are in both cases less than the ideal)
                        } else {
                            //And if the width of the image is greater than the heigh, apply Scaler 3
                            if ( thumbArray[thumbNum].content.width > thumbArray[thumbNum].content.height ) {
                                //Scaler 3 is the ratio of the ideal width to the image width
                                var scaler3 = thumbW / thumbArray[thumbNum].content.width;
                                trace("               scaler3 = " + scaler3);
                                //Apply Scaler 3 to both the width and height of the image
                                thumbArray[thumbNum].content.scaleX = thumbArray[thumbNum].content.scaleY = scaler3;
                                trace("               image width:" + thumbArray[thumbNum].content.width);
                                trace("               image height:" + thumbArray[thumbNum].content.height);
                            } else {
                                //Scaler 4 is the ratio of the ideal width to the image height
                                var scaler4 = thumbW / thumbArray[thumbNum].content.height;
                                trace("               scaler4 = " + scaler4);
                                //Apply Scaler 4 to both the width and height of the image
                                thumbArray[thumbNum].content.scaleX = thumbArray[thumbNum].content.scaleY = scaler4;
                                trace("               image width:" + thumbArray[thumbNum].content.width);
                                trace("               image height:" + thumbArray[thumbNum].content.height);
                        //Here is where we center the images vertically...
                        thumbArray[thumbNum].content.x = - (thumbArray[thumbNum].content.width / 2);
                        //Here is where we center the images horizontally...
                        thumbArray[thumbNum].content.y = - (thumbArray[thumbNum].content.height / 2);
                        //Before placing them in their own container Sprite, so that their relative positions can be
                        //determined accurately (a task that would've been otherwise impossible after the
                        //adjustments to position made above.)
                        var thumby = new MovieClip();
                        thumby.addChild(thumbArray[thumbNum]);
                        //thumbW being the max possible length or width of any one thumbnail (this was done for visual
                        //consistency and codified in the logic tree above), placing two thumbnails thumbW
                        //apart (measuring from center point in either case) will put them edge to edge at best. This is why
                        //we add (thumbW / 8) as additional spacing.
                        thumby.y = (row * (thumbW + (thumbW / 8)));
                        thumby.x = (col * (thumbW + (thumbW / 8)));
                        thumby.buttonMode = true;
                        thumby.useHandCursor = true;
                        var fA:Array = new Array();
                        var dS:DropShadowFilter = new DropShadowFilter(5, 45, 0x000000, 0.33, 5, 5, 1, 1);
                        fA.push(dS);
                        thumby.filters = fA;
                        trace("thumby.width = " + thumby.width);
                        trace("thumby.height = " + thumby.height);
                        batchSprite.addChild(thumby);
                        thumbNum++;
    function enLarge(event:MouseEvent):void {
        var indexNum:Number = new Number();
        indexNum = thumbArray.indexOf(event.currentTarget);
        trace("indexNum = " + indexNum);
        darkStage = new Sprite();
        darkStage.graphics.beginFill(0x333333, .9);
        darkStage.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
        darkStage.addEventListener(MouseEvent.CLICK, reMove);
        darkStage.buttonMode = true;
        darkStage.useHandCursor = true;
        (parent  as  MovieClip).addChild(darkStage);
        loadSprite = new Sprite();
        loadSprite.addChild(loadArray[indexNum]);
        loadSprite.x = (stage.stageWidth / 2);
        loadSprite.y = (stage.stageHeight / 2);
        loadSprite.addEventListener(MouseEvent.CLICK, reMove);
        loadSprite.buttonMode = true;
        loadSprite.useHandCursor = true;
        loadSprite.mouseEnabled = false;
        (parent  as  MovieClip).addChild(loadSprite);
        var urlRequest:URLRequest = new URLRequest("xmls/" + indexNum + ".xml");
        var titleURL:URLLoader = new URLLoader();
        titleURL.addEventListener(Event.COMPLETE, completeListener);
        titleURL.load(urlRequest);
        function completeListener(event:Event):void {
            titleText = new TextField();
            titleText.autoSize = TextFieldAutoSize.LEFT;
            var myFont:Font = new BOF();
            var ttFormat:TextFormat = new TextFormat();
            ttFormat.color = 0xFFFFFF;
            ttFormat.size = 18;
            ttFormat.font = myFont.fontName;
            textSprite = new Sprite();
            textSprite.addChild(titleText);
            (parent  as  MovieClip).addChild(textSprite);
            var titleXML:XML = new XML(titleURL.data);
            titleText.text = titleXML.toXMLString();
            titleText.setTextFormat(ttFormat);
            titleText.embedFonts = true;
            textSprite.y = 570;
            textSprite.x = ((stage.stageWidth / 2) - (titleText.textWidth / 2));
            textSprite.mouseEnabled = false;
            titleText.mouseEnabled = false;
    function reMove(event:MouseEvent):void {
        (parent  as  MovieClip).removeChild(textSprite);
        (parent  as  MovieClip).removeChild(loadSprite);
        (parent  as  MovieClip).removeChild(darkStage);
    function addClickOnThumb():void {
        var cot:ClickOnThumbnail = new ClickOnThumbnail();
        cot.x = 400;
        cot.y = 583;
        (parent  as  MovieClip).addChild(cot);

    Hey Jim
    Wow, that's great; thanks! Can I ask what settings you used to get the files so small?
    Yes, I am familiar with Photoshop and image optimization issues, but I didn't realize that PNG was so much bigger than JPG and that I had so much file size I could shed before I would notice a degradation in image quality. Your advice will certainly help greatly, and I will certainly apply it to the thumbs as well. I think my mom will be very pleased.  : )
    I look forward to hearing what collection of settings you used.
    Thanks and Be Well
    Graham

  • Is there a better way to generate custom timed digital Signals

    I am trying to generate digital output of high and lows with particular delays on different lines. Each daq assistant is activating single line on a port on USB 6501. There more complex high and lows that I need to generate with variable time difference between high and low. There is codebelow which accomplishes what I am trying to achieve but for executing a long pattern of high and low signal is very time consuming to do this way. I am sure there is a better way to do this, I  not a expert on labview so I haven't uncovered its full potential. Can anybody suggest a more effective and a quick way to do this. I would hgihly appreciate. Thanks!
    I have not shown in the code below but through DAQ assistant I have initialized lines to low level logic.
    Solved!
    Go to Solution.

    See the attached file
    Attachments:
    Digital Signal.vi ‏335 KB

  • Is there a better way to stop a Method than Thread.stop()?

    First my basic problem. In one of my programs I am using constraint solver. I call the constraint solver with a set of constraints and it returns a Map with a satisfying assignment. In most cases this works in acceptable time ( less than 1 second). But in some cases it may take hours. Currently I am running the function in a Thread and using Thread.stop(). This look like that:
         public Map<String, Object> getConcreteModel(
                   Collection<Constraint> constraints) {
              WorkingThread t=new WorkingThread(constraints);
              t.setName("WorkingThread");
              t.start();
              try {
                   t.join(Configuration.MAX_TIME);
              } catch (InterruptedException e) {
              if(t.isAlive()){
                   t.stop();
              return t.getSolution();
         }where t.getSolution(); returns null if the Thread was interrupted.
    Unfortunately this sometimes crashes the JVM with:
    # A fatal error has been detected by the Java Runtime Environment:
    #  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000006dbeb527, pid=5788, tid=4188
    # JRE version: 6.0_18-b07
    # Java VM: Java HotSpot(TM) 64-Bit Server VM (16.0-b13 mixed mode windows-amd64 )
    # Problematic frame:
    # V  [jvm.dll+0x3fb527]
    # An error report file with more information is saved as:
    # F:\Eigene Dateien\Masterarbeit\workspace\JPF-Listener-Test\hs_err_pid5788.log
    # If you would like to submit a bug report, please visit:
    #   http://java.sun.com/webapps/bugreport/crash.jsp
    #Does anyone knows a better way to do it?
    Thank you in advance.
    Note 1: the Constraint solver is a Third Party tool and changing it is unfeasible. (I have tried it already)
    Note 2: Using Thread.stop(Throwable t) only chances the error message.

    In case somebody have the same problem here my code which solves the problem. Note it requires to parameters and the result to be serializable.
    The Class which starts to Process:
    public class Solver{
         public Map<String, Object> getConcreteModel(
                   Collection<Constraint> constraints) {
                   try
                        Process p=Runtime.getRuntime().exec(...); //do not forget the classpath
                        new TimeOut(Configuration.MAX_TIME, p).start();
                        ObjectOutputStream out=new ObjectOutputStream(p.getOutputStream());
                        new ErrReader(p.getErrorStream()).start();//not that std.err fills up the pipe
                        out.writeObject(constraints);
                        out.flush();
                        ObjectInputStream in=new ObjectInputStream(p.getInputStream());
                        return (Map<String, Object>) in.readObject();
                   catch(IOException e)
                        return null;
                   } catch (ClassNotFoundException e) {
                        //should not happen
                        return null;
         // For running in a own process
         static private class TimeOut extends Thread
              private int time;
              private Process p;
              public TimeOut(int time, Process p)
                   this.time=time;
                   this.p=p;
              @Override
              public void run() {
                   synchronized (this) {
                        try {
                             this.wait(time);
                        } catch (InterruptedException e) {
                   p.destroy();
         static class ErrReader extends Thread
             InputStream is;
             ErrReader(InputStream is)
                 this.is = is;
                 this.setDaemon(true);
             public void run()
                 try
                     InputStreamReader isr = new InputStreamReader(is);
                     BufferedReader br = new BufferedReader(isr);
                     String line=null;
                     while ( (line = br.readLine()) != null)
                         System.err.println(line);   
                     } catch (IOException ioe)
                         ioe.printStackTrace(); 
    }And the class which executet the Program
    public class SolverProcess {
          * @param args ignored
         public static void main(String[] args){
              try {
                   ObjectInputStream in =new ObjectInputStream(System.in);
                   SolverProcess p=new SolverProcess();
                   p.constraints=(Collection<Constraint>) in.readObject();
                   p.compute();
                   ObjectOutputStream out=new ObjectOutputStream(System.out);
                   out.writeObject(p.solution);
                   out.flush();
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              //System.err.println("solved");
              System.exit(0);
         private Map<String, Object> solution=null;
         private Collection<Constraint> constraints;
           private void compute()
    }

  • Looking for a better way to utilize streams to track deletes in the db.

    I'm trying to figure out a way to track deletes in the database using streams. I found that a dml_hander for deletes could satisfy my needs but it appears I would need to create a dml_handler for each table in the schema. Since I have ~250 tables I'm thinking there has to be a better way to do this. I simply need a way to capture all deletes and insert them into a table before they are deleted from the db. Is there a better way then creating a handler for each table?
    Thanks,
    Doug

    So far you haven't posted a version number or any information about the use of any auditing tool, whether FGA or other auditing so it is impossible to either comment or advise you further.
    If you want help you are going to need to do something you did not do in your original post and that is provide a description of your environment, your business rules, how you have attempted to use FGA or standard auditing, etc. Streams is for replication not auditing so perhaps you mean AQ but so far you haven't said that yet either.
    The more information you can provide, and perhaps some code or clear descriptions of what you've attempted, the better the help possible.

  • Looking for a better way to determine string variable from multiple options

    Hi,
    I trying to figure out a better way to determine a string variable from multiple options.
    Say i have five pictures each with a different filename: img1 - img5...these file names could be named anything really but for this example i will keep them as img1, img2, img3, img4 and img5.
    I want to display a messagebox with the string depending on what a certain variable is.
    So for example, we have the number X, if X = 1 then i want the messagebox to show "img1" as the message
    Essentially the way I have been doing it so far is:
    Private Sub WhichImage()
    Dim ImageName As String = ""
    Dim i as integer
    If i = 0 Then
    ImageName = "img1"
    End If
    If i = 1 Then
    ImageName = "img2"
    End If
    If i = 2 Then
    ImageName = "img3"
    End If
    If i = 3 Then
    ImageName = "img4"
    End If
    If i = 4 Then
    ImageName = "img5"
    End If
    MessageBox.show(imagename, "Name of image", MsgBox.Style.OkOnly, MsgBoxResult.Ok)
    end
    Up until now, this has been fine, but what if I have 50 images, do I have to do this for all 50 images? or is there an easier way like putting the image names into a text file and have it read from the file depending on what the variable i equals? If so,
    how do I go about this? Does each image name go on a separate line? can it just be separated by a comma instead? or is there a better way?
    Please note that i know that i have declared "i" above in my code and not intialised it with anything, in reality "i" comes from somewhere else in the program so please ignore that part, it is not what I am concerned with.
    Thanks
    Mersec

    Does each image name go on a separate line? can it just be separated by a comma instead? or is there a better way?
    Arrays are useful for this.
    Dim imagenames() As String = {"img1", "img2", "img3", "img4", "img5"}
    Dim imagename As String = imagenames(i)
    MessageBox.Show(imagename, "Name of image")
    Any sort of collection will do instead of an array, and may be simpler to manage. There are many other options - the most suitable one probably depends on where the names originally come from.  For instance, if you are getting them from a folder
    using the FileSystem.GetFiles method, then they are already in a collection.
    If the files names never change then you may as well include them in the program code, using something like the code above.  If they can change, then you could use a text file, but that means you need a file update routine.  If that is required
    then the way you store the names will dictate how you access them.

  • Better Way To Do This? Selector Operator...

    I'm currently writing the selection operator for the algorithm. The aim of it is
    to rate how the coursework block have been allocated and give there allocation
    a rating...
    How I have done it is have a method that searches through the one of the parent
    timetables. It looks for coursework time blocks. Once it finds one it notes
    this and looks at the next block along. If this is a coursework time block it
    notes this as well. I then perform an operation comparing these two coursework
    time blocks to find out if they are for the same Module. If they are not this
    is not a very effective coursework timetable strategy.
    Because of this I note in an array the the position of these two coursework time
    block and give them a fitness rating of 1000. I then go on to see if the next
    block is a coursework time block. If it is and its not of the same Module ID of
    the two previous then I not these 3 block down in an array and give them a
    fitness rating of 2000.
    My concern is that I am using allot of if and for loop's and the code is
    starting to look untidy at best. Is there any better way of doing this?
    Below Is my code:
          * @param parentOne
          * @param parentTwo
         public void selectionOperator(ArrayList parentOne, ArrayList parentTwo){
              // Store's the fitness rating of sections of the timetable...          
              ArrayList parentOneBlockFitnessRating = new ArrayList ();
              ArrayList parentTwoBlockFitnessRating = new ArrayList ();
              //Loops through the timetable's timeblocks...
              for (int i = 0; i < parentOne.size(); i++) {
                   //Checks to see if the current time block is of the class: CourseworkTimeBlock,
                   //if so it enters this statement...
                   if(parentOne.get(i).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                        //A temp store for the current CourseworkTimeBlock...
                        CourseworkTimeBlock tempBlockOne = (CourseworkTimeBlock) parentOne.get(i);
                        System.out.println("Got Here!, Module ID...: " + tempBlockOne.getModuleId());
                        //Checks to see if the next time block along is of the class: CourseworkTimeBlock,
                        //if so it enters this statement...
                        if(parentOne.get(i+1).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                             //A temp store for the next CourseworkTimeBlock...
                             CourseworkTimeBlock tempBlockTwo = (CourseworkTimeBlock) parentOne.get(i+1);
                             System.out.println("Got Here Aswell!");
                             //Checks to see if the current and next CourseworkTimeBlock module Id's
                             //are the same, if there arn't then this section is entered...
                             if(!tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId())){
                                  //Checks to see if the second time block along is of the class: CourseworkTimeBlock,
                                  //if so it enters this statement...
                                  if(parentTwo.get(i+2).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                                       //A temp store for the second CourseworkTimeBlock along...
                                       CourseworkTimeBlock tempBlockThree = (CourseworkTimeBlock) parentTwo.get(i+2);
                                       //Checks to see if all 3 of the Module Id's of the CourseworkTimeBlocks match,
                                       //if they don't match this statement is entered...
                                       if(! tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId()) && (tempBlockTwo.getModuleId().equals(tempBlockThree.getModuleId()))) {
                                            //ArrayList to store the fitness rating of the current block
                                            //selection...
                                            ArrayList <Integer> blockFitness = new ArrayList<Integer>();
                                            //Position of first block.
                                            blockFitness.add(i);
                                            //Position of second block.
                                            blockFitness.add(i+1);
                                            //Position of second block.
                                            blockFitness.add(i+2);
                                            //Fitness Value
                                            blockFitness.add(2000);
                                            //Add block rating to main rating ArrayList...
                                            parentOneBlockFitnessRating.add(blockFitness);
                                       else{
                                            //ArrayList to store the fitness rating of the current block
                                            //selection...
                                            ArrayList <Integer> blockFitness = new ArrayList<Integer>();
                                            //Position of first block.
                                            blockFitness.add(i);
                                            //Position of second block.
                                            blockFitness.add(i+1);
                                            //Fitness Value
                                            blockFitness.add(1000);
                                            //Add block rating to main rating ArrayList...
                                            parentOneBlockFitnessRating.add(blockFitness);
              for (int o = 0; o < parentTwo.size(); o++) {
                   if(parentTwo.get(o).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                        CourseworkTimeBlock tempBlockOne = (CourseworkTimeBlock) parentTwo.get(o);
                        System.out.println("Got Here!, Module ID...: " + tempBlockOne.getModuleId());
                        if(parentTwo.get(o+1).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                             CourseworkTimeBlock tempBlockTwo = (CourseworkTimeBlock) parentTwo.get(o+1);
                             System.out.println("Got Here Aswell!");
                             if(!tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId())){
                                  if(parentTwo.get(o+2).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                                       CourseworkTimeBlock tempBlockThree = (CourseworkTimeBlock) parentTwo.get(o+2);
                                       if(! tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId()) && (tempBlockTwo.getModuleId().equals(tempBlockThree.getModuleId()))) {
                                            ArrayList <Integer> blockFitness = new ArrayList<Integer>();
                                            //Position of first block.
                                            blockFitness.add(o);
                                            //Position of second block.
                                            blockFitness.add(o+1);
                                            //Position of second block.
                                            blockFitness.add(o+2);
                                            //Fitness Value
                                            blockFitness.add(2000);
                                            //Add block rating to main rating ArrayList...
                                            parentTwoBlockFitnessRating.add(blockFitness);
                                       else{
                                            ArrayList <Integer> blockFitness = new ArrayList<Integer>();
                                            //Position of first block.
                                            blockFitness.add(o);
                                            //Position of second block.
                                            blockFitness.add(o+1);
                                            //Fitness Value
                                            blockFitness.add(1000);
                                            //Add block rating to main rating ArrayList...
                                            parentTwoBlockFitnessRating.add(blockFitness);
         }As you can see there are allot if statements and some bad coding practice to boot. But I don't know what other ways to do it....
    Any directions of other ways how to do this?
    Many Thanks
    Chris

    Unfortunately, I think you're stuck with a bunch of if-statements.
    Fortunately, I have some things that may help you.
    First, I usually make sure something is of x class via this
    if (someObject instanceof SomeClass) {So, I'd adjust your 'class checking' conditionals from this
    if(parentOne.get(i).getClass().toString().equals("class Timetable.CourseworkTimeBlock"))to this
    if (parentOne.get(i) instanceof Timetable.CourseworkTimeBlock) {Secondly, your code logic is kind of confusing.
    Why do you have a for-loop that iterates through every CourseworkTimeBlock, if you then (within each possible iteration) check iteration+1 and iteration+2? What happens if those throw an ArrayIndexOutOfBoundsException, or are null?

Maybe you are looking for

  • Drilldown malfunction

    Hi all, I am not able to drilldown to lowest level of my dimension. There is no actually error message and only thing that remains forever on the screen is " Searching... To cancel, click here.". I have found connection between number of used filters

  • Error in owa when trying to log in

    I am experiencing this error and am not sure what is going on with this. the log in page is presented fine but once you log in you get the following error. its is effecting all users on the OWA. :-(   something went wrong Sorry, we can't get that inf

  • Convert a SAPScript spooled file to PDF

    I have an urgent request to build a front-end interface to map the parameters to SAP Standard object RFOAVIS_FPAYM. This is the driver program for Remit (Payment) Advice Notes using SAPScript.   I need to create a way to submit RFOAVIS_FPAYM and Retu

  • MRN9 How it will work when the stock is negative qty

    Hi, We have facing one problem while doing inventory valuation. when we running the program MRN9 it will determine the balance sheet value from comparition of lowest price then it will update. But the stock in negativeside like -1000kg qty and the NR

  • SM21 - Error found in PBT environment, FM = SPBT_GET_CURR_RESOURCE_INFO

    Hi, During idoc processing we see following messages generated in SAP system log which complain that the servers are getting disconnects from message server.. SM21 :: Error found in PBT environment, FM = SPBT_GET_CURR_RESOURCE_INFO > Failure checking