Example #1
0
def chr_id_cmp(a, b):
    """
    Sorted the chromosome by the order.
    
    Parameters
    ----------
        a, b : string or int. 
            a and b are the chromosomes' id. They could be 'chr1', 'chr2'
            or '1' and '2'.
    
    Returns
    -------
    Must be one of the number in [True, False]
    """
    a = a.lower().replace("_", "")
    b = b.lower().replace("_", "")
    achr = a[3:] if a.startswith("chr") else a
    bchr = b[3:] if b.startswith("chr") else b

    try:
        # 1~22 chromosome
        return operator.le(int(achr), int(bchr))
    except ValueError:
        # [1] 22 X
        # [2] X Y
        return operator.le(achr, bchr)
Example #2
0
        def range_fn(test):
            # test inside nrange?
            try:
                test = float(test)
            except:
                self.log.raiseException(
                    "range_fn: can't convert test %s (type %s) to float" %
                    (test, type(test)))

            start_res = True  # default: -inf < test
            if start is not None:
                # start <= test
                start_res = operator.le(start, test)

            end_res = True  # default: test < +inf
            if end is not None:
                # test <= end
                end_res = operator.le(test, end)

            tmp_res = operator.and_(start_res, end_res)
            if neg:
                tmp_res = operator.not_(tmp_res)

            self.log.debug(
                "range_fn: test %s start_res %s end_res %s result %s (neg %s)"
                % (test, start_res, end_res, tmp_res, neg))
            return tmp_res
Example #3
0
 def testLessThanEqual(self):
     """Test <=operator"""
     _dt = self.eDatetime + datetime.timedelta(1)
     _other = eventCalBase.event(2, 'event', _dt)
     self.failUnless(operator.le(self.e, _other),
             'a1 <= a2 failed.  a1=%s, a2=%s' % (self.e, _other))
     self.failUnless(operator.le(_other, _other),
             'a1 <= a2 failed.  a1=%s, a2=%s' % (_other, _other))
Example #4
0
 def testLessThanEqual(self):
     """Test <=operator"""
     _dt = self.eDatetime + datetime.timedelta(1)
     _other = eventCalBase.event(2, 'event', _dt)
     self.failUnless(operator.le(self.e, _other),
                     'a1 <= a2 failed.  a1=%s, a2=%s' % (self.e, _other))
     self.failUnless(operator.le(_other, _other),
                     'a1 <= a2 failed.  a1=%s, a2=%s' % (_other, _other))
Example #5
0
 def test_crosslevel_cmp(self, x, y):
     with pytest.raises(TypeError):
         operator.lt(x, y)
     with pytest.raises(TypeError):
         operator.le(x, y)
     with pytest.raises(TypeError):
         operator.gt(x, y)
     with pytest.raises(TypeError):
         operator.ge(x, y)
Example #6
0
def le(A, B):
    """
    A ≤ B
    """
    if isinstance(A, int) and isinstance(B, int):
        return int(operator.le(A, B))

    if fuzzyEquals(A, B):
        return 1

    return int(operator.le(A, B))
Example #7
0
def get_comparision_verdict_with_text(comp_operator,
                                      actual_value,
                                      expected_value,
                                      expected_min_value,
                                      expected_max_value,
                                      property_name):
    """
    comp_operator: Enum comp_operator
    values: for comparision
    property_name: string used for verdict text message.
    Return dictionary with verdict as bool and verdict text
    """

    verdict = False
    expected_filter_string = 'None'
    if comp_operator == 'LESS_THAN':
        verdict = operator.lt(actual_value, expected_value)
        expected_filter_string = ' less than ' + str(expected_value)
    elif comp_operator == 'LESS_THAN_OR_EQUAL':
        verdict = operator.le(actual_value, expected_value)
        expected_filter_string = ' less than or equal to ' + str(expected_value)
    elif comp_operator == 'GREATER_THAN':
        verdict = operator.gt(actual_value, expected_value)
        expected_filter_string = ' greater than ' + str(expected_value)
    elif comp_operator == 'GREATER_THAN_OR_EQUAL':
        verdict = operator.ge(actual_value, expected_value)
        expected_filter_string = ' greater than or equal to ' + str(expected_value)
    elif comp_operator == 'EQUAL':
        verdict = operator.eq(actual_value, expected_value)
        expected_filter_string = ' equal to ' + str(expected_value)
    elif comp_operator == 'NOT_EQUAL':
        verdict = operator.ne(actual_value, expected_value)
        expected_filter_string = ' not equal to ' + str(expected_value)
    elif comp_operator == 'BETWEEN':
        verdict = operator.le(expected_min_value, actual_value) and \
            operator.le(actual_value, expected_max_value)
        expected_filter_string = ' between ' + str(expected_min_value) + \
            ' and ' + str(expected_max_value) + ', inclusive'
    else:
        raise Exception("Unsupported comparision operator {0}".format(comp_operator))

    pass_fail_text = ' does not match '
    if verdict is True:
        pass_fail_text = ' matches '
    verdict_text = 'Actual ' + property_name + pass_fail_text + 'expected ' + \
        property_name + '. Actual count: ' + str(actual_value) + \
        '; expected count:' + expected_filter_string + '.'

    data = {}
    data[ProviderConst.VERDICT] = verdict
    data[ProviderConst.VERDICT_TEXT] = verdict_text
    return data
Example #8
0
def parse_filters(value, filters):
    operators = {
        '$lt': lambda x: operator.lt(value, x),
        '$lte': lambda x: operator.le(value, x),
        '$eq': lambda x: operator.eq(value, x),
        '$ne': lambda x: operator.ne(value, x),
        '$gte': lambda x: operator.ge(value, x),
        '$gt': lambda x: operator.gt(value, x),
        '$between': lambda x: operator.ge(value, x[0]) and operator.le(value, x[-1])
    }

    if isinstance(filters, dict):
        return all(operators[k](v) for k, v in filters.items() if k in operators)
    return True
