def pout(gen, indi) : print name(indi) cols("",10) ndots = 0 while lt(ndots, gen) : out(". ") ndots = add(1,ndots) out("* "+name(indi)) e = birth(indi) if e : out(", b. "+long(e)) nl() (sp,fam,num,iter) = spouses(indi) while sp : cols("",10) ndots = 0 while lt(ndots, gen) : out(" ") ndots = add(1,ndots) out(" m. "+name(sp)) nl() (sp,fam,num) = spouses(iter) next = add(1,gen) if lt(next,15) : (fam,sp,num,iter) = families(indi) while fam : for (no0,child) in children(fam) : pout(next, child) (fam,sp,num) = families(iter)
def __lt__(self,other): try: return operator.lt(self.time, other.time) except: try: return operator.lt(self.time, other) except: raise TypeError("Unorderable types: Point() < " + type(other))
def testLessThan(self): """Test <operator""" _dt = self.eDatetime + datetime.timedelta(1) _other = eventCalBase.event(2, 'event', _dt) self.failUnless(operator.lt(self.e, _other), 'a1 < a2 failed. a1=%s, a2=%s' % (self.e, _other)) self.failIf(operator.lt(_other, _other), 'a1 < a2 failed. a1=%s, a2=%s' % (_other, _other))
def __lt__(self, other): if not isinstance(other, self.__class__): if self.dimensionless: return operator.lt(self.magnitude, other) else: raise ValueError('Cannot compare Quantity and {}'.format(type(other))) if self.units == other.units: return operator.lt(self._magnitude, other._magnitude) if self.dimensionality != other.dimensionality: raise DimensionalityError(self.units, other.units, self.dimensionality, other.dimensionality) return operator.lt(self.convert_to_reference().magnitude, self.convert_to_reference().magnitude)
def test_operator(self): import operator self.assertIs(operator.truth(0), False) self.assertIs(operator.truth(1), True) self.assertIs(operator.not_(1), False) self.assertIs(operator.not_(0), True) self.assertIs(operator.contains([], 1), False) self.assertIs(operator.contains([1], 1), True) self.assertIs(operator.lt(0, 0), False) self.assertIs(operator.lt(0, 1), True) self.assertIs(operator.is_(True, True), True) self.assertIs(operator.is_(True, False), False) self.assertIs(operator.is_not(True, True), False) self.assertIs(operator.is_not(True, False), True)
def MakeMaxHeap(rows, key, E, S): for i in range((E-S)//2 - 1, -1, -1): t = i + S m = 2*i + 1 + S n = 2*i + 2 + S if operator.lt(rows[t][key], rows[m][key]): # swap(rows[t], rows[m]) temp = rows[t] rows[t] = rows[m] rows[m] = temp if operator.lt(n, E) and operator.lt(rows[t][key], rows[n][key]): # swap(rows[i], rows[n]) temp = rows[t] rows[t] = rows[n] rows[n] = temp
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
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
def run(): primes = prime_reader.read_primes_default() last_prime = primes.next() prime_count = 0 diag_total = 1 current = 1 for ring in eu.numbers(2): incr = (ring - 1) * 2 for corner in xrange(3): current = op.iadd(current, incr) while current > last_prime: last_prime = primes.next() if current == last_prime: prime_count = op.iadd(prime_count, 1) current = op.add(current, incr) diag_total = op.iadd(diag_total, 4) perc = op.div(float(prime_count), diag_total) # print ring, side_length(ring), last_prime, diag_total, perc if op.lt(perc, 0.1): return side_length(ring)
def test_process(self): alg=Edge_Body() alg.attribute.set_value("width") alg.operator.set_value("Strictly smaller") pp_alg = invert_body() sg_alg = adaptive_body() gd_alg = guo_body() img_array = cv2.imread("p_polycephalum.jpg") graph = "" pp_alg.process([img_array,graph]) sg_alg.process([pp_alg.result['img'],pp_alg.result['graph']]) gd_alg.process([sg_alg.result['img'],sg_alg.result['graph']]) alg.process([gd_alg.result['img'],gd_alg.result['graph']]) #should be should_graph=gd_alg.result['graph'] to_be_removed = [(u, v) for u, v, data in should_graph.edges_iter(data=True) if op.lt(data["width"],10.0)] should_graph.remove_edges_from(to_be_removed) self.assertEqual(alg.result['graph'],should_graph)
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) }
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)
def scale_slice(sl, s): """ Scales a slice by a scaling factor. Ensures that it returns a valid step value (>1). The scaling factor is reversed """ valid_step = lambda x: tuple_slice( default(lambda a: op.lt(a[-1], 1), x, modify_tuple(x,-1,1)) ) return tuple(valid_step(s_t) for s_t in scale_tuples(map(slice_tuple, sl), reversed(s)))
def pause_count(records, min_pause, max_pause): # The meaning of minVol # is still the minimum volume to count, but now it determines # exclusion not inclusion. silences = filter(lambda x: (operator.eq(0, int(x[3]))), records) time_diffs = [int(records[i][0]) - int(records[i - 1][0]) for i in range(len(records))] return len( filter(lambda x: (operator.and_(operator.gt(x, min_pause), operator.lt(x, max_pause))), time_diffs) ) / float(len(records) - 1)
def NetCountFilterPerItem(self,df,state): # Usado para completar la info y determinar las altas y bajas netas comparison = op.gt(df[self.colsum],0) if state else op.lt(df[self.colsum],0) df_state=df[(df['filter']=='new_filter') & comparison] (index_filter, value_filter)=self.RepositoryProcessSupport.IndexValueState(df_state,self.sort_list,self.order_list,self.colsum,self.nombre_filtro,self.filtro_principal) df.loc[index_filter,'filter']=value_filter return df
def __lt__(self, other): t1 = self.hour, self.minutes, self.seconds t2 = other.hour, other.minutes, other.seconds if operator.eq(t1,t2): return 0 elif operator.lt(t1,t2): return -1 else: return 1
def __lt__(self, other): t1 = self.suit, self.rank t2 = other.suit, other.rank if operator.eq(t1,t2): return 0 elif operator.lt(t1,t2): return -1 else: return 1
def play(self): while(True): print("\n(1) : Rock\n(2) : Paper\n(3) : Scissors\n(4) : Spock\n(5) : Lizard\n") choice = int(input("Enter your move: ")) if operator.gt(choice,0) & operator.lt(choice,6): break else: choice = input("Enter your move: ") choice-=1 return moves[choice]
def authorized(self): """Tests whether requests have been authorized """ if self.authorizer.token_expires is None: return False has_token = bool(self.authorizer.access_token) not_expired = lt(datetime.datetime.utcnow(), self.authorizer.token_expires) return has_token and not_expired
def test_operator(self): import operator self.assertIs(operator.truth(0), False) self.assertIs(operator.truth(1), True) self.assertIs(operator.isNumberType(None), False) self.assertIs(operator.isNumberType(0), True) self.assertIs(operator.not_(1), False) self.assertIs(operator.not_(0), True) self.assertIs(operator.isSequenceType(0), False) self.assertIs(operator.isSequenceType([]), True) self.assertIs(operator.contains([], 1), False) self.assertIs(operator.contains([1], 1), True) self.assertIs(operator.isMappingType(1), False) self.assertIs(operator.isMappingType({}), True) self.assertIs(operator.lt(0, 0), False) self.assertIs(operator.lt(0, 1), True) self.assertIs(operator.is_(True, True), True) self.assertIs(operator.is_(True, False), False) self.assertIs(operator.is_not(True, True), False) self.assertIs(operator.is_not(True, False), True)
def formatted_gedcom(node,key) : out(delimiter) out("0 @"+key+"@ "+tag(node)+"\n") (subnode,level,iter) = traverse(node) while subnode : counter = 0 while lt(counter,level) : out(indenter) counter = add(counter,1) out(d(level)+" "+tag(subnode)+" "+value(subnode)+"\n") (subnode,level) = traverse(iter)
def play(self): while (True): try: print("Please choose a move:\n (1) Rock\n (2) Paper\n (3) Scissors") choice = int(input(" (4) Lizard\n (5) Spock\n")) if (operator.lt(choice, 6) & operator.gt(choice, 0)): break else: print("Please enter a number between 1 and 5.") except ValueError: print("Please enter a number between 1 and 5.") return moves[choice-1]
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)+" ")
def test_lt(self): self.failIf(operator.lt(1, 0)) self.failIf(operator.lt(1, 0.0)) self.failIf(operator.lt(1, 1)) self.failIf(operator.lt(1, 1.0)) self.failUnless(operator.lt(1, 2)) self.failUnless(operator.lt(1, 2.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
def pout(gen, indi) : message(name(indi)+"\n") cols("",add(5,mul(4,gen)),d(add(gen,1))+"-- ") outp(indi) next = add(1,gen) (fam,sp,num,iter) = families(indi) while fam : cols("",add(5,mul(4,gen))," sp-") outp(sp) if lt(next,15) : for (no0,child) in children(fam) : pout(next,child) (fam,sp,num) = families(iter)
def test_operator(self): import operator self.assertIs(operator.truth(0), False) self.assertIs(operator.truth(1), True) with test_support.check_py3k_warnings(): self.assertIs(operator.isCallable(0), False) self.assertIs(operator.isCallable(len), True) self.assertIs(operator.isNumberType(None), False) self.assertIs(operator.isNumberType(0), True) self.assertIs(operator.not_(1), False) self.assertIs(operator.not_(0), True) self.assertIs(operator.isSequenceType(0), False) self.assertIs(operator.isSequenceType([]), True) self.assertIs(operator.contains([], 1), False) self.assertIs(operator.contains([1], 1), True) self.assertIs(operator.isMappingType(1), False) self.assertIs(operator.isMappingType({}), True) self.assertIs(operator.lt(0, 0), False) self.assertIs(operator.lt(0, 1), True) self.assertIs(operator.is_(True, True), True) self.assertIs(operator.is_(True, False), False) self.assertIs(operator.is_not(True, True), False) self.assertIs(operator.is_not(True, False), True)
def test_lt(self): self.assertRaises(TypeError, operator.lt) self.assertRaises(TypeError, operator.lt, 1j, 2j) self.assertFalse(operator.lt(1, 0)) self.assertFalse(operator.lt(1, 0.0)) self.assertFalse(operator.lt(1, 1)) self.assertFalse(operator.lt(1, 1.0)) self.assertTrue(operator.lt(1, 2)) self.assertTrue(operator.lt(1, 2.0))
def test_lt(self): #operator = self.module self.assertRaises(TypeError, operator.lt) self.assertFalse(operator.lt(1, 0)) self.assertFalse(operator.lt(1, 0.0)) self.assertFalse(operator.lt(1, 1)) self.assertFalse(operator.lt(1, 1.0)) self.assertTrue(operator.lt(1, 2)) self.assertTrue(operator.lt(1, 2.0))
def test_lt(self): self.failUnlessRaises(TypeError, operator.lt) self.failUnlessRaises(TypeError, operator.lt, 1j, 2j) self.failIf(operator.lt(1, 0)) self.failIf(operator.lt(1, 0.0)) self.failIf(operator.lt(1, 1)) self.failIf(operator.lt(1, 1.0)) self.failUnless(operator.lt(1, 2)) self.failUnless(operator.lt(1, 2.0))
import math import cmath import random import operator # from math import cos print(dir(math)) print(dir(cmath)) m = math.cos(90) cm = cmath.cos(90) print(m) print(cm) rc = random.choice(range(10, 100, 2)) print(rc) ru = random.uniform(100, 200) print(ru) print(3 * math.pi) ol = operator.lt(10, 15) print(ol) print(bin(12345).replace("0b", "")) print("{0:b}".format(12345))
# map filter lambda reduce = ftools.reduce # NOTE: having a shorter name for partial makes it a lot nicer # to work with in nested function calls. partial = fn = ftools.partial add = op.add sub = op.sub mul = op.mul div = op.truediv floordiv = op.floordiv # Flipping the argument order for comparisons because: # 1) easier currying/partial application # 2) as a function call it reads better as lt(x, y) == "is x less than y?" lt = lambda a, b: op.lt(b, a) le = lambda a, b: op.le(b, a) gt = lambda a, b: op.gt(b, a) ge = lambda a, b: op.ge(b, a) eq = op.eq neq = op.ne #################### # Helper functions # #################### def iscol(x): ''' Allow distinguishing between string types and "true" containers ''' if isinstance(x, Container):
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # https://docs.python.org/3/library/operator.html import operator print('lt(2, -3)= ', operator.lt(2, -3)) # False a = 1.0000000000000001 b = 1.0 print('a = ', a) print('b = ', b) print('eq(a, b) = ', operator.eq(a, b)) # True, compare only first 15 digits
#use of operator module import operator a = int(input("Enter a number :")) b = int(input("enter 2nd number :")) print("\nthe sum is :", operator.add(a, b)) print("The substraction is :", operator.sub(a, b)) print("the Mul is :", operator.mul(a, b), "\n") print("the Division is :", operator.truediv(a, b)) print("the floordivide is :", operator.floordiv(a, b)) print("the pow is :", operator.pow(a, b)) print("the modulas is :", operator.mod(a, b), "\n") #use of relation operator # use of less than print("the use of 'lt' check a<b or not is :", operator.lt(a, b)) print("the use of 'le' check a<= b :", operator.le(a, b)) print("the use of 'eq'check a ==b or not :", operator.eq(a, b), "\n") #use of greater than print("the use of 'gt' check a>b or not is :", operator.gt(a, b)) print("the use of 'ge' check a>= b :", operator.ge(a, b)) print("the use of 'ne'check a !=b or not :", operator.ne(a, b))
def job(): now = datetime.now() current_time = now.strftime("%H:%M:%S") global position # Generate a panda from alpaca data panda = api.get_barset(alpacaTicker, '5Min', limit=600).df # Turn panda to csv panda.to_csv(os.path.abspath(os.getcwd()) + '/' + ticker + '.csv') # This function to calculate the indicator values on the csv and update calvIndicators() # Read the updated csv to a panda nowData = pd.read_csv(file1) # Get the last row date of the panda. Date = nowData["Unnamed: 0"][nowData.index[-1]] toolbox = base.Toolbox() toolbox.register("compile", gp.compile, pset=pset) i = operator.and_( if_then_else(position, operator.gt(rsi(Date, 7), 42), operator.lt(rsi(Date, 7), 53)), operator.lt(ma(Date, 50), ma(Date, 10))) rule = toolbox.compile(expr=i) action = rule(Date, position) if action and position == False: buy = True sell = False elif not action and position == False: sell = False buy = False elif action and position == True: sell = False buy = False elif not action and position == True: sell = True buy = False if buy: print(current_time, ": Buy") position = True if trade: api.submit_order(symbol=alpacaTicker, qty=numShares, side='buy', time_in_force='gtc', type='market') elif sell: print(current_time, ": Sell") position = False if trade: api.submit_order(symbol=alpacaTicker, qty=numShares, side='sell', time_in_force='gtc', type='market') elif position == False: print(current_time, ": Wait") else: print(current_time, ": Hold") return
variableDict = {} for line in sys.stdin: if line == '\n': break instruction = line.strip().split() if instruction[0] == 'define': variableDict[instruction[2]] = int(instruction[1]) else: operation = instruction[2] if instruction[1] not in variableDict or instruction[ 3] not in variableDict: print('undefined') else: vars = [variableDict[instruction[1]], variableDict[instruction[3]]] if operation == '<': result = str(operator.lt(vars[0], vars[1])).lower() print(result) elif operation == '>': result = str(operator.gt(vars[0], vars[1])).lower() print(result) else: result = str(operator.eq(vars[0], vars[1])).lower() print(result)
def __lt__(self, other: DATETIME_LIKE) -> bool: return operator.lt(self.interval, _datetime_interval(other))
return result n = 500 start_t = time.time() result = fib_memo(n) end_t = time.time() time_taken = end_t - start_t print('time elapsed: ', time_taken, ' seconds') ##operator module import operator print(operator.mul(5, 6)) print(operator.sub(5, 6)) print(operator.add(5, 6)) print(operator.lt(5, 6)) #passing higher order functions my_list = [(1, 'hello'), (200, 'world'), (50, 'hi'), (179, 'bye')] #sort according to first value in tuple print(sorted(my_list, key=operator.itemgetter(0), reverse=True)) print(sorted(my_list, key=operator.itemgetter(0), reverse=False)) import timeit from functools import reduce timeit.timeit('reduce(lambda x, y: x * y, range(1,100))') timeit.timeit('reduce(mul, range(1,100))', setup='from operator import mul')
def __lt__(self, other): return operator.lt(*self._get_operands(other))
def __lt__(self, other): return operator.lt(self.weights, other.weights)
if int(segment[0]) == 0: break return versions, int(literal, 2) elif (length_type := int(reader.read(1))) == 0: read_to = int(reader.read(15), 2) + reader.tell() while reader.tell() != read_to: decode() elif length_type == 1: for _ in range(int(reader.read(11), 2)): decode() return versions, operations[packet_type](literals) operations = { 0: sum, 1: prod, 2: min, 3: max, 5: lambda x: gt(*x), 6: lambda x: lt(*x), 7: lambda x: eq(*x) } bits = ''.join(bin(int(c, 16))[2:].zfill(4) for c in sys.stdin.read().strip()) versions, result = parse(StringIO(bits)) print('Part 1:', sum(versions)) print('Part 2:', result)
def __lt__(self, y): if isinstance(y, NonStandardInteger): y = y.val return operator.lt(self.val, y)
def do_less_with_value_type_check(left, right): # None if left is None or right is None: return False # str if isinstance(left, str) and isinstance(right, str): if left.isdigit() and right.isdigit(): return operator.lt(Decimal(left), Decimal(right)) else: raise TypeError( "operator less, the left \"{0}\" is str, the right \"{1}\" is str" .format(left, right)) if isinstance(left, str) and (isinstance(right, int) or isinstance(right, Decimal)): return operator.lt(Decimal(left), right) if isinstance(left, str) and (isinstance(right, datetime) or isinstance(right, date)): try: return operator.lt(arrow.get(left).date(), arrow.get(right).date()) except ParserError: raise TypeError( "operator less, the left \"{0}\" can not be match by date format, the right \"{1}\" is datetime or date" .format(left, right)) if isinstance(left, str) and isinstance(right, dict): raise TypeError( "operator less, the left \"{0}\" is str, the right \"{1}\" is dict" .format(left, right)) if isinstance(left, str) and isinstance(right, list): raise TypeError( "operator less, the left \"{0}\" is str, the right \"{1}\" is list" .format(left, right)) # number, int, decimal if (isinstance(left, int) or isinstance(left, Decimal)) and isinstance( right, str): if right.isdigit(): return operator.lt(Decimal(left), Decimal(right)) else: raise TypeError( "operator less, the left \"{0}\" is int or decimal, the right \"{1}\" is str" .format(left, right)) if (isinstance(left, int) or isinstance(left, Decimal)) and (isinstance( right, int) or isinstance(right, Decimal)): return operator.lt(Decimal(left), Decimal(right)) if (isinstance(left, int) or isinstance(left, Decimal)) and (isinstance( right, datetime) or isinstance(right, date)): try: return operator.lt( arrow.get(str(left)).date(), arrow.get(right).date()) except ParserError: raise TypeError( "operator less, the left \"{0}\" can not be match by date format, the right \"{1}\" is datetime or date" .format(left, right)) if (isinstance(left, int) or isinstance(left, Decimal)) and isinstance( right, dict): raise TypeError( "operator less, the left \"{0}\" is int or decimal, the right \"{1}\" is dict" .format(left, right)) if (isinstance(left, int) or isinstance(left, Decimal)) and isinstance( right, list): raise TypeError( "operator less, the left \"{0}\" is int or decimal, the right \"{1}\" is list" .format(left, right)) # datetime and date if (isinstance(left, datetime) or isinstance(left, date)) and isinstance( right, str): try: return operator.lt(arrow.get(left).date(), arrow.get(right).date()) except ParserError: raise TypeError( "operator less, the left \"{0}\" is datetime or date, the right \"{1}\" is str, can not match date " "format".format(left, right)) if (isinstance(left, datetime) or isinstance(left, date)) and (isinstance( right, int) or isinstance(right, Decimal)): try: return operator.lt( arrow.get(left).date(), arrow.get(str(right)).date()) except ParserError: raise TypeError( "operator less, the left \"{0}\" is datetime or date, the right \"{1}\" is int or decimal" .format(left, right)) if (isinstance(left, datetime) or isinstance(left, date)) and (isinstance( right, datetime) or isinstance(right, date)): return operator.lt(arrow.get(left).date(), arrow.get(right).date()) if (isinstance(left, datetime) or isinstance(left, date)) and isinstance( right, dict): raise TypeError( "operator less, the left \"{0}\" is datetime or date, but the right \"{1}\" is dict" .format(left, right)) if (isinstance(left, datetime) or isinstance(left, date)) and isinstance( right, list): raise TypeError( "operator less, the left \"{0}\" is datetime or date, but the right \"{1}\" is list" .format(left, right)) # dict if isinstance(left, dict) and isinstance(right, str): raise TypeError( "operator less, the left \"{0}\" is dict, the right \"{1}\" is str" .format(left, right)) if isinstance(left, dict) and (isinstance(right, int) or isinstance(right, Decimal)): raise TypeError( "operator less, the left \"{0}\" is dict, the right \"{1}\" is int or decimal" .format(left, right)) if isinstance(left, dict) and (isinstance(right, datetime) or isinstance(right, date)): raise TypeError( "operator less, the left \"{0}\" is dict, the right \"{1}\" is datetime or date" .format(left, right)) if isinstance(left, dict) and isinstance(right, dict): raise TypeError( "operator less, the left \"{0}\" is dict, the right \"{1}\" is dict" .format(left, right)) if isinstance(left, dict) and isinstance(right, list): raise TypeError( "operator less, the left \"{0}\" is dict, the right \"{1}\" is list" .format(left, right)) # list if isinstance(left, list) and isinstance(right, str): raise TypeError( "operator less, the left \"{0}\" is list, the right \"{1}\" is str" .format(left, right)) if isinstance(left, list) and (isinstance(right, int) or isinstance(right, Decimal)): raise TypeError( "operator less, the left \"{0}\" is list, the right \"{1}\" is int or decimal" .format(left, right)) if isinstance(left, list) and (isinstance(right, datetime) or isinstance(right, date)): raise TypeError( "operator less, the left \"{0}\" is list, the right \"{1}\" is datetime or date" .format(left, right)) if isinstance(left, list) and isinstance(right, dict): raise TypeError( "operator less, the left \"{0}\" is list, the right \"{1}\" is dict" .format(left, right)) if isinstance(left, list) and isinstance(right, list): raise TypeError( "operator less, the left \"{0}\" is list, the right \"{1}\" is list" .format(left, right)) return operator.lt(left, right)
def __set__(self,instance,value): if(operator.gt(value,100) or operator.lt(value,0)): raise IOError("out of range") else: self._score=value
print("The exponentiation of numbers is : ", end="") print(operator.pow(a, b)) # using mod() to take modulus of two numbers print("The modulus of numbers is : ", end="") print(operator.mod(a, b)) # Python code to demonstrate working of # lt(), le() and eq() # Initializing variables a = 3 b = 3 # using lt() to check if a is less than b if (operator.lt(a, b)): print("3 is less than 3") else: print("3 is not less than 3") # using le() to check if a is less than or equal to b if (operator.le(a, b)): print("3 is less than or equal to 3") else: print("3 is not less than or equal to 3") # using eq() to check if a is equal to b if (operator.eq(a, b)): print("3 is equal to 3") else: print("3 is not equal to 3")
def __lt__(self, other): if(other == None): return -1 if(not isinstance(other, HeapNode)): return -1 return operator.lt(self.freq,other.freq)
def __lt__(self, other: TIMEDELTA_LIKE) -> bool: return operator.lt(self.interval, _timedelta_interval(other))
def spatial_grid(self, DHW, MPQ, mpqLut, mpq, trs): # Find the most efficient super-block using a tile of size 32 # For ties then pick the larger tile in the W dim (more contiguous memory access) # TODO: allow a mixture of superblock shapes, or maybe odd shapes to get better ulilization ulilization = list() # xxxxx yxxxx yyxxx zyyxx for sb in ((1, 1, 32), (1, 2, 16), (1, 4, 8), (2, 4, 4)): util = float(mpq) / reduce( mul, [ceil_div(*dims) for dims in zip(MPQ, sb)], 32) ulilization.append((1.0 - util, 32 - sb[2], sb)) sb = sorted(ulilization)[0][2] # Map the 32 positions in the superblock to MPQ coordinates # superblock mask: zyyxx : (1,3,3), yxxxx : (0,1,15) sb_mask = [x - 1 for x in sb] # superblock cumulative right-shift: zyyxx : (4,2,0), yxxxx : (5,4,0) shifts = [len(bin(x)) - 3 for x in sb] sb_shift = [shifts[1] + shifts[2], shifts[2], 0] HW = DHW[1] * DHW[2] W = DHW[2] PQ = MPQ[1] * MPQ[2] Q = MPQ[2] # Get the dimension in super blocks mpqDim = [ceil_div(MPQ[i], sb[i]) for i in range(3)] mpq_lut = list() # Iterate over superblocks to build the lut for order, sb_mpq in sorted([(morton(*mpq), mpq) for mpq in np.ndindex(*mpqDim)]): lut32 = [list() for i in range(trs + 1)] for i32 in range(32): # get the mpq coord for each of the 32 positions in the superblock m = sb_mpq[0] * sb[0] + ((i32 >> sb_shift[0]) & sb_mask[0]) p = sb_mpq[1] * sb[1] + ((i32 >> sb_shift[1]) & sb_mask[1]) q = sb_mpq[2] * sb[2] + ((i32 >> sb_shift[2]) & sb_mask[2]) # make sure we didn't fall off the edge if all(lt(*mM) for mM in zip((m, p, q), MPQ)): # add in all the input image offsets for each filter position lut = [ d * HW + h * W + w if all(x >= 0 for x in (d, h, w)) else -1 for d in mpqLut[0][m] for h in mpqLut[1][p] for w in mpqLut[2][q] ] # add the output image offset lut.append(m * PQ + p * Q + q) else: # -1 offsets get zero padded lut = [-1] * (trs + 1) # transpose lut data so contiguous rows are for 32 mpq coords of the same trs value for i in range(trs + 1): lut32[i].append(lut[i]) mpq_lut.append(lut32) return np.array(mpq_lut, dtype=np.int32)
# print(dir(operator)) print(operator.add(1,2)) print(operator.mul(1,2)) print(operator.truediv(10,3)) print(operator.floordiv(15,2)) from functools import reduce print(reduce(lambda x,y : x*y,[1,2,3,4])) # still i did not get how pass three element in lamda in using reduce #using operator we can do without lamda function print(reduce(operator.mul,[1,2,3,4])) print(operator.lt(10,3)) print(operator.truth([])) #empty list is false print(operator.truth([1])) print(operator.truth('')) print(operator.truth(None)) print(operator.truth([0])) #list with any element is True print(operator.truth(0)) print(operator.truth(1)) print(operator.is_("abc","def")) print(operator.is_("abc","abc")) my_list = [1,2,3,4] print(my_list[1]) print(operator.getitem(my_list,3)) #it require two elements
return get_url(uri="desk#List/{0}".format(quoted(doctype))) 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 test_correctness(yamlstrs): """Tests the correctness of the constructors""" res = {} # Load the resolved yaml strings for name, ystr in yamlstrs.items(): print("Name of yamlstr that will be loaded: ", name) if isinstance(name, tuple): # Will fail, don't use continue res[name] = yaml.load(ystr) # Test the ParamDim objects pdims = res["pdims_only"]["pdims"] assert pdims[0].default == 0 assert pdims[0].values == (1, 2, 3) assert pdims[1].default == 0 assert pdims[1].values == tuple(range(10)) assert pdims[2].default == 0 assert pdims[2].values == tuple(np.linspace(1, 2, 3)) assert pdims[3].default == 0 assert pdims[3].values == tuple(np.logspace(1, 2, 3)) assert pdims[4] == 0 # Test the ParamSpace's for psp in res["pspace_only"].values(): assert isinstance(psp, ParamSpace) # Test the utility constructors utils = res["utils"]["utils"] assert utils["any"] == any([False, 0, True]) assert utils["all"] == all([True, 5, 0]) assert utils["abs"] == abs(-1) assert utils["int"] == int(1.23) assert utils["round"] == round(9.87) == 10 assert utils["min"] == min([1, 2, 3]) assert utils["max"] == max([1, 2, 3]) assert utils["sorted"] == sorted([2, 1, 3]) assert utils["isorted"] == sorted([2, 1, 3], reverse=True) assert utils["sum"] == sum([1, 2, 3]) assert utils["prod"] == 2 * 3 * 4 assert utils["add"] == operator.add(*[1, 2]) assert utils["sub"] == operator.sub(*[2, 1]) assert utils["mul"] == operator.mul(*[3, 4]) assert utils["truediv"] == operator.truediv(*[3, 2]) assert utils["floordiv"] == operator.floordiv(*[3, 2]) assert utils["mod"] == operator.mod(*[3, 2]) assert utils["pow"] == 2**4 assert utils["pow_mod"] == 2**4 % 3 == pow(2, 4, 3) assert utils["pow_mod2"] == 2**4 % 3 == pow(2, 4, 3) assert utils["not"] == operator.not_(*[True]) assert utils["and"] == operator.and_(*[True, False]) assert utils["or"] == operator.or_(*[True, False]) assert utils["xor"] == operator.xor(*[True, True]) assert utils["lt"] == operator.lt(*[1, 2]) assert utils["le"] == operator.le(*[2, 2]) assert utils["eq"] == operator.eq(*[3, 3]) assert utils["ne"] == operator.ne(*[3, 1]) assert utils["ge"] == operator.ge(*[2, 2]) assert utils["gt"] == operator.gt(*[4, 3]) assert utils["negate"] == operator.neg(*[1]) assert utils["invert"] == operator.invert(*[True]) assert utils["contains"] == operator.contains(*[[1, 2, 3], 4]) assert utils["concat"] == [1, 2, 3] + [4, 5] + [6, 7, 8] assert utils["format1"] == "foo is not bar" assert utils["format2"] == "fish: spam" assert utils["format3"] == "results: 1.63 ± 0.03" assert utils["list1"] == [0, 2, 4, 6, 8] assert utils["list2"] == [3, 6, 9, 100] assert utils["lin"] == [-1.0, -0.5, 0.0, 0.5, 1.0] assert utils["log"] == [10.0, 100.0, 1000.0, 10000.0] assert np.isclose(utils["arange"], [0.0, 0.2, 0.4, 0.6, 0.8]).all() assert utils["some_map"] assert utils["some_other_map"] assert utils["merged"] == { "foo": { "bar": "baz", "baz": "bar", }, "spam": "fish", "fish": "spam", } assert utils["merged"] == recursive_update(utils["some_map"], utils["some_other_map"])
def url_link(extra_log2_value_file): path_id = str(extra_log2_value_file)[10:18] # mmu00190 print path_id + "\t", # http://www.kegg.jp/kegg-bin/show_pathway?hsa04530/default%3white/hsa:6709%09%23ff1493/hsa:8531%09%230000ff,red x = open(extra_log2_value_file, 'r') # extra_log2_value.r kegg_line = "http://www.kegg.jp/kegg-bin/show_pathway?" + path_id + "/default%3white" for line in x: if re.search("^\d+\s+\w+\d+\s+.*$", line): #print line sub = re.search("^(\d+)\s+\w+\d+\s+(.*)$", line) entrez_id = sub.group(1) log_value = sub.group(2) if operator.ne(log_value, "NA"): if operator.gt(float(log_value), 0): # 255,255,255 -> white # 255,0,0 -> red # 255,20,147 -> pink color_code_1_red = hex(255).split('x')[1] color_code_2_red = hex(255 - int(255 * float(log_value))).split('x')[1] color_code_total_red = str(color_code_1_red) + str( color_code_2_red) + str(color_code_2_red) # print "/mmu:"+str(entrez_id)+"%09%23ff1493" kegg_line = kegg_line + "/hsa:" + str( entrez_id) + "%09%23" + str(color_code_total_red) # kegg_line = kegg_line+"/mmu:"+str(entrez_id)+"%09%23ff1493" elif operator.lt(float(log_value), 0): # 255,255,255 -> white # 0,0,255 -> blue color_code_2_blue = hex(255).split('x')[1] color_code_1_blue = hex( 255 - abs(int(255 * float(log_value)))).split('x')[1] color_code_total_blue = str(color_code_1_blue) + str( color_code_1_blue) + str(color_code_2_blue) kegg_line = kegg_line + "/hsa:" + str( entrez_id) + "%09%23" + str(color_code_total_blue) # kegg_line = kegg_line+"/mmu:"+str(entrez_id)+"%09%230000ff,red" else: kegg_line = kegg_line + "/hsa:" + str(entrez_id) else: kegg_line = " " print str(kegg_line)
def __lt__(self, other): return operator.lt(self.frequency, other.frequency)
def cmp(a, b): if a is not None and b is not None: return operator.gt(a, b) - operator.lt(a, b) else: return 0
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
def less_than(field, param=None, value=None, **kwargs): param_or_value = param or value return operator.lt(field, param_or_value)
description = self.project_description, name = self.project_name, url = self.project_url, author = self.author_name, author_email = self.author_email, license = self.license, # targets to build windows = [{ 'script': self.script, 'icon_resources': [(0, self.icon_file)], 'copyright': self.copyright }], options = {'py2exe': {'optimize': 2, 'bundle_files': 1, 'compressed': True, \ 'excludes': self.exclude_modules, 'packages': self.extra_modules, \ 'dll_excludes': self.exclude_dll, 'includes': self.extra_scripts} }, zipfile = self.zipfile_name, data_files = extra_datas, dist_dir = self.dist_dir ) if os.path.isdir('build'): #Clean up build dir shutil.rmtree('build') if __name__ == '__main__': if operator.lt(len(sys.argv), 2): sys.argv.append('py2exe') BuildExe().run() #Run generation raw_input("Press any key to continue") #Pause to let user see that things ends
#删除列表中的元素 del ss[1] print(ss) a = [1, 2, 3] print(a * 2) #结果为:[1,2,3,1,2,3] b = [1, 2, 3, 4] print(a + b) #列表拼接 #获取列表的长度 print("列表的长度为:" + str(len(a))) #比较两个列表的元素 print(operator.lt(a, b)) #判断小于 print(operator.eq(a, b)) #判断等于 aa = ["a", "1", "5", "8", "9"] #获取中元素个数 print(len(b)) print(max(aa)) aa.append("bb") print(aa) bb = ["c", "d"] aa.extend(bb) print(aa)
else: return get_url(uri = "desk#query-report/{0}".format(quoted(name))) 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)):
def my_lt(self, other): ''' create my own lt function ''' return operator.lt(self.val, other.val)