repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
Pylons/plaster_pastedeploy
src/plaster_pastedeploy/__init__.py
Loader.setup_logging
def setup_logging(self, defaults=None): """ 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 when passed to :func:`logging.config.fileConfig`. :return: ``None``. """ if "loggers" in self.get_sections(): defaults = self._get_defaults(defaults) fileConfig(self.uri.path, defaults, disable_existing_loggers=False) else: logging.basicConfig()
python
def setup_logging(self, defaults=None): """ 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 when passed to :func:`logging.config.fileConfig`. :return: ``None``. """ if "loggers" in self.get_sections(): defaults = self._get_defaults(defaults) fileConfig(self.uri.path, defaults, disable_existing_loggers=False) else: logging.basicConfig()
[ "def", "setup_logging", "(", "self", ",", "defaults", "=", "None", ")", ":", "if", "\"loggers\"", "in", "self", ".", "get_sections", "(", ")", ":", "defaults", "=", "self", ".", "_get_defaults", "(", "defaults", ")", "fileConfig", "(", "self", ".", "uri", ".", "path", ",", "defaults", ",", "disable_existing_loggers", "=", "False", ")", "else", ":", "logging", ".", "basicConfig", "(", ")" ]
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 when passed to :func:`logging.config.fileConfig`. :return: ``None``.
[ "Set", "up", "logging", "via", ":", "func", ":", "logging", ".", "config", ".", "fileConfig", "." ]
72a08f3fb6d11a0b039f381ade83f045668cfcb0
https://github.com/Pylons/plaster_pastedeploy/blob/72a08f3fb6d11a0b039f381ade83f045668cfcb0/src/plaster_pastedeploy/__init__.py#L208-L226
train
Pylons/plaster_pastedeploy
src/plaster_pastedeploy/__init__.py
Loader._maybe_get_default_name
def _maybe_get_default_name(self, name): """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. """ if name is None and self.uri.fragment: name = self.uri.fragment return name
python
def _maybe_get_default_name(self, name): """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. """ if name is None and self.uri.fragment: name = self.uri.fragment return name
[ "def", "_maybe_get_default_name", "(", "self", ",", "name", ")", ":", "if", "name", "is", "None", "and", "self", ".", "uri", ".", "fragment", ":", "name", "=", "self", ".", "uri", ".", "fragment", "return", "name" ]
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.
[ "Checks", "a", "name", "and", "determines", "whether", "to", "use", "the", "default", "name", "." ]
72a08f3fb6d11a0b039f381ade83f045668cfcb0
https://github.com/Pylons/plaster_pastedeploy/blob/72a08f3fb6d11a0b039f381ade83f045668cfcb0/src/plaster_pastedeploy/__init__.py#L245-L253
train
j4321/tkColorPicker
tkcolorpicker/gradientbar.py
GradientBar.set
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)
python
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)
[ "def", "set", "(", "self", ",", "hue", ")", ":", "x", "=", "hue", "/", "360.", "*", "self", ".", "winfo_width", "(", ")", "self", ".", "coords", "(", "'cursor'", ",", "x", ",", "0", ",", "x", ",", "self", ".", "winfo_height", "(", ")", ")", "self", ".", "_variable", ".", "set", "(", "hue", ")" ]
Set cursor position on the color corresponding to the hue value.
[ "Set", "cursor", "position", "on", "the", "color", "corresponding", "to", "the", "hue", "value", "." ]
ee2d583115e0c7ad7f29795763fc6b4ddc4e8c1d
https://github.com/j4321/tkColorPicker/blob/ee2d583115e0c7ad7f29795763fc6b4ddc4e8c1d/tkcolorpicker/gradientbar.py#L115-L119
train
twisted/axiom
twisted/plugins/axiom_plugins.py
AxiomaticStart.makeService
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 jm is not None: jm = jm.decode('ascii') store = Store(options['dbdir'], debug=options['debug'], journalMode=jm) service = IService(store) _CheckSystemVersion(store).setServiceParent(service) return service
python
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 jm is not None: jm = jm.decode('ascii') store = Store(options['dbdir'], debug=options['debug'], journalMode=jm) service = IService(store) _CheckSystemVersion(store).setServiceParent(service) return service
[ "def", "makeService", "(", "cls", ",", "options", ")", ":", "from", "axiom", ".", "store", "import", "Store", "jm", "=", "options", "[", "'journal-mode'", "]", "if", "jm", "is", "not", "None", ":", "jm", "=", "jm", ".", "decode", "(", "'ascii'", ")", "store", "=", "Store", "(", "options", "[", "'dbdir'", "]", ",", "debug", "=", "options", "[", "'debug'", "]", ",", "journalMode", "=", "jm", ")", "service", "=", "IService", "(", "store", ")", "_CheckSystemVersion", "(", "store", ")", ".", "setServiceParent", "(", "service", ")", "return", "service" ]
Create an L{IService} for the database specified by the given configuration.
[ "Create", "an", "L", "{", "IService", "}", "for", "the", "database", "specified", "by", "the", "given", "configuration", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/twisted/plugins/axiom_plugins.py#L49-L61
train
swharden/PyOriginTools
PyOriginTools/highlevel.py
pageNames
def pageNames(matching=False,workbooks=True,graphs=True): """ 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 what you requested """ # first collect the pages we want pages=[] if workbooks: pages.extend(PyOrigin.WorksheetPages()) if graphs: pages.extend(PyOrigin.GraphPages()) # then turn them into a list of strings pages = [x.GetName() for x in pages] # do our string matching if it's needed if matching: pages=[x for x in pages if matching in x] return pages
python
def pageNames(matching=False,workbooks=True,graphs=True): """ 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 what you requested """ # first collect the pages we want pages=[] if workbooks: pages.extend(PyOrigin.WorksheetPages()) if graphs: pages.extend(PyOrigin.GraphPages()) # then turn them into a list of strings pages = [x.GetName() for x in pages] # do our string matching if it's needed if matching: pages=[x for x in pages if matching in x] return pages
[ "def", "pageNames", "(", "matching", "=", "False", ",", "workbooks", "=", "True", ",", "graphs", "=", "True", ")", ":", "# first collect the pages we want", "pages", "=", "[", "]", "if", "workbooks", ":", "pages", ".", "extend", "(", "PyOrigin", ".", "WorksheetPages", "(", ")", ")", "if", "graphs", ":", "pages", ".", "extend", "(", "PyOrigin", ".", "GraphPages", "(", ")", ")", "# then turn them into a list of strings", "pages", "=", "[", "x", ".", "GetName", "(", ")", "for", "x", "in", "pages", "]", "# do our string matching if it's needed", "if", "matching", ":", "pages", "=", "[", "x", "for", "x", "in", "pages", "if", "matching", "in", "x", "]", "return", "pages" ]
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 what you requested
[ "Returns", "the", "names", "of", "everything", "(", "books", "notes", "graphs", "etc", ".", ")", "in", "the", "project", "." ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/highlevel.py#L24-L49
train
swharden/PyOriginTools
PyOriginTools/highlevel.py
getPageType
def getPageType(name,number=False): """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: string of the type of object the page is """ if not name in pageNames(): return None pageType=PyOrigin.Pages(name).GetType() if number: return str(pageType) if pageType==1: return "matrix" if pageType==2: return "book" if pageType==3: return "graph" if pageType==4: return "layout" if pageType==5: return "notes"
python
def getPageType(name,number=False): """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: string of the type of object the page is """ if not name in pageNames(): return None pageType=PyOrigin.Pages(name).GetType() if number: return str(pageType) if pageType==1: return "matrix" if pageType==2: return "book" if pageType==3: return "graph" if pageType==4: return "layout" if pageType==5: return "notes"
[ "def", "getPageType", "(", "name", ",", "number", "=", "False", ")", ":", "if", "not", "name", "in", "pageNames", "(", ")", ":", "return", "None", "pageType", "=", "PyOrigin", ".", "Pages", "(", "name", ")", ".", "GetType", "(", ")", "if", "number", ":", "return", "str", "(", "pageType", ")", "if", "pageType", "==", "1", ":", "return", "\"matrix\"", "if", "pageType", "==", "2", ":", "return", "\"book\"", "if", "pageType", "==", "3", ":", "return", "\"graph\"", "if", "pageType", "==", "4", ":", "return", "\"layout\"", "if", "pageType", "==", "5", ":", "return", "\"notes\"" ]
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: string of the type of object the page is
[ "Returns", "the", "type", "of", "the", "page", "with", "that", "name", ".", "If", "that", "name", "doesn", "t", "exist", "None", "is", "returned", "." ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/highlevel.py#L117-L143
train
swharden/PyOriginTools
PyOriginTools/highlevel.py
listEverything
def listEverything(matching=False): """Prints every page in the project to the console. Args: matching (str, optional): if given, only return names with this string in it """ pages=pageNames() if matching: pages=[x for x in pages if matching in x] for i,page in enumerate(pages): pages[i]="%s%s (%s)"%(pageFolder(page),page,getPageType(page)) print("\n".join(sorted(pages)))
python
def listEverything(matching=False): """Prints every page in the project to the console. Args: matching (str, optional): if given, only return names with this string in it """ pages=pageNames() if matching: pages=[x for x in pages if matching in x] for i,page in enumerate(pages): pages[i]="%s%s (%s)"%(pageFolder(page),page,getPageType(page)) print("\n".join(sorted(pages)))
[ "def", "listEverything", "(", "matching", "=", "False", ")", ":", "pages", "=", "pageNames", "(", ")", "if", "matching", ":", "pages", "=", "[", "x", "for", "x", "in", "pages", "if", "matching", "in", "x", "]", "for", "i", ",", "page", "in", "enumerate", "(", "pages", ")", ":", "pages", "[", "i", "]", "=", "\"%s%s (%s)\"", "%", "(", "pageFolder", "(", "page", ")", ",", "page", ",", "getPageType", "(", "page", ")", ")", "print", "(", "\"\\n\"", ".", "join", "(", "sorted", "(", "pages", ")", ")", ")" ]
Prints every page in the project to the console. Args: matching (str, optional): if given, only return names with this string in it
[ "Prints", "every", "page", "in", "the", "project", "to", "the", "console", "." ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/highlevel.py#L145-L157
train
swharden/PyOriginTools
PyOriginTools/highlevel.py
sheetNames
def sheetNames(book=None): """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. """ if book: if not book.lower() in [x.lower() for x in bookNames()]: return False else: book=activeBook() if not book: return False poBook=PyOrigin.WorksheetPages(book) if not len(poBook): return None return [x.GetName() for x in poBook.Layers()]
python
def sheetNames(book=None): """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. """ if book: if not book.lower() in [x.lower() for x in bookNames()]: return False else: book=activeBook() if not book: return False poBook=PyOrigin.WorksheetPages(book) if not len(poBook): return None return [x.GetName() for x in poBook.Layers()]
[ "def", "sheetNames", "(", "book", "=", "None", ")", ":", "if", "book", ":", "if", "not", "book", ".", "lower", "(", ")", "in", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "bookNames", "(", ")", "]", ":", "return", "False", "else", ":", "book", "=", "activeBook", "(", ")", "if", "not", "book", ":", "return", "False", "poBook", "=", "PyOrigin", ".", "WorksheetPages", "(", "book", ")", "if", "not", "len", "(", "poBook", ")", ":", "return", "None", "return", "[", "x", ".", "GetName", "(", ")", "for", "x", "in", "poBook", ".", "Layers", "(", ")", "]" ]
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.
[ "return", "sheet", "names", "of", "a", "book", "." ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/highlevel.py#L202-L225
train
swharden/PyOriginTools
PyOriginTools/highlevel.py
getSheet
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: book=activeBook().lower() if book is None: print("no book given or selected") return # figure out what sheet to use if sheet and not sheet.lower() in [x.lower() for x in sheetNames(book)]: print("sheet %s doesn't exist"%sheet) return if sheet is None: sheet=activeSheet().lower() if sheet is None: return("no sheet given or selected") print # by now, we know the book/sheet exists and can be found for poSheet in PyOrigin.WorksheetPages(book).Layers(): if poSheet.GetName().lower()==sheet.lower(): return poSheet return False
python
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: book=activeBook().lower() if book is None: print("no book given or selected") return # figure out what sheet to use if sheet and not sheet.lower() in [x.lower() for x in sheetNames(book)]: print("sheet %s doesn't exist"%sheet) return if sheet is None: sheet=activeSheet().lower() if sheet is None: return("no sheet given or selected") print # by now, we know the book/sheet exists and can be found for poSheet in PyOrigin.WorksheetPages(book).Layers(): if poSheet.GetName().lower()==sheet.lower(): return poSheet return False
[ "def", "getSheet", "(", "book", "=", "None", ",", "sheet", "=", "None", ")", ":", "# 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", ":", "book", "=", "activeBook", "(", ")", ".", "lower", "(", ")", "if", "book", "is", "None", ":", "print", "(", "\"no book given or selected\"", ")", "return", "# figure out what sheet to use", "if", "sheet", "and", "not", "sheet", ".", "lower", "(", ")", "in", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "sheetNames", "(", "book", ")", "]", ":", "print", "(", "\"sheet %s doesn't exist\"", "%", "sheet", ")", "return", "if", "sheet", "is", "None", ":", "sheet", "=", "activeSheet", "(", ")", ".", "lower", "(", ")", "if", "sheet", "is", "None", ":", "return", "(", "\"no sheet given or selected\"", ")", "print", "# by now, we know the book/sheet exists and can be found", "for", "poSheet", "in", "PyOrigin", ".", "WorksheetPages", "(", "book", ")", ".", "Layers", "(", ")", ":", "if", "poSheet", ".", "GetName", "(", ")", ".", "lower", "(", ")", "==", "sheet", ".", "lower", "(", ")", ":", "return", "poSheet", "return", "False" ]
returns the pyorigin object for a sheet.
[ "returns", "the", "pyorigin", "object", "for", "a", "sheet", "." ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/highlevel.py#L227-L254
train
swharden/PyOriginTools
PyOriginTools/highlevel.py
sheetDelete
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).Layers(sheetNames().index(sheet)).Destroy()
python
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).Layers(sheetNames().index(sheet)).Destroy()
[ "def", "sheetDelete", "(", "book", "=", "None", ",", "sheet", "=", "None", ")", ":", "if", "book", "is", "None", ":", "book", "=", "activeBook", "(", ")", "if", "sheet", "in", "sheetNames", "(", ")", ":", "PyOrigin", ".", "WorksheetPages", "(", "book", ")", ".", "Layers", "(", "sheetNames", "(", ")", ".", "index", "(", "sheet", ")", ")", ".", "Destroy", "(", ")" ]
Delete a sheet from a book. If either isn't given, use the active one.
[ "Delete", "a", "sheet", "from", "a", "book", ".", "If", "either", "isn", "t", "given", "use", "the", "active", "one", "." ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/highlevel.py#L260-L267
train
swharden/PyOriginTools
PyOriginTools/highlevel.py
sheetDeleteEmpty
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 poBook=PyOrigin.WorksheetPages(bookName) namesToKill=[] for i,poSheet in enumerate([poSheet for poSheet in poBook.Layers()]): poFirstCol=poSheet.Columns(0) if poFirstCol.GetLongName()=="" and poFirstCol.GetData()==[]: namesToKill.append(poSheet.GetName()) for sheetName in namesToKill: print("deleting empty sheet",sheetName) sheetDelete(bookName,sheetName)
python
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 poBook=PyOrigin.WorksheetPages(bookName) namesToKill=[] for i,poSheet in enumerate([poSheet for poSheet in poBook.Layers()]): poFirstCol=poSheet.Columns(0) if poFirstCol.GetLongName()=="" and poFirstCol.GetData()==[]: namesToKill.append(poSheet.GetName()) for sheetName in namesToKill: print("deleting empty sheet",sheetName) sheetDelete(bookName,sheetName)
[ "def", "sheetDeleteEmpty", "(", "bookName", "=", "None", ")", ":", "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", "poBook", "=", "PyOrigin", ".", "WorksheetPages", "(", "bookName", ")", "namesToKill", "=", "[", "]", "for", "i", ",", "poSheet", "in", "enumerate", "(", "[", "poSheet", "for", "poSheet", "in", "poBook", ".", "Layers", "(", ")", "]", ")", ":", "poFirstCol", "=", "poSheet", ".", "Columns", "(", "0", ")", "if", "poFirstCol", ".", "GetLongName", "(", ")", "==", "\"\"", "and", "poFirstCol", ".", "GetData", "(", ")", "==", "[", "]", ":", "namesToKill", ".", "append", "(", "poSheet", ".", "GetName", "(", ")", ")", "for", "sheetName", "in", "namesToKill", ":", "print", "(", "\"deleting empty sheet\"", ",", "sheetName", ")", "sheetDelete", "(", "bookName", ",", "sheetName", ")" ]
Delete all sheets which contain no data
[ "Delete", "all", "sheets", "which", "contain", "no", "data" ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/highlevel.py#L275-L290
train
swharden/PyOriginTools
PyOriginTools/highlevel.py
pickle_load
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"))
python
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"))
[ "def", "pickle_load", "(", "fname", ")", ":", "assert", "type", "(", "fname", ")", "is", "str", "and", "os", ".", "path", ".", "exists", "(", "fname", ")", "print", "(", "\"loaded\"", ",", "fname", ")", "return", "pickle", ".", "load", "(", "open", "(", "fname", ",", "\"rb\"", ")", ")" ]
return the contents of a pickle file
[ "return", "the", "contents", "of", "a", "pickle", "file" ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/highlevel.py#L303-L307
train
swharden/PyOriginTools
PyOriginTools/highlevel.py
pickle_save
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_PROTOCOL) print("saved",fname)
python
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_PROTOCOL) print("saved",fname)
[ "def", "pickle_save", "(", "thing", ",", "fname", "=", "None", ")", ":", "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_PROTOCOL", ")", "print", "(", "\"saved\"", ",", "fname", ")" ]
save something to a pickle file
[ "save", "something", "to", "a", "pickle", "file" ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/highlevel.py#L309-L315
train
swharden/PyOriginTools
PyOriginTools/highlevel.py
sheetToHTML
def sheetToHTML(sheet): """ 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. """ assert "SHEET" in str(type(sheet)) #data,names=None,units=None,bookName=None,sheetName=None,xCol=None #sheet=OR.SHEET() data=sheet.data names=sheet.colDesc units=sheet.colUnits bookName=sheet.bookName sheetName=sheet.sheetName def htmlListToTR(l,trClass=None,tdClass=None,td1Class=None): """ turns a list into a <tr><td>something</td></tr> call this when generating HTML tables dynamically. """ html="<tr>" for item in l: html+="<td>%s</td>"%item html+="</tr>" if trClass: html=html.replace("<tr>",'<tr class="%s">'%trClass) if td1Class: html=html.replace("<td>",'<td class="%s">'%td1Class,1) if tdClass: html=html.replace("<td>",'<td class="%s">'%tdClass) return html htmlFname = os.path.expanduser("~")+"/WKS-%s.%s.html"%(bookName,sheetName) html="""<body> <style> body { background-color: #ababab; padding:20px; } table { font-size:12px; border-spacing: 0; border-collapse: collapse; } .name {background-color:#fafac8;text-align:center;} .units {background-color:#fafac8;text-align:center;} .data0 {background-color:#FFFFFF;font-family: monospace;text-align:center;} .data1 {background-color:#FAFAFA;font-family: monospace;text-align:center;} .labelRow {background-color:#e0dfe4; text-align:right;border:1px solid #000000;} .labelCol {background-color:#e0dfe4; text-align:center;border:1px solid #000000; padding-left: 20px; padding-right: 20px;} td { border:1px solid #c0c0c0; padding:5px; font-family: Arial, Helvetica, sans-serif; } </style> <html>""" html+="<h1>FauxRigin</h1>" if bookName or sheetName: html+='<code><b>%s / %s</b></code><br><br>'%(bookName,sheetName) html+="<table>" colNames=[''] for i in range(len(units)): shortName=chr(i%26+ord('A')) if i>=26: shortName=chr(int(i/26-1)+ord('A'))+shortName label="%s(%s)"%(shortName,"X" if sheet.colTypes[i]==3 else "Y") colNames.append(label) html+=htmlListToTR(colNames,'labelCol','labelCol') html+=htmlListToTR(['Long Name']+list(names),'name',td1Class='labelRow') html+=htmlListToTR(['Units']+list(units),'units',td1Class='labelRow') cutOff=False for y in range(len(data)): html+=htmlListToTR([y+1]+list(data[y]),trClass='data%d'%(y%2),td1Class='labelRow') if y>=200: cutOff=True break html+="</table>" html=html.replace(">nan<",">--<") html=html.replace(">None<","><") if cutOff: html+="<h3>... showing only %d of %d rows ...</h3>"%(y,len(data)) html+="</body></html>" with open(htmlFname,'w') as f: f.write(html) import webbrowser webbrowser.open(htmlFname) return
python
def sheetToHTML(sheet): """ 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. """ assert "SHEET" in str(type(sheet)) #data,names=None,units=None,bookName=None,sheetName=None,xCol=None #sheet=OR.SHEET() data=sheet.data names=sheet.colDesc units=sheet.colUnits bookName=sheet.bookName sheetName=sheet.sheetName def htmlListToTR(l,trClass=None,tdClass=None,td1Class=None): """ turns a list into a <tr><td>something</td></tr> call this when generating HTML tables dynamically. """ html="<tr>" for item in l: html+="<td>%s</td>"%item html+="</tr>" if trClass: html=html.replace("<tr>",'<tr class="%s">'%trClass) if td1Class: html=html.replace("<td>",'<td class="%s">'%td1Class,1) if tdClass: html=html.replace("<td>",'<td class="%s">'%tdClass) return html htmlFname = os.path.expanduser("~")+"/WKS-%s.%s.html"%(bookName,sheetName) html="""<body> <style> body { background-color: #ababab; padding:20px; } table { font-size:12px; border-spacing: 0; border-collapse: collapse; } .name {background-color:#fafac8;text-align:center;} .units {background-color:#fafac8;text-align:center;} .data0 {background-color:#FFFFFF;font-family: monospace;text-align:center;} .data1 {background-color:#FAFAFA;font-family: monospace;text-align:center;} .labelRow {background-color:#e0dfe4; text-align:right;border:1px solid #000000;} .labelCol {background-color:#e0dfe4; text-align:center;border:1px solid #000000; padding-left: 20px; padding-right: 20px;} td { border:1px solid #c0c0c0; padding:5px; font-family: Arial, Helvetica, sans-serif; } </style> <html>""" html+="<h1>FauxRigin</h1>" if bookName or sheetName: html+='<code><b>%s / %s</b></code><br><br>'%(bookName,sheetName) html+="<table>" colNames=[''] for i in range(len(units)): shortName=chr(i%26+ord('A')) if i>=26: shortName=chr(int(i/26-1)+ord('A'))+shortName label="%s(%s)"%(shortName,"X" if sheet.colTypes[i]==3 else "Y") colNames.append(label) html+=htmlListToTR(colNames,'labelCol','labelCol') html+=htmlListToTR(['Long Name']+list(names),'name',td1Class='labelRow') html+=htmlListToTR(['Units']+list(units),'units',td1Class='labelRow') cutOff=False for y in range(len(data)): html+=htmlListToTR([y+1]+list(data[y]),trClass='data%d'%(y%2),td1Class='labelRow') if y>=200: cutOff=True break html+="</table>" html=html.replace(">nan<",">--<") html=html.replace(">None<","><") if cutOff: html+="<h3>... showing only %d of %d rows ...</h3>"%(y,len(data)) html+="</body></html>" with open(htmlFname,'w') as f: f.write(html) import webbrowser webbrowser.open(htmlFname) return
[ "def", "sheetToHTML", "(", "sheet", ")", ":", "assert", "\"SHEET\"", "in", "str", "(", "type", "(", "sheet", ")", ")", "#data,names=None,units=None,bookName=None,sheetName=None,xCol=None", "#sheet=OR.SHEET()", "data", "=", "sheet", ".", "data", "names", "=", "sheet", ".", "colDesc", "units", "=", "sheet", ".", "colUnits", "bookName", "=", "sheet", ".", "bookName", "sheetName", "=", "sheet", ".", "sheetName", "def", "htmlListToTR", "(", "l", ",", "trClass", "=", "None", ",", "tdClass", "=", "None", ",", "td1Class", "=", "None", ")", ":", "\"\"\"\n turns a list into a <tr><td>something</td></tr>\n call this when generating HTML tables dynamically.\n \"\"\"", "html", "=", "\"<tr>\"", "for", "item", "in", "l", ":", "html", "+=", "\"<td>%s</td>\"", "%", "item", "html", "+=", "\"</tr>\"", "if", "trClass", ":", "html", "=", "html", ".", "replace", "(", "\"<tr>\"", ",", "'<tr class=\"%s\">'", "%", "trClass", ")", "if", "td1Class", ":", "html", "=", "html", ".", "replace", "(", "\"<td>\"", ",", "'<td class=\"%s\">'", "%", "td1Class", ",", "1", ")", "if", "tdClass", ":", "html", "=", "html", ".", "replace", "(", "\"<td>\"", ",", "'<td class=\"%s\">'", "%", "tdClass", ")", "return", "html", "htmlFname", "=", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", "+", "\"/WKS-%s.%s.html\"", "%", "(", "bookName", ",", "sheetName", ")", "html", "=", "\"\"\"<body>\n <style>\n body {\n background-color: #ababab;\n padding:20px;\n }\n table {\n font-size:12px;\n border-spacing: 0;\n border-collapse: collapse;\n }\n .name {background-color:#fafac8;text-align:center;}\n .units {background-color:#fafac8;text-align:center;}\n .data0 {background-color:#FFFFFF;font-family: monospace;text-align:center;}\n .data1 {background-color:#FAFAFA;font-family: monospace;text-align:center;}\n .labelRow {background-color:#e0dfe4; text-align:right;border:1px solid #000000;}\n .labelCol {background-color:#e0dfe4; text-align:center;border:1px solid #000000; padding-left: 20px; padding-right: 20px;}\n td {\n border:1px solid #c0c0c0; padding:5px;\n font-family: Arial, Helvetica, sans-serif;\n }\n </style>\n <html>\"\"\"", "html", "+=", "\"<h1>FauxRigin</h1>\"", "if", "bookName", "or", "sheetName", ":", "html", "+=", "'<code><b>%s / %s</b></code><br><br>'", "%", "(", "bookName", ",", "sheetName", ")", "html", "+=", "\"<table>\"", "colNames", "=", "[", "''", "]", "for", "i", "in", "range", "(", "len", "(", "units", ")", ")", ":", "shortName", "=", "chr", "(", "i", "%", "26", "+", "ord", "(", "'A'", ")", ")", "if", "i", ">=", "26", ":", "shortName", "=", "chr", "(", "int", "(", "i", "/", "26", "-", "1", ")", "+", "ord", "(", "'A'", ")", ")", "+", "shortName", "label", "=", "\"%s(%s)\"", "%", "(", "shortName", ",", "\"X\"", "if", "sheet", ".", "colTypes", "[", "i", "]", "==", "3", "else", "\"Y\"", ")", "colNames", ".", "append", "(", "label", ")", "html", "+=", "htmlListToTR", "(", "colNames", ",", "'labelCol'", ",", "'labelCol'", ")", "html", "+=", "htmlListToTR", "(", "[", "'Long Name'", "]", "+", "list", "(", "names", ")", ",", "'name'", ",", "td1Class", "=", "'labelRow'", ")", "html", "+=", "htmlListToTR", "(", "[", "'Units'", "]", "+", "list", "(", "units", ")", ",", "'units'", ",", "td1Class", "=", "'labelRow'", ")", "cutOff", "=", "False", "for", "y", "in", "range", "(", "len", "(", "data", ")", ")", ":", "html", "+=", "htmlListToTR", "(", "[", "y", "+", "1", "]", "+", "list", "(", "data", "[", "y", "]", ")", ",", "trClass", "=", "'data%d'", "%", "(", "y", "%", "2", ")", ",", "td1Class", "=", "'labelRow'", ")", "if", "y", ">=", "200", ":", "cutOff", "=", "True", "break", "html", "+=", "\"</table>\"", "html", "=", "html", ".", "replace", "(", "\">nan<\"", ",", "\">--<\"", ")", "html", "=", "html", ".", "replace", "(", "\">None<\"", ",", "\"><\"", ")", "if", "cutOff", ":", "html", "+=", "\"<h3>... showing only %d of %d rows ...</h3>\"", "%", "(", "y", ",", "len", "(", "data", ")", ")", "html", "+=", "\"</body></html>\"", "with", "open", "(", "htmlFname", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "html", ")", "import", "webbrowser", "webbrowser", ".", "open", "(", "htmlFname", ")", "return" ]
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.
[ "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", "." ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/highlevel.py#L318-L405
train
swharden/PyOriginTools
documentation/PyOrigin-examples/convert_html.py
getCodeBlocks
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_"): continue code=[x[4:] for x in block.split("\n")[1:] if x.startswith(" ")] d[title]="\n".join(code).strip() return d
python
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_"): continue code=[x[4:] for x in block.split("\n")[1:] if x.startswith(" ")] d[title]="\n".join(code).strip() return d
[ "def", "getCodeBlocks", "(", ")", ":", "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_\"", ")", ":", "continue", "code", "=", "[", "x", "[", "4", ":", "]", "for", "x", "in", "block", ".", "split", "(", "\"\\n\"", ")", "[", "1", ":", "]", "if", "x", ".", "startswith", "(", "\" \"", ")", "]", "d", "[", "title", "]", "=", "\"\\n\"", ".", "join", "(", "code", ")", ".", "strip", "(", ")", "return", "d" ]
return a dict with the code for each function
[ "return", "a", "dict", "with", "the", "code", "for", "each", "function" ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/documentation/PyOrigin-examples/convert_html.py#L15-L25
train
swharden/PyOriginTools
documentation/PyOrigin-examples/convert_html.py
getOutputBlocks
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[title]=block.split("\nfinished in ")[0] return d
python
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[title]=block.split("\nfinished in ")[0] return d
[ "def", "getOutputBlocks", "(", ")", ":", "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", "[", "title", "]", "=", "block", ".", "split", "(", "\"\\nfinished in \"", ")", "[", "0", "]", "return", "d" ]
return a dict with the output of each function
[ "return", "a", "dict", "with", "the", "output", "of", "each", "function" ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/documentation/PyOrigin-examples/convert_html.py#L27-L35
train
twisted/axiom
axiom/scripts/axiomatic.py
AxiomaticSubCommandMixin.decodeCommandLine
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)
python
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)
[ "def", "decodeCommandLine", "(", "self", ",", "cmdline", ")", ":", "codec", "=", "getattr", "(", "sys", ".", "stdin", ",", "'encoding'", ",", "None", ")", "or", "sys", ".", "getdefaultencoding", "(", ")", "return", "unicode", "(", "cmdline", ",", "codec", ")" ]
Turn a byte string from the command line into a unicode string.
[ "Turn", "a", "byte", "string", "from", "the", "command", "line", "into", "a", "unicode", "string", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/scripts/axiomatic.py#L20-L24
train
davidmcclure/textplot
textplot/utils.py
tokenize
def tokenize(text): """ Yield tokens. Args: text (str): The original text. Yields: dict: The next token. """ stem = PorterStemmer().stem tokens = re.finditer('[a-z]+', text.lower()) for offset, match in enumerate(tokens): # Get the raw token. unstemmed = match.group(0) yield { # Emit the token. 'stemmed': stem(unstemmed), 'unstemmed': unstemmed, 'offset': offset }
python
def tokenize(text): """ Yield tokens. Args: text (str): The original text. Yields: dict: The next token. """ stem = PorterStemmer().stem tokens = re.finditer('[a-z]+', text.lower()) for offset, match in enumerate(tokens): # Get the raw token. unstemmed = match.group(0) yield { # Emit the token. 'stemmed': stem(unstemmed), 'unstemmed': unstemmed, 'offset': offset }
[ "def", "tokenize", "(", "text", ")", ":", "stem", "=", "PorterStemmer", "(", ")", ".", "stem", "tokens", "=", "re", ".", "finditer", "(", "'[a-z]+'", ",", "text", ".", "lower", "(", ")", ")", "for", "offset", ",", "match", "in", "enumerate", "(", "tokens", ")", ":", "# Get the raw token.", "unstemmed", "=", "match", ".", "group", "(", "0", ")", "yield", "{", "# Emit the token.", "'stemmed'", ":", "stem", "(", "unstemmed", ")", ",", "'unstemmed'", ":", "unstemmed", ",", "'offset'", ":", "offset", "}" ]
Yield tokens. Args: text (str): The original text. Yields: dict: The next token.
[ "Yield", "tokens", "." ]
889b949a637d99097ecec44ed4bfee53b1964dee
https://github.com/davidmcclure/textplot/blob/889b949a637d99097ecec44ed4bfee53b1964dee/textplot/utils.py#L12-L36
train
davidmcclure/textplot
textplot/utils.py
sort_dict
def sort_dict(d, desc=True): """ Sort an ordered dictionary by value, descending. Args: d (OrderedDict): An ordered dictionary. desc (bool): If true, sort desc. Returns: OrderedDict: The sorted dictionary. """ sort = sorted(d.items(), key=lambda x: x[1], reverse=desc) return OrderedDict(sort)
python
def sort_dict(d, desc=True): """ Sort an ordered dictionary by value, descending. Args: d (OrderedDict): An ordered dictionary. desc (bool): If true, sort desc. Returns: OrderedDict: The sorted dictionary. """ sort = sorted(d.items(), key=lambda x: x[1], reverse=desc) return OrderedDict(sort)
[ "def", "sort_dict", "(", "d", ",", "desc", "=", "True", ")", ":", "sort", "=", "sorted", "(", "d", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "desc", ")", "return", "OrderedDict", "(", "sort", ")" ]
Sort an ordered dictionary by value, descending. Args: d (OrderedDict): An ordered dictionary. desc (bool): If true, sort desc. Returns: OrderedDict: The sorted dictionary.
[ "Sort", "an", "ordered", "dictionary", "by", "value", "descending", "." ]
889b949a637d99097ecec44ed4bfee53b1964dee
https://github.com/davidmcclure/textplot/blob/889b949a637d99097ecec44ed4bfee53b1964dee/textplot/utils.py#L39-L53
train
davidmcclure/textplot
textplot/utils.py
window
def window(seq, n=2): """ Yield a sliding window over an iterable. Args: seq (iter): The sequence. n (int): The window width. Yields: tuple: The next window. """ it = iter(seq) result = tuple(islice(it, n)) if len(result) == n: yield result for token in it: result = result[1:] + (token,) yield result
python
def window(seq, n=2): """ Yield a sliding window over an iterable. Args: seq (iter): The sequence. n (int): The window width. Yields: tuple: The next window. """ it = iter(seq) result = tuple(islice(it, n)) if len(result) == n: yield result for token in it: result = result[1:] + (token,) yield result
[ "def", "window", "(", "seq", ",", "n", "=", "2", ")", ":", "it", "=", "iter", "(", "seq", ")", "result", "=", "tuple", "(", "islice", "(", "it", ",", "n", ")", ")", "if", "len", "(", "result", ")", "==", "n", ":", "yield", "result", "for", "token", "in", "it", ":", "result", "=", "result", "[", "1", ":", "]", "+", "(", "token", ",", ")", "yield", "result" ]
Yield a sliding window over an iterable. Args: seq (iter): The sequence. n (int): The window width. Yields: tuple: The next window.
[ "Yield", "a", "sliding", "window", "over", "an", "iterable", "." ]
889b949a637d99097ecec44ed4bfee53b1964dee
https://github.com/davidmcclure/textplot/blob/889b949a637d99097ecec44ed4bfee53b1964dee/textplot/utils.py#L56-L77
train
twisted/axiom
axiom/userbase.py
insertUserStore
def insertUserStore(siteStore, userStorePath): """ 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} """ # The following may, but does not need to be in a transaction, because it # is merely an attempt to guess a reasonable filesystem name to use for # this avatar. The user store being operated on is expected to be used # exclusively by this process. ls = siteStore.findUnique(LoginSystem) unattachedSubStore = Store(userStorePath) for lm in unattachedSubStore.query(LoginMethod, LoginMethod.account == unattachedSubStore.findUnique(LoginAccount), sort=LoginMethod.internal.descending): if ls.accountByAddress(lm.localpart, lm.domain) is None: localpart, domain = lm.localpart, lm.domain break else: raise AllNamesConflict() unattachedSubStore.close() insertLocation = siteStore.newFilePath('account', domain, localpart + '.axiom') insertParentLoc = insertLocation.parent() if not insertParentLoc.exists(): insertParentLoc.makedirs() if insertLocation.exists(): raise DatabaseDirectoryConflict() userStorePath.moveTo(insertLocation) ss = SubStore(store=siteStore, storepath=insertLocation) attachedStore = ss.open() # migrateUp() manages its own transactions because it interacts with two # different stores. attachedStore.findUnique(LoginAccount).migrateUp()
python
def insertUserStore(siteStore, userStorePath): """ 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} """ # The following may, but does not need to be in a transaction, because it # is merely an attempt to guess a reasonable filesystem name to use for # this avatar. The user store being operated on is expected to be used # exclusively by this process. ls = siteStore.findUnique(LoginSystem) unattachedSubStore = Store(userStorePath) for lm in unattachedSubStore.query(LoginMethod, LoginMethod.account == unattachedSubStore.findUnique(LoginAccount), sort=LoginMethod.internal.descending): if ls.accountByAddress(lm.localpart, lm.domain) is None: localpart, domain = lm.localpart, lm.domain break else: raise AllNamesConflict() unattachedSubStore.close() insertLocation = siteStore.newFilePath('account', domain, localpart + '.axiom') insertParentLoc = insertLocation.parent() if not insertParentLoc.exists(): insertParentLoc.makedirs() if insertLocation.exists(): raise DatabaseDirectoryConflict() userStorePath.moveTo(insertLocation) ss = SubStore(store=siteStore, storepath=insertLocation) attachedStore = ss.open() # migrateUp() manages its own transactions because it interacts with two # different stores. attachedStore.findUnique(LoginAccount).migrateUp()
[ "def", "insertUserStore", "(", "siteStore", ",", "userStorePath", ")", ":", "# The following may, but does not need to be in a transaction, because it", "# is merely an attempt to guess a reasonable filesystem name to use for", "# this avatar. The user store being operated on is expected to be used", "# exclusively by this process.", "ls", "=", "siteStore", ".", "findUnique", "(", "LoginSystem", ")", "unattachedSubStore", "=", "Store", "(", "userStorePath", ")", "for", "lm", "in", "unattachedSubStore", ".", "query", "(", "LoginMethod", ",", "LoginMethod", ".", "account", "==", "unattachedSubStore", ".", "findUnique", "(", "LoginAccount", ")", ",", "sort", "=", "LoginMethod", ".", "internal", ".", "descending", ")", ":", "if", "ls", ".", "accountByAddress", "(", "lm", ".", "localpart", ",", "lm", ".", "domain", ")", "is", "None", ":", "localpart", ",", "domain", "=", "lm", ".", "localpart", ",", "lm", ".", "domain", "break", "else", ":", "raise", "AllNamesConflict", "(", ")", "unattachedSubStore", ".", "close", "(", ")", "insertLocation", "=", "siteStore", ".", "newFilePath", "(", "'account'", ",", "domain", ",", "localpart", "+", "'.axiom'", ")", "insertParentLoc", "=", "insertLocation", ".", "parent", "(", ")", "if", "not", "insertParentLoc", ".", "exists", "(", ")", ":", "insertParentLoc", ".", "makedirs", "(", ")", "if", "insertLocation", ".", "exists", "(", ")", ":", "raise", "DatabaseDirectoryConflict", "(", ")", "userStorePath", ".", "moveTo", "(", "insertLocation", ")", "ss", "=", "SubStore", "(", "store", "=", "siteStore", ",", "storepath", "=", "insertLocation", ")", "attachedStore", "=", "ss", ".", "open", "(", ")", "# migrateUp() manages its own transactions because it interacts with two", "# different stores.", "attachedStore", ".", "findUnique", "(", "LoginAccount", ")", ".", "migrateUp", "(", ")" ]
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}
[ "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", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/userbase.py#L306-L342
train
twisted/axiom
axiom/userbase.py
extractUserStore
def extractUserStore(userAccount, extractionDestination, legacySiteAuthoritative=True): """ 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 legacySiteAuthoritative: before moving the user store, clear its authentication information, copy that which is associated with it in the site store rather than trusting its own. Currently this flag is necessary (and defaults to true) because things like the ClickChronicle password-changer gizmo still operate on the site store. """ if legacySiteAuthoritative: # migrateDown() manages its own transactions, since it is copying items # between two different stores. userAccount.migrateDown() av = userAccount.avatars av.open().close() def _(): # We're separately deleting several Items from the site store, then # we're moving some files. If we cannot move the files, we don't want # to delete the items. # There is one unaccounted failure mode here: if the destination of the # move is on a different mount point, the moveTo operation will fall # back to a non-atomic copy; if all of the copying succeeds, but then # part of the deletion of the source files fails, we will be left # without a complete store in this site store's files directory, but # the account Items will remain. This will cause odd errors on login # and at other unpredictable times. The database is only one file, so # we will either remove it all or none of it. Resolving this requires # manual intervention currently: delete the substore's database # directory and the account items (LoginAccount and LoginMethods) # manually. # However, this failure is extremely unlikely, as it would almost # certainly indicate a misconfiguration of the permissions on the site # store's files area. As described above, a failure of the call to # os.rename(), if the platform's rename is atomic (which it generally # is assumed to be) will not move any files and will cause a revert of # the transaction which would have deleted the accompanying items. av.deleteFromStore() userAccount.deleteLoginMethods() userAccount.deleteFromStore() av.storepath.moveTo(extractionDestination) userAccount.store.transact(_)
python
def extractUserStore(userAccount, extractionDestination, legacySiteAuthoritative=True): """ 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 legacySiteAuthoritative: before moving the user store, clear its authentication information, copy that which is associated with it in the site store rather than trusting its own. Currently this flag is necessary (and defaults to true) because things like the ClickChronicle password-changer gizmo still operate on the site store. """ if legacySiteAuthoritative: # migrateDown() manages its own transactions, since it is copying items # between two different stores. userAccount.migrateDown() av = userAccount.avatars av.open().close() def _(): # We're separately deleting several Items from the site store, then # we're moving some files. If we cannot move the files, we don't want # to delete the items. # There is one unaccounted failure mode here: if the destination of the # move is on a different mount point, the moveTo operation will fall # back to a non-atomic copy; if all of the copying succeeds, but then # part of the deletion of the source files fails, we will be left # without a complete store in this site store's files directory, but # the account Items will remain. This will cause odd errors on login # and at other unpredictable times. The database is only one file, so # we will either remove it all or none of it. Resolving this requires # manual intervention currently: delete the substore's database # directory and the account items (LoginAccount and LoginMethods) # manually. # However, this failure is extremely unlikely, as it would almost # certainly indicate a misconfiguration of the permissions on the site # store's files area. As described above, a failure of the call to # os.rename(), if the platform's rename is atomic (which it generally # is assumed to be) will not move any files and will cause a revert of # the transaction which would have deleted the accompanying items. av.deleteFromStore() userAccount.deleteLoginMethods() userAccount.deleteFromStore() av.storepath.moveTo(extractionDestination) userAccount.store.transact(_)
[ "def", "extractUserStore", "(", "userAccount", ",", "extractionDestination", ",", "legacySiteAuthoritative", "=", "True", ")", ":", "if", "legacySiteAuthoritative", ":", "# migrateDown() manages its own transactions, since it is copying items", "# between two different stores.", "userAccount", ".", "migrateDown", "(", ")", "av", "=", "userAccount", ".", "avatars", "av", ".", "open", "(", ")", ".", "close", "(", ")", "def", "_", "(", ")", ":", "# We're separately deleting several Items from the site store, then", "# we're moving some files. If we cannot move the files, we don't want", "# to delete the items.", "# There is one unaccounted failure mode here: if the destination of the", "# move is on a different mount point, the moveTo operation will fall", "# back to a non-atomic copy; if all of the copying succeeds, but then", "# part of the deletion of the source files fails, we will be left", "# without a complete store in this site store's files directory, but", "# the account Items will remain. This will cause odd errors on login", "# and at other unpredictable times. The database is only one file, so", "# we will either remove it all or none of it. Resolving this requires", "# manual intervention currently: delete the substore's database", "# directory and the account items (LoginAccount and LoginMethods)", "# manually.", "# However, this failure is extremely unlikely, as it would almost", "# certainly indicate a misconfiguration of the permissions on the site", "# store's files area. As described above, a failure of the call to", "# os.rename(), if the platform's rename is atomic (which it generally", "# is assumed to be) will not move any files and will cause a revert of", "# the transaction which would have deleted the accompanying items.", "av", ".", "deleteFromStore", "(", ")", "userAccount", ".", "deleteLoginMethods", "(", ")", "userAccount", ".", "deleteFromStore", "(", ")", "av", ".", "storepath", ".", "moveTo", "(", "extractionDestination", ")", "userAccount", ".", "store", ".", "transact", "(", "_", ")" ]
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 legacySiteAuthoritative: before moving the user store, clear its authentication information, copy that which is associated with it in the site store rather than trusting its own. Currently this flag is necessary (and defaults to true) because things like the ClickChronicle password-changer gizmo still operate on the site store.
[ "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", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/userbase.py#L345-L397
train
twisted/axiom
axiom/userbase.py
getLoginMethods
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.protocol == u'*', LoginMethod.protocol == protocol) else: comp = None return store.query(LoginMethod, comp)
python
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.protocol == u'*', LoginMethod.protocol == protocol) else: comp = None return store.query(LoginMethod, comp)
[ "def", "getLoginMethods", "(", "store", ",", "protocol", "=", "None", ")", ":", "if", "protocol", "is", "not", "None", ":", "comp", "=", "OR", "(", "LoginMethod", ".", "protocol", "==", "u'*'", ",", "LoginMethod", ".", "protocol", "==", "protocol", ")", "else", ":", "comp", "=", "None", "return", "store", ".", "query", "(", "LoginMethod", ",", "comp", ")" ]
Retrieve L{LoginMethod} items from store C{store}, optionally constraining them by protocol
[ "Retrieve", "L", "{", "LoginMethod", "}", "items", "from", "store", "C", "{", "store", "}", "optionally", "constraining", "them", "by", "protocol" ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/userbase.py#L599-L609
train
twisted/axiom
axiom/userbase.py
getAccountNames
def getAccountNames(store, protocol=None): """ 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. """ return ((meth.localpart, meth.domain) for meth in getLoginMethods(store, protocol))
python
def getAccountNames(store, protocol=None): """ 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. """ return ((meth.localpart, meth.domain) for meth in getLoginMethods(store, protocol))
[ "def", "getAccountNames", "(", "store", ",", "protocol", "=", "None", ")", ":", "return", "(", "(", "meth", ".", "localpart", ",", "meth", ".", "domain", ")", "for", "meth", "in", "getLoginMethods", "(", "store", ",", "protocol", ")", ")" ]
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.
[ "Retrieve", "account", "name", "information", "about", "the", "given", "database", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/userbase.py#L612-L624
train
twisted/axiom
axiom/userbase.py
getDomainNames
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, LoginMethod.domain != None)).getColumn("domain").distinct()) return sorted(domains)
python
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, LoginMethod.domain != None)).getColumn("domain").distinct()) return sorted(domains)
[ "def", "getDomainNames", "(", "store", ")", ":", "domains", "=", "set", "(", ")", "domains", ".", "update", "(", "store", ".", "query", "(", "LoginMethod", ",", "AND", "(", "LoginMethod", ".", "internal", "==", "True", ",", "LoginMethod", ".", "domain", "!=", "None", ")", ")", ".", "getColumn", "(", "\"domain\"", ")", ".", "distinct", "(", ")", ")", "return", "sorted", "(", "domains", ")" ]
Retrieve a list of all local domain names represented in the given store.
[ "Retrieve", "a", "list", "of", "all", "local", "domain", "names", "represented", "in", "the", "given", "store", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/userbase.py#L627-L636
train
twisted/axiom
axiom/userbase.py
LoginAccount.migrateDown
def migrateDown(self): """ 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. """ ss = self.avatars.open() def _(): oldAccounts = ss.query(LoginAccount) oldMethods = ss.query(LoginMethod) for x in list(oldAccounts) + list(oldMethods): x.deleteFromStore() self.cloneInto(ss, ss) IScheduler(ss).migrateDown() ss.transact(_)
python
def migrateDown(self): """ 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. """ ss = self.avatars.open() def _(): oldAccounts = ss.query(LoginAccount) oldMethods = ss.query(LoginMethod) for x in list(oldAccounts) + list(oldMethods): x.deleteFromStore() self.cloneInto(ss, ss) IScheduler(ss).migrateDown() ss.transact(_)
[ "def", "migrateDown", "(", "self", ")", ":", "ss", "=", "self", ".", "avatars", ".", "open", "(", ")", "def", "_", "(", ")", ":", "oldAccounts", "=", "ss", ".", "query", "(", "LoginAccount", ")", "oldMethods", "=", "ss", ".", "query", "(", "LoginMethod", ")", "for", "x", "in", "list", "(", "oldAccounts", ")", "+", "list", "(", "oldMethods", ")", ":", "x", ".", "deleteFromStore", "(", ")", "self", ".", "cloneInto", "(", "ss", ",", "ss", ")", "IScheduler", "(", "ss", ")", ".", "migrateDown", "(", ")", "ss", ".", "transact", "(", "_", ")" ]
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.
[ "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", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/userbase.py#L189-L204
train
twisted/axiom
axiom/userbase.py
LoginAccount.migrateUp
def migrateUp(self): """ 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. """ siteStore = self.store.parent def _(): # No convenience method for the following because needing to do it is # *rare*. It *should* be ugly; 99% of the time if you need to do this # you're making a mistake. -glyph siteStoreSubRef = siteStore.getItemByID(self.store.idInParent) self.cloneInto(siteStore, siteStoreSubRef) IScheduler(self.store).migrateUp() siteStore.transact(_)
python
def migrateUp(self): """ 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. """ siteStore = self.store.parent def _(): # No convenience method for the following because needing to do it is # *rare*. It *should* be ugly; 99% of the time if you need to do this # you're making a mistake. -glyph siteStoreSubRef = siteStore.getItemByID(self.store.idInParent) self.cloneInto(siteStore, siteStoreSubRef) IScheduler(self.store).migrateUp() siteStore.transact(_)
[ "def", "migrateUp", "(", "self", ")", ":", "siteStore", "=", "self", ".", "store", ".", "parent", "def", "_", "(", ")", ":", "# No convenience method for the following because needing to do it is", "# *rare*. It *should* be ugly; 99% of the time if you need to do this", "# you're making a mistake. -glyph", "siteStoreSubRef", "=", "siteStore", ".", "getItemByID", "(", "self", ".", "store", ".", "idInParent", ")", "self", ".", "cloneInto", "(", "siteStore", ",", "siteStoreSubRef", ")", "IScheduler", "(", "self", ".", "store", ")", ".", "migrateUp", "(", ")", "siteStore", ".", "transact", "(", "_", ")" ]
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.
[ "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", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/userbase.py#L207-L221
train
twisted/axiom
axiom/userbase.py
LoginAccount.cloneInto
def cloneInto(self, newStore, avatars): """ Create a copy of this LoginAccount and all associated LoginMethods in a different Store. Return the copied LoginAccount. """ la = LoginAccount(store=newStore, password=self.password, avatars=avatars, disabled=self.disabled) for siteMethod in self.store.query(LoginMethod, LoginMethod.account == self): LoginMethod(store=newStore, localpart=siteMethod.localpart, domain=siteMethod.domain, internal=siteMethod.internal, protocol=siteMethod.protocol, verified=siteMethod.verified, account=la) return la
python
def cloneInto(self, newStore, avatars): """ Create a copy of this LoginAccount and all associated LoginMethods in a different Store. Return the copied LoginAccount. """ la = LoginAccount(store=newStore, password=self.password, avatars=avatars, disabled=self.disabled) for siteMethod in self.store.query(LoginMethod, LoginMethod.account == self): LoginMethod(store=newStore, localpart=siteMethod.localpart, domain=siteMethod.domain, internal=siteMethod.internal, protocol=siteMethod.protocol, verified=siteMethod.verified, account=la) return la
[ "def", "cloneInto", "(", "self", ",", "newStore", ",", "avatars", ")", ":", "la", "=", "LoginAccount", "(", "store", "=", "newStore", ",", "password", "=", "self", ".", "password", ",", "avatars", "=", "avatars", ",", "disabled", "=", "self", ".", "disabled", ")", "for", "siteMethod", "in", "self", ".", "store", ".", "query", "(", "LoginMethod", ",", "LoginMethod", ".", "account", "==", "self", ")", ":", "LoginMethod", "(", "store", "=", "newStore", ",", "localpart", "=", "siteMethod", ".", "localpart", ",", "domain", "=", "siteMethod", ".", "domain", ",", "internal", "=", "siteMethod", ".", "internal", ",", "protocol", "=", "siteMethod", ".", "protocol", ",", "verified", "=", "siteMethod", ".", "verified", ",", "account", "=", "la", ")", "return", "la" ]
Create a copy of this LoginAccount and all associated LoginMethods in a different Store. Return the copied LoginAccount.
[ "Create", "a", "copy", "of", "this", "LoginAccount", "and", "all", "associated", "LoginMethods", "in", "a", "different", "Store", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/userbase.py#L224-L243
train
twisted/axiom
axiom/userbase.py
LoginAccount.addLoginMethod
def addLoginMethod(self, localpart, domain, protocol=ANY_PROTOCOL, verified=False, internal=False): """ Add a login method to this account, propogating up or down as necessary to site store or user store to maintain consistency. """ # Out takes you west or something if self.store.parent is None: # West takes you in otherStore = self.avatars.open() peer = otherStore.findUnique(LoginAccount) else: # In takes you east otherStore = self.store.parent subStoreItem = self.store.parent.getItemByID(self.store.idInParent) peer = otherStore.findUnique(LoginAccount, LoginAccount.avatars == subStoreItem) # Up and down take you home for store, account in [(otherStore, peer), (self.store, self)]: store.findOrCreate(LoginMethod, account=account, localpart=localpart, domain=domain, protocol=protocol, verified=verified, internal=internal)
python
def addLoginMethod(self, localpart, domain, protocol=ANY_PROTOCOL, verified=False, internal=False): """ Add a login method to this account, propogating up or down as necessary to site store or user store to maintain consistency. """ # Out takes you west or something if self.store.parent is None: # West takes you in otherStore = self.avatars.open() peer = otherStore.findUnique(LoginAccount) else: # In takes you east otherStore = self.store.parent subStoreItem = self.store.parent.getItemByID(self.store.idInParent) peer = otherStore.findUnique(LoginAccount, LoginAccount.avatars == subStoreItem) # Up and down take you home for store, account in [(otherStore, peer), (self.store, self)]: store.findOrCreate(LoginMethod, account=account, localpart=localpart, domain=domain, protocol=protocol, verified=verified, internal=internal)
[ "def", "addLoginMethod", "(", "self", ",", "localpart", ",", "domain", ",", "protocol", "=", "ANY_PROTOCOL", ",", "verified", "=", "False", ",", "internal", "=", "False", ")", ":", "# Out takes you west or something", "if", "self", ".", "store", ".", "parent", "is", "None", ":", "# West takes you in", "otherStore", "=", "self", ".", "avatars", ".", "open", "(", ")", "peer", "=", "otherStore", ".", "findUnique", "(", "LoginAccount", ")", "else", ":", "# In takes you east", "otherStore", "=", "self", ".", "store", ".", "parent", "subStoreItem", "=", "self", ".", "store", ".", "parent", ".", "getItemByID", "(", "self", ".", "store", ".", "idInParent", ")", "peer", "=", "otherStore", ".", "findUnique", "(", "LoginAccount", ",", "LoginAccount", ".", "avatars", "==", "subStoreItem", ")", "# Up and down take you home", "for", "store", ",", "account", "in", "[", "(", "otherStore", ",", "peer", ")", ",", "(", "self", ".", "store", ",", "self", ")", "]", ":", "store", ".", "findOrCreate", "(", "LoginMethod", ",", "account", "=", "account", ",", "localpart", "=", "localpart", ",", "domain", "=", "domain", ",", "protocol", "=", "protocol", ",", "verified", "=", "verified", ",", "internal", "=", "internal", ")" ]
Add a login method to this account, propogating up or down as necessary to site store or user store to maintain consistency.
[ "Add", "a", "login", "method", "to", "this", "account", "propogating", "up", "or", "down", "as", "necessary", "to", "site", "store", "or", "user", "store", "to", "maintain", "consistency", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/userbase.py#L250-L275
train
twisted/axiom
axiom/userbase.py
LoginAccount.replacePassword
def replacePassword(self, currentPassword, newPassword): """ 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 not match. """ if unicode(currentPassword) != self.password: return fail(BadCredentials()) return self.setPassword(newPassword)
python
def replacePassword(self, currentPassword, newPassword): """ 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 not match. """ if unicode(currentPassword) != self.password: return fail(BadCredentials()) return self.setPassword(newPassword)
[ "def", "replacePassword", "(", "self", ",", "currentPassword", ",", "newPassword", ")", ":", "if", "unicode", "(", "currentPassword", ")", "!=", "self", ".", "password", ":", "return", "fail", "(", "BadCredentials", "(", ")", ")", "return", "self", ".", "setPassword", "(", "newPassword", ")" ]
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 not match.
[ "Set", "this", "account", "s", "password", "if", "the", "current", "password", "matches", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/userbase.py#L290-L302
train
twisted/axiom
axiom/userbase.py
LoginBase.addAccount
def addAccount(self, username, domain, password, avatars=None, protocol=u'email', disabled=0, internal=False, verified=True): """ 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 domain, a SIP domain, an HTTP realm, or an email address domain - right now the assumption is generally that it's an email address domain, but not always] @param password: A shared secret. @param avatars: (Optional). A SubStore which, if passed, will be used by cred as the target of all adaptations for this user. By default, I will create a SubStore, and plugins can be installed on that substore using the powerUp method to provide implementations of cred client interfaces. @raise DuplicateUniqueItem: if the 'avatars' argument already contains a LoginAccount. @return: an instance of a LoginAccount, with all attributes filled out as they are passed in, stored in my store. """ # unicode(None) == u'None', kids. if username is not None: username = unicode(username) if domain is not None: domain = unicode(domain) if password is not None: password = unicode(password) if self.accountByAddress(username, domain) is not None: raise DuplicateUser(username, domain) if avatars is None: avatars = self.makeAvatars(domain, username) subStore = avatars.open() # create this unconditionally; as the docstring says, we must be run # within a transaction, so if something goes wrong in the substore # transaction this item's creation will be reverted... la = LoginAccount(store=self.store, password=password, avatars=avatars, disabled=disabled) def createSubStoreAccountObjects(): LoginAccount(store=subStore, password=password, disabled=disabled, avatars=subStore) la.addLoginMethod(localpart=username, domain=domain, protocol=protocol, internal=internal, verified=verified) subStore.transact(createSubStoreAccountObjects) return la
python
def addAccount(self, username, domain, password, avatars=None, protocol=u'email', disabled=0, internal=False, verified=True): """ 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 domain, a SIP domain, an HTTP realm, or an email address domain - right now the assumption is generally that it's an email address domain, but not always] @param password: A shared secret. @param avatars: (Optional). A SubStore which, if passed, will be used by cred as the target of all adaptations for this user. By default, I will create a SubStore, and plugins can be installed on that substore using the powerUp method to provide implementations of cred client interfaces. @raise DuplicateUniqueItem: if the 'avatars' argument already contains a LoginAccount. @return: an instance of a LoginAccount, with all attributes filled out as they are passed in, stored in my store. """ # unicode(None) == u'None', kids. if username is not None: username = unicode(username) if domain is not None: domain = unicode(domain) if password is not None: password = unicode(password) if self.accountByAddress(username, domain) is not None: raise DuplicateUser(username, domain) if avatars is None: avatars = self.makeAvatars(domain, username) subStore = avatars.open() # create this unconditionally; as the docstring says, we must be run # within a transaction, so if something goes wrong in the substore # transaction this item's creation will be reverted... la = LoginAccount(store=self.store, password=password, avatars=avatars, disabled=disabled) def createSubStoreAccountObjects(): LoginAccount(store=subStore, password=password, disabled=disabled, avatars=subStore) la.addLoginMethod(localpart=username, domain=domain, protocol=protocol, internal=internal, verified=verified) subStore.transact(createSubStoreAccountObjects) return la
[ "def", "addAccount", "(", "self", ",", "username", ",", "domain", ",", "password", ",", "avatars", "=", "None", ",", "protocol", "=", "u'email'", ",", "disabled", "=", "0", ",", "internal", "=", "False", ",", "verified", "=", "True", ")", ":", "# unicode(None) == u'None', kids.", "if", "username", "is", "not", "None", ":", "username", "=", "unicode", "(", "username", ")", "if", "domain", "is", "not", "None", ":", "domain", "=", "unicode", "(", "domain", ")", "if", "password", "is", "not", "None", ":", "password", "=", "unicode", "(", "password", ")", "if", "self", ".", "accountByAddress", "(", "username", ",", "domain", ")", "is", "not", "None", ":", "raise", "DuplicateUser", "(", "username", ",", "domain", ")", "if", "avatars", "is", "None", ":", "avatars", "=", "self", ".", "makeAvatars", "(", "domain", ",", "username", ")", "subStore", "=", "avatars", ".", "open", "(", ")", "# create this unconditionally; as the docstring says, we must be run", "# within a transaction, so if something goes wrong in the substore", "# transaction this item's creation will be reverted...", "la", "=", "LoginAccount", "(", "store", "=", "self", ".", "store", ",", "password", "=", "password", ",", "avatars", "=", "avatars", ",", "disabled", "=", "disabled", ")", "def", "createSubStoreAccountObjects", "(", ")", ":", "LoginAccount", "(", "store", "=", "subStore", ",", "password", "=", "password", ",", "disabled", "=", "disabled", ",", "avatars", "=", "subStore", ")", "la", ".", "addLoginMethod", "(", "localpart", "=", "username", ",", "domain", "=", "domain", ",", "protocol", "=", "protocol", ",", "internal", "=", "internal", ",", "verified", "=", "verified", ")", "subStore", ".", "transact", "(", "createSubStoreAccountObjects", ")", "return", "la" ]
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 domain, a SIP domain, an HTTP realm, or an email address domain - right now the assumption is generally that it's an email address domain, but not always] @param password: A shared secret. @param avatars: (Optional). A SubStore which, if passed, will be used by cred as the target of all adaptations for this user. By default, I will create a SubStore, and plugins can be installed on that substore using the powerUp method to provide implementations of cred client interfaces. @raise DuplicateUniqueItem: if the 'avatars' argument already contains a LoginAccount. @return: an instance of a LoginAccount, with all attributes filled out as they are passed in, stored in my store.
[ "Create", "a", "user", "account", "add", "it", "to", "this", "LoginBase", "and", "return", "it", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/userbase.py#L465-L533
train
twisted/axiom
axiom/_pysqlite2.py
Connection.identifySQLError
def identifySQLError(self, sql, args, e): """ Identify an appropriate SQL error object for the given message for the supported versions of sqlite. @return: an SQLError """ message = e.args[0] if message.startswith("table") and message.endswith("already exists"): return errors.TableAlreadyExists(sql, args, e) return errors.SQLError(sql, args, e)
python
def identifySQLError(self, sql, args, e): """ Identify an appropriate SQL error object for the given message for the supported versions of sqlite. @return: an SQLError """ message = e.args[0] if message.startswith("table") and message.endswith("already exists"): return errors.TableAlreadyExists(sql, args, e) return errors.SQLError(sql, args, e)
[ "def", "identifySQLError", "(", "self", ",", "sql", ",", "args", ",", "e", ")", ":", "message", "=", "e", ".", "args", "[", "0", "]", "if", "message", ".", "startswith", "(", "\"table\"", ")", "and", "message", ".", "endswith", "(", "\"already exists\"", ")", ":", "return", "errors", ".", "TableAlreadyExists", "(", "sql", ",", "args", ",", "e", ")", "return", "errors", ".", "SQLError", "(", "sql", ",", "args", ",", "e", ")" ]
Identify an appropriate SQL error object for the given message for the supported versions of sqlite. @return: an SQLError
[ "Identify", "an", "appropriate", "SQL", "error", "object", "for", "the", "given", "message", "for", "the", "supported", "versions", "of", "sqlite", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/_pysqlite2.py#L52-L62
train
twisted/axiom
axiom/_fincache.py
createCacheRemoveCallback
def createCacheRemoveCallback(cacheRef, key, finalizer): """ 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 weakref to the cache in which the corresponding cache item was stored. @param key: The key for which this value is cached. @type finalizer: callable taking 0 arguments @param finalizer: A user-provided callable that will be called when the weakref callback runs. """ def remove(reference): # Weakref callbacks cannot raise exceptions or DOOM ensues try: finalizer() except: logErrorNoMatterWhat() try: cache = cacheRef() if cache is not None: if key in cache.data: if cache.data[key] is reference: del cache.data[key] except: logErrorNoMatterWhat() return remove
python
def createCacheRemoveCallback(cacheRef, key, finalizer): """ 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 weakref to the cache in which the corresponding cache item was stored. @param key: The key for which this value is cached. @type finalizer: callable taking 0 arguments @param finalizer: A user-provided callable that will be called when the weakref callback runs. """ def remove(reference): # Weakref callbacks cannot raise exceptions or DOOM ensues try: finalizer() except: logErrorNoMatterWhat() try: cache = cacheRef() if cache is not None: if key in cache.data: if cache.data[key] is reference: del cache.data[key] except: logErrorNoMatterWhat() return remove
[ "def", "createCacheRemoveCallback", "(", "cacheRef", ",", "key", ",", "finalizer", ")", ":", "def", "remove", "(", "reference", ")", ":", "# Weakref callbacks cannot raise exceptions or DOOM ensues", "try", ":", "finalizer", "(", ")", "except", ":", "logErrorNoMatterWhat", "(", ")", "try", ":", "cache", "=", "cacheRef", "(", ")", "if", "cache", "is", "not", "None", ":", "if", "key", "in", "cache", ".", "data", ":", "if", "cache", ".", "data", "[", "key", "]", "is", "reference", ":", "del", "cache", ".", "data", "[", "key", "]", "except", ":", "logErrorNoMatterWhat", "(", ")", "return", "remove" ]
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 weakref to the cache in which the corresponding cache item was stored. @param key: The key for which this value is cached. @type finalizer: callable taking 0 arguments @param finalizer: A user-provided callable that will be called when the weakref callback runs.
[ "Construct", "a", "callable", "to", "be", "used", "as", "a", "weakref", "callback", "for", "cache", "entries", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/_fincache.py#L39-L71
train
twisted/axiom
axiom/_fincache.py
FinalizingCache.cache
def cache(self, key, value): """ 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: The value for the cache entry. """ fin = value.__finalizer__() try: # It's okay if there's already a cache entry for this key as long # as the weakref has already been broken. See the comment in # get() for an explanation of why this might happen. if self.data[key]() is not None: raise CacheInconsistency( "Duplicate cache key: %r %r %r" % ( key, value, self.data[key])) except KeyError: pass callback = createCacheRemoveCallback(self._ref(self), key, fin) self.data[key] = self._ref(value, callback) return value
python
def cache(self, key, value): """ 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: The value for the cache entry. """ fin = value.__finalizer__() try: # It's okay if there's already a cache entry for this key as long # as the weakref has already been broken. See the comment in # get() for an explanation of why this might happen. if self.data[key]() is not None: raise CacheInconsistency( "Duplicate cache key: %r %r %r" % ( key, value, self.data[key])) except KeyError: pass callback = createCacheRemoveCallback(self._ref(self), key, fin) self.data[key] = self._ref(value, callback) return value
[ "def", "cache", "(", "self", ",", "key", ",", "value", ")", ":", "fin", "=", "value", ".", "__finalizer__", "(", ")", "try", ":", "# It's okay if there's already a cache entry for this key as long", "# as the weakref has already been broken. See the comment in", "# get() for an explanation of why this might happen.", "if", "self", ".", "data", "[", "key", "]", "(", ")", "is", "not", "None", ":", "raise", "CacheInconsistency", "(", "\"Duplicate cache key: %r %r %r\"", "%", "(", "key", ",", "value", ",", "self", ".", "data", "[", "key", "]", ")", ")", "except", "KeyError", ":", "pass", "callback", "=", "createCacheRemoveCallback", "(", "self", ".", "_ref", "(", "self", ")", ",", "key", ",", "fin", ")", "self", ".", "data", "[", "key", "]", "=", "self", ".", "_ref", "(", "value", ",", "callback", ")", "return", "value" ]
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: The value for the cache entry.
[ "Add", "an", "entry", "to", "the", "cache", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/_fincache.py#L89-L114
train
twisted/axiom
axiom/_fincache.py
FinalizingCache.uncache
def uncache(self, key, value): """ 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. """ try: assert self.get(key) is value del self.data[key] except KeyError: # If the entry has already been removed from the cache, this will # result in KeyError which we ignore. If the entry is still in the # cache, but the weakref has been broken, this will result in # CacheFault (a KeyError subclass) which we also ignore. See the # comment in get() for an explanation of why this might happen. pass
python
def uncache(self, key, value): """ 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. """ try: assert self.get(key) is value del self.data[key] except KeyError: # If the entry has already been removed from the cache, this will # result in KeyError which we ignore. If the entry is still in the # cache, but the weakref has been broken, this will result in # CacheFault (a KeyError subclass) which we also ignore. See the # comment in get() for an explanation of why this might happen. pass
[ "def", "uncache", "(", "self", ",", "key", ",", "value", ")", ":", "try", ":", "assert", "self", ".", "get", "(", "key", ")", "is", "value", "del", "self", ".", "data", "[", "key", "]", "except", "KeyError", ":", "# If the entry has already been removed from the cache, this will", "# result in KeyError which we ignore. If the entry is still in the", "# cache, but the weakref has been broken, this will result in", "# CacheFault (a KeyError subclass) which we also ignore. See the", "# comment in get() for an explanation of why this might happen.", "pass" ]
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.
[ "Remove", "a", "key", "from", "the", "cache", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/_fincache.py#L117-L137
train
twisted/axiom
axiom/_fincache.py
FinalizingCache.get
def get(self, key): """ 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. """ o = self.data[key]() if o is None: # On CPython, the weakref callback will always(?) run before any # other code has a chance to observe that the weakref is broken; # and since the callback removes the item from the dict, this # branch of code should never run. However, on PyPy (and possibly # other Python implementations), the weakref callback does not run # immediately, thus we may be able to observe this intermediate # state. Should this occur, we remove the dict item ourselves, # and raise CacheFault (which is a KeyError subclass). del self.data[key] raise CacheFault( "FinalizingCache has %r but its value is no more." % (key,)) log.msg(interface=iaxiom.IStatEvent, stat_cache_hits=1, key=key) return o
python
def get(self, key): """ 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. """ o = self.data[key]() if o is None: # On CPython, the weakref callback will always(?) run before any # other code has a chance to observe that the weakref is broken; # and since the callback removes the item from the dict, this # branch of code should never run. However, on PyPy (and possibly # other Python implementations), the weakref callback does not run # immediately, thus we may be able to observe this intermediate # state. Should this occur, we remove the dict item ourselves, # and raise CacheFault (which is a KeyError subclass). del self.data[key] raise CacheFault( "FinalizingCache has %r but its value is no more." % (key,)) log.msg(interface=iaxiom.IStatEvent, stat_cache_hits=1, key=key) return o
[ "def", "get", "(", "self", ",", "key", ")", ":", "o", "=", "self", ".", "data", "[", "key", "]", "(", ")", "if", "o", "is", "None", ":", "# On CPython, the weakref callback will always(?) run before any", "# other code has a chance to observe that the weakref is broken;", "# and since the callback removes the item from the dict, this", "# branch of code should never run. However, on PyPy (and possibly", "# other Python implementations), the weakref callback does not run", "# immediately, thus we may be able to observe this intermediate", "# state. Should this occur, we remove the dict item ourselves,", "# and raise CacheFault (which is a KeyError subclass).", "del", "self", ".", "data", "[", "key", "]", "raise", "CacheFault", "(", "\"FinalizingCache has %r but its value is no more.\"", "%", "(", "key", ",", ")", ")", "log", ".", "msg", "(", "interface", "=", "iaxiom", ".", "IStatEvent", ",", "stat_cache_hits", "=", "1", ",", "key", "=", "key", ")", "return", "o" ]
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.
[ "Get", "an", "entry", "from", "the", "cache", "by", "key", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/_fincache.py#L140-L163
train
ubc/ubcpi
ubcpi/serialize.py
parse_question_xml
def parse_question_xml(root): """ 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?', 'image_url': '', 'image_position': 'below', 'image_show_fields': 0, 'image_alt': 'description' } Raises: ValidationError: The XML definition is invalid. """ question_dict = dict() question_prompt_el = root.find('text') if question_prompt_el is not None: question_dict['text'] = _safe_get_text(question_prompt_el) else: raise ValidationError(_('Question must have text element.')) # optional image element question_dict.update(parse_image_xml(root)) return question_dict
python
def parse_question_xml(root): """ 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?', 'image_url': '', 'image_position': 'below', 'image_show_fields': 0, 'image_alt': 'description' } Raises: ValidationError: The XML definition is invalid. """ question_dict = dict() question_prompt_el = root.find('text') if question_prompt_el is not None: question_dict['text'] = _safe_get_text(question_prompt_el) else: raise ValidationError(_('Question must have text element.')) # optional image element question_dict.update(parse_image_xml(root)) return question_dict
[ "def", "parse_question_xml", "(", "root", ")", ":", "question_dict", "=", "dict", "(", ")", "question_prompt_el", "=", "root", ".", "find", "(", "'text'", ")", "if", "question_prompt_el", "is", "not", "None", ":", "question_dict", "[", "'text'", "]", "=", "_safe_get_text", "(", "question_prompt_el", ")", "else", ":", "raise", "ValidationError", "(", "_", "(", "'Question must have text element.'", ")", ")", "# optional image element", "question_dict", ".", "update", "(", "parse_image_xml", "(", "root", ")", ")", "return", "question_dict" ]
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?', 'image_url': '', 'image_position': 'below', 'image_show_fields': 0, 'image_alt': 'description' } Raises: ValidationError: The XML definition is invalid.
[ "Parse", "<question", ">", "element", "in", "the", "UBCPI", "XBlock", "s", "content", "XML", "." ]
7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e
https://github.com/ubc/ubcpi/blob/7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e/ubcpi/serialize.py#L67-L98
train
ubc/ubcpi
ubcpi/serialize.py
parse_options_xml
def parse_options_xml(root): """ 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_position': 'below', 'image_show_fields': 0, 'image_alt': '' }, {.... }] Raises: ValidationError: The XML definition is invalid. """ options = [] correct_option = None rationale = None for option_el in root.findall('option'): option_dict = dict() option_prompt_el = option_el.find('text') if option_prompt_el is not None: option_dict['text'] = _safe_get_text(option_prompt_el) else: raise ValidationError(_('Option must have text element.')) # optional image element option_dict.update(parse_image_xml(option_el)) if 'correct' in option_el.attrib and _parse_boolean(option_el.attrib['correct']): if correct_option is None: correct_option = len(options) rationale_el = option_el.find('rationale') if rationale_el is not None: rationale = {'text': _safe_get_text(rationale_el)} else: raise ValidationError(_('Missing rationale for correct answer.')) else: raise ValidationError(_('Only one correct answer can be defined in options.')) options.append(option_dict) if correct_option is None or rationale is None: raise ValidationError(_('Correct answer and rationale are required and have to be defined in one of the option.')) return options, correct_option, rationale
python
def parse_options_xml(root): """ 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_position': 'below', 'image_show_fields': 0, 'image_alt': '' }, {.... }] Raises: ValidationError: The XML definition is invalid. """ options = [] correct_option = None rationale = None for option_el in root.findall('option'): option_dict = dict() option_prompt_el = option_el.find('text') if option_prompt_el is not None: option_dict['text'] = _safe_get_text(option_prompt_el) else: raise ValidationError(_('Option must have text element.')) # optional image element option_dict.update(parse_image_xml(option_el)) if 'correct' in option_el.attrib and _parse_boolean(option_el.attrib['correct']): if correct_option is None: correct_option = len(options) rationale_el = option_el.find('rationale') if rationale_el is not None: rationale = {'text': _safe_get_text(rationale_el)} else: raise ValidationError(_('Missing rationale for correct answer.')) else: raise ValidationError(_('Only one correct answer can be defined in options.')) options.append(option_dict) if correct_option is None or rationale is None: raise ValidationError(_('Correct answer and rationale are required and have to be defined in one of the option.')) return options, correct_option, rationale
[ "def", "parse_options_xml", "(", "root", ")", ":", "options", "=", "[", "]", "correct_option", "=", "None", "rationale", "=", "None", "for", "option_el", "in", "root", ".", "findall", "(", "'option'", ")", ":", "option_dict", "=", "dict", "(", ")", "option_prompt_el", "=", "option_el", ".", "find", "(", "'text'", ")", "if", "option_prompt_el", "is", "not", "None", ":", "option_dict", "[", "'text'", "]", "=", "_safe_get_text", "(", "option_prompt_el", ")", "else", ":", "raise", "ValidationError", "(", "_", "(", "'Option must have text element.'", ")", ")", "# optional image element", "option_dict", ".", "update", "(", "parse_image_xml", "(", "option_el", ")", ")", "if", "'correct'", "in", "option_el", ".", "attrib", "and", "_parse_boolean", "(", "option_el", ".", "attrib", "[", "'correct'", "]", ")", ":", "if", "correct_option", "is", "None", ":", "correct_option", "=", "len", "(", "options", ")", "rationale_el", "=", "option_el", ".", "find", "(", "'rationale'", ")", "if", "rationale_el", "is", "not", "None", ":", "rationale", "=", "{", "'text'", ":", "_safe_get_text", "(", "rationale_el", ")", "}", "else", ":", "raise", "ValidationError", "(", "_", "(", "'Missing rationale for correct answer.'", ")", ")", "else", ":", "raise", "ValidationError", "(", "_", "(", "'Only one correct answer can be defined in options.'", ")", ")", "options", ".", "append", "(", "option_dict", ")", "if", "correct_option", "is", "None", "or", "rationale", "is", "None", ":", "raise", "ValidationError", "(", "_", "(", "'Correct answer and rationale are required and have to be defined in one of the option.'", ")", ")", "return", "options", ",", "correct_option", ",", "rationale" ]
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_position': 'below', 'image_show_fields': 0, 'image_alt': '' }, {.... }] Raises: ValidationError: The XML definition is invalid.
[ "Parse", "<options", ">", "element", "in", "the", "UBCPI", "XBlock", "s", "content", "XML", "." ]
7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e
https://github.com/ubc/ubcpi/blob/7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e/ubcpi/serialize.py#L101-L154
train
ubc/ubcpi
ubcpi/serialize.py
parse_seeds_xml
def parse_seeds_xml(root): """ 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 is a seeded answer', }, {.... }] Raises: ValidationError: The XML definition is invalid. """ seeds = [] for seed_el in root.findall('seed'): seed_dict = dict() seed_dict['rationale'] = _safe_get_text(seed_el) if 'option' in seed_el.attrib: seed_dict['answer'] = int(seed_el.attrib['option']) - 1 else: raise ValidationError(_('Seed element must have an option attribute.')) seeds.append(seed_dict) return seeds
python
def parse_seeds_xml(root): """ 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 is a seeded answer', }, {.... }] Raises: ValidationError: The XML definition is invalid. """ seeds = [] for seed_el in root.findall('seed'): seed_dict = dict() seed_dict['rationale'] = _safe_get_text(seed_el) if 'option' in seed_el.attrib: seed_dict['answer'] = int(seed_el.attrib['option']) - 1 else: raise ValidationError(_('Seed element must have an option attribute.')) seeds.append(seed_dict) return seeds
[ "def", "parse_seeds_xml", "(", "root", ")", ":", "seeds", "=", "[", "]", "for", "seed_el", "in", "root", ".", "findall", "(", "'seed'", ")", ":", "seed_dict", "=", "dict", "(", ")", "seed_dict", "[", "'rationale'", "]", "=", "_safe_get_text", "(", "seed_el", ")", "if", "'option'", "in", "seed_el", ".", "attrib", ":", "seed_dict", "[", "'answer'", "]", "=", "int", "(", "seed_el", ".", "attrib", "[", "'option'", "]", ")", "-", "1", "else", ":", "raise", "ValidationError", "(", "_", "(", "'Seed element must have an option attribute.'", ")", ")", "seeds", ".", "append", "(", "seed_dict", ")", "return", "seeds" ]
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 is a seeded answer', }, {.... }] Raises: ValidationError: The XML definition is invalid.
[ "Parse", "<seeds", ">", "element", "in", "the", "UBCPI", "XBlock", "s", "content", "XML", "." ]
7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e
https://github.com/ubc/ubcpi/blob/7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e/ubcpi/serialize.py#L157-L189
train
ubc/ubcpi
ubcpi/serialize.py
parse_from_xml
def parse_from_xml(root): """ 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 all of the XBlock's content. Raises: UpdateFromXmlError: The XML definition is invalid """ # Check that the root has the correct tag if root.tag != 'ubcpi': raise UpdateFromXmlError(_('Every peer instruction tool must contain an "ubcpi" element.')) display_name_el = root.find('display_name') if display_name_el is None: raise UpdateFromXmlError(_('Every peer instruction tool must contain a "display_name" element.')) else: display_name = _safe_get_text(display_name_el) rationale_size_min = int(root.attrib['rationale_size_min']) if 'rationale_size_min' in root.attrib else None rationale_size_max = int(root.attrib['rationale_size_max']) if 'rationale_size_max' in root.attrib else None question_el = root.find('question') if question_el is None: raise UpdateFromXmlError(_('Every peer instruction must tool contain a "question" element.')) else: question = parse_question_xml(question_el) options_el = root.find('options') if options_el is None: raise UpdateFromXmlError(_('Every peer instruction must tool contain a "options" element.')) else: options, correct_answer, correct_rationale = parse_options_xml(options_el) seeds_el = root.find('seeds') if seeds_el is None: raise UpdateFromXmlError(_('Every peer instruction must tool contain a "seeds" element.')) else: seeds = parse_seeds_xml(seeds_el) algo = unicode(root.attrib['algorithm']) if 'algorithm' in root.attrib else None num_responses = unicode(root.attrib['num_responses']) if 'num_responses' in root.attrib else None return { 'display_name': display_name, 'question_text': question, 'options': options, 'rationale_size': {'min': rationale_size_min, 'max': rationale_size_max}, 'correct_answer': correct_answer, 'correct_rationale': correct_rationale, 'seeds': seeds, 'algo': {"name": algo, 'num_responses': num_responses} }
python
def parse_from_xml(root): """ 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 all of the XBlock's content. Raises: UpdateFromXmlError: The XML definition is invalid """ # Check that the root has the correct tag if root.tag != 'ubcpi': raise UpdateFromXmlError(_('Every peer instruction tool must contain an "ubcpi" element.')) display_name_el = root.find('display_name') if display_name_el is None: raise UpdateFromXmlError(_('Every peer instruction tool must contain a "display_name" element.')) else: display_name = _safe_get_text(display_name_el) rationale_size_min = int(root.attrib['rationale_size_min']) if 'rationale_size_min' in root.attrib else None rationale_size_max = int(root.attrib['rationale_size_max']) if 'rationale_size_max' in root.attrib else None question_el = root.find('question') if question_el is None: raise UpdateFromXmlError(_('Every peer instruction must tool contain a "question" element.')) else: question = parse_question_xml(question_el) options_el = root.find('options') if options_el is None: raise UpdateFromXmlError(_('Every peer instruction must tool contain a "options" element.')) else: options, correct_answer, correct_rationale = parse_options_xml(options_el) seeds_el = root.find('seeds') if seeds_el is None: raise UpdateFromXmlError(_('Every peer instruction must tool contain a "seeds" element.')) else: seeds = parse_seeds_xml(seeds_el) algo = unicode(root.attrib['algorithm']) if 'algorithm' in root.attrib else None num_responses = unicode(root.attrib['num_responses']) if 'num_responses' in root.attrib else None return { 'display_name': display_name, 'question_text': question, 'options': options, 'rationale_size': {'min': rationale_size_min, 'max': rationale_size_max}, 'correct_answer': correct_answer, 'correct_rationale': correct_rationale, 'seeds': seeds, 'algo': {"name": algo, 'num_responses': num_responses} }
[ "def", "parse_from_xml", "(", "root", ")", ":", "# Check that the root has the correct tag", "if", "root", ".", "tag", "!=", "'ubcpi'", ":", "raise", "UpdateFromXmlError", "(", "_", "(", "'Every peer instruction tool must contain an \"ubcpi\" element.'", ")", ")", "display_name_el", "=", "root", ".", "find", "(", "'display_name'", ")", "if", "display_name_el", "is", "None", ":", "raise", "UpdateFromXmlError", "(", "_", "(", "'Every peer instruction tool must contain a \"display_name\" element.'", ")", ")", "else", ":", "display_name", "=", "_safe_get_text", "(", "display_name_el", ")", "rationale_size_min", "=", "int", "(", "root", ".", "attrib", "[", "'rationale_size_min'", "]", ")", "if", "'rationale_size_min'", "in", "root", ".", "attrib", "else", "None", "rationale_size_max", "=", "int", "(", "root", ".", "attrib", "[", "'rationale_size_max'", "]", ")", "if", "'rationale_size_max'", "in", "root", ".", "attrib", "else", "None", "question_el", "=", "root", ".", "find", "(", "'question'", ")", "if", "question_el", "is", "None", ":", "raise", "UpdateFromXmlError", "(", "_", "(", "'Every peer instruction must tool contain a \"question\" element.'", ")", ")", "else", ":", "question", "=", "parse_question_xml", "(", "question_el", ")", "options_el", "=", "root", ".", "find", "(", "'options'", ")", "if", "options_el", "is", "None", ":", "raise", "UpdateFromXmlError", "(", "_", "(", "'Every peer instruction must tool contain a \"options\" element.'", ")", ")", "else", ":", "options", ",", "correct_answer", ",", "correct_rationale", "=", "parse_options_xml", "(", "options_el", ")", "seeds_el", "=", "root", ".", "find", "(", "'seeds'", ")", "if", "seeds_el", "is", "None", ":", "raise", "UpdateFromXmlError", "(", "_", "(", "'Every peer instruction must tool contain a \"seeds\" element.'", ")", ")", "else", ":", "seeds", "=", "parse_seeds_xml", "(", "seeds_el", ")", "algo", "=", "unicode", "(", "root", ".", "attrib", "[", "'algorithm'", "]", ")", "if", "'algorithm'", "in", "root", ".", "attrib", "else", "None", "num_responses", "=", "unicode", "(", "root", ".", "attrib", "[", "'num_responses'", "]", ")", "if", "'num_responses'", "in", "root", ".", "attrib", "else", "None", "return", "{", "'display_name'", ":", "display_name", ",", "'question_text'", ":", "question", ",", "'options'", ":", "options", ",", "'rationale_size'", ":", "{", "'min'", ":", "rationale_size_min", ",", "'max'", ":", "rationale_size_max", "}", ",", "'correct_answer'", ":", "correct_answer", ",", "'correct_rationale'", ":", "correct_rationale", ",", "'seeds'", ":", "seeds", ",", "'algo'", ":", "{", "\"name\"", ":", "algo", ",", "'num_responses'", ":", "num_responses", "}", "}" ]
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 all of the XBlock's content. Raises: UpdateFromXmlError: The XML definition is invalid
[ "Update", "the", "UBCPI", "XBlock", "s", "content", "from", "an", "XML", "definition", "." ]
7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e
https://github.com/ubc/ubcpi/blob/7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e/ubcpi/serialize.py#L192-L252
train
ubc/ubcpi
ubcpi/serialize.py
serialize_options
def serialize_options(options, block): """ 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 """ for index, option_dict in enumerate(block.options): option = etree.SubElement(options, 'option') # set correct option and rationale if index == block.correct_answer: option.set('correct', u'True') if hasattr(block, 'correct_rationale'): rationale = etree.SubElement(option, 'rationale') rationale.text = block.correct_rationale['text'] text = etree.SubElement(option, 'text') text.text = option_dict.get('text', '') serialize_image(option_dict, option)
python
def serialize_options(options, block): """ 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 """ for index, option_dict in enumerate(block.options): option = etree.SubElement(options, 'option') # set correct option and rationale if index == block.correct_answer: option.set('correct', u'True') if hasattr(block, 'correct_rationale'): rationale = etree.SubElement(option, 'rationale') rationale.text = block.correct_rationale['text'] text = etree.SubElement(option, 'text') text.text = option_dict.get('text', '') serialize_image(option_dict, option)
[ "def", "serialize_options", "(", "options", ",", "block", ")", ":", "for", "index", ",", "option_dict", "in", "enumerate", "(", "block", ".", "options", ")", ":", "option", "=", "etree", ".", "SubElement", "(", "options", ",", "'option'", ")", "# set correct option and rationale", "if", "index", "==", "block", ".", "correct_answer", ":", "option", ".", "set", "(", "'correct'", ",", "u'True'", ")", "if", "hasattr", "(", "block", ",", "'correct_rationale'", ")", ":", "rationale", "=", "etree", ".", "SubElement", "(", "option", ",", "'rationale'", ")", "rationale", ".", "text", "=", "block", ".", "correct_rationale", "[", "'text'", "]", "text", "=", "etree", ".", "SubElement", "(", "option", ",", "'text'", ")", "text", ".", "text", "=", "option_dict", ".", "get", "(", "'text'", ",", "''", ")", "serialize_image", "(", "option_dict", ",", "option", ")" ]
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
[ "Serialize", "the", "options", "in", "peer", "instruction", "XBlock", "to", "xml" ]
7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e
https://github.com/ubc/ubcpi/blob/7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e/ubcpi/serialize.py#L255-L279
train
ubc/ubcpi
ubcpi/serialize.py
serialize_seeds
def serialize_seeds(seeds, block): """ 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 """ for seed_dict in block.seeds: seed = etree.SubElement(seeds, 'seed') # options in xml starts with 1 seed.set('option', unicode(seed_dict.get('answer', 0) + 1)) seed.text = seed_dict.get('rationale', '')
python
def serialize_seeds(seeds, block): """ 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 """ for seed_dict in block.seeds: seed = etree.SubElement(seeds, 'seed') # options in xml starts with 1 seed.set('option', unicode(seed_dict.get('answer', 0) + 1)) seed.text = seed_dict.get('rationale', '')
[ "def", "serialize_seeds", "(", "seeds", ",", "block", ")", ":", "for", "seed_dict", "in", "block", ".", "seeds", ":", "seed", "=", "etree", ".", "SubElement", "(", "seeds", ",", "'seed'", ")", "# options in xml starts with 1", "seed", ".", "set", "(", "'option'", ",", "unicode", "(", "seed_dict", ".", "get", "(", "'answer'", ",", "0", ")", "+", "1", ")", ")", "seed", ".", "text", "=", "seed_dict", ".", "get", "(", "'rationale'", ",", "''", ")" ]
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
[ "Serialize", "the", "seeds", "in", "peer", "instruction", "XBlock", "to", "xml" ]
7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e
https://github.com/ubc/ubcpi/blob/7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e/ubcpi/serialize.py#L292-L307
train
ubc/ubcpi
ubcpi/serialize.py
serialize_to_xml
def serialize_to_xml(root, block): """ 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 """ root.tag = 'ubcpi' if block.rationale_size is not None: if block.rationale_size.get('min'): root.set('rationale_size_min', unicode(block.rationale_size.get('min'))) if block.rationale_size.get('max'): root.set('rationale_size_max', unicode(block.rationale_size['max'])) if block.algo: if block.algo.get('name'): root.set('algorithm', block.algo.get('name')) if block.algo.get('num_responses'): root.set('num_responses', unicode(block.algo.get('num_responses'))) display_name = etree.SubElement(root, 'display_name') display_name.text = block.display_name question = etree.SubElement(root, 'question') question_text = etree.SubElement(question, 'text') question_text.text = block.question_text['text'] serialize_image(block.question_text, question) options = etree.SubElement(root, 'options') serialize_options(options, block) seeds = etree.SubElement(root, 'seeds') serialize_seeds(seeds, block)
python
def serialize_to_xml(root, block): """ 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 """ root.tag = 'ubcpi' if block.rationale_size is not None: if block.rationale_size.get('min'): root.set('rationale_size_min', unicode(block.rationale_size.get('min'))) if block.rationale_size.get('max'): root.set('rationale_size_max', unicode(block.rationale_size['max'])) if block.algo: if block.algo.get('name'): root.set('algorithm', block.algo.get('name')) if block.algo.get('num_responses'): root.set('num_responses', unicode(block.algo.get('num_responses'))) display_name = etree.SubElement(root, 'display_name') display_name.text = block.display_name question = etree.SubElement(root, 'question') question_text = etree.SubElement(question, 'text') question_text.text = block.question_text['text'] serialize_image(block.question_text, question) options = etree.SubElement(root, 'options') serialize_options(options, block) seeds = etree.SubElement(root, 'seeds') serialize_seeds(seeds, block)
[ "def", "serialize_to_xml", "(", "root", ",", "block", ")", ":", "root", ".", "tag", "=", "'ubcpi'", "if", "block", ".", "rationale_size", "is", "not", "None", ":", "if", "block", ".", "rationale_size", ".", "get", "(", "'min'", ")", ":", "root", ".", "set", "(", "'rationale_size_min'", ",", "unicode", "(", "block", ".", "rationale_size", ".", "get", "(", "'min'", ")", ")", ")", "if", "block", ".", "rationale_size", ".", "get", "(", "'max'", ")", ":", "root", ".", "set", "(", "'rationale_size_max'", ",", "unicode", "(", "block", ".", "rationale_size", "[", "'max'", "]", ")", ")", "if", "block", ".", "algo", ":", "if", "block", ".", "algo", ".", "get", "(", "'name'", ")", ":", "root", ".", "set", "(", "'algorithm'", ",", "block", ".", "algo", ".", "get", "(", "'name'", ")", ")", "if", "block", ".", "algo", ".", "get", "(", "'num_responses'", ")", ":", "root", ".", "set", "(", "'num_responses'", ",", "unicode", "(", "block", ".", "algo", ".", "get", "(", "'num_responses'", ")", ")", ")", "display_name", "=", "etree", ".", "SubElement", "(", "root", ",", "'display_name'", ")", "display_name", ".", "text", "=", "block", ".", "display_name", "question", "=", "etree", ".", "SubElement", "(", "root", ",", "'question'", ")", "question_text", "=", "etree", ".", "SubElement", "(", "question", ",", "'text'", ")", "question_text", ".", "text", "=", "block", ".", "question_text", "[", "'text'", "]", "serialize_image", "(", "block", ".", "question_text", ",", "question", ")", "options", "=", "etree", ".", "SubElement", "(", "root", ",", "'options'", ")", "serialize_options", "(", "options", ",", "block", ")", "seeds", "=", "etree", ".", "SubElement", "(", "root", ",", "'seeds'", ")", "serialize_seeds", "(", "seeds", ",", "block", ")" ]
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
[ "Serialize", "the", "Peer", "Instruction", "XBlock", "s", "content", "to", "XML", "." ]
7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e
https://github.com/ubc/ubcpi/blob/7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e/ubcpi/serialize.py#L310-L348
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.open
def open(self): """ 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 """ if not self.handle: self.lvm.open() self.__vgh = lvm_vg_open(self.lvm.handle, self.name, self.mode) if not bool(self.__vgh): raise HandleError("Failed to initialize VG Handle.")
python
def open(self): """ 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 """ if not self.handle: self.lvm.open() self.__vgh = lvm_vg_open(self.lvm.handle, self.name, self.mode) if not bool(self.__vgh): raise HandleError("Failed to initialize VG Handle.")
[ "def", "open", "(", "self", ")", ":", "if", "not", "self", ".", "handle", ":", "self", ".", "lvm", ".", "open", "(", ")", "self", ".", "__vgh", "=", "lvm_vg_open", "(", "self", ".", "lvm", ".", "handle", ",", "self", ".", "name", ",", "self", ".", "mode", ")", "if", "not", "bool", "(", "self", ".", "__vgh", ")", ":", "raise", "HandleError", "(", "\"Failed to initialize VG Handle.\"", ")" ]
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
[ "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" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L67-L80
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.close
def close(self): """ 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 """ if self.handle: cl = lvm_vg_close(self.handle) if cl != 0: raise HandleError("Failed to close VG handle after init check.") self.__vgh = None self.lvm.close()
python
def close(self): """ 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 """ if self.handle: cl = lvm_vg_close(self.handle) if cl != 0: raise HandleError("Failed to close VG handle after init check.") self.__vgh = None self.lvm.close()
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "handle", ":", "cl", "=", "lvm_vg_close", "(", "self", ".", "handle", ")", "if", "cl", "!=", "0", ":", "raise", "HandleError", "(", "\"Failed to close VG handle after init check.\"", ")", "self", ".", "__vgh", "=", "None", "self", ".", "lvm", ".", "close", "(", ")" ]
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
[ "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" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L82-L96
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.uuid
def uuid(self): """ Returns the volume group uuid. """ self.open() uuid = lvm_vg_get_uuid(self.handle) self.close() return uuid
python
def uuid(self): """ Returns the volume group uuid. """ self.open() uuid = lvm_vg_get_uuid(self.handle) self.close() return uuid
[ "def", "uuid", "(", "self", ")", ":", "self", ".", "open", "(", ")", "uuid", "=", "lvm_vg_get_uuid", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "uuid" ]
Returns the volume group uuid.
[ "Returns", "the", "volume", "group", "uuid", "." ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L120-L127
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.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
python
def extent_count(self): """ Returns the volume group extent count. """ self.open() count = lvm_vg_get_extent_count(self.handle) self.close() return count
[ "def", "extent_count", "(", "self", ")", ":", "self", ".", "open", "(", ")", "count", "=", "lvm_vg_get_extent_count", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "count" ]
Returns the volume group extent count.
[ "Returns", "the", "volume", "group", "extent", "count", "." ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L137-L144
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.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
python
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
[ "def", "free_extent_count", "(", "self", ")", ":", "self", ".", "open", "(", ")", "count", "=", "lvm_vg_get_free_extent_count", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "count" ]
Returns the volume group free extent count.
[ "Returns", "the", "volume", "group", "free", "extent", "count", "." ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L147-L154
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.pv_count
def pv_count(self): """ Returns the physical volume count. """ self.open() count = lvm_vg_get_pv_count(self.handle) self.close() return count
python
def pv_count(self): """ Returns the physical volume count. """ self.open() count = lvm_vg_get_pv_count(self.handle) self.close() return count
[ "def", "pv_count", "(", "self", ")", ":", "self", ".", "open", "(", ")", "count", "=", "lvm_vg_get_pv_count", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "count" ]
Returns the physical volume count.
[ "Returns", "the", "physical", "volume", "count", "." ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L157-L164
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.max_pv_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
python
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
[ "def", "max_pv_count", "(", "self", ")", ":", "self", ".", "open", "(", ")", "count", "=", "lvm_vg_get_max_pv", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "count" ]
Returns the maximum allowed physical volume count.
[ "Returns", "the", "maximum", "allowed", "physical", "volume", "count", "." ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L167-L174
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.max_lv_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
python
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
[ "def", "max_lv_count", "(", "self", ")", ":", "self", ".", "open", "(", ")", "count", "=", "lvm_vg_get_max_lv", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "count" ]
Returns the maximum allowed logical volume count.
[ "Returns", "the", "maximum", "allowed", "logical", "volume", "count", "." ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L177-L184
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.is_clustered
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)
python
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)
[ "def", "is_clustered", "(", "self", ")", ":", "self", ".", "open", "(", ")", "clust", "=", "lvm_vg_is_clustered", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "bool", "(", "clust", ")" ]
Returns True if the VG is clustered, False otherwise.
[ "Returns", "True", "if", "the", "VG", "is", "clustered", "False", "otherwise", "." ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L187-L194
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.is_exported
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)
python
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)
[ "def", "is_exported", "(", "self", ")", ":", "self", ".", "open", "(", ")", "exp", "=", "lvm_vg_is_exported", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "bool", "(", "exp", ")" ]
Returns True if the VG is exported, False otherwise.
[ "Returns", "True", "if", "the", "VG", "is", "exported", "False", "otherwise", "." ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L197-L204
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.is_partial
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)
python
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)
[ "def", "is_partial", "(", "self", ")", ":", "self", ".", "open", "(", ")", "part", "=", "lvm_vg_is_partial", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "bool", "(", "part", ")" ]
Returns True if the VG is partial, False otherwise.
[ "Returns", "True", "if", "the", "VG", "is", "partial", "False", "otherwise", "." ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L207-L214
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.sequence
def sequence(self): """ Returns the volume group sequence number. This number increases everytime the volume group is modified. """ self.open() seq = lvm_vg_get_seqno(self.handle) self.close() return seq
python
def sequence(self): """ Returns the volume group sequence number. This number increases everytime the volume group is modified. """ self.open() seq = lvm_vg_get_seqno(self.handle) self.close() return seq
[ "def", "sequence", "(", "self", ")", ":", "self", ".", "open", "(", ")", "seq", "=", "lvm_vg_get_seqno", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "seq" ]
Returns the volume group sequence number. This number increases everytime the volume group is modified.
[ "Returns", "the", "volume", "group", "sequence", "number", ".", "This", "number", "increases", "everytime", "the", "volume", "group", "is", "modified", "." ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L217-L225
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.size
def size(self, units="MiB"): """ Returns the volume group size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. """ self.open() size = lvm_vg_get_size(self.handle) self.close() return size_convert(size, units)
python
def size(self, units="MiB"): """ Returns the volume group size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. """ self.open() size = lvm_vg_get_size(self.handle) self.close() return size_convert(size, units)
[ "def", "size", "(", "self", ",", "units", "=", "\"MiB\"", ")", ":", "self", ".", "open", "(", ")", "size", "=", "lvm_vg_get_size", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "size_convert", "(", "size", ",", "units", ")" ]
Returns the volume group size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB.
[ "Returns", "the", "volume", "group", "size", "in", "the", "given", "units", ".", "Default", "units", "are", "MiB", "." ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L227-L238
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.free_size
def free_size(self, units="MiB"): """ 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. """ self.open() size = lvm_vg_get_free_size(self.handle) self.close() return size_convert(size, units)
python
def free_size(self, units="MiB"): """ 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. """ self.open() size = lvm_vg_get_free_size(self.handle) self.close() return size_convert(size, units)
[ "def", "free_size", "(", "self", ",", "units", "=", "\"MiB\"", ")", ":", "self", ".", "open", "(", ")", "size", "=", "lvm_vg_get_free_size", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "size_convert", "(", "size", ",", "units", ")" ]
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.
[ "Returns", "the", "volume", "group", "free", "size", "in", "the", "given", "units", ".", "Default", "units", "are", "MiB", "." ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L240-L251
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.extent_size
def extent_size(self, units="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. """ self.open() size = lvm_vg_get_extent_size(self.handle) self.close() return size_convert(size, units)
python
def extent_size(self, units="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. """ self.open() size = lvm_vg_get_extent_size(self.handle) self.close() return size_convert(size, units)
[ "def", "extent_size", "(", "self", ",", "units", "=", "\"MiB\"", ")", ":", "self", ".", "open", "(", ")", "size", "=", "lvm_vg_get_extent_size", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "size_convert", "(", "size", ",", "units", ")" ]
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.
[ "Returns", "the", "volume", "group", "extent", "size", "in", "the", "given", "units", ".", "Default", "units", "are", "MiB", "." ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L253-L264
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.add_pv
def add_pv(self, device): """ 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:* * ValueError, CommitError, HandleError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised. """ if not os.path.exists(device): raise ValueError("%s does not exist." % device) self.open() ext = lvm_vg_extend(self.handle, device) if ext != 0: self.close() raise CommitError("Failed to extend Volume Group.") self._commit() self.close() return PhysicalVolume(self, name=device)
python
def add_pv(self, device): """ 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:* * ValueError, CommitError, HandleError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised. """ if not os.path.exists(device): raise ValueError("%s does not exist." % device) self.open() ext = lvm_vg_extend(self.handle, device) if ext != 0: self.close() raise CommitError("Failed to extend Volume Group.") self._commit() self.close() return PhysicalVolume(self, name=device)
[ "def", "add_pv", "(", "self", ",", "device", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "device", ")", ":", "raise", "ValueError", "(", "\"%s does not exist.\"", "%", "device", ")", "self", ".", "open", "(", ")", "ext", "=", "lvm_vg_extend", "(", "self", ".", "handle", ",", "device", ")", "if", "ext", "!=", "0", ":", "self", ".", "close", "(", ")", "raise", "CommitError", "(", "\"Failed to extend Volume Group.\"", ")", "self", ".", "_commit", "(", ")", "self", ".", "close", "(", ")", "return", "PhysicalVolume", "(", "self", ",", "name", "=", "device", ")" ]
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:* * ValueError, CommitError, HandleError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised.
[ "Initializes", "a", "device", "as", "a", "physical", "volume", "and", "adds", "it", "to", "the", "volume", "group", "::" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L272-L304
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.get_pv
def get_pv(self, device): """ 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, HandleError """ if not os.path.exists(device): raise ValueError("%s does not exist." % device) return PhysicalVolume(self, name=device)
python
def get_pv(self, device): """ 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, HandleError """ if not os.path.exists(device): raise ValueError("%s does not exist." % device) return PhysicalVolume(self, name=device)
[ "def", "get_pv", "(", "self", ",", "device", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "device", ")", ":", "raise", "ValueError", "(", "\"%s does not exist.\"", "%", "device", ")", "return", "PhysicalVolume", "(", "self", ",", "name", "=", "device", ")" ]
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, HandleError
[ "Returns", "the", "physical", "volume", "associated", "with", "the", "given", "device", "::" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L306-L326
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.remove_pv
def remove_pv(self, pv): """ 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:* * HandleError, CommitError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised. Also, when removing the last physical volume, the volume group is deleted in lvm, leaving the instance with a null handle. """ name = pv.name self.open() rm = lvm_vg_reduce(self.handle, name) if rm != 0: self.close() raise CommitError("Failed to remove %s." % name) self._commit() self.close()
python
def remove_pv(self, pv): """ 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:* * HandleError, CommitError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised. Also, when removing the last physical volume, the volume group is deleted in lvm, leaving the instance with a null handle. """ name = pv.name self.open() rm = lvm_vg_reduce(self.handle, name) if rm != 0: self.close() raise CommitError("Failed to remove %s." % name) self._commit() self.close()
[ "def", "remove_pv", "(", "self", ",", "pv", ")", ":", "name", "=", "pv", ".", "name", "self", ".", "open", "(", ")", "rm", "=", "lvm_vg_reduce", "(", "self", ".", "handle", ",", "name", ")", "if", "rm", "!=", "0", ":", "self", ".", "close", "(", ")", "raise", "CommitError", "(", "\"Failed to remove %s.\"", "%", "name", ")", "self", ".", "_commit", "(", ")", "self", ".", "close", "(", ")" ]
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:* * HandleError, CommitError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised. Also, when removing the last physical volume, the volume group is deleted in lvm, leaving the instance with a null handle.
[ "Removes", "a", "physical", "volume", "from", "the", "volume", "group", "::" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L348-L380
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.pvscan
def pvscan(self): """ 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 """ self.open() pv_list = [] pv_handles = lvm_vg_list_pvs(self.handle) if not bool(pv_handles): return pv_list pvh = dm_list_first(pv_handles) while pvh: c = cast(pvh, POINTER(lvm_pv_list)) pv = PhysicalVolume(self, pvh=c.contents.pv) pv_list.append(pv) if dm_list_end(pv_handles, pvh): # end of linked list break pvh = dm_list_next(pv_handles, pvh) self.close() return pv_list
python
def pvscan(self): """ 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 """ self.open() pv_list = [] pv_handles = lvm_vg_list_pvs(self.handle) if not bool(pv_handles): return pv_list pvh = dm_list_first(pv_handles) while pvh: c = cast(pvh, POINTER(lvm_pv_list)) pv = PhysicalVolume(self, pvh=c.contents.pv) pv_list.append(pv) if dm_list_end(pv_handles, pvh): # end of linked list break pvh = dm_list_next(pv_handles, pvh) self.close() return pv_list
[ "def", "pvscan", "(", "self", ")", ":", "self", ".", "open", "(", ")", "pv_list", "=", "[", "]", "pv_handles", "=", "lvm_vg_list_pvs", "(", "self", ".", "handle", ")", "if", "not", "bool", "(", "pv_handles", ")", ":", "return", "pv_list", "pvh", "=", "dm_list_first", "(", "pv_handles", ")", "while", "pvh", ":", "c", "=", "cast", "(", "pvh", ",", "POINTER", "(", "lvm_pv_list", ")", ")", "pv", "=", "PhysicalVolume", "(", "self", ",", "pvh", "=", "c", ".", "contents", ".", "pv", ")", "pv_list", ".", "append", "(", "pv", ")", "if", "dm_list_end", "(", "pv_handles", ",", "pvh", ")", ":", "# end of linked list", "break", "pvh", "=", "dm_list_next", "(", "pv_handles", ",", "pvh", ")", "self", ".", "close", "(", ")", "return", "pv_list" ]
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
[ "Probes", "the", "volume", "group", "for", "physical", "volumes", "and", "returns", "a", "list", "of", "PhysicalVolume", "instances", "::" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L382-L412
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.lvscan
def lvscan(self): """ 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 """ self.open() lv_list = [] lv_handles = lvm_vg_list_lvs(self.handle) if not bool(lv_handles): return lv_list lvh = dm_list_first(lv_handles) while lvh: c = cast(lvh, POINTER(lvm_lv_list)) lv = LogicalVolume(self, lvh=c.contents.lv) lv_list.append(lv) if dm_list_end(lv_handles, lvh): # end of linked list break lvh = dm_list_next(lv_handles, lvh) self.close() return lv_list
python
def lvscan(self): """ 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 """ self.open() lv_list = [] lv_handles = lvm_vg_list_lvs(self.handle) if not bool(lv_handles): return lv_list lvh = dm_list_first(lv_handles) while lvh: c = cast(lvh, POINTER(lvm_lv_list)) lv = LogicalVolume(self, lvh=c.contents.lv) lv_list.append(lv) if dm_list_end(lv_handles, lvh): # end of linked list break lvh = dm_list_next(lv_handles, lvh) self.close() return lv_list
[ "def", "lvscan", "(", "self", ")", ":", "self", ".", "open", "(", ")", "lv_list", "=", "[", "]", "lv_handles", "=", "lvm_vg_list_lvs", "(", "self", ".", "handle", ")", "if", "not", "bool", "(", "lv_handles", ")", ":", "return", "lv_list", "lvh", "=", "dm_list_first", "(", "lv_handles", ")", "while", "lvh", ":", "c", "=", "cast", "(", "lvh", ",", "POINTER", "(", "lvm_lv_list", ")", ")", "lv", "=", "LogicalVolume", "(", "self", ",", "lvh", "=", "c", ".", "contents", ".", "lv", ")", "lv_list", ".", "append", "(", "lv", ")", "if", "dm_list_end", "(", "lv_handles", ",", "lvh", ")", ":", "# end of linked list", "break", "lvh", "=", "dm_list_next", "(", "lv_handles", ",", "lvh", ")", "self", ".", "close", "(", ")", "return", "lv_list" ]
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
[ "Probes", "the", "volume", "group", "for", "logical", "volumes", "and", "returns", "a", "list", "of", "LogicalVolume", "instances", "::" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L414-L444
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.create_lv
def create_lv(self, name, length, units): """ 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 desired logical volume name. * length (int): The desired size. * units (str): The size units. *Raises:* * HandleError, CommitError, ValueError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised. """ if units != "%": size = size_units[units] * length else: if not (0 < length <= 100) or type(length) is float: raise ValueError("Length not supported.") size = (self.size("B") / 100) * length self.open() lvh = lvm_vg_create_lv_linear(self.handle, name, c_ulonglong(size)) if not bool(lvh): self.close() raise CommitError("Failed to create LV.") lv = LogicalVolume(self, lvh=lvh) self.close() return lv
python
def create_lv(self, name, length, units): """ 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 desired logical volume name. * length (int): The desired size. * units (str): The size units. *Raises:* * HandleError, CommitError, ValueError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised. """ if units != "%": size = size_units[units] * length else: if not (0 < length <= 100) or type(length) is float: raise ValueError("Length not supported.") size = (self.size("B") / 100) * length self.open() lvh = lvm_vg_create_lv_linear(self.handle, name, c_ulonglong(size)) if not bool(lvh): self.close() raise CommitError("Failed to create LV.") lv = LogicalVolume(self, lvh=lvh) self.close() return lv
[ "def", "create_lv", "(", "self", ",", "name", ",", "length", ",", "units", ")", ":", "if", "units", "!=", "\"%\"", ":", "size", "=", "size_units", "[", "units", "]", "*", "length", "else", ":", "if", "not", "(", "0", "<", "length", "<=", "100", ")", "or", "type", "(", "length", ")", "is", "float", ":", "raise", "ValueError", "(", "\"Length not supported.\"", ")", "size", "=", "(", "self", ".", "size", "(", "\"B\"", ")", "/", "100", ")", "*", "length", "self", ".", "open", "(", ")", "lvh", "=", "lvm_vg_create_lv_linear", "(", "self", ".", "handle", ",", "name", ",", "c_ulonglong", "(", "size", ")", ")", "if", "not", "bool", "(", "lvh", ")", ":", "self", ".", "close", "(", ")", "raise", "CommitError", "(", "\"Failed to create LV.\"", ")", "lv", "=", "LogicalVolume", "(", "self", ",", "lvh", "=", "lvh", ")", "self", ".", "close", "(", ")", "return", "lv" ]
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 desired logical volume name. * length (int): The desired size. * units (str): The size units. *Raises:* * HandleError, CommitError, ValueError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised.
[ "Creates", "a", "logical", "volume", "and", "returns", "the", "LogicalVolume", "instance", "associated", "with", "the", "lv_t", "handle", "::" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L446-L485
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.remove_lv
def remove_lv(self, lv): """ 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:* * HandleError, CommitError, ValueError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised. """ lv.open() rm = lvm_vg_remove_lv(lv.handle) lv.close() if rm != 0: raise CommitError("Failed to remove LV.")
python
def remove_lv(self, lv): """ 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:* * HandleError, CommitError, ValueError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised. """ lv.open() rm = lvm_vg_remove_lv(lv.handle) lv.close() if rm != 0: raise CommitError("Failed to remove LV.")
[ "def", "remove_lv", "(", "self", ",", "lv", ")", ":", "lv", ".", "open", "(", ")", "rm", "=", "lvm_vg_remove_lv", "(", "lv", ".", "handle", ")", "lv", ".", "close", "(", ")", "if", "rm", "!=", "0", ":", "raise", "CommitError", "(", "\"Failed to remove LV.\"", ")" ]
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:* * HandleError, CommitError, ValueError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised.
[ "Removes", "a", "logical", "volume", "from", "the", "volume", "group", "::" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L487-L515
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.remove_all_lvs
def remove_all_lvs(self): """ Removes all logical volumes from the volume group. *Raises:* * HandleError, CommitError """ lvs = self.lvscan() for lv in lvs: self.remove_lv(lv)
python
def remove_all_lvs(self): """ Removes all logical volumes from the volume group. *Raises:* * HandleError, CommitError """ lvs = self.lvscan() for lv in lvs: self.remove_lv(lv)
[ "def", "remove_all_lvs", "(", "self", ")", ":", "lvs", "=", "self", ".", "lvscan", "(", ")", "for", "lv", "in", "lvs", ":", "self", ".", "remove_lv", "(", "lv", ")" ]
Removes all logical volumes from the volume group. *Raises:* * HandleError, CommitError
[ "Removes", "all", "logical", "volumes", "from", "the", "volume", "group", "." ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L517-L527
train
xzased/lvm2py
lvm2py/vg.py
VolumeGroup.set_extent_size
def set_extent_size(self, length, units): """ 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 ("MiB", "GiB", etc...). *Raises:* * HandleError, CommitError, KeyError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised. """ size = length * size_units[units] self.open() ext = lvm_vg_set_extent_size(self.handle, c_ulong(size)) self._commit() self.close() if ext != 0: raise CommitError("Failed to set extent size.")
python
def set_extent_size(self, length, units): """ 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 ("MiB", "GiB", etc...). *Raises:* * HandleError, CommitError, KeyError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised. """ size = length * size_units[units] self.open() ext = lvm_vg_set_extent_size(self.handle, c_ulong(size)) self._commit() self.close() if ext != 0: raise CommitError("Failed to set extent size.")
[ "def", "set_extent_size", "(", "self", ",", "length", ",", "units", ")", ":", "size", "=", "length", "*", "size_units", "[", "units", "]", "self", ".", "open", "(", ")", "ext", "=", "lvm_vg_set_extent_size", "(", "self", ".", "handle", ",", "c_ulong", "(", "size", ")", ")", "self", ".", "_commit", "(", ")", "self", ".", "close", "(", ")", "if", "ext", "!=", "0", ":", "raise", "CommitError", "(", "\"Failed to set extent size.\"", ")" ]
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 ("MiB", "GiB", etc...). *Raises:* * HandleError, CommitError, KeyError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised.
[ "Sets", "the", "volume", "group", "extent", "size", "in", "the", "given", "units", "::" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L541-L571
train
davidmcclure/textplot
textplot/matrix.py
Matrix.set_pair
def set_pair(self, term1, term2, value, **kwargs): """ Set the value for a pair of terms. Args: term1 (str) term2 (str) value (mixed) """ key = self.key(term1, term2) self.keys.update([term1, term2]) self.pairs[key] = value
python
def set_pair(self, term1, term2, value, **kwargs): """ Set the value for a pair of terms. Args: term1 (str) term2 (str) value (mixed) """ key = self.key(term1, term2) self.keys.update([term1, term2]) self.pairs[key] = value
[ "def", "set_pair", "(", "self", ",", "term1", ",", "term2", ",", "value", ",", "*", "*", "kwargs", ")", ":", "key", "=", "self", ".", "key", "(", "term1", ",", "term2", ")", "self", ".", "keys", ".", "update", "(", "[", "term1", ",", "term2", "]", ")", "self", ".", "pairs", "[", "key", "]", "=", "value" ]
Set the value for a pair of terms. Args: term1 (str) term2 (str) value (mixed)
[ "Set", "the", "value", "for", "a", "pair", "of", "terms", "." ]
889b949a637d99097ecec44ed4bfee53b1964dee
https://github.com/davidmcclure/textplot/blob/889b949a637d99097ecec44ed4bfee53b1964dee/textplot/matrix.py#L50-L63
train
davidmcclure/textplot
textplot/matrix.py
Matrix.get_pair
def get_pair(self, term1, term2): """ Get the value for a pair of terms. Args: term1 (str) term2 (str) Returns: The stored value. """ key = self.key(term1, term2) return self.pairs.get(key, None)
python
def get_pair(self, term1, term2): """ Get the value for a pair of terms. Args: term1 (str) term2 (str) Returns: The stored value. """ key = self.key(term1, term2) return self.pairs.get(key, None)
[ "def", "get_pair", "(", "self", ",", "term1", ",", "term2", ")", ":", "key", "=", "self", ".", "key", "(", "term1", ",", "term2", ")", "return", "self", ".", "pairs", ".", "get", "(", "key", ",", "None", ")" ]
Get the value for a pair of terms. Args: term1 (str) term2 (str) Returns: The stored value.
[ "Get", "the", "value", "for", "a", "pair", "of", "terms", "." ]
889b949a637d99097ecec44ed4bfee53b1964dee
https://github.com/davidmcclure/textplot/blob/889b949a637d99097ecec44ed4bfee53b1964dee/textplot/matrix.py#L66-L80
train
davidmcclure/textplot
textplot/matrix.py
Matrix.index
def index(self, text, terms=None, **kwargs): """ Index all term pair distances. Args: text (Text): The source text. terms (list): Terms to index. """ self.clear() # By default, use all terms. terms = terms or text.terms.keys() pairs = combinations(terms, 2) count = comb(len(terms), 2) for t1, t2 in bar(pairs, expected_size=count, every=1000): # Set the Bray-Curtis distance. score = text.score_braycurtis(t1, t2, **kwargs) self.set_pair(t1, t2, score)
python
def index(self, text, terms=None, **kwargs): """ Index all term pair distances. Args: text (Text): The source text. terms (list): Terms to index. """ self.clear() # By default, use all terms. terms = terms or text.terms.keys() pairs = combinations(terms, 2) count = comb(len(terms), 2) for t1, t2 in bar(pairs, expected_size=count, every=1000): # Set the Bray-Curtis distance. score = text.score_braycurtis(t1, t2, **kwargs) self.set_pair(t1, t2, score)
[ "def", "index", "(", "self", ",", "text", ",", "terms", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "clear", "(", ")", "# By default, use all terms.", "terms", "=", "terms", "or", "text", ".", "terms", ".", "keys", "(", ")", "pairs", "=", "combinations", "(", "terms", ",", "2", ")", "count", "=", "comb", "(", "len", "(", "terms", ")", ",", "2", ")", "for", "t1", ",", "t2", "in", "bar", "(", "pairs", ",", "expected_size", "=", "count", ",", "every", "=", "1000", ")", ":", "# Set the Bray-Curtis distance.", "score", "=", "text", ".", "score_braycurtis", "(", "t1", ",", "t2", ",", "*", "*", "kwargs", ")", "self", ".", "set_pair", "(", "t1", ",", "t2", ",", "score", ")" ]
Index all term pair distances. Args: text (Text): The source text. terms (list): Terms to index.
[ "Index", "all", "term", "pair", "distances", "." ]
889b949a637d99097ecec44ed4bfee53b1964dee
https://github.com/davidmcclure/textplot/blob/889b949a637d99097ecec44ed4bfee53b1964dee/textplot/matrix.py#L83-L105
train
davidmcclure/textplot
textplot/matrix.py
Matrix.anchored_pairs
def anchored_pairs(self, anchor): """ Get distances between an anchor term and all other terms. Args: anchor (str): The anchor term. Returns: OrderedDict: The distances, in descending order. """ pairs = OrderedDict() for term in self.keys: score = self.get_pair(anchor, term) if score: pairs[term] = score return utils.sort_dict(pairs)
python
def anchored_pairs(self, anchor): """ Get distances between an anchor term and all other terms. Args: anchor (str): The anchor term. Returns: OrderedDict: The distances, in descending order. """ pairs = OrderedDict() for term in self.keys: score = self.get_pair(anchor, term) if score: pairs[term] = score return utils.sort_dict(pairs)
[ "def", "anchored_pairs", "(", "self", ",", "anchor", ")", ":", "pairs", "=", "OrderedDict", "(", ")", "for", "term", "in", "self", ".", "keys", ":", "score", "=", "self", ".", "get_pair", "(", "anchor", ",", "term", ")", "if", "score", ":", "pairs", "[", "term", "]", "=", "score", "return", "utils", ".", "sort_dict", "(", "pairs", ")" ]
Get distances between an anchor term and all other terms. Args: anchor (str): The anchor term. Returns: OrderedDict: The distances, in descending order.
[ "Get", "distances", "between", "an", "anchor", "term", "and", "all", "other", "terms", "." ]
889b949a637d99097ecec44ed4bfee53b1964dee
https://github.com/davidmcclure/textplot/blob/889b949a637d99097ecec44ed4bfee53b1964dee/textplot/matrix.py#L108-L126
train
magarcia/python-x256
x256/x256.py
from_rgb
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 best or d <= best['distance']): best = {'distance': d, 'index': index} if 'index' in best: return best['index'] else: return 1
python
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 best or d <= best['distance']): best = {'distance': d, 'index': index} if 'index' in best: return best['index'] else: return 1
[ "def", "from_rgb", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "c", "=", "r", "if", "isinstance", "(", "r", ",", "list", ")", "else", "[", "r", ",", "g", ",", "b", "]", "best", "=", "{", "}", "for", "index", ",", "item", "in", "enumerate", "(", "colors", ")", ":", "d", "=", "__distance", "(", "item", ",", "c", ")", "if", "(", "not", "best", "or", "d", "<=", "best", "[", "'distance'", "]", ")", ":", "best", "=", "{", "'distance'", ":", "d", ",", "'index'", ":", "index", "}", "if", "'index'", "in", "best", ":", "return", "best", "[", "'index'", "]", "else", ":", "return", "1" ]
Return the nearest xterm 256 color code from rgb input.
[ "Return", "the", "nearest", "xterm", "256", "color", "code", "from", "rgb", "input", "." ]
d4bc9f763a34eb15cce4f23a2e09eff3adc8a032
https://github.com/magarcia/python-x256/blob/d4bc9f763a34eb15cce4f23a2e09eff3adc8a032/x256/x256.py#L283-L298
train
magarcia/python-x256
x256/x256.py
entry
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', help='Value for the action', ) parsed = parser.parse_args() if parsed.action != "from_hex": try: parsed.value = int(parsed.value) except ValueError: raise argparse.ArgumentError( "Value for this action should be an integer", ) print(globals()[parsed.action](parsed.value))
python
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', help='Value for the action', ) parsed = parser.parse_args() if parsed.action != "from_hex": try: parsed.value = int(parsed.value) except ValueError: raise argparse.ArgumentError( "Value for this action should be an integer", ) print(globals()[parsed.action](parsed.value))
[ "def", "entry", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'action'", ",", "help", "=", "'Action to take'", ",", "choices", "=", "[", "'from_hex'", ",", "'to_rgb'", ",", "'to_hex'", "]", ",", ")", "parser", ".", "add_argument", "(", "'value'", ",", "help", "=", "'Value for the action'", ",", ")", "parsed", "=", "parser", ".", "parse_args", "(", ")", "if", "parsed", ".", "action", "!=", "\"from_hex\"", ":", "try", ":", "parsed", ".", "value", "=", "int", "(", "parsed", ".", "value", ")", "except", "ValueError", ":", "raise", "argparse", ".", "ArgumentError", "(", "\"Value for this action should be an integer\"", ",", ")", "print", "(", "globals", "(", ")", "[", "parsed", ".", "action", "]", "(", "parsed", ".", "value", ")", ")" ]
Parse command line arguments and run utilities.
[ "Parse", "command", "line", "arguments", "and", "run", "utilities", "." ]
d4bc9f763a34eb15cce4f23a2e09eff3adc8a032
https://github.com/magarcia/python-x256/blob/d4bc9f763a34eb15cce4f23a2e09eff3adc8a032/x256/x256.py#L321-L339
train
twisted/axiom
axiom/listversions.py
makeSoftwareVersion
def makeSoftwareVersion(store, version, systemVersion): """ Return the SoftwareVersion object from store corresponding to the version object, creating it if it doesn't already exist. """ return store.findOrCreate(SoftwareVersion, systemVersion=systemVersion, package=unicode(version.package), version=unicode(version.short()), major=version.major, minor=version.minor, micro=version.micro)
python
def makeSoftwareVersion(store, version, systemVersion): """ Return the SoftwareVersion object from store corresponding to the version object, creating it if it doesn't already exist. """ return store.findOrCreate(SoftwareVersion, systemVersion=systemVersion, package=unicode(version.package), version=unicode(version.short()), major=version.major, minor=version.minor, micro=version.micro)
[ "def", "makeSoftwareVersion", "(", "store", ",", "version", ",", "systemVersion", ")", ":", "return", "store", ".", "findOrCreate", "(", "SoftwareVersion", ",", "systemVersion", "=", "systemVersion", ",", "package", "=", "unicode", "(", "version", ".", "package", ")", ",", "version", "=", "unicode", "(", "version", ".", "short", "(", ")", ")", ",", "major", "=", "version", ".", "major", ",", "minor", "=", "version", ".", "minor", ",", "micro", "=", "version", ".", "micro", ")" ]
Return the SoftwareVersion object from store corresponding to the version object, creating it if it doesn't already exist.
[ "Return", "the", "SoftwareVersion", "object", "from", "store", "corresponding", "to", "the", "version", "object", "creating", "it", "if", "it", "doesn", "t", "already", "exist", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/listversions.py#L91-L102
train
twisted/axiom
axiom/listversions.py
listVersionHistory
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]
python
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]
[ "def", "listVersionHistory", "(", "store", ")", ":", "q", "=", "store", ".", "query", "(", "SystemVersion", ",", "sort", "=", "SystemVersion", ".", "creation", ".", "descending", ")", "return", "[", "sv", ".", "longWindedRepr", "(", ")", "for", "sv", "in", "q", "]" ]
List the software package version history of store.
[ "List", "the", "software", "package", "version", "history", "of", "store", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/listversions.py#L106-L111
train
twisted/axiom
axiom/listversions.py
checkSystemVersion
def checkSystemVersion(s, versions=None): """ 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. """ if versions is None: versions = getSystemVersions() currentVersionMap = dict([(v.package, v) for v in versions]) mostRecentSystemVersion = s.findFirst(SystemVersion, sort=SystemVersion.creation.descending) mostRecentVersionMap = dict([(v.package, v.asVersion()) for v in s.query(SoftwareVersion, (SoftwareVersion.systemVersion == mostRecentSystemVersion))]) if mostRecentVersionMap != currentVersionMap: currentSystemVersion = SystemVersion(store=s, creation=Time()) for v in currentVersionMap.itervalues(): makeSoftwareVersion(s, v, currentSystemVersion)
python
def checkSystemVersion(s, versions=None): """ 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. """ if versions is None: versions = getSystemVersions() currentVersionMap = dict([(v.package, v) for v in versions]) mostRecentSystemVersion = s.findFirst(SystemVersion, sort=SystemVersion.creation.descending) mostRecentVersionMap = dict([(v.package, v.asVersion()) for v in s.query(SoftwareVersion, (SoftwareVersion.systemVersion == mostRecentSystemVersion))]) if mostRecentVersionMap != currentVersionMap: currentSystemVersion = SystemVersion(store=s, creation=Time()) for v in currentVersionMap.itervalues(): makeSoftwareVersion(s, v, currentSystemVersion)
[ "def", "checkSystemVersion", "(", "s", ",", "versions", "=", "None", ")", ":", "if", "versions", "is", "None", ":", "versions", "=", "getSystemVersions", "(", ")", "currentVersionMap", "=", "dict", "(", "[", "(", "v", ".", "package", ",", "v", ")", "for", "v", "in", "versions", "]", ")", "mostRecentSystemVersion", "=", "s", ".", "findFirst", "(", "SystemVersion", ",", "sort", "=", "SystemVersion", ".", "creation", ".", "descending", ")", "mostRecentVersionMap", "=", "dict", "(", "[", "(", "v", ".", "package", ",", "v", ".", "asVersion", "(", ")", ")", "for", "v", "in", "s", ".", "query", "(", "SoftwareVersion", ",", "(", "SoftwareVersion", ".", "systemVersion", "==", "mostRecentSystemVersion", ")", ")", "]", ")", "if", "mostRecentVersionMap", "!=", "currentVersionMap", ":", "currentSystemVersion", "=", "SystemVersion", "(", "store", "=", "s", ",", "creation", "=", "Time", "(", ")", ")", "for", "v", "in", "currentVersionMap", ".", "itervalues", "(", ")", ":", "makeSoftwareVersion", "(", "s", ",", "v", ",", "currentSystemVersion", ")" ]
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.
[ "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", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/listversions.py#L121-L142
train
twisted/axiom
axiom/listversions.py
SoftwareVersion.asVersion
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)
python
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)
[ "def", "asVersion", "(", "self", ")", ":", "return", "versions", ".", "Version", "(", "self", ".", "package", ",", "self", ".", "major", ",", "self", ".", "minor", ",", "self", ".", "micro", ")" ]
Convert the version data in this item to a L{twisted.python.versions.Version}.
[ "Convert", "the", "version", "data", "in", "this", "item", "to", "a", "L", "{", "twisted", ".", "python", ".", "versions", ".", "Version", "}", "." ]
7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68
https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/listversions.py#L78-L83
train
swharden/PyOriginTools
PyOriginTools/workbook.py
SHEET.reset
def reset(self): """clears all columns""" self.colNames,self.colDesc,self.colUnits,self.colComments,\ self.colTypes,self.colData=[],[],[],[],[],[]
python
def reset(self): """clears all columns""" self.colNames,self.colDesc,self.colUnits,self.colComments,\ self.colTypes,self.colData=[],[],[],[],[],[]
[ "def", "reset", "(", "self", ")", ":", "self", ".", "colNames", ",", "self", ".", "colDesc", ",", "self", ".", "colUnits", ",", "self", ".", "colComments", ",", "self", ".", "colTypes", ",", "self", ".", "colData", "=", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]" ]
clears all columns
[ "clears", "all", "columns" ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/workbook.py#L42-L45
train
swharden/PyOriginTools
PyOriginTools/workbook.py
SHEET.colAdd
def colAdd(self,name="",desc="",unit="",comment="",coltype=0,data=[],pos=None): """ column types: 0: Y 1: Disregard 2: Y Error 3: X 4: Label 5: Z 6: X Error """ if pos is None: pos=len(self.colNames) self.colNames.insert(pos,name) self.colDesc.insert(pos,desc) self.colUnits.insert(pos,unit) self.colComments.insert(pos,comment) self.colTypes.insert(pos,coltype) self.colData.insert(pos,data) return
python
def colAdd(self,name="",desc="",unit="",comment="",coltype=0,data=[],pos=None): """ column types: 0: Y 1: Disregard 2: Y Error 3: X 4: Label 5: Z 6: X Error """ if pos is None: pos=len(self.colNames) self.colNames.insert(pos,name) self.colDesc.insert(pos,desc) self.colUnits.insert(pos,unit) self.colComments.insert(pos,comment) self.colTypes.insert(pos,coltype) self.colData.insert(pos,data) return
[ "def", "colAdd", "(", "self", ",", "name", "=", "\"\"", ",", "desc", "=", "\"\"", ",", "unit", "=", "\"\"", ",", "comment", "=", "\"\"", ",", "coltype", "=", "0", ",", "data", "=", "[", "]", ",", "pos", "=", "None", ")", ":", "if", "pos", "is", "None", ":", "pos", "=", "len", "(", "self", ".", "colNames", ")", "self", ".", "colNames", ".", "insert", "(", "pos", ",", "name", ")", "self", ".", "colDesc", ".", "insert", "(", "pos", ",", "desc", ")", "self", ".", "colUnits", ".", "insert", "(", "pos", ",", "unit", ")", "self", ".", "colComments", ".", "insert", "(", "pos", ",", "comment", ")", "self", ".", "colTypes", ".", "insert", "(", "pos", ",", "coltype", ")", "self", ".", "colData", ".", "insert", "(", "pos", ",", "data", ")", "return" ]
column types: 0: Y 1: Disregard 2: Y Error 3: X 4: Label 5: Z 6: X Error
[ "column", "types", ":", "0", ":", "Y", "1", ":", "Disregard", "2", ":", "Y", "Error", "3", ":", "X", "4", ":", "Label", "5", ":", "Z", "6", ":", "X", "Error" ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/workbook.py#L49-L68
train
swharden/PyOriginTools
PyOriginTools/workbook.py
SHEET.colDelete
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) self.colUnits.pop(colI) self.colComments.pop(colI) self.colTypes.pop(colI) self.colData.pop(colI) return
python
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) self.colUnits.pop(colI) self.colComments.pop(colI) self.colTypes.pop(colI) self.colData.pop(colI) return
[ "def", "colDelete", "(", "self", ",", "colI", "=", "-", "1", ")", ":", "# print(\"DELETING COLUMN: [%d] %s\"%(colI,self.colDesc[colI]))", "self", ".", "colNames", ".", "pop", "(", "colI", ")", "self", ".", "colDesc", ".", "pop", "(", "colI", ")", "self", ".", "colUnits", ".", "pop", "(", "colI", ")", "self", ".", "colComments", ".", "pop", "(", "colI", ")", "self", ".", "colTypes", ".", "pop", "(", "colI", ")", "self", ".", "colData", ".", "pop", "(", "colI", ")", "return" ]
delete a column at a single index. Negative numbers count from the end.
[ "delete", "a", "column", "at", "a", "single", "index", ".", "Negative", "numbers", "count", "from", "the", "end", "." ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/workbook.py#L70-L79
train
swharden/PyOriginTools
PyOriginTools/workbook.py
SHEET.onex
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)
python
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)
[ "def", "onex", "(", "self", ")", ":", "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", ")" ]
delete all X columns except the first one.
[ "delete", "all", "X", "columns", "except", "the", "first", "one", "." ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/workbook.py#L81-L88
train
swharden/PyOriginTools
PyOriginTools/workbook.py
SHEET.alignXY
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.colTypes[x]==0] xCols,yCols=np.array(xCols),np.array(yCols) for xCol in xCols: xVals.extend(self.colData[xCol]) #xVals=list(np.round(set(xVals),5)) xVals=list(sorted(list(set(xVals)))) # prepare our new aligned dataset newData=np.empty(len(xVals)*self.nCols) newData[:]=np.nan newData=newData.reshape(len(xVals),self.nCols) oldData=np.round(self.data,5) # do the alignment for xCol in xCols: columnsToShift=[xCol] for col in range(xCol+1,self.nCols): if self.colTypes[col]==0: columnsToShift.append(col) else: break # determine how to move each row for row in range(len(oldData)): oldXvalue=oldData[row,xCol] if oldXvalue in xVals: newRow=xVals.index(oldXvalue) newData[newRow,columnsToShift]=oldData[row,columnsToShift] # commit changes newData[:,0]=xVals self.data=newData self.onex()
python
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.colTypes[x]==0] xCols,yCols=np.array(xCols),np.array(yCols) for xCol in xCols: xVals.extend(self.colData[xCol]) #xVals=list(np.round(set(xVals),5)) xVals=list(sorted(list(set(xVals)))) # prepare our new aligned dataset newData=np.empty(len(xVals)*self.nCols) newData[:]=np.nan newData=newData.reshape(len(xVals),self.nCols) oldData=np.round(self.data,5) # do the alignment for xCol in xCols: columnsToShift=[xCol] for col in range(xCol+1,self.nCols): if self.colTypes[col]==0: columnsToShift.append(col) else: break # determine how to move each row for row in range(len(oldData)): oldXvalue=oldData[row,xCol] if oldXvalue in xVals: newRow=xVals.index(oldXvalue) newData[newRow,columnsToShift]=oldData[row,columnsToShift] # commit changes newData[:,0]=xVals self.data=newData self.onex()
[ "def", "alignXY", "(", "self", ")", ":", "# 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", ".", "colTypes", "[", "x", "]", "==", "0", "]", "xCols", ",", "yCols", "=", "np", ".", "array", "(", "xCols", ")", ",", "np", ".", "array", "(", "yCols", ")", "for", "xCol", "in", "xCols", ":", "xVals", ".", "extend", "(", "self", ".", "colData", "[", "xCol", "]", ")", "#xVals=list(np.round(set(xVals),5))", "xVals", "=", "list", "(", "sorted", "(", "list", "(", "set", "(", "xVals", ")", ")", ")", ")", "# prepare our new aligned dataset", "newData", "=", "np", ".", "empty", "(", "len", "(", "xVals", ")", "*", "self", ".", "nCols", ")", "newData", "[", ":", "]", "=", "np", ".", "nan", "newData", "=", "newData", ".", "reshape", "(", "len", "(", "xVals", ")", ",", "self", ".", "nCols", ")", "oldData", "=", "np", ".", "round", "(", "self", ".", "data", ",", "5", ")", "# do the alignment", "for", "xCol", "in", "xCols", ":", "columnsToShift", "=", "[", "xCol", "]", "for", "col", "in", "range", "(", "xCol", "+", "1", ",", "self", ".", "nCols", ")", ":", "if", "self", ".", "colTypes", "[", "col", "]", "==", "0", ":", "columnsToShift", ".", "append", "(", "col", ")", "else", ":", "break", "# determine how to move each row", "for", "row", "in", "range", "(", "len", "(", "oldData", ")", ")", ":", "oldXvalue", "=", "oldData", "[", "row", ",", "xCol", "]", "if", "oldXvalue", "in", "xVals", ":", "newRow", "=", "xVals", ".", "index", "(", "oldXvalue", ")", "newData", "[", "newRow", ",", "columnsToShift", "]", "=", "oldData", "[", "row", ",", "columnsToShift", "]", "# commit changes", "newData", "[", ":", ",", "0", "]", "=", "xVals", "self", ".", "data", "=", "newData", "self", ".", "onex", "(", ")" ]
aligns XY pairs (or XYYY etc) by X value.
[ "aligns", "XY", "pairs", "(", "or", "XYYY", "etc", ")", "by", "X", "value", "." ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/workbook.py#L90-L127
train
swharden/PyOriginTools
PyOriginTools/workbook.py
SHEET.wiggle
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
python
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
[ "def", "wiggle", "(", "self", ",", "noiseLevel", "=", ".1", ")", ":", "noise", "=", "(", "np", ".", "random", ".", "rand", "(", "*", "self", ".", "data", ".", "shape", ")", ")", "-", ".5", "self", ".", "data", "=", "self", ".", "data", "+", "noise", "*", "noiseLevel" ]
Slightly changes value of every cell in the worksheet. Used for testing.
[ "Slightly", "changes", "value", "of", "every", "cell", "in", "the", "worksheet", ".", "Used", "for", "testing", "." ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/workbook.py#L131-L134
train
swharden/PyOriginTools
PyOriginTools/workbook.py
SHEET.pull
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 self.sheetName: sheetName=self.sheetName if bookName is None: bookName=OR.activeBook() if bookName and sheetName is None: sheetName=OR.activeSheet() if not bookName or not sheetName: print("can't figure out where to pull from! [%s]%s"%(bookName,sheetName)) return # finally doing the thing poSheet=OR.getSheet(bookName,sheetName) self.bookName=bookName self.sheetName=sheetName self.desc=poSheet.GetLongName() self.colNames=[poCol.GetName() for poCol in poSheet.Columns()] self.colDesc=[poCol.GetLongName() for poCol in poSheet.Columns()] self.colUnits=[poCol.GetUnits() for poCol in poSheet.Columns()] self.colComments=[poCol.GetComments() for poCol in poSheet.Columns()] self.colTypes=[poCol.GetType() for poCol in poSheet.Columns()] self.colData=[poCol.GetData() for poCol in poSheet.Columns()]
python
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 self.sheetName: sheetName=self.sheetName if bookName is None: bookName=OR.activeBook() if bookName and sheetName is None: sheetName=OR.activeSheet() if not bookName or not sheetName: print("can't figure out where to pull from! [%s]%s"%(bookName,sheetName)) return # finally doing the thing poSheet=OR.getSheet(bookName,sheetName) self.bookName=bookName self.sheetName=sheetName self.desc=poSheet.GetLongName() self.colNames=[poCol.GetName() for poCol in poSheet.Columns()] self.colDesc=[poCol.GetLongName() for poCol in poSheet.Columns()] self.colUnits=[poCol.GetUnits() for poCol in poSheet.Columns()] self.colComments=[poCol.GetComments() for poCol in poSheet.Columns()] self.colTypes=[poCol.GetType() for poCol in poSheet.Columns()] self.colData=[poCol.GetData() for poCol in poSheet.Columns()]
[ "def", "pull", "(", "self", ",", "bookName", "=", "None", ",", "sheetName", "=", "None", ")", ":", "# tons of validation", "if", "bookName", "is", "None", "and", "self", ".", "bookName", ":", "bookName", "=", "self", ".", "bookName", "if", "sheetName", "is", "None", "and", "self", ".", "sheetName", ":", "sheetName", "=", "self", ".", "sheetName", "if", "bookName", "is", "None", ":", "bookName", "=", "OR", ".", "activeBook", "(", ")", "if", "bookName", "and", "sheetName", "is", "None", ":", "sheetName", "=", "OR", ".", "activeSheet", "(", ")", "if", "not", "bookName", "or", "not", "sheetName", ":", "print", "(", "\"can't figure out where to pull from! [%s]%s\"", "%", "(", "bookName", ",", "sheetName", ")", ")", "return", "# finally doing the thing", "poSheet", "=", "OR", ".", "getSheet", "(", "bookName", ",", "sheetName", ")", "self", ".", "bookName", "=", "bookName", "self", ".", "sheetName", "=", "sheetName", "self", ".", "desc", "=", "poSheet", ".", "GetLongName", "(", ")", "self", ".", "colNames", "=", "[", "poCol", ".", "GetName", "(", ")", "for", "poCol", "in", "poSheet", ".", "Columns", "(", ")", "]", "self", ".", "colDesc", "=", "[", "poCol", ".", "GetLongName", "(", ")", "for", "poCol", "in", "poSheet", ".", "Columns", "(", ")", "]", "self", ".", "colUnits", "=", "[", "poCol", ".", "GetUnits", "(", ")", "for", "poCol", "in", "poSheet", ".", "Columns", "(", ")", "]", "self", ".", "colComments", "=", "[", "poCol", ".", "GetComments", "(", ")", "for", "poCol", "in", "poSheet", ".", "Columns", "(", ")", "]", "self", ".", "colTypes", "=", "[", "poCol", ".", "GetType", "(", ")", "for", "poCol", "in", "poSheet", ".", "Columns", "(", ")", "]", "self", ".", "colData", "=", "[", "poCol", ".", "GetData", "(", ")", "for", "poCol", "in", "poSheet", ".", "Columns", "(", ")", "]" ]
pull data into this OR.SHEET from a real book/sheet in Origin
[ "pull", "data", "into", "this", "OR", ".", "SHEET", "from", "a", "real", "book", "/", "sheet", "in", "Origin" ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/workbook.py#L138-L160
train
swharden/PyOriginTools
PyOriginTools/workbook.py
SHEET.push
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.sheetName in OR.sheetNames(bookName): print("can't find [%s]%s!"%(bookName,sheetName)) return # clear out out sheet by deleting EVERY column poSheet=OR.getSheet(bookName,sheetName) # CPyWorksheetPageI if not poSheet: print("WARNING: didn't get posheet",poSheet,bookName,sheetName) for poCol in [x for x in poSheet if x.IsValid()]: poCol.Destroy() # create columns and assign properties to each for i in range(len(self.colNames)): poSheet.InsertCol(i,self.colNames[i]) poSheet.Columns(i).SetName(self.colNames[i]) poSheet.Columns(i).SetLongName(self.colDesc[i]) poSheet.Columns(i).SetUnits(self.colUnits[i]) poSheet.Columns(i).SetComments(self.colComments[i]) poSheet.Columns(i).SetType(self.colTypes[i]) poSheet.Columns(i).SetData(self.colData[i])
python
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.sheetName in OR.sheetNames(bookName): print("can't find [%s]%s!"%(bookName,sheetName)) return # clear out out sheet by deleting EVERY column poSheet=OR.getSheet(bookName,sheetName) # CPyWorksheetPageI if not poSheet: print("WARNING: didn't get posheet",poSheet,bookName,sheetName) for poCol in [x for x in poSheet if x.IsValid()]: poCol.Destroy() # create columns and assign properties to each for i in range(len(self.colNames)): poSheet.InsertCol(i,self.colNames[i]) poSheet.Columns(i).SetName(self.colNames[i]) poSheet.Columns(i).SetLongName(self.colDesc[i]) poSheet.Columns(i).SetUnits(self.colUnits[i]) poSheet.Columns(i).SetComments(self.colComments[i]) poSheet.Columns(i).SetType(self.colTypes[i]) poSheet.Columns(i).SetData(self.colData[i])
[ "def", "push", "(", "self", ",", "bookName", "=", "None", ",", "sheetName", "=", "None", ",", "overwrite", "=", "False", ")", ":", "# tons of validation", "if", "bookName", ":", "self", ".", "bookName", "=", "bookName", "if", "sheetName", ":", "self", ".", "sheetName", "=", "sheetName", "if", "not", "self", ".", "sheetName", "in", "OR", ".", "sheetNames", "(", "bookName", ")", ":", "print", "(", "\"can't find [%s]%s!\"", "%", "(", "bookName", ",", "sheetName", ")", ")", "return", "# clear out out sheet by deleting EVERY column", "poSheet", "=", "OR", ".", "getSheet", "(", "bookName", ",", "sheetName", ")", "# CPyWorksheetPageI", "if", "not", "poSheet", ":", "print", "(", "\"WARNING: didn't get posheet\"", ",", "poSheet", ",", "bookName", ",", "sheetName", ")", "for", "poCol", "in", "[", "x", "for", "x", "in", "poSheet", "if", "x", ".", "IsValid", "(", ")", "]", ":", "poCol", ".", "Destroy", "(", ")", "# create columns and assign properties to each", "for", "i", "in", "range", "(", "len", "(", "self", ".", "colNames", ")", ")", ":", "poSheet", ".", "InsertCol", "(", "i", ",", "self", ".", "colNames", "[", "i", "]", ")", "poSheet", ".", "Columns", "(", "i", ")", ".", "SetName", "(", "self", ".", "colNames", "[", "i", "]", ")", "poSheet", ".", "Columns", "(", "i", ")", ".", "SetLongName", "(", "self", ".", "colDesc", "[", "i", "]", ")", "poSheet", ".", "Columns", "(", "i", ")", ".", "SetUnits", "(", "self", ".", "colUnits", "[", "i", "]", ")", "poSheet", ".", "Columns", "(", "i", ")", ".", "SetComments", "(", "self", ".", "colComments", "[", "i", "]", ")", "poSheet", ".", "Columns", "(", "i", ")", ".", "SetType", "(", "self", ".", "colTypes", "[", "i", "]", ")", "poSheet", ".", "Columns", "(", "i", ")", ".", "SetData", "(", "self", ".", "colData", "[", "i", "]", ")" ]
pull this OR.SHEET into a real book/sheet in Origin
[ "pull", "this", "OR", ".", "SHEET", "into", "a", "real", "book", "/", "sheet", "in", "Origin" ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/workbook.py#L162-L186
train
swharden/PyOriginTools
PyOriginTools/workbook.py
SHEET.nRows
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
python
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
[ "def", "nRows", "(", "self", ")", ":", "if", "self", ".", "nCols", ":", "return", "max", "(", "[", "len", "(", "x", ")", "for", "x", "in", "self", ".", "colData", "]", ")", "else", ":", "return", "0" ]
returns maximum number of rows based on the longest colData
[ "returns", "maximum", "number", "of", "rows", "based", "on", "the", "longest", "colData" ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/workbook.py#L191-L194
train
swharden/PyOriginTools
PyOriginTools/workbook.py
SHEET.data
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([np.isreal(v) for v in colData])[0] validData=np.ones(len(colData))*np.nan validData[validIs]=np.array(colData)[validIs] data[:len(colData),colNum]=validData # only fill cells that have data return data
python
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([np.isreal(v) for v in colData])[0] validData=np.ones(len(colData))*np.nan validData[validIs]=np.array(colData)[validIs] data[:len(colData),colNum]=validData # only fill cells that have data return data
[ "def", "data", "(", "self", ")", ":", "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", "(", "[", "np", ".", "isreal", "(", "v", ")", "for", "v", "in", "colData", "]", ")", "[", "0", "]", "validData", "=", "np", ".", "ones", "(", "len", "(", "colData", ")", ")", "*", "np", ".", "nan", "validData", "[", "validIs", "]", "=", "np", ".", "array", "(", "colData", ")", "[", "validIs", "]", "data", "[", ":", "len", "(", "colData", ")", ",", "colNum", "]", "=", "validData", "# only fill cells that have data", "return", "data" ]
return all of colData as a 2D numpy array.
[ "return", "all", "of", "colData", "as", "a", "2D", "numpy", "array", "." ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/workbook.py#L204-L214
train
swharden/PyOriginTools
PyOriginTools/workbook.py
SHEET.data
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()
python
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()
[ "def", "data", "(", "self", ",", "data", ")", ":", "assert", "type", "(", "data", ")", "is", "np", ".", "ndarray", "assert", "data", ".", "shape", "[", "1", "]", "==", "self", ".", "nCols", "for", "i", "in", "range", "(", "self", ".", "nCols", ")", ":", "self", ".", "colData", "[", "i", "]", "=", "data", "[", ":", ",", "i", "]", ".", "tolist", "(", ")" ]
Given a 2D numpy array, fill colData with it.
[ "Given", "a", "2D", "numpy", "array", "fill", "colData", "with", "it", "." ]
536fb8e11234ffdc27e26b1800e0358179ca7d26
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/workbook.py#L217-L222
train
j4321/tkColorPicker
tkcolorpicker/spinbox.py
Spinbox.focusout
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",)) self.style.configure("%s.spinbox.TFrame" % self.frame, bordercolor=bc, darkcolor=dc, lightcolor=lc)
python
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",)) self.style.configure("%s.spinbox.TFrame" % self.frame, bordercolor=bc, darkcolor=dc, lightcolor=lc)
[ "def", "focusout", "(", "self", ",", "event", ")", ":", "bc", "=", "self", ".", "style", ".", "lookup", "(", "\"TEntry\"", ",", "\"bordercolor\"", ",", "(", "\"!focus\"", ",", ")", ")", "dc", "=", "self", ".", "style", ".", "lookup", "(", "\"TEntry\"", ",", "\"darkcolor\"", ",", "(", "\"!focus\"", ",", ")", ")", "lc", "=", "self", ".", "style", ".", "lookup", "(", "\"TEntry\"", ",", "\"lightcolor\"", ",", "(", "\"!focus\"", ",", ")", ")", "self", ".", "style", ".", "configure", "(", "\"%s.spinbox.TFrame\"", "%", "self", ".", "frame", ",", "bordercolor", "=", "bc", ",", "darkcolor", "=", "dc", ",", "lightcolor", "=", "lc", ")" ]
Change style on focus out events.
[ "Change", "style", "on", "focus", "out", "events", "." ]
ee2d583115e0c7ad7f29795763fc6b4ddc4e8c1d
https://github.com/j4321/tkColorPicker/blob/ee2d583115e0c7ad7f29795763fc6b4ddc4e8c1d/tkcolorpicker/spinbox.py#L99-L105
train
j4321/tkColorPicker
tkcolorpicker/spinbox.py
Spinbox.focusin
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", "lightcolor", ("focus",)) self.style.configure("%s.spinbox.TFrame" % self.frame, bordercolor=bc, darkcolor=dc, lightcolor=lc)
python
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", "lightcolor", ("focus",)) self.style.configure("%s.spinbox.TFrame" % self.frame, bordercolor=bc, darkcolor=dc, lightcolor=lc)
[ "def", "focusin", "(", "self", ",", "event", ")", ":", "self", ".", "old_value", "=", "self", ".", "get", "(", ")", "bc", "=", "self", ".", "style", ".", "lookup", "(", "\"TEntry\"", ",", "\"bordercolor\"", ",", "(", "\"focus\"", ",", ")", ")", "dc", "=", "self", ".", "style", ".", "lookup", "(", "\"TEntry\"", ",", "\"darkcolor\"", ",", "(", "\"focus\"", ",", ")", ")", "lc", "=", "self", ".", "style", ".", "lookup", "(", "\"TEntry\"", ",", "\"lightcolor\"", ",", "(", "\"focus\"", ",", ")", ")", "self", ".", "style", ".", "configure", "(", "\"%s.spinbox.TFrame\"", "%", "self", ".", "frame", ",", "bordercolor", "=", "bc", ",", "darkcolor", "=", "dc", ",", "lightcolor", "=", "lc", ")" ]
Change style on focus in events.
[ "Change", "style", "on", "focus", "in", "events", "." ]
ee2d583115e0c7ad7f29795763fc6b4ddc4e8c1d
https://github.com/j4321/tkColorPicker/blob/ee2d583115e0c7ad7f29795763fc6b4ddc4e8c1d/tkcolorpicker/spinbox.py#L107-L114
train
xzased/lvm2py
lvm2py/lvm.py
LVM.open
def open(self): """ 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 """ if not self.handle: try: path = self.system_dir except AttributeError: path = '' self.__handle = lvm_init(path) if not bool(self.__handle): raise HandleError("Failed to initialize LVM handle.")
python
def open(self): """ 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 """ if not self.handle: try: path = self.system_dir except AttributeError: path = '' self.__handle = lvm_init(path) if not bool(self.__handle): raise HandleError("Failed to initialize LVM handle.")
[ "def", "open", "(", "self", ")", ":", "if", "not", "self", ".", "handle", ":", "try", ":", "path", "=", "self", ".", "system_dir", "except", "AttributeError", ":", "path", "=", "''", "self", ".", "__handle", "=", "lvm_init", "(", "path", ")", "if", "not", "bool", "(", "self", ".", "__handle", ")", ":", "raise", "HandleError", "(", "\"Failed to initialize LVM handle.\"", ")" ]
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
[ "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" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/lvm.py#L57-L73
train
xzased/lvm2py
lvm2py/lvm.py
LVM.close
def close(self): """ 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 """ if self.handle: q = lvm_quit(self.handle) if q != 0: raise HandleError("Failed to close LVM handle.") self.__handle = None
python
def close(self): """ 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 """ if self.handle: q = lvm_quit(self.handle) if q != 0: raise HandleError("Failed to close LVM handle.") self.__handle = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "handle", ":", "q", "=", "lvm_quit", "(", "self", ".", "handle", ")", "if", "q", "!=", "0", ":", "raise", "HandleError", "(", "\"Failed to close LVM handle.\"", ")", "self", ".", "__handle", "=", "None" ]
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
[ "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" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/lvm.py#L75-L88
train
xzased/lvm2py
lvm2py/lvm.py
LVM.get_vg
def get_vg(self, name, mode="r"): """ 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 parameter to "w":: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") *Args:* * name (str): An existing volume group name. * mode (str): "r" or "w" for read/write respectively. Default is "r". *Raises:* * HandleError """ vg = VolumeGroup(self, name=name, mode=mode) return vg
python
def get_vg(self, name, mode="r"): """ 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 parameter to "w":: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") *Args:* * name (str): An existing volume group name. * mode (str): "r" or "w" for read/write respectively. Default is "r". *Raises:* * HandleError """ vg = VolumeGroup(self, name=name, mode=mode) return vg
[ "def", "get_vg", "(", "self", ",", "name", ",", "mode", "=", "\"r\"", ")", ":", "vg", "=", "VolumeGroup", "(", "self", ",", "name", "=", "name", ",", "mode", "=", "mode", ")", "return", "vg" ]
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 parameter to "w":: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") *Args:* * name (str): An existing volume group name. * mode (str): "r" or "w" for read/write respectively. Default is "r". *Raises:* * HandleError
[ "Returns", "an", "instance", "of", "VolumeGroup", ".", "The", "name", "parameter", "should", "be", "an", "existing", "volume", "group", ".", "By", "default", "all", "volume", "groups", "are", "open", "in", "read", "mode", "::" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/lvm.py#L130-L157
train
xzased/lvm2py
lvm2py/lvm.py
LVM.create_vg
def create_vg(self, name, devices): """ 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. * devices (list): A list of device paths. *Raises:* * HandleError, CommitError, ValueError """ self.open() vgh = lvm_vg_create(self.handle, name) if not bool(vgh): self.close() raise HandleError("Failed to create VG.") for device in devices: if not os.path.exists(device): self._destroy_vg(vgh) raise ValueError("%s does not exist." % device) ext = lvm_vg_extend(vgh, device) if ext != 0: self._destroy_vg(vgh) raise CommitError("Failed to extend Volume Group.") try: self._commit_vg(vgh) except CommitError: self._destroy_vg(vgh) raise CommitError("Failed to add %s to VolumeGroup." % device) self._close_vg(vgh) vg = VolumeGroup(self, name) return vg
python
def create_vg(self, name, devices): """ 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. * devices (list): A list of device paths. *Raises:* * HandleError, CommitError, ValueError """ self.open() vgh = lvm_vg_create(self.handle, name) if not bool(vgh): self.close() raise HandleError("Failed to create VG.") for device in devices: if not os.path.exists(device): self._destroy_vg(vgh) raise ValueError("%s does not exist." % device) ext = lvm_vg_extend(vgh, device) if ext != 0: self._destroy_vg(vgh) raise CommitError("Failed to extend Volume Group.") try: self._commit_vg(vgh) except CommitError: self._destroy_vg(vgh) raise CommitError("Failed to add %s to VolumeGroup." % device) self._close_vg(vgh) vg = VolumeGroup(self, name) return vg
[ "def", "create_vg", "(", "self", ",", "name", ",", "devices", ")", ":", "self", ".", "open", "(", ")", "vgh", "=", "lvm_vg_create", "(", "self", ".", "handle", ",", "name", ")", "if", "not", "bool", "(", "vgh", ")", ":", "self", ".", "close", "(", ")", "raise", "HandleError", "(", "\"Failed to create VG.\"", ")", "for", "device", "in", "devices", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "device", ")", ":", "self", ".", "_destroy_vg", "(", "vgh", ")", "raise", "ValueError", "(", "\"%s does not exist.\"", "%", "device", ")", "ext", "=", "lvm_vg_extend", "(", "vgh", ",", "device", ")", "if", "ext", "!=", "0", ":", "self", ".", "_destroy_vg", "(", "vgh", ")", "raise", "CommitError", "(", "\"Failed to extend Volume Group.\"", ")", "try", ":", "self", ".", "_commit_vg", "(", "vgh", ")", "except", "CommitError", ":", "self", ".", "_destroy_vg", "(", "vgh", ")", "raise", "CommitError", "(", "\"Failed to add %s to VolumeGroup.\"", "%", "device", ")", "self", ".", "_close_vg", "(", "vgh", ")", "vg", "=", "VolumeGroup", "(", "self", ",", "name", ")", "return", "vg" ]
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. * devices (list): A list of device paths. *Raises:* * HandleError, CommitError, ValueError
[ "Returns", "a", "new", "instance", "of", "VolumeGroup", "with", "the", "given", "name", "and", "added", "physycal", "volumes", "(", "devices", ")", "::" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/lvm.py#L159-L198
train
xzased/lvm2py
lvm2py/lvm.py
LVM.remove_vg
def remove_vg(self, vg): """ 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:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised. """ vg.open() rm = lvm_vg_remove(vg.handle) if rm != 0: vg.close() raise CommitError("Failed to remove VG.") com = lvm_vg_write(vg.handle) if com != 0: vg.close() raise CommitError("Failed to commit changes to disk.") vg.close()
python
def remove_vg(self, vg): """ 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:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised. """ vg.open() rm = lvm_vg_remove(vg.handle) if rm != 0: vg.close() raise CommitError("Failed to remove VG.") com = lvm_vg_write(vg.handle) if com != 0: vg.close() raise CommitError("Failed to commit changes to disk.") vg.close()
[ "def", "remove_vg", "(", "self", ",", "vg", ")", ":", "vg", ".", "open", "(", ")", "rm", "=", "lvm_vg_remove", "(", "vg", ".", "handle", ")", "if", "rm", "!=", "0", ":", "vg", ".", "close", "(", ")", "raise", "CommitError", "(", "\"Failed to remove VG.\"", ")", "com", "=", "lvm_vg_write", "(", "vg", ".", "handle", ")", "if", "com", "!=", "0", ":", "vg", ".", "close", "(", ")", "raise", "CommitError", "(", "\"Failed to commit changes to disk.\"", ")", "vg", ".", "close", "(", ")" ]
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:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised.
[ "Removes", "a", "volume", "group", "::" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/lvm.py#L200-L232
train
xzased/lvm2py
lvm2py/lvm.py
LVM.vgscan
def vgscan(self): """ Probes the system for volume groups and returns a list of VolumeGroup instances:: from lvm2py import * lvm = LVM() vgs = lvm.vgscan() *Raises:* * HandleError """ vg_list = [] self.open() names = lvm_list_vg_names(self.handle) if not bool(names): return vg_list vgnames = [] vg = dm_list_first(names) while vg: c = cast(vg, POINTER(lvm_str_list)) vgnames.append(c.contents.str) if dm_list_end(names, vg): # end of linked list break vg = dm_list_next(names, vg) self.close() for name in vgnames: vginst = self.get_vg(name) vg_list.append(vginst) return vg_list
python
def vgscan(self): """ Probes the system for volume groups and returns a list of VolumeGroup instances:: from lvm2py import * lvm = LVM() vgs = lvm.vgscan() *Raises:* * HandleError """ vg_list = [] self.open() names = lvm_list_vg_names(self.handle) if not bool(names): return vg_list vgnames = [] vg = dm_list_first(names) while vg: c = cast(vg, POINTER(lvm_str_list)) vgnames.append(c.contents.str) if dm_list_end(names, vg): # end of linked list break vg = dm_list_next(names, vg) self.close() for name in vgnames: vginst = self.get_vg(name) vg_list.append(vginst) return vg_list
[ "def", "vgscan", "(", "self", ")", ":", "vg_list", "=", "[", "]", "self", ".", "open", "(", ")", "names", "=", "lvm_list_vg_names", "(", "self", ".", "handle", ")", "if", "not", "bool", "(", "names", ")", ":", "return", "vg_list", "vgnames", "=", "[", "]", "vg", "=", "dm_list_first", "(", "names", ")", "while", "vg", ":", "c", "=", "cast", "(", "vg", ",", "POINTER", "(", "lvm_str_list", ")", ")", "vgnames", ".", "append", "(", "c", ".", "contents", ".", "str", ")", "if", "dm_list_end", "(", "names", ",", "vg", ")", ":", "# end of linked list", "break", "vg", "=", "dm_list_next", "(", "names", ",", "vg", ")", "self", ".", "close", "(", ")", "for", "name", "in", "vgnames", ":", "vginst", "=", "self", ".", "get_vg", "(", "name", ")", "vg_list", ".", "append", "(", "vginst", ")", "return", "vg_list" ]
Probes the system for volume groups and returns a list of VolumeGroup instances:: from lvm2py import * lvm = LVM() vgs = lvm.vgscan() *Raises:* * HandleError
[ "Probes", "the", "system", "for", "volume", "groups", "and", "returns", "a", "list", "of", "VolumeGroup", "instances", "::" ]
34ce69304531a474c2fe4a4009ca445a8c103cd6
https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/lvm.py#L234-L266
train
davidmcclure/textplot
textplot/text.py
Text.from_file
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())
python
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())
[ "def", "from_file", "(", "cls", ",", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ",", "errors", "=", "'replace'", ")", "as", "f", ":", "return", "cls", "(", "f", ".", "read", "(", ")", ")" ]
Create a text from a file. Args: path (str): The file path.
[ "Create", "a", "text", "from", "a", "file", "." ]
889b949a637d99097ecec44ed4bfee53b1964dee
https://github.com/davidmcclure/textplot/blob/889b949a637d99097ecec44ed4bfee53b1964dee/textplot/text.py#L22-L32
train
davidmcclure/textplot
textplot/text.py
Text.load_stopwords
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.stopwords = set(f.read().splitlines()) else: self.stopwords = set( pkgutil .get_data('textplot', 'data/stopwords.txt') .decode('utf8') .splitlines() )
python
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.stopwords = set(f.read().splitlines()) else: self.stopwords = set( pkgutil .get_data('textplot', 'data/stopwords.txt') .decode('utf8') .splitlines() )
[ "def", "load_stopwords", "(", "self", ",", "path", ")", ":", "if", "path", ":", "with", "open", "(", "path", ")", "as", "f", ":", "self", ".", "stopwords", "=", "set", "(", "f", ".", "read", "(", ")", ".", "splitlines", "(", ")", ")", "else", ":", "self", ".", "stopwords", "=", "set", "(", "pkgutil", ".", "get_data", "(", "'textplot'", ",", "'data/stopwords.txt'", ")", ".", "decode", "(", "'utf8'", ")", ".", "splitlines", "(", ")", ")" ]
Load a set of stopwords. Args: path (str): The stopwords file path.
[ "Load", "a", "set", "of", "stopwords", "." ]
889b949a637d99097ecec44ed4bfee53b1964dee
https://github.com/davidmcclure/textplot/blob/889b949a637d99097ecec44ed4bfee53b1964dee/textplot/text.py#L50-L69
train
davidmcclure/textplot
textplot/text.py
Text.tokenize
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: self.tokens.append(None) else: # Token: self.tokens.append(token) # Term: offsets = self.terms.setdefault(token['stemmed'], []) offsets.append(token['offset'])
python
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: self.tokens.append(None) else: # Token: self.tokens.append(token) # Term: offsets = self.terms.setdefault(token['stemmed'], []) offsets.append(token['offset'])
[ "def", "tokenize", "(", "self", ")", ":", "self", ".", "tokens", "=", "[", "]", "self", ".", "terms", "=", "OrderedDict", "(", ")", "# Generate tokens.", "for", "token", "in", "utils", ".", "tokenize", "(", "self", ".", "text", ")", ":", "# Ignore stopwords.", "if", "token", "[", "'unstemmed'", "]", "in", "self", ".", "stopwords", ":", "self", ".", "tokens", ".", "append", "(", "None", ")", "else", ":", "# Token:", "self", ".", "tokens", ".", "append", "(", "token", ")", "# Term:", "offsets", "=", "self", ".", "terms", ".", "setdefault", "(", "token", "[", "'stemmed'", "]", ",", "[", "]", ")", "offsets", ".", "append", "(", "token", "[", "'offset'", "]", ")" ]
Tokenize the text.
[ "Tokenize", "the", "text", "." ]
889b949a637d99097ecec44ed4bfee53b1964dee
https://github.com/davidmcclure/textplot/blob/889b949a637d99097ecec44ed4bfee53b1964dee/textplot/text.py#L72-L95
train
davidmcclure/textplot
textplot/text.py
Text.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]) return utils.sort_dict(counts)
python
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]) return utils.sort_dict(counts)
[ "def", "term_counts", "(", "self", ")", ":", "counts", "=", "OrderedDict", "(", ")", "for", "term", "in", "self", ".", "terms", ":", "counts", "[", "term", "]", "=", "len", "(", "self", ".", "terms", "[", "term", "]", ")", "return", "utils", ".", "sort_dict", "(", "counts", ")" ]
Returns: OrderedDict: An ordered dictionary of term counts.
[ "Returns", ":", "OrderedDict", ":", "An", "ordered", "dictionary", "of", "term", "counts", "." ]
889b949a637d99097ecec44ed4bfee53b1964dee
https://github.com/davidmcclure/textplot/blob/889b949a637d99097ecec44ed4bfee53b1964dee/textplot/text.py#L98-L109
train