def parse_operator(target, query):

    import operator as op

    split = query.split(',')

    '''one tail query '''
    if len(split) == 1:

        part = split[0].partition('=')  
        if part[-1].isdigit():
            if part[0] == '>':
                resp = op.ge(target,int(part[-1]))
            else:
                resp = op.le(target,int(part[-1]))    
        else:
            if part[0][0] == '>':
                resp = op.gt(target,int(part[0][1:]))
            else:
                resp = op.lt(target,int(part[0][1:]))  

    elif len(split) == 2:
        
        top = split[0][0]  
        va1 = int(split[0][1:])        
        bot = split[1][-1]
        va2 = int(split[1][:-1])

        if top == '[' and bot == ']':
            resp = op.ge(target,va1) & op.le(target,va2)
            
        elif top == '[' and bot == '[':
            resp = op.ge(target,va1) & op.lt(target,va2)
            
        elif top == ']' and bot == ']':
            resp = op.gt(target,va1) & op.le(target,va2)
            
        elif top == ']' and bot == '[':
            resp = op.gt(target,va1) & op.lt(target,va2)
        
    return resp
        
        
        
        
        
    
    
def ApproximatePatternCount(Text, Pattern, d):
    """Counting the total number of occurences of Patter in Text with
    d mismatches at most."""

    return PatternCount(Text, Pattern,
                        cmp=lambda a, b:
                        operator.le(HammingDistance(a, b), d))
Example #11
0
def do_date(datenode) :
    (day,month,year) = extractdate(datenode)
    if le(month,0) or gt(month,12) :
        daysinmonth = 0
    elif eq(month,9) or eq(month,4) or eq(month,6) or eq(month,11) :
        daysinmonth = 30
    elif eq(month,2) :
        if eq(mod(year,4),0) and (julian or (ne(mod(year,100),0) or eq(mod(year,400),0))) :
            daysinmonth = 29
        else :
            daysinmonth = 28
    else :
        daysinmonth=31
    future = 0
    if gt(year,toyear) :
        future = 1
    elif eq(year,toyear) :
        if gt(month,tomonth) :
            future=1
        elif eq(month,tomonth) and gt(day,today) :
            future=1
    if gt(day,daysinmonth) or future : out("*")
    if lt(year,0) :
        cols(d(year),6)
    else :
        if lt(year,10) : out("0")
        if lt(year,100) : out("0")
        if lt(year,1000) : out("0")
        out(d(year))
    if lt(month,10) : out("0")
    out(d(month))
    if lt(day,10) : out ("0")
    out(d(day)+" ")
Example #12
0
def parse(instruction):
    global bigmax
    raw = instruction.split()
    compare = raw[4]
    value = int(raw[6])

    if compare not in registers:
        registers[compare] = 0

    ops = { '>': operator.gt(registers[compare], value),
            '<': operator.lt(registers[compare], value),
            '>=': operator.ge(registers[compare], value),
            '<=': operator.le(registers[compare], value),
            '==': operator.eq(registers[compare], value),
            '!=': operator.ne(registers[compare], value),
            }

    if ops[raw[5]]:
        target = raw[0]
        if target not in registers:
            registers[target] = 0
        if raw[1] == "inc":
            bigsum = registers[target] + int(raw[2])
            registers[target] = bigsum
            if bigsum > bigmax:
                bigmax = bigsum
        else:
            bigsum = registers[target] - int(raw[2])
            registers[target] = bigsum
            if bigsum > bigmax:
                bigmax = bigsum
Example #13
0
 def __le__(
     self, other: i_probability_distribution.IProbabilityDistribution
 ) -> "ProbabilityDistribution":
     new_result_map = self._combine_distributions(
         lambda a, b: 1 if operator.le(a, b) else 0, other
     )
     return ProbabilityDistribution(new_result_map)
Example #14
0
    def visit_Compare(self, ast_node_Compare: ast.Compare) -> ast.Constant:
        """
        Compare nodes occur for all sequences of comparison (gt, lt, etc.) operators.

        :param ast_node_Compare: a object comparison of two or more values.
        :return: evaluated value.
        """
        comparators = ast_node_Compare.comparators
        operators = ast_node_Compare.ops

        # Exception case: (A cmp ?)
        if operator.le(len(comparators), 0):
            raise ValueError('There must be at least two operands for compare')

        # Common case: (A cmp B)
        if operator.eq(len(comparators), 1):
            ast_node_BinOp = ast.BinOp(ast_node_Compare.left,
                                       next(iter(operators), None),
                                       next(iter(comparators), None))
            return self.visit(ast_node_BinOp)

        else:
            # Recursive case: (A cmp B cmp C cmp ... etc.)
            ast_values_BoolOp = []
            left_comparator = ast_node_Compare.left
            for ast_type_operator, right_comparator in zip(
                    operators, comparators):
                new_ast_node_Compare = self.visit(
                    ast.Compare(left_comparator, [ast_type_operator],
                                [right_comparator]))
                left_comparator = right_comparator
                ast_values_BoolOp.append(new_ast_node_Compare)
            return self.visit(ast.BoolOp(ast.BitAnd(), ast_values_BoolOp))
Example #15
0
    def evaluate(self):
        result = None
        left = self.left.evaluate()
        right = self.right.evaluate()

        if self.operation == '+':
            result = operator.add(left, right)
        elif self.operation == '-':
            result = operator.sub(left, right)
        elif self.operation == '*':
            result = operator.mul(left, right)
        elif self.operation == '/':
            result = operator.div(left, right)
        elif self.operation == '^':
            result = operator.pow(left, right)
        elif self.operation == 'and':
            result = left and right
        elif self.operation == 'or':
            result = left or right
        elif self.operation == '<':
            result = operator.lt(left, right)
        elif self.operation == '<=':
            result = operator.le(left, right)
        elif self.operation == '==':
            result = operator.eq(left, right)
        elif self.operation == '!=':
            result = operator.ne(left, right)
        elif self.operation == '>':
            result = operator.gt(left, right)
        elif self.operation == '>=':
            result = operator.ge(left, right)
        elif self.operation == 'in':
            result = (left in right)
        return result
