def GetDisabledReason(self): config = self.config.filter ok_to_enable = operator.truth(config.watch_folder_ids) if not ok_to_enable: return _("You must define folders to watch for new messages. " \ "Select the 'Filtering' tab to define these folders.") ok_to_enable = operator.truth(config.spam_folder_id) if not ok_to_enable: return _("You must define the folder to receive your certain spam. " \ "Select the 'Filtering' tab to define this folder.") ms = self.message_store unsure_folder = None if config.unsure_folder_id: try: unsure_folder = ms.GetFolder(config.unsure_folder_id) except ms.MsgStoreException, details: return _("The unsure folder is invalid: %s") % (details,)
def test_truth(self): class C(object): def __nonzero__(self): raise SyntaxError self.assertRaises(TypeError, operator.truth) self.assertRaises(SyntaxError, operator.truth, C()) self.assertTrue(operator.truth(5)) self.assertTrue(operator.truth([0])) self.assertFalse(operator.truth(0)) self.assertFalse(operator.truth([]))
def test_truth(self): class C(object): def __nonzero__(self): raise SyntaxError self.failUnlessRaises(TypeError, operator.truth) self.failUnlessRaises(SyntaxError, operator.truth, C()) self.failUnless(operator.truth(5)) self.failUnless(operator.truth([0])) self.failIf(operator.truth(0)) self.failIf(operator.truth([]))
def test_truth(self): #operator = self.module class C(object): def __bool__(self): raise SyntaxError self.assertRaises(TypeError, operator.truth) self.assertRaises(SyntaxError, operator.truth, C()) self.assertTrue(operator.truth(5)) self.assertTrue(operator.truth([0])) self.assertFalse(operator.truth(0)) self.assertFalse(operator.truth([]))
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 _statement_compare(self, env, node): # need sequences for compare to distinguish between # x < 4 < 3 and (x < 4) < 3 comparators = [] for comp in node.comparators: itr = self._fold_expr(env, comp) while itr: try: yield next(itr) except StopIteration: break comparators.append(env.pop()) # get the left side itr = self._fold_expr(env, node.left) while itr: try: yield next(itr) except StopIteration: break left = env.pop() comparators.insert(0, left) env.push(operator.truth(reduce(operator.and_, [self._perform_comparison(comparators[i], node.ops[i], comparators[i+1]) for i in range(len(node.ops))], 1))) yield node
def __init__(self, name, expression, abbrev=None, doc=None, filter=None, multirecord=1): """FormatObject(name, expression[, abbrev][, doc] [, filter][, multirecord]) name is the name of the object, abbrev is an abbreviation for the name, and doc is some documentation describing the object. expression is a Martel.Expression that can parse this format. filter is an optional Martel.Expression that can be used to quickly determine whether some input is parseable by this format. multirecord is either 0/1 indicating whether this format can be used to parse multiple records. By default, it is 1. """ import operator RegisterableObject.__init__(self, name, abbrev, doc) self.expression = _normalize_expression(expression) self.filter = _normalize_expression(filter) or self.expression self.filter = _support.make_cached_expression(self.filter) self.multirecord = operator.truth(multirecord) self._parser_cache = {} self._iterator_cache = {} self._parents = []
def render(self, context): # get left value lhs = self.resolve_side(self.lhs, context) # three ops if hasattr(self, 'op'): op = operator_lookup_table.get(self.op) if op is None: raise TemplateSyntaxError(self.op) # get right value rhs = self.resolve_side(self.rhs, context) # make op exec_if_branch = op(lhs, rhs) else: # one op exec_if_branch = operator.truth(lhs) if_branch, else_branch = self.split_children() return self.render_children(context, self.if_branch if exec_if_branch else self.else_branch)
def isValidResultItem(result): system, db_ = GetDatabaseUsages._parseSystemToDatabasePair(result) r = truth(system and db_) if not r: logger.warn("Database %s usage (system: %s) will be ignored" % (db_, system)) return r
def testPersistentStuff(self): try: ''.encode('hex') except: return ms = self.makeMailsicle("MAILSICLE_AUTH") from twisted.internet.app import Application msa = mailsicle.MailsicleAuthorizer(ms) a = Application("bobbo", authorizer=msa) mss = mailsicle.MailsicleService(ms, "twisted.stuff", a, msa) bob = mss.createPerspective("bob") bobd = mss.getPerspectiveRequest("bob") l = [] bobd.addCallback(l.append) self.assertEquals(l[0],bob) idn = l[0].makeIdentity("asdf") import operator self.assertEquals(operator.truth(idn.verifyPlainPassword('asdf').result), 1) freezer.clean() l = [] idn.dl = gcall(l.append, 'yes') del idn del bobd self.assertEquals(l[0], 'yes') idn = bob.getIdentityRequest().result from twisted.python import failure if isinstance(idn, failure.Failure): raise idn rslt = idn.verifyPlainPassword('asdf').result self.failUnless(rslt)
def create(self, data, filename, unlock): res = self.get_data("api/create/", data) if not filename: return False, "Bad file name" if res["result"] != "ok": return False, res["error"] else: doc = res["object"] # create a new doc rep = os.path.join(self.PLUGIN_DIR, doc["type"], doc["reference"], doc["revision"]) try: os.makedirs(rep, 0700) except os.error: # directory already exists, just ignores the exception pass gdoc = FreeCAD.ActiveDocument ggui = FreeCAD.Gui.ActiveDocument # for Visibility Checking filename = filename.decode("utf8") path = os.path.join(rep, filename) fileName, fileExtension = os.path.splitext(filename) path_stp=os.path.join(rep, (fileName+".stp")).encode("utf-8") #create temporal file stp lines=re.split('\n',gdoc.DependencyGraph) edges={} for line in lines: if truth(re.match("\A\d+\[label",line) ): labeln=re.sub('];','',re.split('=',line)[-1]) labeln=re.sub('"','',labeln) # UTF-8 national labels current_object=gdoc.getObjectsByLabel(labeln)[0] if "Group" in current_object.PropertiesList: pass else: if ggui.getObject(current_object.Name).Visibility: edges[re.findall("\A\d+",line)[0]]= labeln # Append graph nodes ImportObj=[] for ind in edges.keys(): ImportObj.append(gdoc.getObjectsByLabel(edges[ind])[0]) Part.export(ImportObj, path_stp) gdoc.saveAs(path) save(gdoc) #upload stp and freecad object doc_step_file=self.upload_file(doc, path_stp) doc_file = self.upload_file(doc, path.encode("utf-8")) #remove temporal file stp os.remove(path_stp) self.add_managed_file(doc, doc_file, path) self.load_file(doc, doc_file["id"], path, gdoc) if not unlock: self.get_data("api/object/%s/lock/%s/" % (doc["id"], doc_file["id"])) self.get_data("api/object/%s/lock/%s/" % (doc["id"], doc_step_file["id"])) else: self.send_thumbnail(gdoc) self.forget(gdoc) return True, ""
def getBroadcastAllowed(self): """ Checks if broadcast is currently allowed on this port. @return: Whether this port may broadcast. @rtype: L{bool} """ return operator.truth(self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST))
def alive(self): """does the sprite belong to any groups Sprite.alive(): return bool Returns True when the Sprite belongs to one or more Groups. """ return truth(self.__g)
def __call__(self, arg): self.count += not arg if arg: self.count = 0 self.last = operator.truth(arg) if self.count > self.limit: raise ValueError("Should not call this object anymore.") return self.count < self.limit
def alltrue(self): """Returns 1 (local value) if the local values on all processors are true. """ if self.valid: put(operator.truth(self.value), [0]) combined = reduce(operator.and_, sync(), 1) put(combined, range(numberOfProcessors)) return sync()[0]
def anytrue(self): """Returns 1 (local value) if at least one of the local values on all processors is true. """ if self.valid: put(operator.truth(self.value), [0]) combined = reduce(operator.or_, sync(), 0) put(combined, range(numberOfProcessors)) return sync()[0]
def isValidResultItem(result): # there are ephemeral SAP System entries in database which actually # can be translated to the real sap systems. # i.e. G11 and G1100080, SMN and SMN00065, etc. msgHostname = GetSystems._getMsgServerHostname(result) systemName = GetSystems._getSystemName(result) r = operator.truth(msgHostname and sap.isCorrectSystemName(systemName)) if not r: logger.warn("System %s (msg: %s) will be skipped" % (systemName, msgHostname)) return r
def arch_recursive(folder, zip): files = listdir(folder) for file in files: if file in EXCEPTION_LIST: continue file_name = folder + "\\" + file if path.isdir(file_name): #print file_name arch_recursive(file_name,zip) elif truth(filter_src.search(file)): zip.write(file_name)
def handle_data(self, data): if (truth(Search_PastRef.search(data)) and \ not(self.CurrentHref==None or self.CurrentHref=='')): self.PastRef=self.CurrentHref print 'PastRef = ', self.PastRef if truth(Search_NotSpace.match(data)): # if self.State> # if not(data=='\r\n'): print >>FileLog, ' БЛОК ТЕКСТА\n' # print >>FileLog, 'Match? - ', truth(Search2.search(data)) # print >>FileLog, 'Match? - ', string.find(data, 'П') # ED=encoder(data, 'replace')[0] ED=data print >>FileLog, ED # for c in ED: print >>FileLog, hex(ord(c)), # print >>FileLog # for c in u'П': print >>FileLog, hex(ord(c)), # print >>FileLog htmllib.HTMLParser.handle_data(self, data)
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 _bin_operator(self, exp): arg1, operator_symbol, arg2 = exp.tail print(exp.tail) operator_func = {'+': op.add, '-': op.sub, '*': op.mul, '/': op.truediv, '//': op.floordiv, '%': op.mod, '**': op.pow, '==': op.eq, '!=': op.ne, '<=': op.le, '>=': op.ge, '<': op.lt, '>': op.gt, '||': lambda arg1, arg2: float(op.truth(arg1) or op.truth(arg2)), '&&': lambda arg1, arg2: float(op.truth(arg1) and op.truth(arg2))}[operator_symbol] return operator_func(arg1, arg2)
def alltrue(self): """ @returns: C{True} if the local values on all processors are true. @rtype: Local C{bool} """ if self.valid: put(operator.truth(self.value), [0]) all = sync() if processorID == 0: combined = reduce(operator.and_, all, 1) put(combined, range(numberOfProcessors)) return sync()[0]
def render(self, context): lhs = self.resolve_side(self.lhs, context) if hasattr(self, "op"): op = operator_lookup_table.get(self.op) if op is None: raise TemplateSyntaxError(self.op) rhs = self.resolve_side(self.rhs, context) exec_if_branch = op(lhs, rhs) else: exec_if_branch = operator.truth(lhs) if_branch, else_branch = self.split_children() return self.render_children(context, self.if_branch if exec_if_branch else self.else_branch)
def _inDiscoveredSystems(pairs, sysPairsBySysName): ''' Check whether usage pair has system that belongs discovered systems @types: list[tuple[str, str]], dict[str, tuple[System, osh]] -> bool ''' if pairs: getSystemName = first systems = imap(getSystemName, pairs) r = truth(findFirst(sysPairsBySysName.has_key, systems)) if not r: logger.debug("Databases that do not serve discovered systems: %s" % pairs) return r
def most_popular_movie_for_genre_and_year(movies, genre, year): movies_with_release_date = itertools.ifilter(lambda m : operator.truth(m['release_date']), movies) movies_in_year = itertools.ifilter(lambda m : m['release_date'].tm_year == year, movies_with_release_date) movies_in_year_in_genre = itertools.ifilter(lambda m : genre in m['genres'], movies_in_year) # At this point, the list of movies is going to be very small, and possibly empty # We cannot send an empty generator to max() function call, it fails horribly # So, we convert the generator to a in-memory tuple, and then call most_popular_movie movies_in_year_in_genre = tuple(movies_in_year_in_genre) if movies_in_year_in_genre: return most_popular_movie(movies_in_year_in_genre) else: return None
def eval_condition(self, cond, context): try: if cond.op: result = cond.op(cond.lhs.eval(context), cond.rhs.eval(context)) else: result = operator.truth(cond.lhs.eval(context)) except: # We treat an exception during evaluation as a false result. # We should probably raise an exception of our own here instead. result = False if cond.negated: result = not result return result
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 GetDisabledReason(self): # Gets the reason why the plugin can not be enabled. # If return is None, then it can be enabled (and indeed may be!) # Otherwise return is the string reason config = self.config.filter ok_to_enable = operator.truth(config.watch_folder_ids) if not ok_to_enable: return "You must define folders to watch for new messages. " \ "Select the 'Filtering' tab to define these folders." ok_to_enable = operator.truth(config.spam_folder_id) if not ok_to_enable: return "You must define the folder to receive your certain spam. " \ "Select the 'Filtering' tab to define this folders." # Check that the user hasn't selected the same folder as both # 'Spam' or 'Unsure', and 'Watch' - this would confuse us greatly. ms = self.message_store unsure_folder = None # unsure need not be specified. if config.unsure_folder_id: try: unsure_folder = ms.GetFolder(config.unsure_folder_id) except ms.MsgStoreException, details: return "The unsure folder is invalid: %s" % (details,)
def isEmpty(char): """try to figure out whether the characteristic is None or empty """ try: if char in UNDEFINED: return True except TypeError: pass try: # catch 0 before it goes to operator.truth(). Also catches boolean False. x = int(char) return False except Exception: pass return not operator.truth(char)
def GetDisabledReason(self): config = self.config.filter ok_to_enable = operator.truth(config.watch_folder_ids) if not ok_to_enable: return _("You must define folders to watch for new messages. " \ "Select the 'Filtering' tab to define these folders.") ok_to_enable = operator.truth(config.spam_folder_id) if not ok_to_enable: return _("You must define the folder to receive your certain spam. " \ "Select the 'Filtering' tab to define this folder.") ms = self.message_store unsure_folder = None # unsure need not be specified. if config.unsure_folder_id: try: unsure_folder = ms.GetFolder(config.unsure_folder_id) except ms.MsgStoreException as details: return _("The unsure folder is invalid: %s") % (details,) try: spam_folder = ms.GetFolder(config.spam_folder_id) except ms.MsgStoreException as details: return _("The spam folder is invalid: %s") % (details,) if ok_to_enable: for folder in ms.GetFolderGenerator(config.watch_folder_ids, config.watch_include_sub): bad_folder_type = None if unsure_folder is not None and unsure_folder == folder: bad_folder_type = _("unsure") bad_folder_name = unsure_folder.GetFQName() if spam_folder == folder: bad_folder_type = _("spam") bad_folder_name = spam_folder.GetFQName() if bad_folder_type is not None: return _("You can not specify folder '%s' as both the " \ "%s folder, and as being watched.") \ % (bad_folder_name, bad_folder_type) return None
def parse_category(cursor_in, cursor_out): sql_select = ("select * from categories order by cat_id asc, " "cat_parent_id asc") sql_sel_whr = "select cat_parent_id from categories where cat_id = %s" sql_insert = ("insert into categories(category, parent_id," " category_dlink) values " "(%(category)s, %(parent_id)s, %(category_dlink)s)") sql_insert_map = ("insert into iav_categories_map(new_map_id, " "old_map_id) values (%(new_map_id)s, %(old_map_id)s)") tmp_map = {} try: cursor_in.execute(sql_select) request = cursor_in.fetchall() create_map_table(cursor_out, "iav_categories_map") exclusions = {'opryskivateli': 0, 'sejalki': 0} for row in request: _id, _pid, _level, _name, _full_name = row insert_pattern = { "category": _name, "parent_id": _pid, "category_dlink": slugify(_name) } excl_check = op.contains(exclusions.keys(), slugify(_name)) if op.truth(excl_check): excl_counter = exclusions[slugify(_name)] exclusions[slugify(_name)] += 1 excl_value = f"{slugify(_name)}_{excl_counter}" op.setitem(insert_pattern, "category_dlink", excl_value) if op.ne(_level, 0): new_pid = None if op.contains([1, 2], _level): new_pid = tmp_map.get(_pid, None) if op.ge(_level, 3): try: cursor_in.execute(sql_sel_whr, (_pid, )) except connector.Error as err: print(err) # new_pid = cursor_in.fetchone()[0] new_pid = tmp_map.get(cursor_in.fetchone()[0], None) raw_title = [_id, _pid] raw_title = get_category_title(cursor_in, raw_title, _pid) str_title = ','.join(['%s'] * len(raw_title)) sql_get_title = f"""select group_concat(cat_name separator '/') as title from categories where cat_id in ({str_title})""" cursor_in.execute(sql_get_title, tuple(raw_title)) new_title = cursor_in.fetchone()[0] insert_pattern.update({"category": new_title}) insert_pattern.update({"parent_id": new_pid}) try: cursor_out.execute(sql_insert, insert_pattern) except connector.Error as err: print(err) lri = cursor_out.lastrowid insert_map = {"new_map_id": lri, "old_map_id": _id} tmp_map[_id] = lri try: cursor_out.execute(sql_insert_map, insert_map) except connector.Error as err: print(err) except Exception as e: return type(e).__name__, e.args[0]
def test_truth(a: int): assert op.truth(a) == operator.truth(a)
def writeClientConfigOverrides(options): """ write our "overrides" configuration file This generated file is a configuration mapping file that is used to map settings in up2date and rhn_register when run through a seperate script. """ up2dateConfMap = { # some are directly mapped, others are handled more delicately 'http_proxy': 'httpProxy', 'http_proxy_username': '******', 'http_proxy_password': '******', 'hostname': 'serverURL', 'ssl_cert': 'sslCACert', 'no_gpg': 'useGPG', } _bootstrapDir = cleanupAbsPath(os.path.join(options.pub_tree, 'bootstrap')) if not os.path.exists(_bootstrapDir): print "* creating '%s'" % _bootstrapDir os.makedirs(_bootstrapDir) # permissions should be fine d = {} if options.hostname: scheme = 'https' if options.no_ssl: scheme = 'http' d['serverURL'] = scheme + '://' + options.hostname + '/XMLRPC' d['noSSLServerURL'] = 'http://' + options.hostname + '/XMLRPC' # if proxy, enable it # if "", disable it if options.http_proxy: d['enableProxy'] = '1' d[up2dateConfMap['http_proxy']] = options.http_proxy else: d['enableProxy'] = '0' d[up2dateConfMap['http_proxy']] = "" # if proxy username, enable auth proxy # if "", disable it if options.http_proxy_username: d['enableProxyAuth'] = '1' d[up2dateConfMap['http_proxy_username']] = options.http_proxy_username d[up2dateConfMap['http_proxy_password']] = options.http_proxy_password else: d['enableProxyAuth'] = '0' d[up2dateConfMap['http_proxy_username']] = "" d[up2dateConfMap['http_proxy_password']] = "" # CA SSL certificate is a bit complicated. options.ssl_cert may be a file # or it may be an RPM or it may be "", which means "try to figure it out # by searching through the --pub-tree on your own. _isRpmYN = processCACertPath(options) if not options.ssl_cert: sys.stderr.write( "WARNING: no SSL CA certificate or RPM found in %s\n" % options.pub_tree) if not options.no_ssl: sys.stderr.write( " Fix it by hand or turn off SSL in the clients (--no-ssl)\n" ) _certname = os.path.basename(options.ssl_cert) or CA_CRT_NAME _certdir = os.path.dirname(DEFAULT_CA_CERT_PATH) if _isRpmYN: hdr = rhn_rpm.get_package_header(options.ssl_cert) # Grab the first file out of the rpm d[up2dateConfMap['ssl_cert']] = hdr[rhn_rpm.rpm.RPMTAG_FILENAMES][ 0] # UGLY! else: d[up2dateConfMap['ssl_cert']] = os.path.join(_certdir, _certname) d[up2dateConfMap['no_gpg']] = int(operator.truth(not options.no_gpg)) writeYN = 1 _overrides = cleanupAbsPath(os.path.join(_bootstrapDir, options.overrides)) if os.path.exists(_overrides): if readConfigFile(_overrides) != d: # only back it up if different backup = rotateFile(_overrides, depth=5, verbosity=options.verbose) if backup and options.verbose >= 0: print """\ * WARNING: if there were hand edits to the rotated (backed up) file, some settings may need to be migrated.""" else: # exactly the same... no need to write writeYN = 0 print """\ * client configuration overrides (old and new are identical; not written): '%s'\n""" % _overrides if writeYN: fout = open(_overrides, 'wb') # header fout.write("""\ # RHN Client (rhn_register/up2date) config-overrides file v4.0 # # To be used only in conjuction with client_config_update.py # # This file was autogenerated. # # The simple rules: # - a setting explicitely overwrites the setting in # /etc/syconfig/rhn/{rhn_register,up2date} on the client system. # - if a setting is removed, the client's state for that setting remains # unchanged. """) keys = d.keys() keys.sort() for key in keys: if d[key] is not None: fout.write("%s=%s\n" % (key, d[key])) fout.close() print """\ * bootstrap overrides (written): '%s'\n""" % _overrides if options.verbose >= 0: print "Values written:" for k, v in d.items(): print k + ' ' * (25 - len(k)) + repr(v)
def boolean(value, _truefalse=( False, True)): return _truefalse[operator.truth(value)]
def set_loopback_mode(self, mode): mode = struct.pack("b", operator.truth(mode)) self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, mode)
def __init__(self, value = 0): self.value = operator.truth(value)
def __nonzero__(self): return truth(self.sprites())
def __nonzero__(self): "A Multicast is logically true if all delegate attributes are logically true" return operator.truth( reduce(lambda a, b: a and b, self.data.values(), 1))
def test_truth(self): self.failUnless(operator.truth(5)) self.failUnless(operator.truth([0])) self.failIf(operator.truth(0)) self.failIf(operator.truth([]))
# 以切片刪除值 Python 3.0已經移除 #operator.delslice(seq,1,2) #print("del seq[1:2] = operator.delslice(seq,1,2) = ", seq) # 取得切片值 #print("seq[1:2] = operator.getslice(seq,1,2) = ", operator.getslice(seq,1,2)) # 餘數運算 print("10 % 3 = operator.mod(10, 3) = ", operator.mod(10, 3)) # 減法運算 print("4 - 2 = operator.sub(4, 2) = ", operator.sub(4, 2)) # 真值運算(True或False) print("1 == True, 0 == False = operator.truth(1), operator.truth(0) = ", operator.truth(1), operator.truth(0)) # 比較運算 print("1 < 11 = operator.lt(1,11) = ", operator.lt(1,11)) # 比較運算 print("1 <= 11 = operator.le(1,11) = ", operator.le(1,11)) # 等價運算 print("[1,2,3] == [1,2,3] = operator.eq([1,2,3],[1,2,3]) = ", operator.eq([1,2,3],[1,2,3])) # 差異運算 print("[2,1,3] != [3,2,1] = operator.ne([2,1,3],[3,2,1]) = ", operator.ne([2,1,3],[3,2,1])) # 比較運算 print("11 >= 1 = operator.ge(11,1) = ", operator.ge(11,1))
def __bool__(self): "A multicast is logically true if all delegate attributes are logically true" return operator.truth(reduce(lambda a, b: a and b, list(self.values()), 1))
def _match_re(a, b): if isinstance(b, EvalRegExp): return truth(b.match(text_type(a))) return truth(re.match(b, text_type(a)))
def getTcpNoDelay(self): return operator.truth( self.socket.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY))
def boolean(value, _truefalse=(False, True)): """Convert any Python value to XML-RPC 'boolean'.""" return _truefalse[operator.truth(value)]
def getTcpKeepAlive(self): return operator.truth( self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE))
def bool(self, context, v): return truth(v)
#
# operator: Functional Interface to Built-In Operators # Programming using iterators occasionally requires creating small functions # for simple expressions import operator # ------------------------------------------------------------------------------ # Logical Operations # Functions are provided for determining the boolean equivalent for a value, # negating a value to create the opposite boolean value, and comparing objects # to see if they are identical. a, b, c = [1], [1], [-1] print("not a: ", operator.not_(a)) print("if a: ", operator.truth(a)) print("b is a: ", operator.is_(a, b)) print("b is not a: ", operator.is_not(a, b)) # ------------------------------------------------------------------------------ # Comparison Operators # All of the rich comparison operators are supported a, b = 1, 5.0 print("a = ", a) for func in "lt le eq ne ge gt".split(): print("{}(a, b): {}".format(func, getattr(operator, func)(a, b)))
def test_bool_values(self): from operator import truth for t, v in zip(bool_types, bool_values): self.assertEqual(t(v).value, truth(v))
def __bool__(self): return operator.truth(self.value)
def get_shift_state(shift_name): return operator.truth( reduce(operator.or_, [state[x] for x in shifts[shift_name]]))
def __nonzero__(self): return truth(self.pieces())
class Q(_Q_): """Object query node. This class works like :class:`django.db.models.Q`, but is used for filtering regular Python objects instead of database rows. **Examples** - Match object with ``last_name`` attribute set to "Costanza":: Q(last_name__eq="Costanza") - Match object with ``author.last_name`` attribute set to "Benes":: Q(author__last_name__eq="Benes") - You are not allowed to specify any key without an operator, event though the following would be fine using Django`s Q objects:: Q(author__last_name="Benes") # <-- ERROR, will raise ValueError - Attributes can be nested arbitrarily deep:: Q(a__b__c__d__e__f__g__x__gt=3.03) - The special ``*__eq=True`` means "match any *true-ish* value":: Q(author__account__is_staff__eq=True) - Similarly the ``*__eq=False`` means "match any *false-y*" value":: Q(author__account__is_disabled=False) See :ref:`events-model-filtering-operators`. :returns: :class:`collections.Callable`, to match an object with the given predicates, call the return value with the object to match: ``Q(x__eq==808)(obj)``. """ #: The gate decides the boolean operator of this tree node. #: A node can either be *OR* (``a | b``), or an *AND* note (``a & b``). #: - Default is *AND*. gates = { _Q_.OR: any, _Q_.AND: all, } #: If the node is negated (``~a`` / ``a.negate()``), branch will be True, #: and we reverse the query into a ``not a`` one. branches = { True: operator.not_, False: operator.truth, } #: Mapping of opcode to binary operator function: ``f(a, b)``. #: Operators may return any true-ish or false-y value. operators = { 'eq': operator.eq, 'now_eq': wrap_transition(operator.eq, operator.ne), 'ne': operator.ne, 'now_ne': wrap_transition(operator.ne, operator.ne), 'gt': operator.gt, 'now_gt': wrap_transition(operator.gt, operator.lt), 'lt': operator.lt, 'now_lt': wrap_transition(operator.lt, operator.gt), 'gte': operator.ge, 'now_gte': wrap_transition(operator.ge, operator.le), 'lte': operator.le, 'now_lte': wrap_transition(operator.le, operator.ge), 'in': reverse_arguments(2)(operator.contains), 'now_in': wrap_transition( reverse_arguments(2)(operator.contains), reverse_arguments(2)(not_contains), ), 'not_in': reverse_arguments(2)(not_contains), 'now_not_in': wrap_transition( reverse_arguments(2)(not_contains), reverse_arguments(2)(operator.contains), ), 'is': operator.is_, 'now_is': wrap_transition(operator.is_, operator.is_not), 'is_not': operator.is_not, 'now_is_not': wrap_transition(operator.is_not, lambda a, _: a is None), 'contains': operator.contains, 'now_contains': wrap_transition( operator.contains, negate(operator.contains), ), 'not': lambda x, _: operator.not_(x), 'true': lambda x, _: operator.truth(x), 'startswith': startswith, 'now_startswith': wrap_transition(startswith, negate(startswith)), 'endswith': endswith, 'now_endswith': wrap_transition(endswith, negate(endswith)), } def __call__(self, obj): # NOT?( AND|OR(...) ) return self.branches[self.negated](self.gate( f(obj) for f in self.stack)) def compile(self, fields): # this does not traverse the tree, but compiles the nodes # in ``self.children`` only. The nodes below will be compiled # and cached when they are called. return [self.compile_node(field) for field in fields] def compile_node(self, field): """Compiles node into a cached function that performs the match. :returns: unary :class:`collections.Callable` taking the object to match. """ # can embed other Q objects if isinstance(field, type(self)): return field # convert Django Q objects in-place. elif isinstance(field, _Q_): field.__class__ = type(self) return field # or it's a key, value pair. lhs, rhs = field lhs, opcode = self.prepare_statement(lhs, rhs) # this creates the new matching function to be added to the stack. return self.compile_op(lhs, rhs, opcode) def prepare_statement(self, lhs, rhs): lhs, _, opcode = lhs.rpartition('__') if not opcode or opcode not in self.operators: raise ValueError(E_FILTER_FIELD_MISSING_OP.format(lhs)) return lhs.replace('__', '.'), self.prepare_opcode(opcode, rhs) def prepare_opcode(self, O, rhs): # eq=True and friends are special, as they should match any # true-ish value (__bool__), not check for equality. if (O == 'eq' and rhs is True) or O == 'ne' and rhs is False: return 'true' elif (O == 'eq' and rhs is False) or O == 'ne' and rhs is True: return 'not' return O def compile_op(self, lhs, rhs, opcode): return self._compile_op( self.apply_trans_op if 'now' in opcode else self.apply_op, lhs, rhs, opcode, ) def _compile_op(self, apply, lhs, rhs, opcode, *args): return partial(apply, operator.attrgetter(lhs), self.operators[opcode], rhs, *args) def apply_op(self, getter, op, rhs, obj, *args): # compiled nodes end up being partial versions of this method, # with the getter, op and rhs arguments already set. return op(getter(obj), rhs, *args) def apply_trans_op(self, getter, op, rhs, obj): # transition op (e.g. now_eq) only matches if the # value differs from the previous version. return self.apply_op( getter, op, rhs, obj, getter(obj._previous_version), ) @property def gate(self): return self.gates[self.connector] @cached_property def stack(self): # the stack is cached on first call. return self.compile(self.children)
def xor(a, b): from operator import truth return truth(a) ^ truth(b)
def __nonzero__(self): return operator.truth(self.name_chs)
def truth_usecase(p): return operator.truth(p)
def get_all_years(movies): movies_with_release_date = itertools.ifilter( lambda m: operator.truth(m['release_date']), movies) years_possibly_duplicate = itertools.imap( lambda m: m['release_date'].tm_year, movies_with_release_date) return sorted(list(unique_everseen(years_possibly_duplicate)))
def processCommandline(): options = parseCommandline() if options.script[-3:] != '.sh': sys.stderr.write("""\ ERROR: value of --script must end in '.sh': '%s'\n""" % options.script) if not options.force: sys.stderr.write("exiting\n") sys.exit(errnoBadScriptName) options.pub_tree = cleanupAbsPath(options.pub_tree or DEFAULT_APACHE_PUB_DIRECTORY) options.overrides = os.path.basename(options.overrides) options.script = os.path.basename(options.script) if string.find(options.pub_tree, DEFAULT_APACHE_PUB_DIRECTORY) != 0: sys.stderr.write( "WARNING: it's *highly* suggested that --pub-tree is set to:\n") sys.stderr.write(" %s\n" % DEFAULT_APACHE_PUB_DIRECTORY) sys.stderr.write(" It is currently set to:\n") sys.stderr.write(" %s\n" % options.pub_tree) if not options.force: sys.stderr.write("exiting\n") sys.exit(errnoBadPath) if options.overrides == options.script: sys.stderr.write("""\ ERROR: the value of --overrides and --script cannot be the same! '%s'\n""" % options.script) sys.exit(errnoScriptNameClash) if len(string.split(options.hostname, '.')) < 3: msg = ("WARNING: --hostname (%s) doesn't appear to be a FQDN.\n" % options.hostname) sys.stderr.write(msg) if not options.force: sys.stderr.write("exiting\n") sys.exit(errnoNotFQDN) processCACertPath(options) if not options.no_ssl and options.ssl_cert and not os.path.exists( options.ssl_cert): sys.stderr.write("ERROR: CA SSL certificate file or RPM not found\n") sys.exit(errnoCANotFound) if not options.no_gpg and options.gpg_key: for gpg_key in options.gpg_key.split(","): if not os.path.exists(gpg_key): sys.stderr.write( "ERROR: corporate public GPG key file '{0}' not found\n". format(gpg_key)) sys.exit(errnoGPGNotFound) if options.http_proxy != "": options.http_proxy = parseHttpProxyString(options.http_proxy) if not options.http_proxy: options.http_proxy_username = '' if not options.http_proxy_username: options.http_proxy_password = '' # forcing numeric values for opt in [ 'allow_config_actions', 'allow_remote_commands', 'no_ssl', 'no_gpg', 'no_up2date', 'verbose' ]: # operator.truth should return (0, 1) or (False, True) depending on # the version of python; passing any of those values through int() # will return an int val = int(operator.truth(getattr(options, opt))) setattr(options, opt, val) return options
from operator import not_, truth, is_, is_not a = -1 b = 5 print('a = ', a) print('b = ', b) print() print('not_(a) :', not_(a)) # not(a) print('truth(a) :', truth(a)) # bool(a) print('is_(a,b) :', is_(a, b)) # a is b print('is_not(a,b) :', is_not(a, b)) # a is not b
def alive(self): return truth(self.__g)