rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
def _lexcmp(a, b): i = 0 while True: if len(a) == len(b): if i == len(a): return 0 else: if i == len(a): return -1 if i == len(b): return 1 if a[i].isalpha(): if not b[i].isalpha(): return -1 if b[i].isalpha(): if not a[i].isalpha(): return 1 val = cmp(a[i], b[i]) if val != 0: return val i += 1
def getnum(self): str = self.str i = 0 for c in str: if c not in '0123456789': break i += 1
val = cmp(l1, l2)
val = _lexcmp(l1, l2)
def _compare(s1, s2): if s1 == s2: return 0 p1 = VersionParser(s1) p2 = VersionParser(s2) while True: l1 = p1.getlex() l2 = p2.getlex() val = cmp(l1, l2) if val != 0: return val n1 = p1.getnum() n2 = p2.getnum() val = cmp(n1, n2) if val != 0: return val if p1.str == p2.str: return 0
val = cmp(l1, l2)
val = _lexcmp(l1, l2)
def _compare_flat(s1, s2): if s1 == s2: return 0 while True: # parse lexical components i = 0 for c in s1: if c in '0123456789': break i += 1 if i: l1 = s1[:i] s1 = s1[i:] else: l1 = '' i = 0 for c in s2: if c in '0123456789': break i += 1 if i: l2 = s2[:i] s2 = s2[i:] else: l2 = '' val = cmp(l1, l2) if val != 0: ...
files = StockBase.Paths.files + \ [ 'source-versions', 'SYNC_HEAD', 'checkout' ]
files = [ 'source-versions', 'SYNC_HEAD', 'checkout' ]
def __init__(self, path, recursed_paths=[]): StockBase.__init__(self, path) if self.link in recursed_paths: raise CircularDependency("circular dependency detected `%s' is in recursed paths %s" % (self.link, recursed_paths))
path = join(path, ".git") command = "git --git-dir %s init" % commands.mkarg(path)
init_path = join(init_path, ".git") command = "git --git-dir %s init" % commands.mkarg(init_path)
def init_create(cls, path, bare=False, verbose=False): if not lexists(path): os.mkdir(path)
return dir, branch
return realpath(dir), branch
def _parse_stock(stock): try: dir, branch = stock.split("#", 1) except ValueError: dir = stock branch = None
if not self.stocks.has_key(stock_name) or \ self.stocks[stock_name].link != realpath(dir):
matches = [ stock for stock in self.stocks.values() if stock.link == dir and (not branch or stock.branch == branch) ] if not matches:
def unregister(self, stock): dir, branch = self._parse_stock(stock) stock_name = basename(dir) if branch: stock_name += "#" + branch if not self.stocks.has_key(stock_name) or \ self.stocks[stock_name].link != realpath(dir): raise Error("no matches for unregister")
shutil.rmtree(self.stocks[stock_name].path) del self.stocks[stock_name]
if len(matches) > 1: raise Error("multiple implicit matches for unregister") stock = matches[0] shutil.rmtree(stock.path) del self.stocks[stock.name]
def unregister(self, stock): dir, branch = self._parse_stock(stock) stock_name = basename(dir) if branch: stock_name += "#" + branch if not self.stocks.has_key(stock_name) or \ self.stocks[stock_name].link != realpath(dir): raise Error("no matches for unregister")
def getpath_cached(p, package): """get path of cached package, whether in the pool or in a subpool""" path = p.pkgcache.getpath(package)
def pkgcache_list_versions(pool, name): versions = [ pkgcache_version for pkgcache_name, pkgcache_version in pool.pkgcache.list() if pkgcache_name == name ] for subpool in pool.subpools: versions += pkgcache_list_versions(subpool, name) return versions def pkgcache_getpath_newest(pool, name): versions = pkgcache_lis...
def getpath_cached(p, package): """get path of cached package, whether in the pool or in a subpool""" path = p.pkgcache.getpath(package) if path: return path for subpool in p.subpools: path = getpath_cached(subpool, package) if path: return path return None
for subpool in p.subpools: path = getpath_cached(subpool, package) if path: return path
source_package = binary2source(pool, package) if source_package: path = pool.getpath_build_log(source_package)
def getpath_cached(p, package): """get path of cached package, whether in the pool or in a subpool""" path = p.pkgcache.getpath(package) if path: return path for subpool in p.subpools: path = getpath_cached(subpool, package) if path: return path return None
return None
if not path: package_desc = `package` if source_package: package_desc += " (%s)" % source_package fatal("no build log for " + package_desc) return path
def getpath_cached(p, package): """get path of cached package, whether in the pool or in a subpool""" path = p.pkgcache.getpath(package) if path: return path for subpool in p.subpools: path = getpath_cached(subpool, package) if path: return path return None
try: p = pool.Pool() except pool.Error, e: fatal(e)
path = getpath_build_log(package)
def main(): args = sys.argv[1:] if not args: usage() package = args[0] try: p = pool.Pool() except pool.Error, e: fatal(e) source_package = package deb = getpath_cached(p, package) if deb: source_name = extract_source_name(deb) if source_name: source_package = source_name if '=' in package: source_package += "=" + p...
source_package = package deb = getpath_cached(p, package) if deb: source_name = extract_source_name(deb) if source_name: source_package = source_name if '=' in package: source_package += "=" + package.split("=", 1)[1] path = p.getpath_build_log(source_package) if not path: fatal("no build log for `%s' (%s)" % (package...
def main(): args = sys.argv[1:] if not args: usage() package = args[0] try: p = pool.Pool() except pool.Error, e: fatal(e) source_package = package deb = getpath_cached(p, package) if deb: source_name = extract_source_name(deb) if source_name: source_package = source_name if '=' in package: source_package += "=" + p...
if val != 0: return val n1 = p1.getnum() n2 = p2.getnum() val = cmp(n1, n2)
def _compare(s1, s2): if s1 == s2: return 0 p1 = VersionParser(s1) p2 = VersionParser(s2) while True: l1 = p1.getlex() l2 = p2.getlex() val = cmp(l1, l2) if val != 0: return val n1 = p1.getnum() n2 = p2.getnum() val = cmp(n1, n2) if val != 0: return val
epoch = 0
epoch = ''
def parse(v): if ':' in v: epoch, v = v.split(':', 1) else: epoch = 0 if '-' in v: upstream_version, debian_revision = v.rsplit('-', 1) else: upstream_version = v debian_revision = '' return epoch, upstream_version, debian_revision
class VersionParser: def __init__(self, str): self.str = str def getlex(self): lex = re.match(r'(\D*)', self.str).group(1) self.str = self.str[len(lex):] return lex def getnum(self): num = re.match(r'(\d*)', self.str).group(1) self.str = self.str[len(num):] if num: return int(num) return 0 def _compare(s1, s2): i...
def parse(v): if ':' in v: epoch, v = v.split(':', 1) else: epoch = 0 if '-' in v: upstream_version, debian_revision = v.rsplit('-', 1) else: upstream_version = v debian_revision = '' return epoch, upstream_version, debian_revision
epoch = ''
epoch = '0'
def parse(v): if ':' in v: epoch, v = v.split(':', 1) else: epoch = '' if '-' in v: upstream_version, debian_revision = v.rsplit('-', 1) else: upstream_version = v debian_revision = '' return epoch, upstream_version, debian_revision
debian_revision = ''
debian_revision = '0'
def parse(v): if ':' in v: epoch, v = v.split(':', 1) else: epoch = '' if '-' in v: upstream_version, debian_revision = v.rsplit('-', 1) else: upstream_version = v debian_revision = '' return epoch, upstream_version, debian_revision
a = parse(normalize(a)) b = parse(normalize(b))
a = parse(a) b = parse(b)
def compare(a, b): """Compare a with b according to Debian versioning criteria""" a = parse(normalize(a)) b = parse(normalize(b)) for i in (0, 1, 2): val = _compare(a[i], b[i]) if val != 0: return val return 0
val = _compare(a[i], b[i])
val = _compare_flat(a[i], b[i])
def compare(a, b): """Compare a with b according to Debian versioning criteria""" a = parse(normalize(a)) b = parse(normalize(b)) for i in (0, 1, 2): val = _compare(a[i], b[i]) if val != 0: return val return 0
howmany = 1000
howmany = 10000
def test(): import time howmany = 1000 start = time.time() for i in xrange(howmany): compare("0-2010.10.1-d6cbb928", "0-2010.10.10-a9ee521c") end = time.time() elapsed = end - start print "%d runs in %.4f seconds (%.2f per/sec)" % (howmany, elapsed, howmany / elapsed)
packages = dict(self._list())
packages = dict(self._list(all_versions=False))
def resolve(self, unresolved): """Resolve a list of unresolved packages. If unresolved is a single unresolved package, return a single resolved package. If unresolved is a tuple or list of unresolved packages, return a list of resolved packages"""
if val != 0: return val l1 = p1.getlex() l2 = p2.getlex() val = cmp(l1, l2)
def _compare(s1, s2): if s1 == s2: return 0 p1 = VersionParser(s1) p2 = VersionParser(s2) while True: n1 = p1.getnum() n2 = p2.getnum() val = cmp(n1, n2) if val != 0: return val l1 = p1.getlex() l2 = p2.getlex() val = cmp(l1, l2) if val != 0: return val if p1.str == p2.str: return 0
i = 0 for c in s1: if c in '0123456789': break i += 1 if i: l1 = s1[:i] s1 = s1[i:] else: l1 = '' i = 0 for c in s2: if c in '0123456789': break i += 1 if i: l2 = s2[:i] s2 = s2[i:] else: l2 = '' val = cmp(l1, l2) if val != 0: return val
def _compare_flat(s1, s2): if s1 == s2: return 0 while True: # parse numeric component for comparison i = 0 for c in s1: if c not in '0123456789': break i += 1 if i: n1 = int(s1[:i]) s1 = s1[i:] else: n1 = 0 i = 0 for c in s2: if c not in '0123456789': break i += 1 if i: n2 = int(s2[:i]) s2 = s2[i:] else: n2 = 0 ...
if val != 0: return val i = 0 for c in s1: if c in '0123456789': break i += 1 if i: l1 = s1[:i] s1 = s1[i:] else: l1 = '' i = 0 for c in s2: if c in '0123456789': break i += 1 if i: l2 = s2[:i] s2 = s2[i:] else: l2 = '' val = cmp(l1, l2)
def _compare_flat(s1, s2): if s1 == s2: return 0 while True: # parse numeric component for comparison i = 0 for c in s1: if c not in '0123456789': break i += 1 if i: n1 = int(s1[:i]) s1 = s1[i:] else: n1 = 0 i = 0 for c in s2: if c not in '0123456789': break i += 1 if i: n2 = int(s2[:i]) s2 = s2[i:] else: n2 = 0 ...
if not packages and not input:
if not args[1:] and not input:
def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'i:sqt', ['input=', 'strict', 'quiet', 'tree']) except getopt.GetoptError, e: usage(e) if not args: usage() outputdir = args[0] packages = args[1:] input = None opt_strict = False opt_quiet = False opt_tree = False for opt, val in opts: if opt in ('-i', '--i...
packages.sort(reverse=True)
def _cmp(a, b): val = cmp(b[0], a[0]) if val != 0: return val return debversion.compare(a[1], b[1]) packages.sort(cmp=_cmp, reverse=True)
def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'an', ['all-versions', 'name-only']) except getopt.GetoptError, e: usage(e) opt_all_versions = False opt_name_only = False for opt, val in opts: if opt in ('-a', '--all-versions'): opt_all_versions = True elif opt in ('-n', '--name-only'): opt_name_only = True...
paths = self.Paths(path)
paths = cls.Paths(path)
def create(cls, path, link): mkdir(path) paths = self.Paths(path) os.symlink(realpath(link), paths.link)
if self.branch: relative_path = make_relative(self.paths.checkout, dir) else: relative_path = make_relative(self.link, dir)
relative_path = make_relative(self.workdir, dir)
def _sync_update_source_versions(self, dir): """update versions for a particular source package at <dir>""" packages = deb_get_packages(dir) versions = verseek.list(dir)
self.head = Git(self.workdir).rev_parse("HEAD")
self.head = Git(self.paths.checkout).rev_parse("HEAD")
def sync(self): """sync stock by updating source versions and importing binaries into the cache"""
for subpool in subpools:
for subpool in self.subpools:
def print_info(self): if len(self.stocks): print "# stocks" for stock in self.stocks: addr = stock.link if stock.branch: addr += "#" + stock.branch print addr
checkout_path = stock.paths.checkout if exists(join(checkout_path, "arena.internals")): command = "cd %s && sumo-close" % commands.mkarg(checkout_path) error = os.system(command) if error: raise Error("failed command: " + command) shutil.rmtree(stock.paths.path)
def unregister(self, stock): dir, branch = self._parse_stock(stock) stock_name = basename(dir) if branch: stock_name += "#" + branch matches = [ stock for stock in self.stocks.values() if stock.link == dir and (not branch or stock.branch == branch) ] if not matches: raise Error("no matches for unregister")
if stock.name in self.subpools:
if isinstance(stock, StockPool):
def unregister(self, stock): dir, branch = self._parse_stock(stock) stock_name = basename(dir) if branch: stock_name += "#" + branch matches = [ stock for stock in self.stocks.values() if stock.link == dir and (not branch or stock.branch == branch) ] if not matches: raise Error("no matches for unregister")
for name, version in self.pkgcache.list(): packages.add((name, version)) else: newest = {} for name, version in self.pkgcache.list(): if not newest.has_key(name) or newest[name] < version: newest[name] = version for name, version in newest.items(): packages.add((name, version)) return list(packages)
return list(packages) newest = {} for name, version in packages: if not newest.has_key(name) or newest[name] < version: newest[name] = version return newest.items()
def list(self, all_versions=False): """List packages in pool -> list of (name, version) tuples.
commit = orig.rev_parse(self.branch) if not commit: raise Error("no such branch `%s' at %s" % (self.branch, self.link)) checkout.update_ref("refs/heads/" + self.branch, commit)
def dup_branch(branch): commit = orig.rev_parse(branch) if not commit: raise Error("no such branch `%s' at %s" % (branch, self.link)) checkout.update_ref("refs/heads/" + branch, commit) dup_branch(self.branch)
def _get_workdir(self): """Return an initialized workdir path.
return self._getoutput("git-rev-parse", rev + "^0")
return self._getoutput("git-rev-parse", rev)
def rev_parse(self, rev): """git-rev-parse <rev>. Returns object-id of parsed rev. Returns None on failure. """ try: return self._getoutput("git-rev-parse", rev + "^0") except self.Error: return None
for possibleport in configuration['ports']: try: servicelogger.log("[INFO]: Trying to wait") shimstack.waitforconn(unique_id, possibleport, nmconnectionmanager.connection_handler) except Exception, e: servicelogger.log("[ERROR]: when calling waitforconn for the connection_handler: " + str(e)) servicelogger.log_last_ex...
if not private_key_string: raise TypeError("private_key_string must be provided if api_key is not") if not isinstance(private_key_string, basestring): raise TypeError("private_key_string must be a string") if not isinstance(xmlrpc_url, basestring): raise TypeError("xmlrpc_url must be a string") if not isinstance(allow...
def start_accepter(): shimstack = ShimStackInterface('(RSAShim)(NatDeciderShim)') unique_id = rsa_publickey_to_string(configuration['publickey']) unique_id = sha_hexhash(unique_id) + str(configuration['service_vessel']) # do this until we get the accepter started... while True: if is_accepter_started(): # we're don...
servicelogger.log("[ERROR]: cannot find a port for waitforconn.") time.sleep(configuration['pollfrequency']) def is_worker_thread_started(): for thread in threading.enumerate(): if 'WorkerThread' in str(thread): return True else: return False def start_worker_thread(sleeptime): if not is_worker_thread_sta...
raise InternalError(fault.faultString) def _do_pwauth_call(self, function, password, *args): """For use by calls that require a password rather than an api key.""" pwauth = {'username':self.auth['username'], 'password':password}
def start_accepter(): shimstack = ShimStackInterface('(RSAShim)(NatDeciderShim)') unique_id = rsa_publickey_to_string(configuration['publickey']) unique_id = sha_hexhash(unique_id) + str(configuration['service_vessel']) # do this until we get the accepter started... while True: if is_accepter_started(): # we're don...
myip = emulcomm.getmyip() except Exception, e: if len(e.args) >= 1 and e.args[0] == "Cannot detect a connection to the Internet.": pass
return function(pwauth, *args) except socket.error, err: raise CommunicationError("XMLRPC failed: " + str(err)) except xmlrpclib.Fault, fault: if fault.faultCode == FAULTCODE_AUTHERROR: raise AuthenticationError elif fault.faultCode == FAULTCODE_INVALIDREQUEST: raise InvalidRequestError(fault.faultString) elif fault.fa...
def main(): global configuration if not FOREGROUND: # Background ourselves. daemon.daemonize() # ensure that only one instance is running at a time... gotlock = runonce.getprocesslock("seattlenodemanager") if gotlock == True: # I got the lock. All is well... pass else: if gotlock: servicelogger.log("[ERROR]:Anothe...
raise else: break time.sleep(0.1) vesseldict = nmrequesthandler.initialize(myip, configuration['publickey'], version) myname = start_accepter() servicelogger.log('myname = '+str(myname)) start_worker_thread(configuration['pollfrequency']) start_advert_thread(vesseldict, myname, configuration['publickey']) s...
raise InternalError(fault.faultString) def acquire_lan_resources(self, count): """ <Purpose> Acquire LAN vessels. <Arguments> count The number of vessels to acquire. <Exceptions> The common exceptions described in the module comments, as well as: SeattleGENINotEnoughCredits If the account does not have enough availa...
def main(): global configuration if not FOREGROUND: # Background ourselves. daemon.daemonize() # ensure that only one instance is running at a time... gotlock = runonce.getprocesslock("seattlenodemanager") if gotlock == True: # I got the lock. All is well... pass else: if gotlock: servicelogger.log("[ERROR]:Anothe...
main() except Exception,e: servicelogger.log_last_exception() harshexit.harshexit(15)
import M2Crypto except ImportError, err: raise ImportError("In order to use the SeattleGENI XMLRPC client with " + "allow_ssl_insecure=False, you need M2Crypto " + "installed. " + str(err)) class M2CryptoSSLTransport(M2Crypto.m2xmlrpclib.SSL_Transport): def request(self, host, handler, request_body, verbose=0): if h...
def main(): global configuration if not FOREGROUND: # Background ourselves. daemon.daemonize() # ensure that only one instance is running at a time... gotlock = runonce.getprocesslock("seattlenodemanager") if gotlock == True: # I got the lock. All is well... pass else: if gotlock: servicelogger.log("[ERROR]:Anothe...
def drvterm(t,p,q,l,m): dv=t.betx**(p/2.)*t.bety**(q/2.) dv*=exp(+2j*pi*((p-2*l)*t.mux+(q-2*m)*t.muy))
def drvterm(t,p=0,q=0,l=0,m=0): dv=t.betx**(abs(p)/2.)*t.bety**(abs(q)/2.) dv*=_n.exp(+2j*pi*((p-2*l)*t.mux+(q-2*m)*t.muy))
def drvterm(t,p,q,l,m): dv=t.betx**(p/2.)*t.bety**(q/2.) dv*=exp(+2j*pi*((p-2*l)*t.mux+(q-2*m)*t.muy)) return dv
s=self.xaxis
s=self.ont.s
def _lattice(self,names,color,lbl):
prenoms=[unicode(x.strip(),"utf-8") for x in open("prenoms.txt")]
prenoms=[unicode(x.strip(),"utf-8").capitalize() for x in open("prenoms.txt")]
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self)
p1,p2=self.combis.pop() while frozenset((p1,p2)) in self.ballots.ballots.keys(): try: p1,p2=self.combis.pop() except IndexError:
p1,p2=None,None while p1 is None or frozenset((p1,p2)) in self.ballots.ballots.keys(): if not self.combis:
def update(self): p1,p2=self.combis.pop() while frozenset((p1,p2)) in self.ballots.ballots.keys(): try: p1,p2=self.combis.pop() except IndexError: print "Thanks, you are done!" QtGui.QApplication.instance().quit() sys.exit(0) self.ui.prenom1.setText(p1) self.ui.prenom2.setText(p2)
QtGui.QApplication.instance().quit()
def update(self): p1,p2=self.combis.pop() while frozenset((p1,p2)) in self.ballots.ballots.keys(): try: p1,p2=self.combis.pop() except IndexError: print "Thanks, you are done!" QtGui.QApplication.instance().quit() sys.exit(0) self.ui.prenom1.setText(p1) self.ui.prenom2.setText(p2)
old_sep,old_count=self.ballots[self.get_couple(ballot)]
d1,d2,old_sep,old_count=self.ballots[self.get_couple(ballot)]
def add(self,ballot): winner,sep,other,count=ballot winner=winner.capitalize() other=other.capitalize() if not self.is_in(ballot): self.ballots[self.get_couple(ballot)]=(winner,sep,other,count) else: old_sep,old_count=self.ballots[self.get_couple(ballot)] assert(old_sep==sep) self.ballots[self.get_couple(ballot)]=(winn...
return repr(count)+":"+winner+sep+other
return unicode(repr(count))+u":"+winner+sep+other
def ballot_repr(self,ballot): winner,sep,other,count=ballot return repr(count)+":"+winner+sep+other
f.write((self.ballot_repr(ballot)+"\n").encode("utf-8"))
f.write((self.ballot_repr(ballot)+u"\n").encode("utf-8"))
def save(self): with open(self.filename,"w") as f: for ballot in self.ballots.values(): f.write((self.ballot_repr(ballot)+"\n").encode("utf-8"))
b=(unicode(self.ui.prenom1.text()),"=",unicode(self.ui.prenom2.text()),1)
b=(unicode(self.ui.prenom1.text()),u"=",unicode(self.ui.prenom2.text()),1)
def count_ballot_and_update(self,win): if win == 0: b=(unicode(self.ui.prenom1.text()),"=",unicode(self.ui.prenom2.text()),1) elif win==1: b=(unicode(self.ui.prenom1.text()),">",unicode(self.ui.prenom2.text()),1) elif win==2: b=(unicode(self.ui.prenom2.text()),">",unicode(self.ui.prenom1.text()),1) self.ballots.add(b) ...
b=(unicode(self.ui.prenom1.text()),">",unicode(self.ui.prenom2.text()),1)
b=(unicode(self.ui.prenom1.text()),u">",unicode(self.ui.prenom2.text()),1)
def count_ballot_and_update(self,win): if win == 0: b=(unicode(self.ui.prenom1.text()),"=",unicode(self.ui.prenom2.text()),1) elif win==1: b=(unicode(self.ui.prenom1.text()),">",unicode(self.ui.prenom2.text()),1) elif win==2: b=(unicode(self.ui.prenom2.text()),">",unicode(self.ui.prenom1.text()),1) self.ballots.add(b) ...
b=(unicode(self.ui.prenom2.text()),">",unicode(self.ui.prenom1.text()),1)
b=(unicode(self.ui.prenom2.text()),u">",unicode(self.ui.prenom1.text()),1)
def count_ballot_and_update(self,win): if win == 0: b=(unicode(self.ui.prenom1.text()),"=",unicode(self.ui.prenom2.text()),1) elif win==1: b=(unicode(self.ui.prenom1.text()),">",unicode(self.ui.prenom2.text()),1) elif win==2: b=(unicode(self.ui.prenom2.text()),">",unicode(self.ui.prenom1.text()),1) self.ballots.add(b) ...
base.__name__,
base.__plain_name__,
def __new__(meta_class, class_name, bases, class_dict, **kw_arguments): """ Create a new type object, for example through a 'class' statement. Behaves like a class method and is called before __init__(). """ if kw_arguments: # Assigning values to the parameters means specializing the # template. Therefore, derive a su...
@param[in] stats The @c pstats.Stats compatible object whose data is to be represented as the new CallGraph.
@param stats The @c pstats.Stats compatible object whose data is to be represented as the new CallGraph.
def __init__(self, stats): """ Constructs a CallGraph from the given @p stats object. @param[in] stats The @c pstats.Stats compatible object whose data is to be represented as the new CallGraph. """ # Function -> ( Outgoing Calls, Incoming Calls ) self.__functions = {} # Call -> ( Calling Function, Called Functi...
def __bool__(self): """ Test whether the element is non-zero: return @c True if, and only if, it is non-zero. Otherwise return @c False. Implicit conversions to boolean (truth) values use this method, for example when @c x is an element of a Field: @code if x: do_something() @endcode @exception NotImplementedError if...
def __bool__(self): """ Test whether the element is non-zero: return @c True if, and only if, it is non-zero. Otherwise return @c False. Implicit conversions to boolean (truth) values use this method, for example when @c x is an element of a Field: @code if x: do_something() @endcode @exception NotImplementedError if...
method, for example:
method; for example:
def __neq__(self, other): """ Test whether another element @p other is different from @p self; return @c True if that is the case. The infix operator @c != calls this method, for example: @code if self != other: do_something() @endcode """ return not self.__eq__( other )
calls this method if @p self is the minuend (left element), for example:
calls this method if @p self is the minuend (left element); for example:
def __sub__(self, other): """ Return the difference of @p self and @p other. The infix operator @c - calls this method if @p self is the minuend (left element), for example: @code result = self - other @endcode """ return self.__add__( -other )
calls this method if @p self is the dividend, for example:
calls this method if @p self is the dividend; for example:
def __truediv__(self, other): """ Return the quotient of @p self and @p other. The infix operator @c / calls this method if @p self is the dividend, for example: @code result = self / other @endcode @exception ZeroDivisionError if @p other is zero. @exception TypeError if @p other lacks the multiplicative...
print( "platform: {0}".format( platform.platform() ), file = timing_file ) print( "python: {0}".format( platform.python_version() ), file = timing_file ) print( "wall time (s): {0}".format( wall_time ), file = timing_file ) print( "user time (s): {0}".format( user_time ), file = timing_file ) print( "sys time (s): {0}"...
info = [ "node: {0}".format( platform.node() ), "platform: {0}".format( platform.platform() ), "python: {0}".format( platform.python_version() ), "date (Y/M/D h:m:s): {0}".format( datetime.now().strftime("%Y/%m/%d %H:%M:%S") ), "wall time (s): {0}".format( wall_time ), "user time (s): {0}".format( user_time ), "sys tim...
def dump_data(self, extra_information = {}): if self.is_running(): self.stop() # Yes, this is a race condition. self.__profile_file.close() self.__profile.dump_stats( self.__profile_file.name )
print( "{0}: {1}".format( key, value ), file = timing_file )
info.append( "{0}: {1}".format( key, value ) ) print( "\n".join( info ), file=timing_file )
def dump_data(self, extra_information = {}): if self.is_running(): self.stop() # Yes, this is a race condition. self.__profile_file.close() self.__profile.dump_stats( self.__profile_file.name )
while line and not line.strip() and line.strip().startswith( "
while line and (not line.strip() or line.strip().startswith( "
def __iter__(self): # Register: increase the number of parsers with self.__lock() as data: parsers, current_offset, current_line = data self.__update( parsers + 1, current_offset, current_line ) # Iterate until the file ends line = self.__file.readline() while line: with self.__lock() as data: parsers, current_offset,...
yield current_line, tuple( line.split( self.__separator ) )
yield current_line, tuple( line.strip().split( self.__separator ) )
def __iter__(self): # Register: increase the number of parsers with self.__lock() as data: parsers, current_offset, current_line = data self.__update( parsers + 1, current_offset, current_line ) # Iterate until the file ends line = self.__file.readline() while line: with self.__lock() as data: parsers, current_offset,...
self.__input = [ ( "<stdin>", [ (0, tuple( arguments ) ) ] ) ]
self.__input = [] if arguments: self.__input.append( ( "<stdin>", [ (0, tuple( arguments ) ) ] ) )
def __init__(self, algorithm, arguments=sys.argv[1:], algorithm_version="<unknown>" ): self.__algorithm = algorithm self.__algorithm_version = algorithm_version options, arguments = self._parse_arguments( arguments, algorithm_version ) # __input is a list of pairs (<name>, <iterable>); # <iterable> is expected to retu...
modulo_primes = greedy_prime_factors(
torsion_primes = greedy_prime_factors(
def frobenius_trace(curve): """ Compute the trace of the Frobenius endomorphism for the given EllpiticCurve @p curve. This is an implementation of Schoof's original algorithm for counting the points of an elliptic curve over a finite field. @return The trace @f$ t @f$ of the Frobenius endomorphism. The number of p...
if 2 in modulo_primes:
if 2 in torsion_primes:
def frobenius_trace(curve): """ Compute the trace of the Frobenius endomorphism for the given EllpiticCurve @p curve. This is an implementation of Schoof's original algorithm for counting the points of an elliptic curve over a finite field. @return The trace @f$ t @f$ of the Frobenius endomorphism. The number of p...
modulo_primes.remove( 2 )
torsion_primes.remove( 2 )
def frobenius_trace(curve): """ Compute the trace of the Frobenius endomorphism for the given EllpiticCurve @p curve. This is an implementation of Schoof's original algorithm for counting the points of an elliptic curve over a finite field. @return The trace @f$ t @f$ of the Frobenius endomorphism. The number of p...
for prime in modulo_primes:
for prime in torsion_primes:
def frobenius_trace(curve): """ Compute the trace of the Frobenius endomorphism for the given EllpiticCurve @p curve. This is an implementation of Schoof's original algorithm for counting the points of an elliptic curve over a finite field. @return The trace @f$ t @f$ of the Frobenius endomorphism. The number of p...
if not os.path.islink(line): logging.info("creating symlink from %s to %s", reposfilepath + line, line)
if not os.path.islink(line) and accesscontrollist.hasacl(line) and not options.ignoreacl: err = "filetoversion has a 'deny' in ACL permissions (ls -lde %s: %s) \n \ This program is currently not clever enough to check if you have permission to move/delete this file. \n \ To avoid this problem remove deny permissions fr...
def makesymlinks(repospath): reposfilepath = os.path.abspath(repospath) with open(os.path.join(repospath, SYNCHER_DB_FILENAME)) as db: try: for line in db: line = line.strip() if not os.path.islink(line): logging.info("creating symlink from %s to %s", reposfilepath + line, line) if not options.dry: if os.path.exists(li...
acl = None
def makesymlinks(repospath): reposfilepath = os.path.abspath(repospath) with open(os.path.join(repospath, SYNCHER_DB_FILENAME)) as db: try: for line in db: line = line.strip() if not os.path.islink(line): logging.info("creating symlink from %s to %s", reposfilepath + line, line) if not options.dry: if os.path.exists(li...
acl = removeacl(line) util.move(line, line+".beforesyncher") if acl is not None: accesscontrollist.setacl(line, acl)
acl = accesscontrollist.removeacl(line) util.move(line, line+"-beforesyncher")
def makesymlinks(repospath): reposfilepath = os.path.abspath(repospath) with open(os.path.join(repospath, SYNCHER_DB_FILENAME)) as db: try: for line in db: line = line.strip() if not os.path.islink(line): logging.info("creating symlink from %s to %s", reposfilepath + line, line) if not options.dry: if os.path.exists(li...
if self.val.type.code == gdb.TYPE_CODE_RANGE:
if self.val['code'] == gdb.TYPE_CODE_RANGE:
def to_string(self): """Return a pretty-printed image of our main_type. """ fields = [] fields.append("name = %s" % self.val['name']) fields.append("tag_name = %s" % self.val['tag_name']) fields.append("code = %s" % self.val['code']) fields.append("flags = [%s]" % self.flags_to_string()) fields.append("owner = %s" % se...
<<<<<<< HEAD
def search(self, results, media, lang): Log("Searching") fname=Media id=media.name pageUrl="http://localhost:32400/library/metadata/" + media.id page=HTTP.Request(pageUrl) Log(media.primary_metadata) nfoXML = XML.ElementFromURL(pageUrl).xpath('//MediaContainer/Video/Media/Part')[0] path1=nfoXML.get('file') path = os.p...
======= >>>>>>> e5a5e37cb95fd2b91a757284cc694e01ea9da987
def search(self, results, media, lang): Log("Searching") fname=Media id=media.name pageUrl="http://localhost:32400/library/metadata/" + media.id page=HTTP.Request(pageUrl) Log(media.primary_metadata) nfoXML = XML.ElementFromURL(pageUrl).xpath('//MediaContainer/Video/Media/Part')[0] path1=nfoXML.get('file') path = os.p...
======= name="Nfo_" + media.name results.Append(MetadataSearchResult(id=media.id,name=name,year=3000,lang=lang,score=100)) >>>>>>> e5a5e37cb95fd2b91a757284cc694e01ea9da987
def search(self, results, media, lang): Log("Searching") fname=Media id=media.name pageUrl="http://localhost:32400/library/metadata/" + media.id page=HTTP.Request(pageUrl) Log(media.primary_metadata) nfoXML = XML.ElementFromURL(pageUrl).xpath('//MediaContainer/Video/Media/Part')[0] path1=nfoXML.get('file') path = os.p...
<<<<<<< HEAD
def scrapeNfo(self, metadata, media, lang): Log("all your datas are belong to us") Log('UPDATE: ' + media.items[0].parts[0].file) path = os.path.dirname(media.items[0].parts[0].file) id=media.title nfoFile='' Log(path) if os.path.exists(path): for f in os.listdir(path): if f.split(".")[-1].lower() == "nfo": nfoName=f.s...
======= metadata.directors.clear() try: metadata.directors.add(nfoXML.xpath("director")[0].text) except: pass >>>>>>> e5a5e37cb95fd2b91a757284cc694e01ea9da987
def scrapeNfo(self, metadata, media, lang): Log("all your datas are belong to us") Log('UPDATE: ' + media.items[0].parts[0].file) path = os.path.dirname(media.items[0].parts[0].file) id=media.title nfoFile='' Log(path) if os.path.exists(path): for f in os.listdir(path): if f.split(".")[-1].lower() == "nfo": nfoName=f.s...
======= metadata.genres.clear() Log("cleared genres") for r in genres: Log(r) metadata.genres.add(r) Log(metadata.genres) metadata.roles.clear() for actor in nfoXML.findall('./actor'): role = metadata.roles.new() try: role.role = actor.xpath("role")[0].text except: pass try: role.actor = actor.xpath("name")[0].text ex...
def grabPoster(pUrl=thumb.text, i=i): posterUrl = pUrl Log("Adding: " + pUrl) thumbpic = HTTP.Request(pUrl) metadata.posters[posterUrl] = Proxy.Preview(thumbpic, sort_order = i)
return _('''
if mem['SwapTotal'] == 0: swap_message = _("no virtual memory installed.") else: swap_message = \ _("Virtual memory: %.2f Gb total, <strong>%.0f%% free<strong>.") % \ (mem['SwapTotal'], (mem['SwapFree'] * 100.0 / mem['SwapTotal'])) return (_('''
def compute_mem(line, x): #logging.debug(line[0:-1] + " -> " + re.split('\W+', line)[1])
Virtual memory: %.2f Gb total, <strong>%.0f%% free<strong>. ''') % (s, cpus, model, mem['MemTotal'], (mem['Inactive'] + mem['Active']), mem['Cached'], mem['Buffers'], mem['SwapTotal'], (mem['SwapFree'] * 100.0 / mem['SwapTotal']) )
%s''') % (s, cpus, model, mem['MemTotal'], (mem['Inactive'] + mem['Active']), mem['Cached'], mem['Buffers'], swap_message))
def compute_mem(line, x): #logging.debug(line[0:-1] + " -> " + re.split('\W+', line)[1])
LicornMessage(data=text_message),
LicornMessage(data=text_message, channel=1),
def output(self, text_message): return current_thread().listener.process( LicornMessage(data=text_message), options.msgproc.getProxy())
self.reload()
self.reload(full=False)
def __init__(self, configuration): """ Create the user accounts list from the underlying system. """
def reload(self):
def reload(self, full=True):
def reload(self): """ Load (or reload) the data structures from the system data. """
users.reload()
def main(uri, http_user, sort = "login", order = "asc"): """ display all users in a nice HTML page. """ start = time.time() groups.reload() users.reload() # profiles.reload() u = users.users g = groups.groups p = profiles.profiles groups.Select(filters.PRIVILEGED) pri_grps = [ g[gid]['name'] for gid in groups.filter...
self.current_target_object, self.args, self.kwargs
self.current_target, self.args, self.kwargs
def dump_status(self, long_output=False, precision=None): """ get detailled thread status. """
self.current_target_object) \
self.current_target) \
def dump_status(self, long_output=False, precision=None): """ get detailled thread status. """
execute([ 'sudo', 'rm', '-rf', '%s/*' % configuration.home_backup_dir, '%s/*' % configuration.home_archive_dir ]) execute(ADD + ['group', '--system', 'acl,admins,remotessh,licorn-wmi'])
for directory in ( configuration.home_backup_dir, configuration.home_archive_dir ): clean_dir_contents(directory) execute(ADD + ['group', '--system', 'acl,admins,remotessh,licorn-wmi'])
def clean_system(): """ Remove all stuff to make the system clean, testsuite-wise.""" test_message('''cleaning system from previous runs.''') # delete them first in case of a previous failed testsuite run. # don't check exit codes or such, this will be done later. for argument in ( ['user', '''toto,tutu,tata,titi,te...
ScenarioTest([ [ 'sudo', 'rm', '-vrf', '%s/*' % configuration.home_archive_dir ],
clean_dir_contents(configuration.home_archive_dir) ScenarioTest([
def chk_acls_cmds(group, subdir=None): return [ 'sudo', 'getfacl', '-R', '%s/%s/%s%s' % ( configuration.defaults.home_base_path, configuration.groups.names['plural'], group, '/%s' % subdir if subdir else '') ]
[ 'sudo', 'getfacl', '-R', configuration.home_archive_dir ], [ 'sudo', 'rm', '-vrf', '%s/*' % configuration.home_archive_dir ]
[ 'sudo', 'getfacl', '-R', configuration.home_archive_dir ]
def chk_acls_cmds(group, subdir=None): return [ 'sudo', 'getfacl', '-R', '%s/%s/%s%s' % ( configuration.defaults.home_base_path, configuration.groups.names['plural'], group, '/%s' % subdir if subdir else '') ]
logging.warning( 'Adding a default profile on the system (this is mandatory).')
logging.warning('''Adding a default %s profile on the system ''' '''(this is mandatory).''' % styles.stylize(styles.ST_NAME, 'Users'))
def checkDefaultProfile(self): """If no profile exists on the system, create a default one with system group "users"."""
lenghts[0], lenghts[1], lenghts[2], lenghts[3], lenghts[4], lenghts[5], lenghts[6], lenghts[7]
lengths[0], lengths[1], lengths[2], lengths[3], lengths[4], lengths[5], lengths[6], lengths[7]
def run(self): logging.progress("%s: thread running." % (self.name)) Thread.run(self)
if(lenghts[7] > 0):
if(lengths[7] > 0):
def run(self): logging.progress("%s: thread running." % (self.name)) Thread.run(self)
dest = list(user['groups'].copy())
dest = list(user['groups'][:])
def edit(uri, http_user, login): """Edit an user account, based on login.""" users.reload() groups.reload() # profiles.reload() title = _('Edit account %s') % login if protected_user(login): return w.forgery_error(title) data = w.page_body_start(uri, http_user, ctxtnav, title, False) try: user = users.users[users...
count += 1
def fork_wmi(opts, start_wmi = True): """ Start the Web Management Interface (fork it). """ # FIXME: implement start_wmi in argparser module. try: if os.fork() == 0: # FIXME: drop_privileges() → become setuid('licorn:licorn') process.write_pid_file(wpid_path) if opts.daemon: process.use_log_file(wlog_path) pname =...
logging.warning("%s/wmi: socket already in use. waiting (total: %dsec)." % (dname, count))
logging.warning("%s/wmi: socket already in use. waiting (total: %ds)." % (dname, count)) count += 1
def fork_wmi(opts, start_wmi = True): """ Start the Web Management Interface (fork it). """ # FIXME: implement start_wmi in argparser module. try: if os.fork() == 0: # FIXME: drop_privileges() → become setuid('licorn:licorn') process.write_pid_file(wpid_path) if opts.daemon: process.use_log_file(wlog_path) pname =...
def check_dirs_and_contents_perms_and_acls_new(dirs_infos, batch=None,
def check_dirs_and_contents_perms_and_acls_new(dirs_infos, batch=False,
def check_dirs_and_contents_perms_and_acls_new(dirs_infos, batch=None, auto_answer=None): """ general function to check file/dir """ def check_one_dir_and_acl(dir_info, batch=batch, auto_answer=auto_answer): all_went_ok = True # save desired user and group owner of the file/dir try: if dir_info.user: uid = dir_info['us...
if daemon.cmdlistener.role == licornd_roles.SERVER:
if LMC.configuration.licornd.role == licornd_roles.SERVER:
def acceptHost(self, daemon, connection): """ Very basic check for the connection. """ client_addr, client_socket = connection.addr
logging.warning('''%s: socket already in use. ''' '''waiting (total: %ds).''' % (self.name, count))
logging.warning('''%s: %s. ''' '''waiting (total: %ds).''' % (self.name, e, count))
def run(self): assert ltrace('thread', '%s running' % self.name)
self.pyro_daemon.shutdown(True)
def run(self): assert ltrace('thread', '%s running' % self.name)
return (strip_moving_data(output), retcode)
def RunCommand(self, cmdnum, batch=False):
ScenarioTest(commands, descr="integrated help").Run()
ScenarioTest(commands, descr='''test integrated help of all CLI commands''' ).Run()
def test_integrated_help(): """Test extensively argmarser contents and intergated help.""" commands = [] for program in (GET, ADD, MOD, DEL, CHK): commands.extend([ program + ['-h'], program + ['--help']]) if program == ADD: modes = [ 'user', 'users', 'group', 'profile' ] elif program == MOD: modes = [ 'configurati...