Example #16
0
            def evaluate(cond): # Method to evaluate the conditions
                if isinstance(cond,bool):
                    return cond
                left, oper, right = cond
                if not model or not left in model.mgroup.fields:  #check that the field exist
                    return False

                oper = self.OPERAND_MAPPER.get(oper.lower(), oper)
                if oper == '=':
                    res = operator.eq(model[left].get(model),right)
                elif oper == '!=':
                    res = operator.ne(model[left].get(model),right)
                elif oper == '<':
                    res = operator.lt(model[left].get(model),right)
                elif oper == '>':
                    res = operator.gt(model[left].get(model),right)
                elif oper == '<=':
                    res = operator.le(model[left].get(model),right)
                elif oper == '>=':
                    res = operator.ge(model[left].get(model),right)
                elif oper == 'in':
                    res = operator.contains(right, model[left].get(model))
                elif oper == 'not in':
                    res = operator.contains(right, model[left].get(model))
                    res = operator.not_(res)
                return res
Example #17
0
def issorted(seq: Iterable[T], key: Callable[[T], Any] = None) -> bool:
    if key is None:
        key = lambda v: v

    return all(
        operator.le(key(prev), key(curr))
        for prev, curr in sliding_window(2, seq))
Example #18
0
def fuzzyEquals(A, B):
    """
    true if A = B to within the current comparison tolerance
    """
    return operator.le(
        math.fabs(operator.sub(A, B)),
        operator.mul(_CT.python(), max(math.fabs(A), math.fabs(B))))
def cmp_fun():
    a, b = 5, 3
    print (operator.lt(a,b))
    #True Same as a<b.
    print (operator.le(a, b))
    # False
    print (operator.eq(a,b))
    # False
    print (operator.ne(a,b))    
    #TRUE
    print(operator.ge(a,b))
    #False Same as a>=b
    print (operator.gt(a, b))
    # True
    print (operator.__lt__(a, b))
    #TRUE
    print (operator.__le__(a, b))
    #TRUE
    print (operator.__ne__(a, b))
    #TRUE Same as a<b.
    print (operator.__ge__(a, b))    
    #FALSE
    print (operator.__gt__(a, b))
    #FALSE
    print (operator.__eq__(a, b))
Example #20
0
    def __init__(self):
        # xl to py formulas conversion for eval()
        self.__author__ = __author__
        self.__version__ = __version__

        # xl to py formula conversion
        self.fun_database = {
                    'IF' : lambda args : [args[0]*args[1]+(abs(args[0]-1)*args[2])][0],\
                    'AVERAGE' : lambda args : np.average(args[0]),\
                    'STDEV.P' : lambda args : np.std(args[0]),\
                    'TRANSPOSE' : lambda args : np.transpose(args[0]),\
                    'ABS' : lambda args : np.abs(args[0]),\
                    'MMULT' : lambda args : np.dot(*args),\
                    'IFERROR' : lambda args : self.pyxl_error(*args),\
                    'SUM' : lambda args : np.sum(args[0]),\
                    'COUNT' : lambda args : np.size(args[0]),\
                    'SQRT' : lambda args : np.sqrt(args[0]),\
                    '^' : lambda args : np.power(*args),\
                    '<' : lambda args : np.float64(op.lt(*args)),\
                    '>' : lambda args : np.float64(op.gt(*args)),\
                    '<=' : lambda args : np.float64(op.le(*args)),\
                    '>=' : lambda args : np.float64(op.ge(*args)),\
                    '<>' : lambda args : np.float64(op.ne(*args)),\
                    '=' : lambda args : np.float64(op.eq(*args)),\
                    '+' : lambda args : np.add(*args),\
                    '-' : lambda args : np.subtract(*args),\
                    '/' : lambda args : np.divide(*args),\
                    '*' : lambda args : np.multiply(*args)
                    }
Example #21
0
def cmp_key(key, precode):
    """key与前缀编码的比较函数"""
    pre = precode.split('*')[0]
    decode, offset = DictBuild.LineDecompress(precode)
    if pre == '':
        pre = decode[0]
    mlen = min(len(key), len(pre))
    prekey = key[0:mlen]
    pre = pre[0:mlen]
    if operator.lt(prekey, pre):
        if operator.ge(key, decode[0]):
            juge = find(decode, key)
            if juge is not -1:
                return offset[juge]
        return -1
    # key的前缀小于编码的前缀,key小于前缀
    elif operator.gt(prekey, pre):
        if operator.le(key, decode[len(decode) - 1]):
            juge = find(decode, key)
            if juge is not -1:
                return offset[juge]
        return -2
    elif operator.eq(pre, prekey):
        juge = find(decode, key)
        if juge is not -1:
            return offset[juge]
        elif operator.gt(key, decode[len(decode) - 1]):
            return -2
        elif operator.lt(key, decode[0]):
            return -1
Example #22
0
def ApproximatePatternCount(Text, Pattern, d):
    """Counting the total number of occurences of Patter in Text with
    d mismatches at most."""

    return PatternCount(Text,
                        Pattern,
                        cmp=lambda a, b: operator.le(HammingDistance(a, b), d))
Example #23
0
            def evaluate(cond):  # Method to evaluate the conditions
                if isinstance(cond, bool):
                    return cond
                left, oper, right = cond
                if not model or not left in model.mgroup.fields:  #check that the field exist
                    return False

                oper = self.OPERAND_MAPPER.get(oper.lower(), oper)
                if oper == '=':
                    res = operator.eq(model[left].get(model), right)
                elif oper == '!=':
                    res = operator.ne(model[left].get(model), right)
                elif oper == '<':
                    res = operator.lt(model[left].get(model), right)
                elif oper == '>':
                    res = operator.gt(model[left].get(model), right)
                elif oper == '<=':
                    res = operator.le(model[left].get(model), right)
                elif oper == '>=':
                    res = operator.ge(model[left].get(model), right)
                elif oper == 'in':
                    res = operator.contains(right, model[left].get(model))
                elif oper == 'not in':
                    res = operator.contains(right, model[left].get(model))
                    res = operator.not_(res)
                return res
