Boolean expression pars and evaluate

Hi
I need to know if there is code that suggests weather a string is a correct boolean expression or not . if it is, it evaluates it.
foe example :
x+1>8 returns true if x=10 e.g
y-1 is is a wrong boolean expression
thanx
Niema

As far as I know, there is no API that can do something like EVAL in BASIC (which was the last place I saw a feature like this). If you are feeling ambitious, you could write a parser to divide the String into an expression tree, substitute values for variables, and evaluate it.
But in all probability there is simply another (easier) way of approaching whatever you are trying to do.

Similar Messages

  • Search MessageSelector sample for complex boolean express with AND, OR, NOT

    As far as I know I can specify in the "Message Selector" field of a JMS-PartnerLink
    a boolean expression.
    How are AND, OR and NOT written here? Can I use brackets?
    Can I use blanks inside the boolean expression?
    Assume I would like to specify:
    ((myfield1 > 3.0) && (myfield2 == 777)) || (myfield3 != 'aaa')
    Is the syntax correct for this?

    http://www.mcs.csueastbay.edu/support/oracle/doc/10.2/server.102/b14257/jm_create.htm
    11.3 JMS Point-to-Point Model Features/MessageSelector
    that will give you some examples of how to use it

  • I am looking for an boolean and numeric expression evaluator. I want to be able to compare ( ,=, , or, not, and, nand, etc)and evaluate boolean/numeric expression.

    I am looking for an boolean and numeric expression evaluator. I want to be able to compare (>,=, <, or, not, and, nand, etc)and evaluate boolean/numeric expression. Does anyone know if there is any code samples anywhere. If anyone has any input, I would greately appreciate it.

    The problem is that I have to enter a string of that type (any random string), and the program should go and calculate the result for the whole stirng, by looking at which parts to calculate first (figuring out precedence), second, etc. This is like a calculator, you don't know what the user is going to enter next, so I can't just use the boolean palatte. I could use it if the equation was always of the form "a 'operator' b", where the operator is any logic or comparison operator. But that is not what I am trying to accomplish.
    Can you do logic in the formula node? I think it only allows numeric values for inputs and outputs, it doesn't let you enter in and output booleans and stuff..does it?
    Thanks,
    Yuliya

  • Search problems : Boolean expressions and spam folder

    I get about 1000 spam per day that I have to check.
    Some of them contains certain keyword that the real emails would never have.
    I would like to setup a smart folder or similar that found all emails in the spam folder that contains any of those keywords. I read some blogs etc. that said that spotlight boolean expressions could be used but they do not seem to work.
    e.g. "pill OR berry" yields no results at all but when each of the keywords are used on their own they produce 80 or so results each.
    Another problem I have is that I can do a manual search in the spam folder by typing in the search field and it yields results. But if I save that as a smart folder it yields no results at all. It seems that the rules do not work on the spam folder.
    I then tried to do all this from spotlight in the finder. I found the folder where the spam mailbox emails are stored (called "messages"). I managed to construct a nice search query and save it as a search. But if I delete one of the emails from the finder it still remains in Mail and the next time I start Mail it will be regenerated from somewhere.
    Anyone have any insights to provide here?

    I had actually missed that preference. Unfortunately it did not help.
    Even if I make a new smart mailbox with just one rule (the email must be in the spam folder) it doesnt work. It doesn't matter if I change between any/all either.
    I started experimenting with adding a rule saying that the email must not be in any of the other mailboxes but spam. That seemed to work for a bit but as I added more rules, excluding more mailboxes, it eventually broke. I will investigate it a bit more but currently don't have high hopes...

  • Pl/sql boolean expression short circuit behavior and the 10g optimizer

    Oracle documents that a PL/SQL IF condition such as
    IF p OR q
    will always short circuit if p is TRUE. The documents confirm that this is also true for CASE and for COALESCE and DECODE (although DECODE is not available in PL/SQL).
    Charles Wetherell, in his paper "Freedom, Order and PL/SQL Optimization," (available on OTN) says that "For most operators, operands may be evaluated in any order. There are some operators (OR, AND, IN, CASE, and so on) which enforce some order of evaluation on their operands."
    My questions:
    (1) In his list of "operators that enforce some order of evaluation," what does "and so on" include?
    (2) Is short circuit evaluation ALWAYS used with Boolean expressions in PL/SQL, even when they the expression is outside one of these statements? For example:
    boolvariable := p OR q;
    Or:
    CALL foo(p or q);

    This is a very interesting paper. To attempt to answer your questions:-
    1) I suppose BETWEEN would be included in the "and so on" list.
    2) I've tried to come up with a reasonably simple means of investigating this below. What I'm attempting to do it to run a series of evaluations and record everything that is evaluated. To do this, I have a simple package (PKG) that has two functions (F1 and F2), both returning a constant (0 and 1, respectively). These functions are "naughty" in that they write the fact they have been called to a table (T). First the simple code.
    SQL> CREATE TABLE t( c1 VARCHAR2(30), c2 VARCHAR2(30) );
    Table created.
    SQL>
    SQL> CREATE OR REPLACE PACKAGE pkg AS
      2     FUNCTION f1( p IN VARCHAR2 ) RETURN NUMBER;
      3     FUNCTION f2( p IN VARCHAR2 ) RETURN NUMBER;
      4  END pkg;
      5  /
    Package created.
    SQL>
    SQL> CREATE OR REPLACE PACKAGE BODY pkg AS
      2 
      3     PROCEDURE ins( p1 IN VARCHAR2, p2 IN VARCHAR2 ) IS
      4        PRAGMA autonomous_transaction;
      5     BEGIN
      6        INSERT INTO t( c1, c2 ) VALUES( p1, p2 );
      7        COMMIT;
      8     END ins;
      9 
    10     FUNCTION f1( p IN VARCHAR2 ) RETURN NUMBER IS
    11     BEGIN
    12        ins( p, 'F1' );
    13        RETURN 0;
    14     END f1;
    15 
    16     FUNCTION f2( p IN VARCHAR2 ) RETURN NUMBER IS
    17     BEGIN
    18        ins( p, 'F2' );
    19        RETURN 1;
    20     END f2;
    21 
    22  END pkg;
    23  /
    Package body created.Now to demonstrate how CASE and COALESCE short-circuits further evaluations whereas NVL doesn't, we can run a simple SQL statement and look at what we recorded in T after.
    SQL> SELECT SUM(
      2           CASE
      3              WHEN pkg.f1('CASE') = 0
      4              OR   pkg.f2('CASE') = 1
      5              THEN 0
      6              ELSE 1
      7           END
      8           ) AS just_a_number_1
      9  ,      SUM(
    10           NVL( pkg.f1('NVL'), pkg.f2('NVL') )
    11           ) AS just_a_number_2
    12  ,      SUM(
    13           COALESCE(
    14             pkg.f1('COALESCE'),
    15             pkg.f2('COALESCE'))
    16           ) AS just_a_number_3
    17  FROM    user_objects;
    JUST_A_NUMBER_1 JUST_A_NUMBER_2 JUST_A_NUMBER_3
                  0               0               0
    SQL>
    SQL> SELECT c1, c2, count(*)
      2  FROM   t
      3  GROUP  BY
      4         c1, c2;
    C1                             C2                               COUNT(*)
    NVL                            F1                                     41
    NVL                            F2                                     41
    CASE                           F1                                     41
    COALESCE                       F1                                     41We can see that NVL executes both functions even though the first parameter (F1) is never NULL. To see what happens in PL/SQL, I set up the following procedure. In 100 iterations of a loop, this will test both of your queries ( 1) IF ..OR.. and 2) bool := (... OR ...) ).
    SQL> CREATE OR REPLACE PROCEDURE bool_order ( rc OUT SYS_REFCURSOR ) AS
      2 
      3     PROCEDURE take_a_bool( b IN BOOLEAN ) IS
      4     BEGIN
      5        NULL;
      6     END take_a_bool;
      7 
      8  BEGIN
      9 
    10     FOR i IN 1 .. 100 LOOP
    11 
    12        IF pkg.f1('ANON_LOOP') = 0
    13        OR pkg.f2('ANON_LOOP') = 1
    14        THEN
    15           take_a_bool(
    16              pkg.f1('TAKE_A_BOOL') = 0 OR pkg.f2('TAKE_A_BOOL') = 1
    17              );
    18        END IF;
    19 
    20     END LOOP;
    21 
    22     OPEN rc FOR SELECT c1, c2, COUNT(*) AS c3
    23                 FROM   t
    24                 GROUP  BY
    25                        c1, c2;
    26 
    27  END bool_order;
    28  /
    Procedure created.Now to test it...
    SQL> TRUNCATE TABLE t;
    Table truncated.
    SQL>
    SQL> var rc refcursor;
    SQL> set autoprint on
    SQL>
    SQL> exec bool_order(:rc);
    PL/SQL procedure successfully completed.
    C1                             C2                                     C3
    ANON_LOOP                      F1                                    100
    TAKE_A_BOOL                    F1                                    100
    SQL> ALTER SESSION SET PLSQL_OPTIMIZE_LEVEL=0;
    Session altered.
    SQL> exec bool_order(:rc);
    PL/SQL procedure successfully completed.
    C1                             C2                                     C3
    ANON_LOOP                      F1                                    200
    TAKE_A_BOOL                    F1                                    200The above shows that the short-circuiting occurs as documented, under the maximum and minimum optimisation levels ( 10g-specific ). The F2 function is never called. What we have NOT seen, however, is PL/SQL exploiting the freedom to re-order these expressions, presumably because on such a simple example, there is no clear benefit to doing so. And I can verify that switching the order of the calls to F1 and F2 around yields the results in favour of F2 as expected.
    Regards
    Adrian

  • Create and save boolean expressions for later evaluation

    Is it possible to create Boolean expressions by inputs via user interface in LabVIEW and save them for later evaluation? I am interested in creating a 'flexible policy engine' which involves creating 'rules' comprising attribute values of certain attributes of objects based on boolean expressions which can later be used for arriving at some decisions based on the 'rules'.

    Hi Belur,
    Have you considered building a script based on the boolean expressions that you want to create for the flexible policy and saving the script to file?
    Later, you can read the script and depending on the policy, it can re-create the boolean expressions.
    A simple way to implement this is by having various pre-defined expressions places into a Case Statement. The script calls the appropriate cases that create the complete expression.
    You can store the attributes of the objects and when the vi is running, it can first open the initialization file, read the attributes and set them.
    For instance, you can read from and write to Property (and Invoke Nodes) to which you can the attributes.
    Unfortunately, I don't have an example of this that I c
    an share with you. There may be some if you do a search.
    Hope this helps..
    JLV

  • Taking out IF's and returning a boolean expression

    I thought a better way to implement this later method might be to remove the IF's and just return a boolean expression true or false if one date object is later than another date object. I almost have it correct but one case is still not outputting correctly.
    Heres the return statement:
    return ((year > otherDate.year)||(year==otherDate.year)&&(month > otherDate.month)&&
                        (day > otherDate.day));

    someone told you that the code looked right? humm... don't look right to me.
    basically if the years are different you are done and know the answer but if the years are the same you must look to the month
    So why don't you have exactly the same situation to deal with the case where you only look at the day if the months are equal? You need an extra set of parens, and another || condition and a term involving == months.
    Nope, your code just mixes together the code for checking days and checking months.
    You CAN do this all in a single boolean expression, but it is nested two levels deep and too long to fit on a line. And you got it wrong. (this is a hint that the person reading the code will also not be sure that the code is correct)
    You have done no one a favor by removing the IFs and using a single complicated boolean expression.

  • How to get dynamic boolean expression's value?

    String str = "((true)&((false)|true))";
    how to get the result of boolean from str?

    You will need to write a simple parser to parse the string and evaluate the expression.

  • Dynamic boolean expression evaluation

    Hey everyone,
    We have a table that consists of a couple key columns and a column containing a boolean expression. We want to select a number of rows based on the key columns and evaluate the boolean expression in the expression column for each, only returning the first row wherein the boolean expression evaluates to true.
    We are using a context to inject the test variables into the boolean expressions and currently we are selecting all the key rows in a PL/SQL procedure and going through the cursor evaluating each of the boolean expressions with an execute immediate.
    The expressions are currently formated in the columns as anonymous PL/SQL blocks that, when called, will either return true or false to the PL/SQL procedure. Upon returning true, the procedure stops looping and returns true to the caller.
    Psuedo-code would be:
    - set-up sys_context with condition variables
    - create cursor for: select * from expression_tbl et where <key matches>
    - begin loop through cursor
    - execute immediate cursor_row.expression using out :out_is_true
    - if out_is_true = 'Y' then return true
    - loop
    - return false
    The expressions (anonymous PL/SQL blocks) from the table look something like this:
    begin if ((''||sys_context('ctx', '1')||'' = 'FL') AND (''||sys_context('ctx', '3')||'' BETWEEN 1619 AND 4598) ) then :1 := 'Y'; end if; end;
    This works, but it seems like I should be able to do this another way and potentially extract more performance.
    So...a couple questions:
    1) I have read on ask Tom that a dynamic select statement (rather than an anonymous PL/SQL block) can evaulate the boolean expressions. I.E. rather than use an execute immediate clause on an anonymous PL/SQL block contained in the expression column, I would make the expression column compatible with a where clause and create this dynamic SQL query: 'select count(*) from dual where ' || expression. I would then execute that query and if it returns a row then the expression is true, otherwise it is false. My question is, does anyone think the performance of parsing the SQL and executing it would be better than that of executing an anonymous PL/SQL block for every row? Tom said that the SQL could incur a lot of hard-parses and kill performance, but how deathly is the constant compilation of anonymous PL/SQL blocks as shown above in comparison?
    2) Would there be any benefit to pulling the execute routines out of the PL/SQL block and issuing a query such as the following:
    select * from expression_tbl et where <key matches> AND pkg.eval_routine(et.expression) = 'Y' AND rownum <= 1.
    I realize that the evaulating routine would then need to either perform an execute immediate on et.expression (if we keep the current method in place) or formulate the dynamic SQL statement and execute it. But, could this be faster than doing the same loop through rows explicitely in PL/SQL?
    Doing this would trim my PL/SQL down to:
    - set up sys_context
    - execute the above select statmenet
    - if a row is returned then return true otherwise return false
    Seems more elegant, but the peformance is all that matters.
    3) Is there any built-in routine that I may be able to replace pkg.eval_routine from 2 with that would evaulate boolean expressions for me? Or any other way to inline the idea from 1 with 2? I can't think of one given the dynamic nature of the beast, but...maybe there's something I missed.
    Thanks everyone! Hopefully I've expressed myself clearly.

    Brian - According to Tom Kyte Doing PL/SQL inside Execute Immediate should be faster as you are already within the context of a PL/SQL engine. If we choose to do it in SQL then the PL/SQL engine has to hand it over to the SQL Engine for executing the dynamic Select statements and so might be a little slower. But I am not sure if the difference can be quantifiable unless u do your own test of both evaluators and run them for like a few thousand times in a loop.
    If you are using 10g R2 - you might want to look into DBMS_RLMGR package which is the API for the Oracle's version of the embedded business rule manager.
    I looked into it but it didn't fit our needs as its deficient with respect to rule versioning and effective and until date based business rule enforcement/ validation.
    After taking a shot at designing something home grown I feel its not that difficult to construct one that fit our needs inclusive of the features( rule versioning, effective and until dates) that I listed above as deficiencies in the Oracle embedded rule engine.
    If you don't have those requirements may be using the Business Rule manager API of 10g R2 might not be a bad anticipating it will be improved in future versions.
    Regards
    -Suren

  • Short-circuiting boolean expressions

    There is a term used in other languages to describe the behavior of compiled code which evaluates boolean expressions: short circuiting. Basically, it means that if a term in an expression determines its value, then following terms never get evaluated, since they are irrelevant. For example, I have noticed that this always works in AppleScript:
    if class of x is not integer or x > 32 then . . . .
    But this will throw an exception if x is something that can’t be coerced into a number:
    if x > 32 or class of x is not integer then . . . .
    It looks to me that the reason the first always works is that Applescript is short-circuiting, and therefore there is no attempt to evaluate the inequality if x is of inappropriate class.
    Does anyone know if Applescript’s behavior is sufficiently well defined that I can be confident it will always short circuit? I know I can avoid the issue by breaking such expressions into separate, nested, if statements. If there is no such assurance that is what I will probably make a habit of doing. But I thought I'd ask if this is really necessary.

    Hello
    Short-circuiting is well-defined in AppleScript.
    cf. ASLG > Operator References (p.179 of ASLG pdf)
    http://developer.apple.com/library/mac/documentation/AppleScript/Conceptual/Appl eScriptLangGuide/AppleScriptLanguageGuide.pdf
    Regards,
    H

  • Evaluating boolean expressions from a string

    Hi All,
    In my program I am dynamically generating boolean expressions.
    Hence, I store the expression as a string. I want to be able to determine if that expression evaluates to true/false.
    For eg, String expr = "1 < 2";
    I want to be able to evaluate expr and print false(in this case)
    How can I do that? Are there any class that come with JDK1.4 for doing this or can you point me to some API that I can use for this.
    Thanks,
    Vijay

    I can't count how many times this has been askedhere.
    Try searching the forums.Give yourself credit - you could count it if you
    wanted to.
    OK, maybe so. But I can't count it off the top of my
    head. :-) But easier than counting the hairs on your head (well.....presuming you do have some....)
    Really, it's bizarre how much this gets
    asked. I think I'll start a new thread about it...Be realistic....the integer to string or string to integer gets asked a lot more often!

  • Boolean expression examples

    hey peeps, i was stuck with the following questions out of my text book the other day and i just asked my friend for some tips (here are the questions)
    q1) write an expression using boolean var a and b that equate to true when a and b are both trur and false
    q2)write an expression using boolean var a and b that evaluates true when only one of a and b is true and which is false if a and b are both flase or both true ( this is called exclusive or)
    q3) consider the expression (a && b) write an equivelant expression, one that evaluates to true at exactly the same values for a and b without using the && operator
    however, he gave me the answers <good you may think> but that now means i havent learnt anything and i was hoping someone could either set me a couple of similar questions or point me in the direction of a tutorial? I didnt want to ask him again as i dont want to bother him any more
    thanks very much

    Relational and boolean Operators
    Java has the full complement of relational operators. To test for equality you use a double equal sign, ==. For example, the value of
    <address>3 == 7</address>
    is false.
    Use a != for inequality. For example, the value of
    3 != 7
    is true.
    Finally, you have the usual < (less than), > (greater than), <= (less than or equal), and >= (greater than or equal) operators.
    Java, following C++, uses && for the logical "and" operator and || for the logical "or" operator. As you can easily remember from the != operator, the exclamation point ! is the logical negation operator. The && and || operators are evaluated in "short circuit" fashion. This means that when you have an expression like:
    A && Bonce the truth value of the expression A has been determined to be false, the value for the expression B is not calculated. For example, in the expression
    x != 0 && 1 / x > x + y // no division by 0the second part is never evaluated if x equals zero. Thus, 1 / x is not computed if x is zero, and no divide-by-zero error can occur.
    Similarly, if A evaluates to be true, then the value of A || B is automatically true, without evaluating B.
    Finally, Java supports the ternary ?: operator that is occasionally useful. The expression
    condition ? e1 : e2
    evaluates to e1 if the condition is true, to e2 otherwise. For example,
    x < y ? x : ygives the smaller of x and y.
    h3. from:+Core Java&trade; 2: Volume I&ndash;Fundamentals+
    By Cay S. Horstmann, Gary  Cornell
    Publisher : Prentice Hall PTR
    Pub Date : December 01, 2000
    ISBN : 0-13-089468-0
    Pages : 832
    chapter 3

  • Boolean Expression Evaluator

    Hello everyone...
    Does any one know how to create a Java program that will evaluate boolean expression... For example, the user may enter (T AND T) OR F statement and the program will check the expression is valid or not and in addition it gives the answer T for true. Does anyone know where to download the free sample code that will be able to help me.. thanks.
    URGENT!
    -Eugene-

    http://www.japisoft.com/formula
    Features :
    * Decimal, string, boolean operators (or, and, not, xor...)
    * Unicode
    * Boolean expression support : (A or B) and not ( C equals D )
    * String expression support : "abc" != "cba"
    * IF THEN ELSE expression
    * Short expression format : 2x+3y
    * Variable : A=(cos(PI + x )*2) + [y-x]^2
    * Multiple lines expression : A = 1 B = A + 1 ...
    * Functions with decimal, boolean or string arguments
    * Evaluation tree produced by a pluggable parsing system
    * Evaluation optimization for symbol value changes
    * Standard library with 24 mathematical functions
    * Delegate for resolving unknown functions or symbols
    * Extend or add a new library dynamically
    * Share multiple formula context
    * Override any functions from the current library by your one
    * Support for multithreaded computing
    * Many samples (library extension, graphes) for API interesting parts
    * JDK 1.1 compliant (tested on JDK1.1.8 and JDK1.4.2)
    Best regards,
    A.Brillant

  • DNF boolean expressions

    Hi folks,
    I would like to produce a "minimal" boolean expression in disjunctive normal form.
    Something like a AND b OR c to
    DNF: ab or ac
    Therefor i have developed a parser which produces that normal form, but the performance decreases very much if i parse expressions with lots of variables or nested expressions like:
    (a AND (b OR c OR d) AND (e OR f OR g)) OR ((b OR c OR d) AND (e OR f OR g) AND h) OR (i AND (e OR f OR g))
    It lastes up to 5 seconds.
    Do u know any free api, which i could use for this purpose?.
    Thanks in advance.

    Thats the code:
    package com.audatex.axn.ui.vsic.datamodel.util;
    import java.util.Vector;
    public class BooleanExpressionsParser
        private static final Logger _logger =  new Logger( JATOTest.class );
        public static int nVars;
        public static int nAmount;
        public static String sActiveVars;
        public static String sValidInput;
        public boolean isK0, isK1, isKsd, isKlinear, isKmonoton;
        public static boolean[] arResults;
        private static CBoolFkt cBoolFkt = new CBoolFkt();
        public static int format(String exp) {
            int result = cBoolFkt.format(exp);
            if (result == CBoolFkt.OK) {
                nVars = cBoolFkt.nMinVars;
                nAmount = 1 << nVars;
                sActiveVars = cBoolFkt.sActiveVars.toString();
                sValidInput = cBoolFkt.sValidInput.toString();
            return result;
        public static String doCalc() {
            arResults = new boolean[nAmount];
            for (int i = 0; i < nAmount; i++) {
                for (int run = 0; run < nVars; run++) {
                    cBoolFkt.Vars[cBoolFkt.sActiveVars.charAt(run)] = isBitSet(i,
                            nVars - run - 1);
                arResults[i] = cBoolFkt.evaluate();
            return doNF();
        public static String convertExpression(String boolExpression){
            _logger.debug(" " + boolExpression);
            int result = format(boolExpression);
            String res = "";
            if(result == CBoolFkt.OK){
                _logger.debug("The format is O.k ,doing calculation ");
                res = doCalc();
        return res;
        private static String  doNF() {
            StringBuffer sMDNF = new StringBuffer();
            return doQuineMcClusky( sMDNF);
        private static String doQuineMcClusky(StringBuffer sMDNF) {
            Vector arConjunctions = new Vector();
            Vector arUsedVars = new Vector();
            Vector arMarked = new Vector();
            int nUsedVarsMask = nAmount - 1;
            for (int i = 0; i < nAmount; i++) {
                if (arResults) {
    arConjunctions.addElement(new Integer(i));
    arUsedVars.addElement(new Integer(nUsedVarsMask));
    arMarked.addElement(new Boolean(false));
    _logger.debug("arConjunctions.size(): " + arConjunctions.size());
    for (int level = 0; level < nVars; level++) {
    int nConjunctions = arConjunctions.size();
    if (nConjunctions <= 1) {
    break;
    for (int checknr = 0; checknr < nConjunctions - 1; checknr++) {
    for (int comparenr = checknr + 1; comparenr < nConjunctions;
    comparenr++) {
    if (((Integer) arUsedVars.elementAt(checknr)).intValue() ==
    ((Integer) arUsedVars.elementAt(comparenr)).intValue()) {
    int checkval = ((Integer) arConjunctions.elementAt(
    checknr)).intValue();
    int compareval = ((Integer) arConjunctions.elementAt(
    comparenr)).intValue();
    int DifferMask = xOrBits(checkval, compareval);
    if (bitCount(DifferMask) == 1) {
    arMarked.setElementAt(new Boolean(true), checknr);
    arMarked.setElementAt(new Boolean(true), comparenr);
    int NewConj = andBits(checkval, compareval);
    int NewMask = xOrBits(DifferMask,
    ((Integer) arUsedVars.
    elementAt(checknr)).intValue());
    arConjunctions.addElement(new Integer(NewConj));
    arUsedVars.addElement(new Integer(NewMask));
    arMarked.addElement(new Boolean(false));
    nConjunctions = arConjunctions.size();
    for (int checknr = 0; checknr < nConjunctions - 1; checknr++) {
    if (((Boolean) arMarked.elementAt(checknr)).booleanValue() == false) {
    for (int comparenr = checknr + 1; comparenr < nConjunctions;
    comparenr++) {
    if (((Boolean) arMarked.elementAt(comparenr)).
    booleanValue() == false) {
    int checkval = ((Integer) arConjunctions.elementAt(
    checknr)).intValue();
    int compareval = ((Integer) arConjunctions.
    elementAt(comparenr)).intValue();
    int checkmask = ((Integer) arUsedVars.elementAt(
    checknr)).intValue();
    int comparemask = ((Integer) arUsedVars.elementAt(
    comparenr)).intValue();
    int maskand = andBits(checkmask, comparemask);
    if (checkmask == comparemask) {
    if (checkval == compareval) {
    arMarked.setElementAt(new Boolean(true),
    comparenr);
    } else {
    if ((maskand == checkmask) &&
    (andBits(compareval, maskand) == checkval)) {
    arMarked.setElementAt(new Boolean(true),
    comparenr);
    if ((maskand == comparemask) &&
    (andBits(checkval, maskand) == compareval)) {
    arMarked.setElementAt(new Boolean(true),
    checknr);
    for (int cleanup = nConjunctions - 1; cleanup >= 0; cleanup--) {
    if (((Boolean) arMarked.elementAt(cleanup)).booleanValue() == true) {
    arConjunctions.removeElementAt(cleanup);
    arUsedVars.removeElementAt(cleanup);
    arMarked.removeElementAt(cleanup);
    for (int i = 0; i < arConjunctions.size(); i++)
    int nUsed = ((Integer) arUsedVars.elementAt(i)).intValue();
    int nConj = ((Integer) arConjunctions.elementAt(i)).intValue();
    for (int run = 0; run < nVars; run++) {
    if (isBitSet(nUsed, nVars - run - 1)) {
    if (!isBitSet(nConj, nVars - run - 1)) {
    sMDNF.append("!");
    sMDNF.append(cBoolFkt.sActiveVars.charAt(run));
    sMDNF.append(" | ");
    // _logger.debug(arConjunctions.toString());
    //_logger.debug(arUsedVars.toString());
    //_logger.debug(arMarked.toString());
    sMDNF.setLength(sMDNF.length() - 3);
    return sMDNF.toString();
    public static boolean isBitSet(int Number, int Bit) {
    return (Number & (1 << Bit)) > 0;
    public static int andBits(int a, int b) {
    int Result = 0;
    int CurrBit = 0;
    while ((a > 0) || (b > 0)) {
    if (isBitSet(a, 0) && isBitSet(b, 0)) {
    Result += 1 << CurrBit;
    CurrBit++;
    a >>= 1;
    b >>= 1;
    return Result;
    public static int xOrBits(int a, int b) {
    int Result = 0;
    int CurrBit = 0;
    while ((a > 0) || (b > 0)) {
    if (isBitSet(a, 0) != isBitSet(b, 0)) {
    Result += 1 << CurrBit;
    CurrBit++;
    a >>= 1;
    b >>= 1;
    return Result;
    public static int bitCount(int Number) {
    int Result = 0;
    while (Number > 0) {
    if ((Number & 1) != 0) {
    Result++;
    Number >>= 1;
    return Result;
    * @return Returns the cBoolFkt.
    public CBoolFkt getCBoolFkt() {
    return cBoolFkt;
    * @param boolFkt The cBoolFkt to set.
    public void setCBoolFkt(CBoolFkt boolFkt) {
    cBoolFkt = boolFkt;
    public class CBoolFkt {
    // Constants to handle exceptions
    public static final int OK=0, NOTOKEN=1, UNKNOWNTOKEN=2,
    NOVARS=3, VAREXPECTED=4,
    BRACKETEXPECTED=5, BRACKETNOTALLOWED=6;
    // max. number of diferent vbles in the boolean expression
    public final int nMaxVars = 12;
    // Amount of current dif. vbles in the boolean exp.
    public int nMinVars;
    // Name of the current bool. exp sorted by alph. order
    public StringBuffer sActiveVars;
    public StringBuffer sValidInput;
    // Wertebelegung der Variablen by ASCII-Namen, also z.B. Vars['a']=true
    public boolean[] Vars = new boolean[128];
    // Name of the vbles.
    final char A='a', B='b', C='c', D='d',
    E='e', F='f', G='g', H='h',
    I='i', J='j', K='k', L='l',
    // operators
    OR='|', AND='&', XOR='+', EQU='=', _NOT='!',
    LOG='>', LB='(', RB=')', TRUE='1', _FALSE='0',
    _END=0;
    // Words that are replaced by the symbols behind
    final String[] arLongNames = { "or","oder","and","und",
    "xor","not","nicht","=>" };
    final char[] arLongToken = { '|','|','&','&','+','!','!','>' };
    private StringBuffer sExpression;
    private int iExpressionCount;
    private char cToken;
    // Detection of no valid syntax and integration of the expression with the language
    // of the parser
    public int format(String expression)
    boolean bForceVar = true;
    int nBracketCount = 0;
    sValidInput = new StringBuffer();
    if (expression.length()==0)
    return NOTOKEN;
    // convert to lower case
    expression = expression.toLowerCase();
    // for replacing the key words by symbols
    StringBuffer sNoLongNames = new StringBuffer(expression);
    // process de convertion
    for (int i=0; i<arLongNames.length; i++)
    while(sNoLongNames.toString().indexOf(arLongNames[i])!=-1)
    StringBuffer sTemp = new StringBuffer();
    // saveing word address
    int index = sNoLongNames.toString().indexOf(arLongNames[i]);
    if (index>0)
    sTemp.append(sNoLongNames.toString().substring(0,index));
    // replacing word
    sTemp.append(arLongToken[i]);
    if ((index+arLongNames[i].length())<sNoLongNames.length())
    sTemp.append(sNoLongNames.toString().substring(index+arLongNames[i].length()));
    sNoLongNames = sTemp;
    // convertion complete
    expression = sNoLongNames.toString();
    for (int i=0; i<expression.length(); i++)
    // Testing tokens
    switch(expression.charAt(i))
    case ' ': continue;
    // valid tokens
    case FALSE:; case TRUE:;
    case A:; case B:; case C:; case D:;
    case E:; case F:; case G:; case H:;
    case I:; case J:; case K:; case L:
    // every next token ist ok
    bForceVar = false;
    // ok
    sValidInput.append(expression.charAt(i));
    break;
    case _NOT:;
    // the next token must be vble
    bForceVar = true;
    // ok
    sValidInput.append(expression.charAt(i));
    break;
    case AND:; case OR:; case XOR:; case LOG:; case _EQU:;
    if (bForceVar)
    return VAREXPECTED;
    // the next token must be vble
    bForceVar = true;
    // ok
    sValidInput.append(expression.charAt(i));
    break;
    case _LB:;
    nBracketCount++;
    bForceVar = true;
    // ok
    sValidInput.append(expression.charAt(i));
    break;
    case _RB:;
    if (bForceVar||(nBracketCount==0))
    return BRACKETNOTALLOWED;
    nBracketCount--;
    // ok
    sValidInput.append(expression.charAt(i));
    break;
    // not valid token
    default: return UNKNOWNTOKEN;
    if (nBracketCount!=0)
    return BRACKETEXPECTED;
    if (bForceVar)
    return VAREXPECTED;
    // Counter of the number of vbles
    nMinVars=0;
    sActiveVars = new StringBuffer();
    // limitating pos vble names
    String sAllVars = "abcdefghijkl";
    // testing the vbles
    int i;
    for (i=0; i<nMaxVars; i++)
    if (sValidInput.toString().indexOf(sAllVars.charAt(i))!=-1)
    nMinVars++;
    sActiveVars.append(sAllVars.charAt(i));
    if (nMinVars==0)
    return NOVARS;
    expression = sValidInput.toString();
    sExpression = sValidInput;
    sExpression.append(_END);
    return OK;
    public boolean evaluate()
    sExpression = sValidInput;
    iExpressionCount = 0;
    return doEqu(true);
    private boolean doEqu(boolean get)
    boolean left = doLog(get);
    for (;;)
    if (cToken==_EQU)
    left=(doLog(true)==left);
    else
    return left;
    private boolean doLog(boolean get)
    boolean left = doOr(get);
    for (;;)
    if (cToken==_LOG)
    // a>b=!a|b
    left=doOr(true)||!left;
    else
    return left;
    private boolean doOr(boolean get)
    boolean left = doXor(get);
    for (;;)
    if (cToken==_OR)
    left|=doXor(true);
    else
    return left;
    private boolean doXor(boolean get)
    boolean left = doAnd(get);
    for (;;)
    if (cToken==_XOR)
    left^=doAnd(true);
    else
    return left;
    private boolean doAnd(boolean get)
    boolean left = doPrimary(get);
    for (;;)
    switch (cToken)
    case _AND:
    left&=doPrimary(true); break;
    case A:; case B:; case C:; case D:;
    case E:; case F:; case G:; case H:;
    case I:; case J:; case K:; case L:;
    case LB:; case NOT:
    left&=doPrimary(false); break;
    default:
    return left;
    private boolean doPrimary(boolean get)
    if (get)
    getToken();
    boolean temp;
    switch (cToken)
    case A:; case B:; case C:; case D:;
    case E:; case F:; case G:; case H:;
    case I:; case J:; case K:; case L:;
    temp = Vars[cToken];
    getToken();
    return temp;
    case _NOT:
    return !doPrimary(true);
    case _TRUE:
    getToken();
    return true;
    case _FALSE:
    getToken();
    return false;
    case _LB:
    temp = doEqu(true);
    getToken();
    return temp;
    default: return true;
    private void getToken()
    cToken = sExpression.charAt(iExpressionCount++);
    I try to convert the expression, not to evaluate it.
    For example:
    (a and b) or c and (d and b) ---> DNF: b & c & d l a & b

  • Can i use Boolean Expressions in Mail Rules?

    Can i use Boolean Expressions in Mail Rules?
    I need to create a rule to check whether a message contains BOTH a first and last name of EITHER of two people.
    For example, the rule im looking to create goes something like this:
    If ANY of the following conditions are met:
    message content - contains - john & doe
    message content - contains - jane & doe
    ive tried and cant seem to get it to work...
    Message was edited by: mysterioso

    AFAIK Mail rules do not support boolean expressions.
    to do what you want you'd have to create two rules
    rule 1
    if ALL of the following conditions are met
    message content - contains - john
    message content - contains - jdoe
    and similarly for rule 2.

Maybe you are looking for