Coercing Variables

Hello;
I have written a class that replaces strings in strings iteratively throughout the entire main string. However, when I call it, of course, it becomes and [object ReplaceString] when I really need it to be a plain old String. How do I get from one to the other?
Thanks,
Terry

Hello
Well, every now and then I see this sort of question.
return 1.1 - 1.0 = 0.1 -- > false
return 0.5 - 0.4 = 0.1 -- > false
return 0.7 - 0.3 = 0.4 -- > false
return 1.3 - 1.2 = 0.1 -- > false
etc.
Why?
Because it is the nature of binary floating point arithmetic of finite precision, that most computer uses in calculating decimal fractions and numbers larger than N-bit integer. (N depends upon architecture and library)
Indeed,
1.1 - 1.0 - 0.1 = 8.32667268468867E-17
0.5 - 0.4 - 0.1 = -2.77555756156289E-17
0.7 - 0.3 - 0.4 = -5.55111512312578E-17
1.3 - 1.2 - 0.1 = 8.32667268468867E-17
etc.
These results are 'correct', that is they conform to the rule of binary floating point arithmetic of double-precision (IEEE Standard 754).
cf.
Inside Machintosh: PowerPC Numerics (archived pdfs - one file per chapter)
http://developer.apple.com/documentation/mac/PPCNumerics/PPCNumerics-2.html
Idem. (one pdf file)
http://developer.apple.com/documentation/Performance/Conceptual/MacOSX_Numerics/Mac_OSXNumerics.pdf
(Yes, old document but still quite valid about IEEE 754 etc.)
So it is very important practice to round floating point number to some significant digits before comparison. It's also true in most programming language. Remember to round decimals before comparison!
Something like this.
--CODE
set x to 1.1 - 1.0
set y to 0.1
--return roundn(x, -1) = roundn(y, -1) --> true
--return roundn(x, -12) = roundn(y, -12) --> true
return roundn(x - y, -12) = 0 --> true
on roundn(x, d)
number x : source number
integer d : rounding target place (i.e. rounding up/down to (10 ^ d)'s place)
set h to 10 ^ d
return (round (x / h) rounding to nearest) * h
end roundn
--END OF CODE
Hope this may help,
H

Similar Messages

  • Calling a variable in an instance name

    Maybe I am far off here, but I'm hoping someone can help.
    Basically I'm creating a question with 4 answers (i.e. a,b,c,d).
    I have my question working fine, but I'm having a problem adding a check mark beside the answers once the user clicks the submit button.
    I've created four instances of my check mark; rightAns1_mc, rightAns2_mc, rightAns3_mc, rightAns4_mc.  I've set them all to _invisible = false;
    I've also set up a variable; nCheck:Number = 0; and when the user clicks one the radial buttons I have the variable change (i.e. if they click A, it set to nCheck = 1; if they click B, it sets to nCheck = 2; etc)
    So in my if statement for the submit button I figured I could have rightAns(nCheck)_mc._visible = true;
    This completely breaks everything. Like I said, I'm probably far off here. If I am what should I do differently, and if I'm close what am I doing wrong?

    use array notation to coerce flash to resolve strings to objects:
    this["rightAns"+nCheck+"_mc"]._visible=true;

  • Get all file names in a folder, set each as text variable

    First off, I do not know if this is possible.
    For an app I'm writing, I need it to get a list of all the file names inside of a folder, then set a text variable for each of the file names. The app will then display a list of those items, which I know what to do from there.
    If anyone knows how I would be able to do this, or alternatives, I would be extremely grateful.
    Thanks in advance!

    just use any colon separated path (i.e., the desktop would be {color:blue}HD:Users:yourname:Desktop:{colors}) basically, path specifiers come in a number of types:
    # text designations - HD:Users:yourname:Desktop (just a normal text line)
    # posix designations - /Users/yourname/Desktop (how unix expects paths to be written)
    # alias designations - alias "HD:Users:yourname:Desktop" (a pointer to an actual, existing file system element
    # file system referents - file "HD:Users:yourname:Desktop:somefile", folder "HD:Users:yourname:Desktop", etc -
    # file system objects - Folder "Desktop" of folder "yourname" of folder "Users" of disk "HD"
    each has its advantages and disadvantages, and you can coerce between them (though not completely - you need to convert #5 to text before you can convert it to #3, for instance.

  • Oracle BLOB value to a LC variable

    Hello,
    Is it possible in LC ES2 to coerce oracle blob value to some livecycle variable ?
    When mapping sql query result (column of type BLOB) to a LC variable (of type Document), we receive:
    com.adobe.workflow.datatype.InvalidCoercionException: Cannot coerce object: oracle.sql.BLOB@27e7d6 of type: oracle.sql.BLOB to type: com.adobe.idp.Document
    We have tried mapping to string, binary, Document (, we even desperately hardcoded sql.oracle.BLOB to process XML), but none of this works.
    Is it possible to solve this other way, then following ?
    http://groups.google.com/group/livecycle/browse_thread/thread/6c4b9156b52b71a7
    Thanks.

    My idea is to fetch the BLOB column data as UTF8 (base64) encoded string and then use getDocumentFromBase64 available in ES2.
    I am not sure what syntax is to fetch from ORACLE.
    I have used MySql database and the query is:
    SELECT CONVERT(Blob_Column USING UTF8) as MyBlobDataAsBase64Str FROM myTableName;
    Now using SetValue activity to look like:   myXMLvariable = getDocumentFromBase64(strVariableHoldingBase64Data)
    This case works perfectly without any issues.
    The problems is you should find out the appropriate syntax for ORACLE.
    I was searching about CONVERT() & UNISTR() functions. But i'm unable to evaluate.
    Try by yourself..
    Nith

  • Use global Variable for Formatstring

    Hello
    I wanna use a global variable for a format string. see picture. But I don't work.
    Can anybody give me an idea, why it won't work?
    Thanks a lot!!!
    Attachments:
    GlobalVariable.jpg ‏61 KB

    As others said, the problem is not the global.
    See attached a picture of how to do what you want. Since the Format String is unknown at edit time, you must provide the types to all inputs that are not DBL.
    From your example, the while loop has been coded exactly like a for loop. It can be replaced with a for loop with auto-indexing, unless you really want the local variable to be update at each iteration every 50 ms. This delay is not necessary unless the computed array is huge and you want to leave some CPU time to other code in your application. Even then you can enter a delay of 0ms to force to swap to other tasks.
    I don't know what your INT>BOOL VI does but using Scan from String you can read a number directly into a boolean. The number i
    s rounded to an unsigned integer and 0 is False and >0 is True.
    For example you scan a string for a boolean with format string %d.
    "0" --> False
    "24" --> True
    "-18" -- False (coerced to unsigned = 0)
    You scan a string for a boolean with format string %f:
    Negative number up to "0.5" --> False (coerced and rounded to 0)
    Number greater that 0.5 --> True
    LabVIEW, C'est LabVIEW
    Attachments:
    diag.jpg ‏15 KB

  • Variable Searching

    I have a list of document names saved in a XML process variable.  I want to be able to search for a particular document name and see what process is handling it, whether it is complete, running, who is currently assigned, etc.
    My investigation of the API documentation seems to suggest this is impossible through the API.
    You can only set "simple" variables to searchable or visible.
    TaskManagerQueryService.getProcessVariableValues(long taskId) only returns results that are set to searchable or visible.
    Does this leave me with the following alternatives?
    Coerce the XML data into a String?
    Save the information I need to query in a separate database?
    Go directly to the LC database to search for data?

    Well, I decided to go directly to the database to fetch the information.  If you want to get process data, LiveCycle creates a table for every defined process in order to save process instance variable data.  So Process A will store data in table tb_pt_process_a.
    So, given I have a process ID, how do I know what table to go look for the data in?
    Go look in the tb_process_instance table to find the process name?
    Convert process name to table name?
    Or is there a way through JOINS to do this?  Does Adobe have a table somewhere that maps between process names and table names?
    Is there a database schema diagram that explains what all the tables are used for?

  • Latch an "In Range and Coerce" Output until Reset

    I have numerous voltages and signals that I am reading from an PXI system.  Each of these signals needs to fall between a minimum and maximum.
    Right now, the entire "program" is running inside of a While Loop.  Each signal is being read and then passed to an "In Range and Coerce".  This function is working well, in that it notifies me when the value falls outside of the maximum and minimum.  But what I need to do is to "latch" the output from the "In Range and Coerce" until I have completed other functions also running in this While Loop.
    I'm very new to LabView and a hardware engineer on top of that.  I know that the way I'm doing this is probably not the best way.  I am open to any suggestions.
    Thanks,
    -Steve

    It sounds to me like the kind of "latching" you're looking for is automatically available to you as a side-effect of LabVIEW's "dataflow" nature.
    Once a value exits an output terminal of the "In Range and Coerce" function, all wire paths connected to that output will receive the exact same value. I.e., once a value gets on a wire, it remains constant through all branchings connected to that wire.  If you turn on debug highlighting mode, you'll see what this means more visually.
    A common source of LabVIEW problems for people experienced in text languages is overuse of local and/or global variables.  Perhaps this is the root of your issues with "latching?"
    In text languages, data is contained within and "transported" by variables.  In LabVIEW, data is contained within and transported by wires.  In LabVIEW, variables and controls/indicators are just termination points to allow the data to be displayed or passed to/from calling functions.  They aren't really important in and of themselves.
    -Kevin P.

  • XQUERY against an XMLTYPE variable

    I have a procedure which gets xmltype instance and i have to use xquery upon that variable.
    declare
    myxml xmltype;
    s varchar2(20);
    begin
    myxml:=xmltype('<person><name id="1" age="23"/><name id="2" age="25"/></person>');
    SELECT
    XMLQuery(
    'for $i in /person
    where $i/age > 24
    return $i/id'
    PASSING myxml RETURNING CONTENT) into s
    FROM DUAL;
    end;
    BUT i get this error
    ORA-06550: line 6, column 1:
    PLS-00801: internal error [*** ASSERT at file pdw4.c, line  793; Cannot coerce
    between type 43 and type 30; anon_68F441E0__AB[6, 1]]
    Please help it is urgent

    Not sure if you ever received your answer regarding how to pass an XMLType variable in PLSQL to an XQuery command.
    Here is an example of what I've been using... in Oracle 10.2.0.1
    SET SERVEROUTPUT ON SIZE 200000
    DECLARE
    l_result XMLType;
    l_xxDoc XMLType := XMLType(
    <root>
    <things>
    <somestuff>12345</somestuff>
    <morestuff>12345</morestuff>
    </things>
    <things>
    <somestuff>dfgdfg</somestuff>
    <morestuff>werwer</morestuff>
    </things>
    </root>
    PROCEDURE printClobOut
    (p_result IN CLOB)
    IS
    v_xmlstr VARCHAR2(32767);
    v_line VARCHAR2(2000);
    BEGIN
    v_xmlstr := DBMS_LOB.SUBSTR(p_result,32767);
    LOOP
    EXIT WHEN v_xmlstr IS NULL;
    v_line := SUBSTR(v_xmlstr,1,INSTR(v_xmlstr,CHR(10))-1);
    DBMS_OUTPUT.PUT_LINE('| '||v_line);
    v_xmlstr := SUBSTR(v_xmlstr,INSTR(v_xmlstr,CHR(10))+1);
    END LOOP;
    END;
    BEGIN
    select XMLQUERY(
    'for $a in $TheDoc/root
    return <theresult>
    {$a/things}
    </theresult>
    PASSING l_xxDoc as "TheDoc"
    RETURNING CONTENT) into l_result
    from dual;
    printClobOut(l_result.extract('/').getClobVal());
    END;
    Kevin

  • METHOD4의 INTERNAL/EXTERNAL DATATYPE & COERCING DATATYPE(SQLPRC)

    제품 : PRECOMPILERS
    작성날짜 : 1998-05-14
    METHOD4에서는 DATA TYPE을 변경해주어야 하는 경우가 있으므로
    INTERNAL DATATYPE과 EXTERNAL DATATYPE이 어떻게 다르고 이것이
    어떻게 이용되는지 알아야 한다. 그리고 특해 SQLDA->T의 값이
    각 TYPE의 숫자로 들어가므로 아래의 내용을 참조하여 DATA TYPE을
    유추해야한다.
    << Internal Datatype >>
    VARCHAR2          1
    NUMBER               2
    LONG               8
    ROWID               11
    DATE               12
    RAW               23
    LONG RAW          24
    CHARACTER(or CHAR)     96
    MLSLABEL          106
    << External Datatypes >>
    VARCHAR2          1
    NUMBER               2
    INTEGER               3
    FLOAT               4
    STRING               5
    VARNUM               6
    DECIMAL               7
    LONG               8
    ROWID               11
    DATE               12
    VARRAW               15
    RAW               23
    LONG RAW          24
    UNSIGNED          68
    DISPLAY               91
    CHARACTER(or CHAR)     96
    MLSLABEL          106
    << Coercing Datatype >>
    internal 과 external datatype간의 변경이 어려울때가 있다.
    (NUMBER를 FLOAT으로 바꾸는 경우) 이럴경우 select-list는
    DESCIBE SELECT LIST이후 FETCH이전에 T값을 다시 지정해 주어야 하고,
    bind descriptor는 DESCRIBE BIND VARIABLES전에 값을 지정해 준다.
    이때 L값도 같이 지정해준다.
    == 예 ==
    DATE type을 select-list item으로 DESCRIBE할경우 oracle은 12를
    T값에 지정하고, 7byte의 internal format을 return한다.
    그러므로 DD-MON-YY type으로 값을 얻기 위해서는 T를 1 또는 5로하고
    L을 9또는 10으로 맞추어 주어야 한다.
    NUMBER type역시 마찮가지이다. Internal format이 return될것이므로
    그 자체로는 알아보기가 쉽지 않다. 그러므로 T값을 1,3,4,5등으로 맞추어
    주고 sqlprc()를 이용한다.
    이때 platform에 알맞은 값은 sqlprc.h를 참조한다.
    Sqlprc ( long length, int precision, int *scale );
    length          L에 저장되어 있는 NUMBER값의 길이.
    Precision     NUMBER값의 precision. 0값은 표현할수 없는 값이 있을때
              생기는데 이경우에는38을 넣어 준다.
    Scale          NUMBER값의 scale. 반올림되는 자리수이다. scale이 2이면
              소숫점 두자리 아래에서 반올림하고 -3이면 천자리에서
              반올림한다.
    만약 precision ==> 3, scale ==> -2 이면 숫자의 최대크기는 99900이다.
    /* Declare variables for the function call */
    sqlda     select_des; / pointer to select desctiptor */
    int      prec;     /* precision */
    int      scal;     /* scale */
    extern void sqlprc ( ); /*Declare library function */
    /* Extract precision and scale */
    sqlprc ( *&(select_des->L[I]), &prec, &scal );
    /* Allow for maximum size of NUMBER */
    if (prec == 0)
         prec = 38 ;
    /* Allow form possible decimal point and sign */
    select_des->L[I] = prec + 2;
    if (scal < 0 )
    select_des ->L[I] += -scal;

    제품 : PRECOMPILERS
    작성날짜 : 1998-05-14
    METHOD4에서는 DATA TYPE을 변경해주어야 하는 경우가 있으므로
    INTERNAL DATATYPE과 EXTERNAL DATATYPE이 어떻게 다르고 이것이
    어떻게 이용되는지 알아야 한다. 그리고 특해 SQLDA->T의 값이
    각 TYPE의 숫자로 들어가므로 아래의 내용을 참조하여 DATA TYPE을
    유추해야한다.
    << Internal Datatype >>
    VARCHAR2          1
    NUMBER               2
    LONG               8
    ROWID               11
    DATE               12
    RAW               23
    LONG RAW          24
    CHARACTER(or CHAR)     96
    MLSLABEL          106
    << External Datatypes >>
    VARCHAR2          1
    NUMBER               2
    INTEGER               3
    FLOAT               4
    STRING               5
    VARNUM               6
    DECIMAL               7
    LONG               8
    ROWID               11
    DATE               12
    VARRAW               15
    RAW               23
    LONG RAW          24
    UNSIGNED          68
    DISPLAY               91
    CHARACTER(or CHAR)     96
    MLSLABEL          106
    << Coercing Datatype >>
    internal 과 external datatype간의 변경이 어려울때가 있다.
    (NUMBER를 FLOAT으로 바꾸는 경우) 이럴경우 select-list는
    DESCIBE SELECT LIST이후 FETCH이전에 T값을 다시 지정해 주어야 하고,
    bind descriptor는 DESCRIBE BIND VARIABLES전에 값을 지정해 준다.
    이때 L값도 같이 지정해준다.
    == 예 ==
    DATE type을 select-list item으로 DESCRIBE할경우 oracle은 12를
    T값에 지정하고, 7byte의 internal format을 return한다.
    그러므로 DD-MON-YY type으로 값을 얻기 위해서는 T를 1 또는 5로하고
    L을 9또는 10으로 맞추어 주어야 한다.
    NUMBER type역시 마찮가지이다. Internal format이 return될것이므로
    그 자체로는 알아보기가 쉽지 않다. 그러므로 T값을 1,3,4,5등으로 맞추어
    주고 sqlprc()를 이용한다.
    이때 platform에 알맞은 값은 sqlprc.h를 참조한다.
    Sqlprc ( long length, int precision, int *scale );
    length          L에 저장되어 있는 NUMBER값의 길이.
    Precision     NUMBER값의 precision. 0값은 표현할수 없는 값이 있을때
              생기는데 이경우에는38을 넣어 준다.
    Scale          NUMBER값의 scale. 반올림되는 자리수이다. scale이 2이면
              소숫점 두자리 아래에서 반올림하고 -3이면 천자리에서
              반올림한다.
    만약 precision ==> 3, scale ==> -2 이면 숫자의 최대크기는 99900이다.
    /* Declare variables for the function call */
    sqlda     select_des; / pointer to select desctiptor */
    int      prec;     /* precision */
    int      scal;     /* scale */
    extern void sqlprc ( ); /*Declare library function */
    /* Extract precision and scale */
    sqlprc ( *&(select_des->L[I]), &prec, &scal );
    /* Allow for maximum size of NUMBER */
    if (prec == 0)
         prec = 38 ;
    /* Allow form possible decimal point and sign */
    select_des->L[I] = prec + 2;
    if (scal < 0 )
    select_des ->L[I] += -scal;

  • Getting raw data of a variable

    Is anyone aware of a handy way to get the raw (hex) data of an AppleScript variable into a text string? For example:
    «data rdatEFBBBF»
    «data isot323030372D31322D31325431373A34393A3130»
    I can do some comparisons, and put the raw data as text into a variable, but trying to get the actual raw data as text either fails or gets coerced into whatever it is supposed to be (such as ISOT). Well, actually I can do the "force an error and grab the error message" trick, but there has got to be a better way. Perhaps something along the lines of set X to do shell script "whattheheck " & (SomeVariable as data)?

    Hello
    Under OS9/Classic, we can use a mighty 'cast' command of 'programmer's tool' OSAX made by Ed Lai for this kind of task.
    http://osaxen.com/files/programmerstool1.0a10.html
    Under OSX, the ladder has been removed.
    One dirty way I can think of is to use write and read commands to force to replace the class of given data. Somethnig like this, though it won't work properly with AppleScript 2.0 if the input or output data is a sort of text object.
    --SCRIPT
    set x to «data isot323030372D31322D31325431373A34393A3130»
    --set x to «data rdatEFBBBF»
    --set x to current date
    --set x to {1, 2, 3}
    --set x to "ABC" as Unicode text
    set y to dump(x, string)
    set z to dump(y, data)
    return {x, y, z}
    on dump(x, cls)
      anything x : anything to be dumped [1]
      type class cls : resulting class of dumped data. e.g. string, data etc.
      return anything : dumped data as given class [2]
      * Notes.
      [1] x must be what 'write' osax can write to file. (E.g. script object etc cannot be processed by this method)
      [2] It won't return exact raw byte sequence in AppleScript 2.0 if
        - x's class is one of {Unicode text, string, text}; or
        - cls is one of {Unicode text, «class utf8», string, text}.
    set fp to (path to "desk" from user domain as Unicode text) & "scptdump_tempfile" & (random number 1000000)
    try
    set fref to open for access file fp with write permission
    set eof fref to 0
    write x to fref
    close access fref
    set d to read file fp as cls
    on error errs number errn
    try
    close access file fp
    end try
    error "dump():" & errs number errn
    end try
    do shell script "rm -f " & quoted form of POSIX path of fp
    return d
    end dump
    --END OF SCRIPT
    Hope this may be of some help,
    Hiroto
    PS.
    In pre-AS 2.0, we can use 'string' to hold raw byte sequence of any kind of data, although it might be indeed an abuse of 'string' object. In AS 2.0, we seem to have lost this final way to abuse string and I'm yet to know any alternative way to process raw byte sequence safely.
    Now, I think, it would be really nice to see the following basic features being implemented with «class rdat» in order to process raw byte sequence in AppleScript 2.0 or later, where we cannot 'abuse' string anymore:
    • length property; e.g. length of «data rdat0032» (count «data rdat0032») returning 2.
    • way to extract element(s); e.g. item 4 of «data rdat32303037» returning «data rdat37»
    • way to concatenate two data; e.g. «data rdat32» & «data rdat30» returing «data rdat3230»
    • way to perform valid coercion to other class, e.g. «data rdat0032» as Unicode text returning "2" (= U+0032).
    • way to perform coercion from other class, e.g. ("2" as Unicode text) as data returning «data rdat0032»
    Just my daydream. ; )
    Message was edited by: Hiroto (corrected typo)

  • Use Applescript variable in Python command line

    Using automator
    Python Shell Output -> [1,2,3,4,5]
    goes to Applescript
    Run Applescript ->
    on run {input}
        set seq_list_appscript to {}
        do shell script "python -c 'for s in input: print s'"
    end run
    it doesn't work . . . how can I call the "input" which is an Applescript variable within the "do shell script" python command line ?

    If the input is actually a list of items, then you would need to iterate through them or coerce the list to something for the command line.  If the input is just the text "[1,2,3,4,5]", then the variable just needs to be inserted into the text of your script statement - the results of the script are returned by the do shell script command, so they can also be assigned to a variable:
        set whatever to (do shell script "python -c 'for s in " & input & ": print s'")
        display dialog whatever

  • Pass neooffice variable to applescript, open finder

    i have a spreadsheet in neooffice. there is a column which contains
    complete paths and filenames (each cell is a path/filename). i'd like
    to be able to click on the filename and have the finder open and
    highlight the file in question.
    i'm brand new to applescript. have some experience with bash, c,
    powershell, batch. i'm starting by trying to write an applescript
    that will simply tae a hardcoded path/filename and open finder and
    highlight the file. haven't even been able to figure out how to
    do this yet. any help is appreciated.
    secondly, i would then try to pass a variable to replace the
    hardcoded path/filename. the variable would be the path/filename
    from the clicked cell.
    basic actions, then, would seem to be:
    click cell
    script runs
    script collects variable from cell
    script opens finder to path
    script highlights filename
    any help on how to proceed with this is much appreciated.
    thanks,
    BabaG

    This is complicated somewhat by the fact that NeoOffice doesn't support AppleScript, and appears to have what I consider a bug in that it appends a return to the end of the data in a cell when copied. Nevertheless, this should get you close:
    tell application "NeoOffice" to activate
    tell application "System Events"
      tell application process "NeoOffice"
        keystroke "c" using {command down} -- use 'Copy' to get the selected cell content
        set filePath to text 1 through -2 of (get the clipboard) -- trim the return off the end!
      end tell
    end tell
    set theFile to POSIX file filePath -- coerce the path to a file reference
    tell application "Finder" to reveal theFile -- and select it in the Finder
    Note that there's no error checking to ensure that what you copied is a valid path, nor that you only have one cell selected.

  • Learning..Simple variable as text in texteditor

    I'm trying some basic things to learn. I just want the result from vari3 in the text document. But I get an apple event error.on this part 'set text 1 to vari3'
    Please also give a bit advice... so I learn from it. many thanks.
    I did try some changes but don't know what the best solution.
    'set text 1 to "It works" Will work because that's plain text.
    But getting the variable will not work for me.
    set vari1 to 1 + 1
    set vari2 to 1
    set vari3 to vari1 + vari2
    tell application "TextEdit"
    activate
    make new document at beginning
    tell document 1
    set text 1 to vari3
    end tell
    save the front document in ":Users:X:Desktop:testing.rtf" with replacing
    close the front document
    end tell
    --------------------------------------------------

    This is a strange issue of coercion.
    TextEdit should be able to automatically coerce vari3 into a text object, but it fails for some reason. The solution is to be explicit.
    Just change the line:
    set text 1 to vari3
    to:
    set text 1 to vari3 as text
    Off-hand, it isn't clear to me why this is necessary.

  • Problem with Threads and a static variable

    I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
    Code functionality:
    A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
    The problem as far I understand is:
    Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
    Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
    Thanks,
    B.D.
    Code:
    private static volatile boolean bChanged = false;
    private static Thread objMainProcess;
       protected static void Init(){
            objMainProcess = new Thread() {
                public void run() {
                    while( objMainProcess == Thread.currentThread() ) {
                       GetState();
            objMainProcess.setDaemon( true );
            objMainProcess.start();
        public static void initStatusTimer(){
            if(objTimer == null)
                 objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
                    public void actionPerformed( java.awt.event.ActionEvent evt){
                              SetState();
        private static void SetState(){
            if( objMainProcess == null ) return;
            synchronized( objMainProcess ) {
                bChanged = true;
                try{
                    objMainProcess.notify();
                }catch( IllegalMonitorStateException e ) {}
        private static boolean GetState() {
            if( objMainProcess == null ) return false;
            synchronized( objMainProcess ) {
                if( bChanged) {
                    SendMessage();
                    bChanged = false;
                    return true;
                try {
                    objMainProcess.wait();
                }catch( InterruptedException e ) {}
                return false;
        }

    Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
    Again as you said, There is a reason I can't call sendMessage() inside setState().
    The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
    Thanks,
    B.D.

  • Error while offsetting a variable

    Hello Experts
    I want to display the data for last 5 years in my query. So I tried using the SAP exit variable Current Calendar Year (0CYEAR) and the offset it by 5. However, I am getting the following error message for the query "System error in program SAPLRR12 and form REP_ASSIGN_INITIAL_OPT-01"
    Any Help on this is appreciated and points will be assigned.
    Thanks

    Thanks Chetan for your prompt reply. I have assigned points.
    But I would appreciate if you help me clear my understanding of offseting a variable.
    Say if the Current Calendar Year variable returns 2008, then will offseting that variable by 5 return me the data for years 2008, 2007, 2006, 2005 , 2004. Or, will it just return me the data for 2008 - 5 = 2004 only.
    Thanks
    Rishi

Maybe you are looking for