Example #24
0
    def __init__(self):
        # xl to py formulas conversion for eval()
        self.__author__ = __author__
        self.__version__ = __version__

        # xl to py formula conversion
        self.fun_database = {
                    'IF' : lambda args : [args[0]*args[1]+(abs(args[0]-1)*args[2])][0],\
                    'AVERAGE' : lambda args : np.average(args[0]),\
                    'STDEV.P' : lambda args : np.std(args[0]),\
                    'TRANSPOSE' : lambda args : np.transpose(args[0]),\
                    'ABS' : lambda args : np.abs(args[0]),\
                    'MMULT' : lambda args : np.dot(*args),\
                    'IFERROR' : lambda args : self.pyxl_error(*args),\
                    'SUM' : lambda args : np.sum(args[0]),\
                    'COUNT' : lambda args : np.size(args[0]),\
                    'SQRT' : lambda args : np.sqrt(args[0]),\
                    '^' : lambda args : np.power(*args),\
                    '<' : lambda args : np.float64(op.lt(*args)),\
                    '>' : lambda args : np.float64(op.gt(*args)),\
                    '<=' : lambda args : np.float64(op.le(*args)),\
                    '>=' : lambda args : np.float64(op.ge(*args)),\
                    '<>' : lambda args : np.float64(op.ne(*args)),\
                    '=' : lambda args : np.float64(op.eq(*args)),\
                    '+' : lambda args : np.add(*args),\
                    '-' : lambda args : np.subtract(*args),\
                    '/' : lambda args : np.divide(*args),\
                    '*' : lambda args : np.multiply(*args)
                    }
Example #25
0
def rsvp(rsvp_url_path):

    rsvp = get_rsvp_from_url_path(rsvp_url_path.casefold())

    if rsvp is not None:
        try:
            key = request.args.get('key')
        except Exception:
            key = None

        if key is None or key != admin_key:
            rsvp.last_seen = datetime.now()
            rsvp.save()

        return render_template(
            'rsvp.html',
            rsvp=rsvp,
            show_favors_link=ge(
                datetime.now(eastern_timezone),
                datetime(2019, 9, 29, 7, 30, 0, tzinfo=eastern_timezone)),
            ceremony_rehearsal=set(rsvp.url_paths).intersection(
                ('milano', 'slo&smello', 'chiefmoyofficer', 'steve&beth',
                 'steph&josh')),
            allow_sunday_breakfast_schedule_change=le(
                datetime.now(eastern_timezone),
                datetime(2019, 9, 27, 15, 0, 0, tzinfo=eastern_timezone)))

    else:
        return render_template('error.html', rsvp_url_path=rsvp_url_path)
Example #26
0
 def _get_constraint_maps(cls):
     """
     All constraints expect two parameters:
      - the DataFrame to be constrained
      - the constraint
     """
     from functools import reduce
     from operator import eq, gt, ge, lt, le, and_, or_
     return {
         CONSTRAINTS.AND:
         lambda df, c: reduce(and_, (cls._get_constraint_for_df(df, op)
                                     for op in c.operands)),
         CONSTRAINTS.OR:
         lambda df, c: reduce(or_, (cls._get_constraint_for_df(df, op)
                                    for op in c.operands)),
         CONSTRAINTS.EQUALITY:
         lambda df, c: eq(df[c.field], c.value),
         CONSTRAINTS.INEQUALITY_GT:
         lambda df, c: gt(df[c.field], c.value),
         CONSTRAINTS.INEQUALITY_GTE:
         lambda df, c: ge(df[c.field], c.value),
         CONSTRAINTS.INEQUALITY_LT:
         lambda df, c: lt(df[c.field], c.value),
         CONSTRAINTS.INEQUALITY_LTE:
         lambda df, c: le(df[c.field], c.value),
         CONSTRAINTS.IN:
         lambda df, c: df[c.field].isin(c.value),
     }
Example #27
0
def sizeChecker(tenThou, oneHun,bountyNum):
    if operator.ge(float(bountyNum),10000):
        #save to equal or above 10000
        tenThou = tenThou + 1
    if operator.le(float(bountyNum),100):
        #save to equal or above 100
        oneHun = oneHun + 1
    return tenThou, oneHun
Example #28
0
 def specialcases(x):
     operator.lt(x,3)
     operator.le(x,3)
     operator.eq(x,3)
     operator.ne(x,3)
     operator.gt(x,3)
     operator.ge(x,3)
     is_operator(x,3)
     operator.__lt__(x,3)
     operator.__le__(x,3)
     operator.__eq__(x,3)
     operator.__ne__(x,3)
     operator.__gt__(x,3)
     operator.__ge__(x,3)
     # the following ones are constant-folded
     operator.eq(2,3)
     operator.__gt__(2,3)
Example #29
0
def apply_le(left: Column, right):
    if type(right) == Column:
        result, index = apply_fast_le(left.values, right.values,
                                      left.index, right.index)
        return Column(result, index)

    else:
        return Column(operator.le(left.values, right), left.index)
Example #30
0
    def segment(self, message):
        forward_token = self.forward_tokenizer.segment(message)
        backward_token = self.backward_tokenizer.segment(message)

        token_result = [forward_token, backward_token]

        token_count = operator.le(*map(self.compute_token_count, token_result))

        token_granularity = operator.ge(
            *map(self.compute_token_granularity, token_result))

        token_len_variability = operator.le(
            *map(self.compute_token_len_variability, token_result))

        if token_count + token_granularity + token_len_variability >= 2:
            return forward_token
        else:
            return backward_token
Example #31
0
 def _between_date(start, end, all_dates):
     '''modified pandas.DatetimeIndex.indexer_between_time'''
     lop = operator.lt
     if start is None:
         lop = operator.le
         start = all_dates[0]
     mask = operator.and_(lop(start, all_dates),
                          operator.le(all_dates, end))
     return mask.nonzero()[0]
