text
stringlengths
81
112k
Set up logging via :func:`logging.config.fileConfig`. Defaults are specified for the special ``__file__`` and ``here`` variables, similar to PasteDeploy config loading. Extra defaults can optionally be specified as a dict in ``defaults``. :param defaults: The defaults that will be used...
Checks a name and determines whether to use the default name. :param name: The current name to check. :return: Either None or a :class:`str` representing the name. def _maybe_get_default_name(self, name): """Checks a name and determines whether to use the default name. :param name: Th...
Set cursor position on the color corresponding to the hue value. def set(self, hue): """Set cursor position on the color corresponding to the hue value.""" x = hue / 360. * self.winfo_width() self.coords('cursor', x, 0, x, self.winfo_height()) self._variable.set(hue)
Create an L{IService} for the database specified by the given configuration. def makeService(cls, options): """ Create an L{IService} for the database specified by the given configuration. """ from axiom.store import Store jm = options['journal-mode'] if ...
Returns the names of everything (books, notes, graphs, etc.) in the project. Args: matching (str, optional): if given, only return names with this string in it workbooks (bool): if True, return workbooks graphs (bool): if True, return workbooks Returns: A list of the names of w...
Returns the type of the page with that name. If that name doesn't exist, None is returned. Args: name (str): name of the page to get the folder from number (bool): if True, return numbers (i.e., a graph will be 3) if False, return words where appropriate (i.e, "graph") Returns:...
Prints every page in the project to the console. Args: matching (str, optional): if given, only return names with this string in it def listEverything(matching=False): """Prints every page in the project to the console. Args: matching (str, optional): if given, only return names with this...
return sheet names of a book. Args: book (str, optional): If a book is given, pull names from that book. Otherwise, try the active one Returns: list of sheet names (typical case). None if book has no sheets. False if book doesn't exlist. def sheetNames(book=None): ...
returns the pyorigin object for a sheet. def getSheet(book=None,sheet=None): """returns the pyorigin object for a sheet.""" # figure out what book to use if book and not book.lower() in [x.lower() for x in bookNames()]: print("book %s doesn't exist"%book) return if book is None: ...
Delete a sheet from a book. If either isn't given, use the active one. def sheetDelete(book=None,sheet=None): """ Delete a sheet from a book. If either isn't given, use the active one. """ if book is None: book=activeBook() if sheet in sheetNames(): PyOrigin.WorksheetPages(book).Lay...
Delete all sheets which contain no data def sheetDeleteEmpty(bookName=None): """Delete all sheets which contain no data""" if bookName is None: bookName = activeBook() if not bookName.lower() in [x.lower() for x in bookNames()]: print("can't clean up a book that doesn't exist:",bookName) ...
return the contents of a pickle file def pickle_load(fname): """return the contents of a pickle file""" assert type(fname) is str and os.path.exists(fname) print("loaded",fname) return pickle.load(open(fname,"rb"))
save something to a pickle file def pickle_save(thing,fname=None): """save something to a pickle file""" if fname is None: fname=os.path.expanduser("~")+"/%d.pkl"%time.time() assert type(fname) is str and os.path.isdir(os.path.dirname(fname)) pickle.dump(thing, open(fname,"wb"),pickle.HIGHEST_P...
Put 2d numpy data into a temporary HTML file. This is a hack, copy/pasted from an earlier version of this software. It is very messy, but works great! Good enough for me. def sheetToHTML(sheet): """ Put 2d numpy data into a temporary HTML file. This is a hack, copy/pasted from an earlier version of...
return a dict with the code for each function def getCodeBlocks(): """return a dict with the code for each function""" raw=open("examples.py").read() d={} for block in raw.split("if __name__")[0].split("\ndef "): title=block.split("\n")[0].split("(")[0] if not title.startswith("demo_"):...
return a dict with the output of each function def getOutputBlocks(): """return a dict with the output of each function""" raw=open("output.txt").read() d={} for block in raw.split("\n####### ")[1:]: title=block.split("\n")[0].split("(")[0] block=block.split("\n",1)[1].strip() d...
Turn a byte string from the command line into a unicode string. def decodeCommandLine(self, cmdline): """Turn a byte string from the command line into a unicode string. """ codec = getattr(sys.stdin, 'encoding', None) or sys.getdefaultencoding() return unicode(cmdline, codec)
Yield tokens. Args: text (str): The original text. Yields: dict: The next token. def tokenize(text): """ Yield tokens. Args: text (str): The original text. Yields: dict: The next token. """ stem = PorterStemmer().stem tokens = re.finditer('[a-z]...
Sort an ordered dictionary by value, descending. Args: d (OrderedDict): An ordered dictionary. desc (bool): If true, sort desc. Returns: OrderedDict: The sorted dictionary. def sort_dict(d, desc=True): """ Sort an ordered dictionary by value, descending. Args: d ...
Yield a sliding window over an iterable. Args: seq (iter): The sequence. n (int): The window width. Yields: tuple: The next window. def window(seq, n=2): """ Yield a sliding window over an iterable. Args: seq (iter): The sequence. n (int): The window widt...
Move the SubStore at the indicated location into the given site store's directory and then hook it up to the site store's authentication database. @type siteStore: C{Store} @type userStorePath: C{FilePath} def insertUserStore(siteStore, userStorePath): """ Move the SubStore at the indicated locati...
Move the SubStore for the given user account out of the given site store completely. Place the user store's database directory into the given destination directory. @type userAccount: C{LoginAccount} @type extractionDestination: C{FilePath} @type legacySiteAuthoritative: C{bool} @param legac...
Retrieve L{LoginMethod} items from store C{store}, optionally constraining them by protocol def getLoginMethods(store, protocol=None): """ Retrieve L{LoginMethod} items from store C{store}, optionally constraining them by protocol """ if protocol is not None: comp = OR(LoginMethod.proto...
Retrieve account name information about the given database. @param store: An Axiom Store representing a user account. It must have been opened through the store which contains its account information. @return: A generator of two-tuples of (username, domain) which refer to the given store. def ge...
Retrieve a list of all local domain names represented in the given store. def getDomainNames(store): """ Retrieve a list of all local domain names represented in the given store. """ domains = set() domains.update(store.query( LoginMethod, AND(LoginMethod.internal == True, ...
Assuming that self.avatars is a SubStore which should contain *only* the LoginAccount for the user I represent, remove all LoginAccounts and LoginMethods from that store and copy all methods from the site store down into it. def migrateDown(self): """ Assuming that self.avatars ...
Copy this LoginAccount and all associated LoginMethods from my store (which is assumed to be a SubStore, most likely a user store) into the site store which contains it. def migrateUp(self): """ Copy this LoginAccount and all associated LoginMethods from my store (which is assum...
Create a copy of this LoginAccount and all associated LoginMethods in a different Store. Return the copied LoginAccount. def cloneInto(self, newStore, avatars): """ Create a copy of this LoginAccount and all associated LoginMethods in a different Store. Return the copied LoginAccount....
Add a login method to this account, propogating up or down as necessary to site store or user store to maintain consistency. def addLoginMethod(self, localpart, domain, protocol=ANY_PROTOCOL, verified=False, internal=False): """ Add a login method to this account, propogating up or down as nece...
Set this account's password if the current password matches. @param currentPassword: The password to match against the current one. @param newPassword: The new password. @return: A deferred firing when the password has been changed. @raise BadCredentials: If the current password did no...
Create a user account, add it to this LoginBase, and return it. This method must be called within a transaction in my store. @param username: the user's name. @param domain: the domain part of the user's name [XXX TODO: this really ought to say something about whether it's a Q2Q domai...
Identify an appropriate SQL error object for the given message for the supported versions of sqlite. @return: an SQLError def identifySQLError(self, sql, args, e): """ Identify an appropriate SQL error object for the given message for the supported versions of sqlite. ...
Construct a callable to be used as a weakref callback for cache entries. The callable will invoke the provided finalizer, as well as removing the cache entry if the cache still exists and contains an entry for the given key. @type cacheRef: L{weakref.ref} to L{FinalizingCache} @param cacheRef: A ...
Add an entry to the cache. A weakref to the value is stored, rather than a direct reference. The value must have a C{__finalizer__} method that returns a callable which will be invoked when the weakref is broken. @param key: The key identifying the cache entry. @param value: T...
Remove a key from the cache. As a sanity check, if the specified key is present in the cache, it must have the given value. @param key: The key to remove. @param value: The expected value for the key. def uncache(self, key, value): """ Remove a key from the cache. ...
Get an entry from the cache by key. @raise KeyError: if the given key is not present in the cache. @raise CacheFault: (a L{KeyError} subclass) if the given key is present in the cache, but the value it points to is gone. def get(self, key): """ Get an entry from the cache ...
Parse <question> element in the UBCPI XBlock's content XML. Args: root (lxml.etree.Element): The root of the <question> node in the tree. Returns: dict, a deserialized representation of a question. E.g. { 'text': 'What is the answer to life, the universe and everything?', ...
Parse <options> element in the UBCPI XBlock's content XML. Args: root (lxml.etree.Element): The root of the <options> node in the tree. Returns: a list of deserialized representation of options. E.g. [{ 'text': 'Option 1', 'image_url': '', 'image_pos...
Parse <seeds> element in the UBCPI XBlock's content XML. Args: root (lxml.etree.Element): The root of the <seeds> node in the tree. Returns: a list of deserialized representation of seeds. E.g. [{ 'answer': 1, # option index starting from one 'rationale': 'This...
Update the UBCPI XBlock's content from an XML definition. We need to be strict about the XML we accept, to avoid setting the XBlock to an invalid state (which will then be persisted). Args: root (lxml.etree.Element): The XML definition of the XBlock's content. Returns: A dictionary of...
Serialize the options in peer instruction XBlock to xml Args: options (lxml.etree.Element): The <options> XML element. block (PeerInstructionXBlock): The XBlock with configuration to serialize. Returns: None def serialize_options(options, block): """ Serialize the options in p...
Serialize the seeds in peer instruction XBlock to xml Args: seeds (lxml.etree.Element): The <seeds> XML element. block (PeerInstructionXBlock): The XBlock with configuration to serialize. Returns: None def serialize_seeds(seeds, block): """ Serialize the seeds in peer instruct...
Serialize the Peer Instruction XBlock's content to XML. Args: block (PeerInstructionXBlock): The peer instruction block to serialize. root (etree.Element): The XML root node to update. Returns: etree.Element def serialize_to_xml(root, block): """ Serialize the Peer Instruction...
Obtains the lvm and vg_t handle. Usually you would never need to use this method unless you are doing operations using the ctypes function wrappers in conversion.py *Raises:* * HandleError def open(self): """ Obtains the lvm and vg_t handle. Usually you would never need ...
Closes the lvm and vg_t handle. Usually you would never need to use this method unless you are doing operations using the ctypes function wrappers in conversion.py *Raises:* * HandleError def close(self): """ Closes the lvm and vg_t handle. Usually you would never need t...
Returns the volume group uuid. def uuid(self): """ Returns the volume group uuid. """ self.open() uuid = lvm_vg_get_uuid(self.handle) self.close() return uuid
Returns the volume group extent count. def extent_count(self): """ Returns the volume group extent count. """ self.open() count = lvm_vg_get_extent_count(self.handle) self.close() return count
Returns the volume group free extent count. def free_extent_count(self): """ Returns the volume group free extent count. """ self.open() count = lvm_vg_get_free_extent_count(self.handle) self.close() return count
Returns the physical volume count. def pv_count(self): """ Returns the physical volume count. """ self.open() count = lvm_vg_get_pv_count(self.handle) self.close() return count
Returns the maximum allowed physical volume count. def max_pv_count(self): """ Returns the maximum allowed physical volume count. """ self.open() count = lvm_vg_get_max_pv(self.handle) self.close() return count
Returns the maximum allowed logical volume count. def max_lv_count(self): """ Returns the maximum allowed logical volume count. """ self.open() count = lvm_vg_get_max_lv(self.handle) self.close() return count
Returns True if the VG is clustered, False otherwise. def is_clustered(self): """ Returns True if the VG is clustered, False otherwise. """ self.open() clust = lvm_vg_is_clustered(self.handle) self.close() return bool(clust)
Returns True if the VG is exported, False otherwise. def is_exported(self): """ Returns True if the VG is exported, False otherwise. """ self.open() exp = lvm_vg_is_exported(self.handle) self.close() return bool(exp)
Returns True if the VG is partial, False otherwise. def is_partial(self): """ Returns True if the VG is partial, False otherwise. """ self.open() part = lvm_vg_is_partial(self.handle) self.close() return bool(part)
Returns the volume group sequence number. This number increases everytime the volume group is modified. def sequence(self): """ Returns the volume group sequence number. This number increases everytime the volume group is modified. """ self.open() seq = lvm_vg_ge...
Returns the volume group size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. def size(self, units="MiB"): """ Returns the volume group size in the given units. Default units are MiB. *Args:* ...
Returns the volume group free size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. def free_size(self, units="MiB"): """ Returns the volume group free size in the given units. Default units are MiB. ...
Returns the volume group extent size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. def extent_size(self, units="MiB"): """ Returns the volume group extent size in the given units. Default units are MiB. ...
Initializes a device as a physical volume and adds it to the volume group:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") vg.add_pv("/dev/sdbX") *Args:* * device (str): An existing device. *Raises:* * Val...
Returns the physical volume associated with the given device:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") vg.get_pv("/dev/sdb1") *Args:* * device (str): An existing device. *Raises:* * ValueError, Hand...
Removes a physical volume from the volume group:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") pv = vg.pvscan()[0] vg.remove_pv(pv) *Args:* * pv (obj): A PhysicalVolume instance. *Raises:* * ...
Probes the volume group for physical volumes and returns a list of PhysicalVolume instances:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg") pvs = vg.pvscan() *Raises:* * HandleError def pvscan(self): """ Probes...
Probes the volume group for logical volumes and returns a list of LogicalVolume instances:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg") lvs = vg.lvscan() *Raises:* * HandleError def lvscan(self): """ Probes t...
Creates a logical volume and returns the LogicalVolume instance associated with the lv_t handle:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") lv = vg.create_lv("mylv", 40, "MiB") *Args:* * name (str): The des...
Removes a logical volume from the volume group:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") lv = vg.lvscan()[0] vg.remove_lv(lv) *Args:* * lv (obj): A LogicalVolume instance. *Raises:* * ...
Removes all logical volumes from the volume group. *Raises:* * HandleError, CommitError def remove_all_lvs(self): """ Removes all logical volumes from the volume group. *Raises:* * HandleError, CommitError """ lvs = self.lvscan() ...
Sets the volume group extent size in the given units:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") vg.set_extent_size(2, "MiB") *Args:* * length (int): The desired length size. * units (str): The desired units...
Set the value for a pair of terms. Args: term1 (str) term2 (str) value (mixed) def set_pair(self, term1, term2, value, **kwargs): """ Set the value for a pair of terms. Args: term1 (str) term2 (str) value (mixed)...
Get the value for a pair of terms. Args: term1 (str) term2 (str) Returns: The stored value. def get_pair(self, term1, term2): """ Get the value for a pair of terms. Args: term1 (str) term2 (str) Returns: ...
Index all term pair distances. Args: text (Text): The source text. terms (list): Terms to index. def index(self, text, terms=None, **kwargs): """ Index all term pair distances. Args: text (Text): The source text. terms (list): Terms to ...
Get distances between an anchor term and all other terms. Args: anchor (str): The anchor term. Returns: OrderedDict: The distances, in descending order. def anchored_pairs(self, anchor): """ Get distances between an anchor term and all other terms. Ar...
Return the nearest xterm 256 color code from rgb input. def from_rgb(r, g=None, b=None): """ Return the nearest xterm 256 color code from rgb input. """ c = r if isinstance(r, list) else [r, g, b] best = {} for index, item in enumerate(colors): d = __distance(item, c) if(not be...
Parse command line arguments and run utilities. def entry(): """Parse command line arguments and run utilities.""" parser = argparse.ArgumentParser() parser.add_argument( 'action', help='Action to take', choices=['from_hex', 'to_rgb', 'to_hex'], ) parser.add_argument( 'value...
Return the SoftwareVersion object from store corresponding to the version object, creating it if it doesn't already exist. def makeSoftwareVersion(store, version, systemVersion): """ Return the SoftwareVersion object from store corresponding to the version object, creating it if it doesn't already exis...
List the software package version history of store. def listVersionHistory(store): """ List the software package version history of store. """ q = store.query(SystemVersion, sort=SystemVersion.creation.descending) return [sv.longWindedRepr() for sv in q]
Check if the current version is different from the previously recorded version. If it is, or if there is no previously recorded version, create a version matching the current config. def checkSystemVersion(s, versions=None): """ Check if the current version is different from the previously recorded ...
Convert the version data in this item to a L{twisted.python.versions.Version}. def asVersion(self): """ Convert the version data in this item to a L{twisted.python.versions.Version}. """ return versions.Version(self.package, self.major, self.minor, self.micro)
clears all columns def reset(self): """clears all columns""" self.colNames,self.colDesc,self.colUnits,self.colComments,\ self.colTypes,self.colData=[],[],[],[],[],[]
column types: 0: Y 1: Disregard 2: Y Error 3: X 4: Label 5: Z 6: X Error def colAdd(self,name="",desc="",unit="",comment="",coltype=0,data=[],pos=None): """ column types: 0: Y 1: Disregard ...
delete a column at a single index. Negative numbers count from the end. def colDelete(self,colI=-1): """delete a column at a single index. Negative numbers count from the end.""" # print("DELETING COLUMN: [%d] %s"%(colI,self.colDesc[colI])) self.colNames.pop(colI) self.colDesc.pop(colI) ...
delete all X columns except the first one. def onex(self): """ delete all X columns except the first one. """ xCols=[i for i in range(self.nCols) if self.colTypes[i]==3] if len(xCols)>1: for colI in xCols[1:][::-1]: self.colDelete(colI)
aligns XY pairs (or XYYY etc) by X value. def alignXY(self): """aligns XY pairs (or XYYY etc) by X value.""" # figure out what data we have and will align to xVals=[] xCols=[x for x in range(self.nCols) if self.colTypes[x]==3] yCols=[x for x in range(self.nCols) if self.colType...
Slightly changes value of every cell in the worksheet. Used for testing. def wiggle(self,noiseLevel=.1): """Slightly changes value of every cell in the worksheet. Used for testing.""" noise=(np.random.rand(*self.data.shape))-.5 self.data=self.data+noise*noiseLevel
pull data into this OR.SHEET from a real book/sheet in Origin def pull(self,bookName=None,sheetName=None): """pull data into this OR.SHEET from a real book/sheet in Origin""" # tons of validation if bookName is None and self.bookName: bookName=self.bookName if sheetName is None and sel...
pull this OR.SHEET into a real book/sheet in Origin def push(self,bookName=None,sheetName=None,overwrite=False): """pull this OR.SHEET into a real book/sheet in Origin""" # tons of validation if bookName: self.bookName=bookName if sheetName: self.sheetName=sheetName if not self....
returns maximum number of rows based on the longest colData def nRows(self): """returns maximum number of rows based on the longest colData""" if self.nCols: return max([len(x) for x in self.colData]) else: return 0
return all of colData as a 2D numpy array. def data(self): """return all of colData as a 2D numpy array.""" data=np.empty((self.nRows,self.nCols),dtype=np.float) data[:]=np.nan # make everything nan by default for colNum,colData in enumerate(self.colData): validIs=np.where([...
Given a 2D numpy array, fill colData with it. def data(self,data): """Given a 2D numpy array, fill colData with it.""" assert type(data) is np.ndarray assert data.shape[1] == self.nCols for i in range(self.nCols): self.colData[i]=data[:,i].tolist()
Change style on focus out events. def focusout(self, event): """Change style on focus out events.""" bc = self.style.lookup("TEntry", "bordercolor", ("!focus",)) dc = self.style.lookup("TEntry", "darkcolor", ("!focus",)) lc = self.style.lookup("TEntry", "lightcolor", ("!focus",)) ...
Change style on focus in events. def focusin(self, event): """Change style on focus in events.""" self.old_value = self.get() bc = self.style.lookup("TEntry", "bordercolor", ("focus",)) dc = self.style.lookup("TEntry", "darkcolor", ("focus",)) lc = self.style.lookup("TEntry", "l...
Obtains the lvm handle. Usually you would never need to use this method unless you are trying to do operations using the ctypes function wrappers in conversion.py *Raises:* * HandleError def open(self): """ Obtains the lvm handle. Usually you would never need to use this...
Closes the lvm handle. Usually you would never need to use this method unless you are trying to do operations using the ctypes function wrappers in conversion.py *Raises:* * HandleError def close(self): """ Closes the lvm handle. Usually you would never need to use this ...
Returns an instance of VolumeGroup. The name parameter should be an existing volume group. By default, all volume groups are open in "read" mode:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg") To open a volume group with write permissions set the mode pa...
Returns a new instance of VolumeGroup with the given name and added physycal volumes (devices):: from lvm2py import * lvm = LVM() vg = lvm.create_vg("myvg", ["/dev/sdb1", "/dev/sdb2"]) *Args:* * name (str): A volume group name. * ...
Removes a volume group:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") lvm.remove_vg(vg) *Args:* * vg (obj): A VolumeGroup instance. *Raises:* * HandleError, CommitError .. note:: ...
Probes the system for volume groups and returns a list of VolumeGroup instances:: from lvm2py import * lvm = LVM() vgs = lvm.vgscan() *Raises:* * HandleError def vgscan(self): """ Probes the system for volume groups and returns a lis...
Create a text from a file. Args: path (str): The file path. def from_file(cls, path): """ Create a text from a file. Args: path (str): The file path. """ with open(path, 'r', errors='replace') as f: return cls(f.read())
Load a set of stopwords. Args: path (str): The stopwords file path. def load_stopwords(self, path): """ Load a set of stopwords. Args: path (str): The stopwords file path. """ if path: with open(path) as f: self.sto...
Tokenize the text. def tokenize(self): """ Tokenize the text. """ self.tokens = [] self.terms = OrderedDict() # Generate tokens. for token in utils.tokenize(self.text): # Ignore stopwords. if token['unstemmed'] in self.stopwords: ...
Returns: OrderedDict: An ordered dictionary of term counts. def term_counts(self): """ Returns: OrderedDict: An ordered dictionary of term counts. """ counts = OrderedDict() for term in self.terms: counts[term] = len(self.terms[term]) ...