Example #32
0
 def _get_xs_or_ys(self, get_y=True):
     res = [self.c1[get_y], self.c2[get_y]]
     if op.le(*res):
         res[-1] += 1
         res.append(1)
     else:
         res[-1] -= 1
         res.append(-1)
     return res
Example #33
0
def between(a, b, c):
    '''
    b <= a <= c
    '''
    try:
        if c is not None and b < c:
            return operator.ge(a, b) and operator.le(a, c)
    except TypeError:
        return False
Example #34
0
 def specialcases(x):
     operator.lt(x, 3)
     operator.le(x, 3)
     operator.eq(x, 3)
     operator.ne(x, 3)
     operator.gt(x, 3)
     operator.ge(x, 3)
     is_operator(x, 3)
     operator.__lt__(x, 3)
     operator.__le__(x, 3)
     operator.__eq__(x, 3)
     operator.__ne__(x, 3)
     operator.__gt__(x, 3)
     operator.__ge__(x, 3)
     operator.xor(x, 3)
     # the following ones are constant-folded
     operator.eq(2, 3)
     operator.__gt__(2, 3)
Example #35
0
def _op(comp, a, b):
    return {'<': lambda: operator.lt(a, b),
            '>': lambda: operator.gt(a, b),
            '==': lambda: operator.eq(a, b),
            '>=': lambda: operator.ge(a, b),
            '<=': lambda: operator.le(a, b),
            '!=': lambda: operator.ne(a, b),
            'inc': lambda: operator.add(a, b),
            'dec': lambda: operator.sub(a, b),
            }[comp]()
Example #36
0
def _pred(filter):
    """
    Create a SqlAlchemy Binary Expression given a single search criteria.

    :param filter: A dictionary with keys 'name', 'op' and 'val', indicating the attribute name, comparison operation
        and the comparison value we wish to use.
        'name' can be any supported attribute name of a variable (e.g. 'name'/'data_source'),
            or one of 'response'/'topic'/'umbrella'.
        'op' can be one of 'like','eq','neq','gt','gte','lt','lte' (where the op name corresponds to the usual
            semantics of these binary comparison operators.
            Note that specifying 'like' performs a fuzzy (LIKE) query in the database. Corresponding wildcards ('%')
            must be provided in the 'val' attribute for this to take effect.
        'val' is the value we wish to compare against. This is either a string or a numeric, corresponding to the
            type of the attribute specified by 'name'. Comparison against values work as expected, but
            comparison against another attribute is not supported.

    :return: A SqlAlchemy BinaryExpression object corresponding to given search criteria.
    """
    # Note: We may not have a 'val' key (for is_null/is_not_null)
    name, op, val = filter['name'], filter['op'], filter.get('val')
    op = op.lower().strip()

    if name in variable_attrs:
        column = getattr(Variable, name)
    elif name == 'response':
        column = Response.label
    else:
        return api_error(400, "Invalid name for search.")

    if op == 'like':
        pred = column.like(val)
    elif op in ('eq', '=='):
        pred = operator.eq(column, val)
    elif op in ('neq', 'ne', '!='):
        pred = operator.ne(column, val)
    elif op in ('gt', '>'):
        pred = operator.gt(column, val)
    elif op in ('gte', 'ge', '>='):
        pred = operator.ge(column, val)
    elif op in ('lt', '<'):
        pred = operator.lt(column, val)
    elif op in ('lte', 'le', '<='):
        pred = operator.le(column, val)
    elif op in ('in', ):
        pred = column.in_(val)
    elif op in ('not_in', ):
        pred = ~column.in_(val)
    elif op in ('is_null', ):
        pred = operator.eq(column, None)
    elif op in ('is_not_null', ):
        pred = operator.ne(column, None)
    else:
        return api_error(400, "Unrecognized operator")

    return pred
Example #37
0
    def is_first_exchange_day(p_no):
        session = Session()

        num = session.scalar(
            'select count(*) from wx_product_history where deleted=0 and p_no=:p_no',
            {'p_no': p_no})

        if operator.le(num, 1):
            return True

        return False
Example #38
0
    def is_contain(self, str_one, str_two):
        '''
        判断一个字符串是否在另外一个字符串中
        str_one:查找的字符串
        str_two:被查找的字符串
        '''
        # flag = None
        # if isinstance(str_one, str):
        #     str_one = str_one.encode('unicode-escape').decode('string_escape')

        return operator.le(str_one, str_two)
Example #39
0
def pedout(indi, gen, max, top, bot) :
    if indi and le(gen,max) :
        gen = add(1,gen)
        fath = father(indi)
        moth = mother(indi)
        height = add(1,sub(bot,top))
        offset = div(sub(height,8),2)
        block(indi,add(top,offset),mul(10,sub(gen,2)))
        half = div(height,2)
        pedout(fath,gen,max,top,sub(add(top,half),1))
        pedout(moth,gen,max,add(top,half),bot)
 def test_le(self):
     self.failIf(operator.le(1, 0))
     self.failIf(operator.le(1, 0.0))
     self.failUnless(operator.le(1, 1))
     self.failUnless(operator.le(1, 1.0))
     self.failUnless(operator.le(1, 2))
     self.failUnless(operator.le(1, 2.0))
Example #41
0
def _is_prime(x, priors):
    '''
    helper function for gen_primes. This determines if x is a prime number,
    given the list 'priors' which is all primes less than x.
    '''
    s = int(math.sqrt(x))
    for p in priors:
        if operator.le(p, s):
            if operator.mod(x,p) == 0:
                return False
        else:
            break
    return True
Example #42
0
 def test_le(self):
     #operator = self.module
     self.assertRaises(TypeError, operator.le)
     self.assertFalse(operator.le(1, 0))
     self.assertFalse(operator.le(1, 0.0))
     self.assertTrue(operator.le(1, 1))
     self.assertTrue(operator.le(1, 1.0))
     self.assertTrue(operator.le(1, 2))
     self.assertTrue(operator.le(1, 2.0))
Example #43
0
 def test_le(self):
     self.assertRaises(TypeError, operator.le)
     self.assertRaises(TypeError, operator.le, 1j, 2j)
     self.assertFalse(operator.le(1, 0))
     self.assertFalse(operator.le(1, 0.0))
     self.assertTrue(operator.le(1, 1))
     self.assertTrue(operator.le(1, 1.0))
     self.assertTrue(operator.le(1, 2))
     self.assertTrue(operator.le(1, 2.0))
Example #44
0
 def test_le(self):
     self.failUnlessRaises(TypeError, operator.le)
     self.failUnlessRaises(TypeError, operator.le, 1j, 2j)
     self.failIf(operator.le(1, 0))
     self.failIf(operator.le(1, 0.0))
     self.failUnless(operator.le(1, 1))
     self.failUnless(operator.le(1, 1.0))
     self.failUnless(operator.le(1, 2))
     self.failUnless(operator.le(1, 2.0))
Example #45
0
        def range_fn(test):
            # test inside nrange?
            try:
                test = float(test)
            except ValueError:
                self.log.raiseException("range_fn: can't convert test %s (type %s) to float" % (test, type(test)))

            start_res = True  # default: -inf < test
            if start is not None:
                # start <= test
                start_res = operator.le(start, test)

            end_res = True  # default: test < +inf
            if end is not None:
                # test <= end
                end_res = operator.le(test, end)

            tmp_res = operator.and_(start_res, end_res)
            if neg:
                tmp_res = operator.not_(tmp_res)

            self.log.debug("range_fn: test %s start_res %s end_res %s result %s (neg %s)" %
                           (test, start_res, end_res, tmp_res, neg))
            return tmp_res
Example #46
0
def check_condition(operand_a, oper, operand_b):
    """
    Checks condition:
    \t**operand_a op operand_b**

    where:
    \t\t*operand_a*, *operand_b* - numbers\n
    \t\t*op* - operator = [< | > | <= | >= | == | =]
    Returns True if condition is met, False otherwise.

    :param operand_a: number
    :type operand_a: int
    :param oper: operator = [< | > | <= | >= | == | =]
    :type oper: str
    :param operand_b: number
    :type operand_b: int
    :returns: True if condition is met, False otherwise.
    :raise Exception: when operator is not in [< | > | <= | >= | == | =]
    """

    if isinstance(operand_a, int):
    # if type(operand_a) is not int:
        a_n = int(operand_a)
    else:
        a_n = operand_a

    if isinstance(operand_b, int):
    # if type(operand_b) is not int:
        b_n = int(operand_b)
    else:
        b_n = operand_b

    if oper == "=" or  oper == "==":
        return operator.eq(a_n, b_n)
    elif oper == "<=":
        return operator.le(a_n, b_n)
    elif oper == "<":
        return operator.lt(a_n, b_n)
    elif oper == ">=":
        return operator.ge(a_n, b_n)
    elif oper == ">":
        return operator.gt(a_n, b_n)
    else:
        raise Exception("Not supported operator: " + oper)
	def execute_binary_operator(cls, val, x, y):
		"""Execute binary operators
		
		Execute binary operator
		
		Arguments:
			val {int} -- int
			x {int} -- int
			y {int} -- int
		
		Returns:
			int -- operation result
		"""

		if val == 0:
			return operator.add(x,y)
		elif val == 1:
			return operator.sub(x,y)
		elif val == 2:
			return operator.mul(x,y)
		elif val == 3:
			return operator.div(x,y)
		elif val == 4:
			return operator.lt(x,y)
		elif val == 5:
			return operator.gt(x,y)
		elif val == 6:
			return operator.le(x,y)
		elif val == 7:
			return operator.ge(x,y)
		elif val == 8:
			return operator.eq(x,y)
		elif val == 9:
			return operator.ne(x,y)
		elif val == 12:
			return operator.mod(x,y)
Example #48
0
 def __call__(self, x, y):
     return operator.le(x, y)
Example #49
0
operator_map = {
	# startswith
	"^": lambda a, b: (a or "").startswith(b),

	# in or not in a list
	"in": lambda a, b: operator.contains(b, a),
	"not in": lambda a, b: not operator.contains(b, a),

	# comparison operators
	"=": lambda a, b: operator.eq(a, b),
	"!=": lambda a, b: operator.ne(a, b),
	">": lambda a, b: operator.gt(a, b),
	"<": lambda a, b: operator.lt(a, b),
	">=": lambda a, b: operator.ge(a, b),
	"<=": lambda a, b: operator.le(a, b),
	"not None": lambda a, b: a and True or False,
	"None": lambda a, b: (not a) and True or False
}

def evaluate_filters(doc, filters):
	'''Returns true if doc matches filters'''
	if isinstance(filters, dict):
		for key, value in iteritems(filters):
			f = get_filter(None, {key:value})
			if not compare(doc.get(f.fieldname), f.operator, f.value):
				return False

	elif isinstance(filters, (list, tuple)):
		for d in filters:
			f = get_filter(None, d)
Example #50
0
 def __le__(self, y):
   if isinstance(y, NonStandardInteger):
     y = y.val
   return operator.le(self.val, y)
Example #51
0
 def __le__(self, other):
     return operator.le(self.to_timestamp(), other.to_timestamp())
Example #52
0
operator_map = {
	# startswith
	"^": lambda (a, b): (a or "").startswith(b),

	# in or not in a list
	"in": lambda (a, b): operator.contains(b, a),
	"not in": lambda (a, b): not operator.contains(b, a),

	# comparison operators
	"=": lambda (a, b): operator.eq(a, b),
	"!=": lambda (a, b): operator.ne(a, b),
	">": lambda (a, b): operator.gt(a, b),
	"<": lambda (a, b): operator.lt(a, b),
	">=": lambda (a, b): operator.ge(a, b),
	"<=": lambda (a, b): operator.le(a, b),
	"not None": lambda (a, b): a and True or False,
	"None": lambda (a, b): (not a) and True or False
}

def compare(val1, condition, val2):
	ret = False
	if condition in operator_map:
		ret = operator_map[condition]((val1, val2))

	return ret

def scrub_urls(html):
	html = expand_relative_urls(html)
	html = quote_urls(html)
	return html
Example #53
0
 def check(self):  # pragma: no cover
     """re-sort any items in self that are not sorted"""
     for unsorted in iter(self[i] for i in range(len(self) - 2) if not operator.le(self[i], self[i + 1])):
         self.resort(unsorted)
Example #54
0
 def __ge__(self, other):
     return operator.le(self.obj, other.obj)
Example #55
0
    def filter(self):

        number_of_rows = self.tmTableWidget.rowCount()
        for row_index in xrange(number_of_rows):
            # Retrieve text / value of filter widgets
            sequence_filter = str(self.tmFilterBySequenceComboBox.currentText())
            shot_filter = str(self.tmFilterByShotComboBox.currentText())
            department_filter = self.tmFilterByDeptComboBox.currentText()
            status_filter = self.tmFilterByStatusComboBox.currentText()
            member_filter = self.tmFilterByMemberComboBox.currentText()
            daysleft_filter = self.tmFilterByDaysLeftComboBox.value()
            daysleft_operation = self.tmDaysLeftOperationComboBox.currentText()
            bid_filter = self.tmFilterByBidComboBox.value()
            bid_operation = self.tmBidOperationComboBox.currentText()

            task_id = str(self.tmTableWidget.item(row_index, 0).text())
            task = self.Task(self, task_id)
            task.get_infos_from_id()

            # If filters are set to default value, set the filters variables to the current row values
            if sequence_filter == "None": sequence_filter = task.sequence
            if shot_filter == "None": shot_filter = task.shot
            if department_filter == "None": department_filter = task.department
            if status_filter == "None" : status_filter = task.status
            if member_filter == "None" : member_filter = self.members[task.assignation]
            if bid_filter == 0: bid_filter = task.bid
            days_left = QtCore.QDate.currentDate().daysTo(QtCore.QDate.fromString(task.end, "dd/MM/yyyy"))
            if daysleft_filter == 0:
                daysleft_filter = days_left

            if str(bid_operation) == ">=": bid_result = operator.le(int(bid_filter), int(task.bid))
            elif str(bid_operation) == "<=": bid_result = operator.ge(int(bid_filter), int(task.bid))

            if str(daysleft_operation) == ">=": days_left_result = operator.le(int(daysleft_filter), int(days_left))
            elif str(daysleft_operation) == "<=": days_left_result = operator.ge(int(daysleft_filter), int(days_left))

            if sequence_filter == task.sequence and shot_filter == task.shot and department_filter == task.department and status_filter == task.status and member_filter == self.members[task.assignation] and bid_result and days_left_result:
                # Check each row for "Done" and "Confirmed"
                if self.tmHideDoneCheckBox.isChecked() and self.tmHideConfirmedCheckBox.isChecked():
                    if task.status == "Done":
                        self.tmTableWidget.hideRow(row_index)
                        continue
                    if task.confirmation == "1":
                        self.tmTableWidget.hideRow(row_index)
                        continue
                    self.tmTableWidget.showRow(row_index)
                # Check each row for "Done" only
                elif self.tmHideDoneCheckBox.isChecked() and not self.tmHideConfirmedCheckBox.isChecked():
                    if task.status == "Done":
                        self.tmTableWidget.hideRow(row_index)
                        continue
                    self.tmTableWidget.showRow(row_index)
                # Check each row for "Confirmed" only
                elif not self.tmHideDoneCheckBox.isChecked() and self.tmHideConfirmedCheckBox.isChecked():
                    if task.confirmation == "1":
                        self.tmTableWidget.hideRow(row_index)
                        continue
                    self.tmTableWidget.showRow(row_index)
                else:
                    self.tmTableWidget.showRow(row_index)
            else:
                self.tmTableWidget.hideRow(row_index)

        self.tmTableWidget.resizeColumnsToContents()
        self.tmTableWidget.horizontalHeader().setResizeMode(1, QtGui.QHeaderView.Stretch)
Example #56
0
def cmp_le(x,y): return _op.le(x,y)

@cutype("(a, a) -> Bool")
Example #57
0
 def le_usecase(x, y):
     return operator.le(x, y)
    def test_view_set(self):
        oc = NSDictionary(a=1, b=2, c=3, d=4, e=5)

        v = oc.viewkeys() | {'a', 'f' }
        self.assertEqual(v, {'a', 'b', 'c', 'd', 'e', 'f' })
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.or_, oc.viewkeys(), ('a', 'f'))
        self.assertRaises(TypeError, operator.or_, ('a', 'f'), oc.keys())

        v = oc.viewkeys() & {'a', 'f' }
        self.assertEqual(v, {'a'})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.and_, oc.viewkeys(), ('a', 'f'))
        self.assertRaises(TypeError, operator.and_, ('a', 'f'), oc.keys())

        v = oc.viewkeys() ^ {'a', 'f' }
        self.assertEqual(v, {'b', 'c', 'd', 'e', 'f'})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.xor, oc.viewkeys(), ('a', 'f'))
        self.assertRaises(TypeError, operator.xor, ('a', 'f'), oc.keys())

        v = oc.viewkeys() - {'a', 'f' }
        self.assertEqual(v, {'b', 'c', 'd', 'e'})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.sub, oc.viewkeys(), ('a', 'f'))
        self.assertRaises(TypeError, operator.sub, ('a', 'f'), oc.keys())

        self.assertTrue(operator.lt(oc.viewkeys(), ('a', 'f')))
        self.assertTrue(operator.le(oc.viewkeys(), ('a', 'f')))
        self.assertFalse(operator.gt(oc.viewkeys(), ('a', 'f')))
        self.assertFalse(operator.ge(oc.viewkeys(), ('a', 'f')))



        v = oc.viewvalues() | {1, 9 }
        self.assertEqual(v, {1,2,3,4,5,9})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.or_, oc.viewvalues(), (1, 9))
        self.assertRaises(TypeError, operator.or_, (1, 9), oc.viewvalues())

        v = oc.viewvalues() & {1, 9 }
        self.assertEqual(v, {1})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.and_, oc.viewvalues(), (1, 9))
        self.assertRaises(TypeError, operator.and_, (1, 9), oc.viewvalues())

        v = oc.viewvalues() ^ {1, 9 }
        self.assertEqual(v, {2, 3, 4, 5, 9})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.xor, oc.viewvalues(), (1, 9))
        self.assertRaises(TypeError, operator.xor, (1, 9), oc.viewvalues())

        v = oc.viewvalues() - {1, 9 }
        self.assertEqual(v, {2,3,4,5})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.sub, oc.viewvalues(), (1, 9))
        self.assertRaises(TypeError, operator.sub, (1, 9), oc.viewvalues())

        self.assertTrue(operator.lt(oc.viewvalues(), (1, 9)))
        self.assertTrue(operator.le(oc.viewvalues(), (1, 9)))
        self.assertFalse(operator.gt(oc.viewvalues(), (1, 9)))
        self.assertFalse(operator.ge(oc.viewvalues(), (1, 9)))



        v = oc.viewitems() | {('a', 1), ('f', 9) }
        self.assertEqual(v, {('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 9)})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.or_, oc.viewitems(), (('a', 1), ('f', 9)))
        self.assertRaises(TypeError, operator.or_, (1, 9), oc.viewitems())

        v = oc.viewitems() & {('a',1), ('f',9)}
        self.assertEqual(v, {('a', 1)})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.and_, oc.viewitems(), (('a', 1), ('f', 9)))
        self.assertRaises(TypeError, operator.and_, (('a', 1), ('f', 9)), oc.viewitems())

        v = oc.viewitems() ^ {('a',1), ('f',9)}
        self.assertEqual(v, {('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 9)})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.xor, oc.viewitems(), (('a', 1), ('f', 9)))
        self.assertRaises(TypeError, operator.xor, (('a', 1), ('f', 9)), oc.viewitems())

        v = oc.viewitems() - {('a',1), ('f',9)}
        self.assertEqual(v, {('b', 2), ('c', 3), ('d', 4), ('e', 5)})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.sub, oc.viewitems(), (('a', 1), ('f', 9)))
        self.assertRaises(TypeError, operator.sub, (('a', 1), ('f', 9)), oc.viewitems())

        self.assertTrue(operator.lt(oc.viewitems(), (('a', 1), ('f', 9))))
        self.assertTrue(operator.le(oc.viewitems(), (('a', 1), ('f', 9))))
        self.assertFalse(operator.gt(oc.viewitems(), (('a', 1), ('f', 9))))
        self.assertFalse(operator.ge(oc.viewitems(), (('a', 1), ('f', 9))))
Example #59
0
def le(val_a, val_b):
    """less than or equal op for conditionals in generated code"""
    return operator.le(val_a, val_b)
    def _satisfies_extra_specs(self, capabilities, instance_type):
        """Check that the capabilities provided by the compute service
        satisfy the extra specs associated with the instance type"""
        if 'extra_specs' not in instance_type:
            return True

        # Now, it can do various operations:
        #   =, s==, s!=, s>=, s>, s<=, s<, <in>, <or>, ==, !=, >=, <=
        op_methods = {'=': lambda x, y: (float(x) >= float(y)),
                      '=+': lambda x, y: (float(x) >= float(y)),
                      '=-': lambda x, y: (float(x) >= float(y)),
                      '<in>': lambda x, y: (x.find(y) != -1),
                      '==': lambda x, y: (float(x) == float(y)),
                      '==+': lambda x, y: (float(x) == float(y)),
                      '==-': lambda x, y: (float(x) == float(y)),
                      '!=': lambda x, y: (float(x) != float(y)),
                      '!=+': lambda x, y: (float(x) != float(y)),
                      '!=-': lambda x, y: (float(x) != float(y)),
                      '>=': lambda x, y: (float(x) >= float(y)),
                      '>=+': lambda x, y: (float(x) >= float(y)),
                      '>=-': lambda x, y: (float(x) >= float(y)),
                      '<=': lambda x, y: (float(x) <= float(y)),
                      '<=+': lambda x, y: (float(x) <= float(y)),
                      '<=-': lambda x, y: (float(x) <= float(y)),
                      's==': lambda x, y: operator.eq(x, y),
                      's!=': lambda x, y: operator.ne(x, y),
                      's<': lambda x, y: operator.lt(x, y),
                      's<=': lambda x, y: operator.le(x, y),
                      's>': lambda x, y: operator.gt(x, y),
                      's>=': lambda x, y: operator.ge(x, y)}

        cap_extra_specs = capabilities.get('instance_type_extra_specs', None)
        for key, req in instance_type['extra_specs'].iteritems():
            cap = cap_extra_specs.get(key, None)
            if cap == None:
                return False
            if (type(req) == BooleanType or type(req) == IntType or
                type(req) == LongType or type(req) == FloatType):
                    if cap != req:
                        return False
            else:
                words = req.split()
                if len(words) == 1:
                    if cap != req:
                        return False
                else:
                    op = words[0]
                    method = op_methods.get(op)
                    new_req = words[1]
                    for i in range(2, len(words)):
                        new_req += words[i]

                    if op == '<or>':  # Ex: <or> v1 <or> v2 <or> v3
                        found = 0
                        for idx in range(1, len(words), 2):
                            if words[idx] == cap:
                                found = 1
                                break
                        if found == 0:
                            return False
                    elif method:
                        if method(cap, new_req) == False:
                            return False
                    else:
                        if cap != req:
                            return False
        return True