id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
238,100
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.reference
def reference(self, taskfileinfo): """Reference the entity into the scene. Only possible if the current status is None. This will create a new refobject, then call :meth:`RefobjInterface.reference` and afterwards set the refobj on the :class:`Reftrack` instance. :param taskfileinfo: the taskfileinfo to reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """ assert self.status() is None,\ "Can only reference, if the entity is not already referenced/imported. Use replace instead." refobj = self.create_refobject() with self.set_parent_on_new(refobj): self.get_refobjinter().reference(taskfileinfo, refobj) self.set_refobj(refobj) self.fetch_new_children() self.update_restrictions() self.emit_data_changed()
python
def reference(self, taskfileinfo): """Reference the entity into the scene. Only possible if the current status is None. This will create a new refobject, then call :meth:`RefobjInterface.reference` and afterwards set the refobj on the :class:`Reftrack` instance. :param taskfileinfo: the taskfileinfo to reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """ assert self.status() is None,\ "Can only reference, if the entity is not already referenced/imported. Use replace instead." refobj = self.create_refobject() with self.set_parent_on_new(refobj): self.get_refobjinter().reference(taskfileinfo, refobj) self.set_refobj(refobj) self.fetch_new_children() self.update_restrictions() self.emit_data_changed()
[ "def", "reference", "(", "self", ",", "taskfileinfo", ")", ":", "assert", "self", ".", "status", "(", ")", "is", "None", ",", "\"Can only reference, if the entity is not already referenced/imported. Use replace instead.\"", "refobj", "=", "self", ".", "create_refobject", "(", ")", "with", "self", ".", "set_parent_on_new", "(", "refobj", ")", ":", "self", ".", "get_refobjinter", "(", ")", ".", "reference", "(", "taskfileinfo", ",", "refobj", ")", "self", ".", "set_refobj", "(", "refobj", ")", "self", ".", "fetch_new_children", "(", ")", "self", ".", "update_restrictions", "(", ")", "self", ".", "emit_data_changed", "(", ")" ]
Reference the entity into the scene. Only possible if the current status is None. This will create a new refobject, then call :meth:`RefobjInterface.reference` and afterwards set the refobj on the :class:`Reftrack` instance. :param taskfileinfo: the taskfileinfo to reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError`
[ "Reference", "the", "entity", "into", "the", "scene", ".", "Only", "possible", "if", "the", "current", "status", "is", "None", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1116-L1136
238,101
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.load
def load(self, ): """If the reference is in the scene but unloaded, load it. .. Note:: Do not confuse this with reference or import. Load means that it is already referenced. But the data from the reference was not read until now. Load loads the data from the reference. This will call :meth:`RefobjInterface.load` and set the status to :data:`Reftrack.LOADED`. :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """ assert self.status() == self.UNLOADED,\ "Cannot load if there is no unloaded reference. Use reference instead." self.get_refobjinter().load(self._refobj) self.set_status(self.LOADED) self.fetch_new_children() self.update_restrictions() self.emit_data_changed()
python
def load(self, ): """If the reference is in the scene but unloaded, load it. .. Note:: Do not confuse this with reference or import. Load means that it is already referenced. But the data from the reference was not read until now. Load loads the data from the reference. This will call :meth:`RefobjInterface.load` and set the status to :data:`Reftrack.LOADED`. :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """ assert self.status() == self.UNLOADED,\ "Cannot load if there is no unloaded reference. Use reference instead." self.get_refobjinter().load(self._refobj) self.set_status(self.LOADED) self.fetch_new_children() self.update_restrictions() self.emit_data_changed()
[ "def", "load", "(", "self", ",", ")", ":", "assert", "self", ".", "status", "(", ")", "==", "self", ".", "UNLOADED", ",", "\"Cannot load if there is no unloaded reference. Use reference instead.\"", "self", ".", "get_refobjinter", "(", ")", ".", "load", "(", "self", ".", "_refobj", ")", "self", ".", "set_status", "(", "self", ".", "LOADED", ")", "self", ".", "fetch_new_children", "(", ")", "self", ".", "update_restrictions", "(", ")", "self", ".", "emit_data_changed", "(", ")" ]
If the reference is in the scene but unloaded, load it. .. Note:: Do not confuse this with reference or import. Load means that it is already referenced. But the data from the reference was not read until now. Load loads the data from the reference. This will call :meth:`RefobjInterface.load` and set the status to :data:`Reftrack.LOADED`. :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError`
[ "If", "the", "reference", "is", "in", "the", "scene", "but", "unloaded", "load", "it", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1139-L1157
238,102
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.unload
def unload(self, ): """If the reference is loaded, unload it. .. Note:: Do not confuse this with a delete. This means, that the reference stays in the scene, but no data is read from the reference. This will call :meth:`RefobjInterface.unload` and set the status to :data:`Reftrack.UNLOADED`. It will also throw away all children :class:`Reftrack`. They will return after :meth:`Reftrack.load`. The problem might be that children depend on their parent, but will not get unloaded. E.g. you imported a child. It will stay in the scene after the unload and become an orphan. In this case an error is raised. It is not possible to unload such an entity. The orphan might get its parents back after you call load, but it will introduce bugs when wrapping children of unloaded entities. So we simply disable the feature in that case and raise an :class:`IntegrityError` :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """ assert self.status() == self.LOADED,\ "Cannot unload if there is no loaded reference. \ Use delete if you want to get rid of a reference or import." childrentodelete = self.get_children_to_delete() if childrentodelete: raise ReftrackIntegrityError("Cannot unload because children of the reference would become orphans.", childrentodelete) self.get_refobjinter().unload(self._refobj) self.set_status(self.UNLOADED) self.throw_children_away() self.update_restrictions() self.emit_data_changed()
python
def unload(self, ): """If the reference is loaded, unload it. .. Note:: Do not confuse this with a delete. This means, that the reference stays in the scene, but no data is read from the reference. This will call :meth:`RefobjInterface.unload` and set the status to :data:`Reftrack.UNLOADED`. It will also throw away all children :class:`Reftrack`. They will return after :meth:`Reftrack.load`. The problem might be that children depend on their parent, but will not get unloaded. E.g. you imported a child. It will stay in the scene after the unload and become an orphan. In this case an error is raised. It is not possible to unload such an entity. The orphan might get its parents back after you call load, but it will introduce bugs when wrapping children of unloaded entities. So we simply disable the feature in that case and raise an :class:`IntegrityError` :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """ assert self.status() == self.LOADED,\ "Cannot unload if there is no loaded reference. \ Use delete if you want to get rid of a reference or import." childrentodelete = self.get_children_to_delete() if childrentodelete: raise ReftrackIntegrityError("Cannot unload because children of the reference would become orphans.", childrentodelete) self.get_refobjinter().unload(self._refobj) self.set_status(self.UNLOADED) self.throw_children_away() self.update_restrictions() self.emit_data_changed()
[ "def", "unload", "(", "self", ",", ")", ":", "assert", "self", ".", "status", "(", ")", "==", "self", ".", "LOADED", ",", "\"Cannot unload if there is no loaded reference. \\\nUse delete if you want to get rid of a reference or import.\"", "childrentodelete", "=", "self", ".", "get_children_to_delete", "(", ")", "if", "childrentodelete", ":", "raise", "ReftrackIntegrityError", "(", "\"Cannot unload because children of the reference would become orphans.\"", ",", "childrentodelete", ")", "self", ".", "get_refobjinter", "(", ")", ".", "unload", "(", "self", ".", "_refobj", ")", "self", ".", "set_status", "(", "self", ".", "UNLOADED", ")", "self", ".", "throw_children_away", "(", ")", "self", ".", "update_restrictions", "(", ")", "self", ".", "emit_data_changed", "(", ")" ]
If the reference is loaded, unload it. .. Note:: Do not confuse this with a delete. This means, that the reference stays in the scene, but no data is read from the reference. This will call :meth:`RefobjInterface.unload` and set the status to :data:`Reftrack.UNLOADED`. It will also throw away all children :class:`Reftrack`. They will return after :meth:`Reftrack.load`. The problem might be that children depend on their parent, but will not get unloaded. E.g. you imported a child. It will stay in the scene after the unload and become an orphan. In this case an error is raised. It is not possible to unload such an entity. The orphan might get its parents back after you call load, but it will introduce bugs when wrapping children of unloaded entities. So we simply disable the feature in that case and raise an :class:`IntegrityError` :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError`
[ "If", "the", "reference", "is", "loaded", "unload", "it", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1160-L1190
238,103
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.import_file
def import_file(self, taskfileinfo): """Import the file for the given taskfileinfo This will also update the status to :data:`Reftrack.IMPORTED`. This will also call :meth:`fetch_new_children`. Because after the import, we might have new children. :param taskfileinfo: the taskfileinfo to import. If None is given, try to import the current reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` | None :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """ assert self.status() is None,\ "Entity is already in scene. Use replace instead." refobjinter = self.get_refobjinter() refobj = self.create_refobject() with self.set_parent_on_new(refobj): refobjinter.import_taskfile(refobj, taskfileinfo) self.set_refobj(refobj) self.set_status(self.IMPORTED) self.fetch_new_children() self.update_restrictions() self.emit_data_changed()
python
def import_file(self, taskfileinfo): """Import the file for the given taskfileinfo This will also update the status to :data:`Reftrack.IMPORTED`. This will also call :meth:`fetch_new_children`. Because after the import, we might have new children. :param taskfileinfo: the taskfileinfo to import. If None is given, try to import the current reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` | None :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """ assert self.status() is None,\ "Entity is already in scene. Use replace instead." refobjinter = self.get_refobjinter() refobj = self.create_refobject() with self.set_parent_on_new(refobj): refobjinter.import_taskfile(refobj, taskfileinfo) self.set_refobj(refobj) self.set_status(self.IMPORTED) self.fetch_new_children() self.update_restrictions() self.emit_data_changed()
[ "def", "import_file", "(", "self", ",", "taskfileinfo", ")", ":", "assert", "self", ".", "status", "(", ")", "is", "None", ",", "\"Entity is already in scene. Use replace instead.\"", "refobjinter", "=", "self", ".", "get_refobjinter", "(", ")", "refobj", "=", "self", ".", "create_refobject", "(", ")", "with", "self", ".", "set_parent_on_new", "(", "refobj", ")", ":", "refobjinter", ".", "import_taskfile", "(", "refobj", ",", "taskfileinfo", ")", "self", ".", "set_refobj", "(", "refobj", ")", "self", ".", "set_status", "(", "self", ".", "IMPORTED", ")", "self", ".", "fetch_new_children", "(", ")", "self", ".", "update_restrictions", "(", ")", "self", ".", "emit_data_changed", "(", ")" ]
Import the file for the given taskfileinfo This will also update the status to :data:`Reftrack.IMPORTED`. This will also call :meth:`fetch_new_children`. Because after the import, we might have new children. :param taskfileinfo: the taskfileinfo to import. If None is given, try to import the current reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` | None :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError`
[ "Import", "the", "file", "for", "the", "given", "taskfileinfo" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1193-L1216
238,104
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.import_reference
def import_reference(self, ): """Import the currently loaded reference This will also update the status to :data:`Reftrack.IMPORTED`. :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """ assert self.status() in (self.LOADED, self.UNLOADED),\ "There is no reference for this entity." refobjinter = self.get_refobjinter() refobjinter.import_reference(self.get_refobj()) self.set_status(self.IMPORTED) self.update_restrictions() for c in self.get_all_children(): c.update_restrictions() self.emit_data_changed()
python
def import_reference(self, ): """Import the currently loaded reference This will also update the status to :data:`Reftrack.IMPORTED`. :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """ assert self.status() in (self.LOADED, self.UNLOADED),\ "There is no reference for this entity." refobjinter = self.get_refobjinter() refobjinter.import_reference(self.get_refobj()) self.set_status(self.IMPORTED) self.update_restrictions() for c in self.get_all_children(): c.update_restrictions() self.emit_data_changed()
[ "def", "import_reference", "(", "self", ",", ")", ":", "assert", "self", ".", "status", "(", ")", "in", "(", "self", ".", "LOADED", ",", "self", ".", "UNLOADED", ")", ",", "\"There is no reference for this entity.\"", "refobjinter", "=", "self", ".", "get_refobjinter", "(", ")", "refobjinter", ".", "import_reference", "(", "self", ".", "get_refobj", "(", ")", ")", "self", ".", "set_status", "(", "self", ".", "IMPORTED", ")", "self", ".", "update_restrictions", "(", ")", "for", "c", "in", "self", ".", "get_all_children", "(", ")", ":", "c", ".", "update_restrictions", "(", ")", "self", ".", "emit_data_changed", "(", ")" ]
Import the currently loaded reference This will also update the status to :data:`Reftrack.IMPORTED`. :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError`
[ "Import", "the", "currently", "loaded", "reference" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1219-L1236
238,105
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.replace
def replace(self, taskfileinfo): """Replace the current reference or imported entity. If the given refobj is not replaceable, e.g. it might be imported or it is not possible to switch the data, then the entity will be deleted, then referenced or imported again, depending on the current status. A replaced entity might have other children. This introduces a problem: A child might get deleted, e.g. an asset which itself has another child, that will not get deleted, e.g. an imported shader. In this case the imported shader will be left as an orphan. This will check all children that will not be deleted (:meth:`Reftrack.get_children_to_delete`) and checks if they are orphans after the replace. If they are, they will get deleted! After the replace, all children will be reset. This will simply throw away all children reftracks (the content will not be deleted) and wrap all new children again. See: :meth:`Reftrack.fetch_new_children`. :param taskfileinfo: the taskfileinfo that will replace the old entity :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: ReftrackIntegrityError """ assert self.status() is not None,\ "Can only replace entities that are already in the scene." refobjinter = self.get_refobjinter() refobj = self.get_refobj() if self.status() in (self.LOADED, self.UNLOADED) and refobjinter.is_replaceable(refobj): # possible orphans will not get replaced, by replace # but their parent might dissapear in the process possibleorphans = self.get_children_to_delete() with self.set_parent_on_new(refobj): refobjinter.replace(refobj, taskfileinfo) self.set_taskfileinfo(taskfileinfo) self.fetch_uptodate() for o in possibleorphans: # find if orphans were created and delete them # we get the refobj of the parent # if it still exists, it is no orphan parent = o.get_parent() refobj = parent.get_refobj() if not parent.get_refobjinter().exists(refobj): # orphans will be deleted! # this is politically incorrect, i know! # the world of programming is a harsh place. o.delete() # reset the children # throw them away at first self.throw_children_away() # gather them again self.fetch_new_children() else: status = self.status() self.delete(removealien=False) if status == self.IMPORTED: self.import_file(taskfileinfo) else: self.reference(taskfileinfo) self.update_restrictions() self.emit_data_changed()
python
def replace(self, taskfileinfo): """Replace the current reference or imported entity. If the given refobj is not replaceable, e.g. it might be imported or it is not possible to switch the data, then the entity will be deleted, then referenced or imported again, depending on the current status. A replaced entity might have other children. This introduces a problem: A child might get deleted, e.g. an asset which itself has another child, that will not get deleted, e.g. an imported shader. In this case the imported shader will be left as an orphan. This will check all children that will not be deleted (:meth:`Reftrack.get_children_to_delete`) and checks if they are orphans after the replace. If they are, they will get deleted! After the replace, all children will be reset. This will simply throw away all children reftracks (the content will not be deleted) and wrap all new children again. See: :meth:`Reftrack.fetch_new_children`. :param taskfileinfo: the taskfileinfo that will replace the old entity :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: ReftrackIntegrityError """ assert self.status() is not None,\ "Can only replace entities that are already in the scene." refobjinter = self.get_refobjinter() refobj = self.get_refobj() if self.status() in (self.LOADED, self.UNLOADED) and refobjinter.is_replaceable(refobj): # possible orphans will not get replaced, by replace # but their parent might dissapear in the process possibleorphans = self.get_children_to_delete() with self.set_parent_on_new(refobj): refobjinter.replace(refobj, taskfileinfo) self.set_taskfileinfo(taskfileinfo) self.fetch_uptodate() for o in possibleorphans: # find if orphans were created and delete them # we get the refobj of the parent # if it still exists, it is no orphan parent = o.get_parent() refobj = parent.get_refobj() if not parent.get_refobjinter().exists(refobj): # orphans will be deleted! # this is politically incorrect, i know! # the world of programming is a harsh place. o.delete() # reset the children # throw them away at first self.throw_children_away() # gather them again self.fetch_new_children() else: status = self.status() self.delete(removealien=False) if status == self.IMPORTED: self.import_file(taskfileinfo) else: self.reference(taskfileinfo) self.update_restrictions() self.emit_data_changed()
[ "def", "replace", "(", "self", ",", "taskfileinfo", ")", ":", "assert", "self", ".", "status", "(", ")", "is", "not", "None", ",", "\"Can only replace entities that are already in the scene.\"", "refobjinter", "=", "self", ".", "get_refobjinter", "(", ")", "refobj", "=", "self", ".", "get_refobj", "(", ")", "if", "self", ".", "status", "(", ")", "in", "(", "self", ".", "LOADED", ",", "self", ".", "UNLOADED", ")", "and", "refobjinter", ".", "is_replaceable", "(", "refobj", ")", ":", "# possible orphans will not get replaced, by replace", "# but their parent might dissapear in the process", "possibleorphans", "=", "self", ".", "get_children_to_delete", "(", ")", "with", "self", ".", "set_parent_on_new", "(", "refobj", ")", ":", "refobjinter", ".", "replace", "(", "refobj", ",", "taskfileinfo", ")", "self", ".", "set_taskfileinfo", "(", "taskfileinfo", ")", "self", ".", "fetch_uptodate", "(", ")", "for", "o", "in", "possibleorphans", ":", "# find if orphans were created and delete them", "# we get the refobj of the parent", "# if it still exists, it is no orphan", "parent", "=", "o", ".", "get_parent", "(", ")", "refobj", "=", "parent", ".", "get_refobj", "(", ")", "if", "not", "parent", ".", "get_refobjinter", "(", ")", ".", "exists", "(", "refobj", ")", ":", "# orphans will be deleted!", "# this is politically incorrect, i know!", "# the world of programming is a harsh place.", "o", ".", "delete", "(", ")", "# reset the children", "# throw them away at first", "self", ".", "throw_children_away", "(", ")", "# gather them again", "self", ".", "fetch_new_children", "(", ")", "else", ":", "status", "=", "self", ".", "status", "(", ")", "self", ".", "delete", "(", "removealien", "=", "False", ")", "if", "status", "==", "self", ".", "IMPORTED", ":", "self", ".", "import_file", "(", "taskfileinfo", ")", "else", ":", "self", ".", "reference", "(", "taskfileinfo", ")", "self", ".", "update_restrictions", "(", ")", "self", ".", "emit_data_changed", "(", ")" ]
Replace the current reference or imported entity. If the given refobj is not replaceable, e.g. it might be imported or it is not possible to switch the data, then the entity will be deleted, then referenced or imported again, depending on the current status. A replaced entity might have other children. This introduces a problem: A child might get deleted, e.g. an asset which itself has another child, that will not get deleted, e.g. an imported shader. In this case the imported shader will be left as an orphan. This will check all children that will not be deleted (:meth:`Reftrack.get_children_to_delete`) and checks if they are orphans after the replace. If they are, they will get deleted! After the replace, all children will be reset. This will simply throw away all children reftracks (the content will not be deleted) and wrap all new children again. See: :meth:`Reftrack.fetch_new_children`. :param taskfileinfo: the taskfileinfo that will replace the old entity :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: ReftrackIntegrityError
[ "Replace", "the", "current", "reference", "or", "imported", "entity", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1239-L1299
238,106
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack._delete
def _delete(self, ): """Internal implementation for deleting a reftrack. This will just delete the reftrack, set the children to None, update the status, and the rootobject. If the object is an alien, it will also set the parent to None, so it dissapears from the model. :returns: None :rtype: None :raises: None """ refobjinter = self.get_refobjinter() refobjinter.delete(self.get_refobj()) self.set_refobj(None, setParent=False) if self.alien(): # it should not be in the scene # so also remove it from the model # so we cannot load it again parent = self.get_parent() if parent: parent.remove_child(self) self._treeitem.parent().remove_child(self._treeitem) else: # only remove all children from the model and set their parent to None for c in self.get_all_children(): c._parent = None self._treeitem.remove_child(c._treeitem) # this should not have any children anymore self._children = [] self.set_status(None)
python
def _delete(self, ): """Internal implementation for deleting a reftrack. This will just delete the reftrack, set the children to None, update the status, and the rootobject. If the object is an alien, it will also set the parent to None, so it dissapears from the model. :returns: None :rtype: None :raises: None """ refobjinter = self.get_refobjinter() refobjinter.delete(self.get_refobj()) self.set_refobj(None, setParent=False) if self.alien(): # it should not be in the scene # so also remove it from the model # so we cannot load it again parent = self.get_parent() if parent: parent.remove_child(self) self._treeitem.parent().remove_child(self._treeitem) else: # only remove all children from the model and set their parent to None for c in self.get_all_children(): c._parent = None self._treeitem.remove_child(c._treeitem) # this should not have any children anymore self._children = [] self.set_status(None)
[ "def", "_delete", "(", "self", ",", ")", ":", "refobjinter", "=", "self", ".", "get_refobjinter", "(", ")", "refobjinter", ".", "delete", "(", "self", ".", "get_refobj", "(", ")", ")", "self", ".", "set_refobj", "(", "None", ",", "setParent", "=", "False", ")", "if", "self", ".", "alien", "(", ")", ":", "# it should not be in the scene", "# so also remove it from the model", "# so we cannot load it again", "parent", "=", "self", ".", "get_parent", "(", ")", "if", "parent", ":", "parent", ".", "remove_child", "(", "self", ")", "self", ".", "_treeitem", ".", "parent", "(", ")", ".", "remove_child", "(", "self", ".", "_treeitem", ")", "else", ":", "# only remove all children from the model and set their parent to None", "for", "c", "in", "self", ".", "get_all_children", "(", ")", ":", "c", ".", "_parent", "=", "None", "self", ".", "_treeitem", ".", "remove_child", "(", "c", ".", "_treeitem", ")", "# this should not have any children anymore", "self", ".", "_children", "=", "[", "]", "self", ".", "set_status", "(", "None", ")" ]
Internal implementation for deleting a reftrack. This will just delete the reftrack, set the children to None, update the status, and the rootobject. If the object is an alien, it will also set the parent to None, so it dissapears from the model. :returns: None :rtype: None :raises: None
[ "Internal", "implementation", "for", "deleting", "a", "reftrack", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1338-L1367
238,107
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.get_all_children
def get_all_children(self): """Get all children including children of children :returns: all children including children of children :rtype: list of :class:`Reftrack` :raises: None """ children = self._children[:] oldlen = 0 newlen = len(children) while oldlen != newlen: start = oldlen oldlen = len(children) for i in range(start, len(children)): children.extend(children[i]._children) newlen = len(children) return children
python
def get_all_children(self): """Get all children including children of children :returns: all children including children of children :rtype: list of :class:`Reftrack` :raises: None """ children = self._children[:] oldlen = 0 newlen = len(children) while oldlen != newlen: start = oldlen oldlen = len(children) for i in range(start, len(children)): children.extend(children[i]._children) newlen = len(children) return children
[ "def", "get_all_children", "(", "self", ")", ":", "children", "=", "self", ".", "_children", "[", ":", "]", "oldlen", "=", "0", "newlen", "=", "len", "(", "children", ")", "while", "oldlen", "!=", "newlen", ":", "start", "=", "oldlen", "oldlen", "=", "len", "(", "children", ")", "for", "i", "in", "range", "(", "start", ",", "len", "(", "children", ")", ")", ":", "children", ".", "extend", "(", "children", "[", "i", "]", ".", "_children", ")", "newlen", "=", "len", "(", "children", ")", "return", "children" ]
Get all children including children of children :returns: all children including children of children :rtype: list of :class:`Reftrack` :raises: None
[ "Get", "all", "children", "including", "children", "of", "children" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1383-L1399
238,108
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.get_children_to_delete
def get_children_to_delete(self): """Return all children that are not referenced :returns: list or :class:`Reftrack` :rtype: list :raises: None """ refobjinter = self.get_refobjinter() children = self.get_all_children() todelete = [] for c in children: if c.status() is None: # if child is not in scene we do not have to delete it continue rby = refobjinter.referenced_by(c.get_refobj()) if rby is None: # child is not part of another reference. # we have to delete it for sure todelete.append(c) continue # check if child is referenced by any parent up to self # if it is not referenced by any refrence of a parent, then we # can assume it is referenced by a parent of a greater scope, # e.g. the parent of self. because we do not delete anything above self # we would have to delete the child manually parent = c.get_parent() while parent != self.get_parent(): if refobjinter.get_reference(parent.get_refobj()) == rby: # is referenced by a parent so it will get delted when the parent is deleted. break parent = parent.get_parent() else: todelete.append(c) return todelete
python
def get_children_to_delete(self): """Return all children that are not referenced :returns: list or :class:`Reftrack` :rtype: list :raises: None """ refobjinter = self.get_refobjinter() children = self.get_all_children() todelete = [] for c in children: if c.status() is None: # if child is not in scene we do not have to delete it continue rby = refobjinter.referenced_by(c.get_refobj()) if rby is None: # child is not part of another reference. # we have to delete it for sure todelete.append(c) continue # check if child is referenced by any parent up to self # if it is not referenced by any refrence of a parent, then we # can assume it is referenced by a parent of a greater scope, # e.g. the parent of self. because we do not delete anything above self # we would have to delete the child manually parent = c.get_parent() while parent != self.get_parent(): if refobjinter.get_reference(parent.get_refobj()) == rby: # is referenced by a parent so it will get delted when the parent is deleted. break parent = parent.get_parent() else: todelete.append(c) return todelete
[ "def", "get_children_to_delete", "(", "self", ")", ":", "refobjinter", "=", "self", ".", "get_refobjinter", "(", ")", "children", "=", "self", ".", "get_all_children", "(", ")", "todelete", "=", "[", "]", "for", "c", "in", "children", ":", "if", "c", ".", "status", "(", ")", "is", "None", ":", "# if child is not in scene we do not have to delete it", "continue", "rby", "=", "refobjinter", ".", "referenced_by", "(", "c", ".", "get_refobj", "(", ")", ")", "if", "rby", "is", "None", ":", "# child is not part of another reference.", "# we have to delete it for sure", "todelete", ".", "append", "(", "c", ")", "continue", "# check if child is referenced by any parent up to self", "# if it is not referenced by any refrence of a parent, then we", "# can assume it is referenced by a parent of a greater scope,", "# e.g. the parent of self. because we do not delete anything above self", "# we would have to delete the child manually", "parent", "=", "c", ".", "get_parent", "(", ")", "while", "parent", "!=", "self", ".", "get_parent", "(", ")", ":", "if", "refobjinter", ".", "get_reference", "(", "parent", ".", "get_refobj", "(", ")", ")", "==", "rby", ":", "# is referenced by a parent so it will get delted when the parent is deleted.", "break", "parent", "=", "parent", ".", "get_parent", "(", ")", "else", ":", "todelete", ".", "append", "(", "c", ")", "return", "todelete" ]
Return all children that are not referenced :returns: list or :class:`Reftrack` :rtype: list :raises: None
[ "Return", "all", "children", "that", "are", "not", "referenced" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1401-L1435
238,109
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.fetch_new_children
def fetch_new_children(self, ): """Collect all new children and add the suggestions to the children as well When an entity is loaded, referenced, imported etc there might be new children. Also it might want to suggest children itself, like a Shader for an asset. First we wrap all unwrapped children. See: :meth:`Reftrack.get_unwrapped`, :meth:`Reftrack.wrap`. Then we get the suggestions. See: :meth:`Reftrack.get_suggestions`. All suggestions that are not already a child of this Reftrack instance, will be used to create a new Reftrack with the type and element of the suggestion and the this instance as parent. :returns: None :rtype: None :raises: None """ root = self.get_root() refobjinter = self.get_refobjinter() unwrapped = self.get_unwrapped(root, refobjinter) self.wrap(self.get_root(), self.get_refobjinter(), unwrapped) suggestions = self.get_suggestions() for typ, element in suggestions: for c in self._children: if typ == c.get_typ() and element == c.get_element(): break else: Reftrack(root=root, refobjinter=refobjinter, typ=typ, element=element, parent=self)
python
def fetch_new_children(self, ): """Collect all new children and add the suggestions to the children as well When an entity is loaded, referenced, imported etc there might be new children. Also it might want to suggest children itself, like a Shader for an asset. First we wrap all unwrapped children. See: :meth:`Reftrack.get_unwrapped`, :meth:`Reftrack.wrap`. Then we get the suggestions. See: :meth:`Reftrack.get_suggestions`. All suggestions that are not already a child of this Reftrack instance, will be used to create a new Reftrack with the type and element of the suggestion and the this instance as parent. :returns: None :rtype: None :raises: None """ root = self.get_root() refobjinter = self.get_refobjinter() unwrapped = self.get_unwrapped(root, refobjinter) self.wrap(self.get_root(), self.get_refobjinter(), unwrapped) suggestions = self.get_suggestions() for typ, element in suggestions: for c in self._children: if typ == c.get_typ() and element == c.get_element(): break else: Reftrack(root=root, refobjinter=refobjinter, typ=typ, element=element, parent=self)
[ "def", "fetch_new_children", "(", "self", ",", ")", ":", "root", "=", "self", ".", "get_root", "(", ")", "refobjinter", "=", "self", ".", "get_refobjinter", "(", ")", "unwrapped", "=", "self", ".", "get_unwrapped", "(", "root", ",", "refobjinter", ")", "self", ".", "wrap", "(", "self", ".", "get_root", "(", ")", ",", "self", ".", "get_refobjinter", "(", ")", ",", "unwrapped", ")", "suggestions", "=", "self", ".", "get_suggestions", "(", ")", "for", "typ", ",", "element", "in", "suggestions", ":", "for", "c", "in", "self", ".", "_children", ":", "if", "typ", "==", "c", ".", "get_typ", "(", ")", "and", "element", "==", "c", ".", "get_element", "(", ")", ":", "break", "else", ":", "Reftrack", "(", "root", "=", "root", ",", "refobjinter", "=", "refobjinter", ",", "typ", "=", "typ", ",", "element", "=", "element", ",", "parent", "=", "self", ")" ]
Collect all new children and add the suggestions to the children as well When an entity is loaded, referenced, imported etc there might be new children. Also it might want to suggest children itself, like a Shader for an asset. First we wrap all unwrapped children. See: :meth:`Reftrack.get_unwrapped`, :meth:`Reftrack.wrap`. Then we get the suggestions. See: :meth:`Reftrack.get_suggestions`. All suggestions that are not already a child of this Reftrack instance, will be used to create a new Reftrack with the type and element of the suggestion and the this instance as parent. :returns: None :rtype: None :raises: None
[ "Collect", "all", "new", "children", "and", "add", "the", "suggestions", "to", "the", "children", "as", "well" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1459-L1485
238,110
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.set_parent_on_new
def set_parent_on_new(self, parentrefobj): """Contextmanager that on close will get all new unwrapped refobjects, and for every refobject with no parent sets is to the given one. :returns: None :rtype: None :raises: None """ refobjinter = self.get_refobjinter() # to make sure we only get the new one # we get all current unwrapped first old = self.get_unwrapped(self.get_root(), refobjinter) yield new = self.get_unwrapped(self.get_root(), refobjinter) - old for refobj in new: if refobjinter.get_parent(refobj) is None: refobjinter.set_parent(refobj, parentrefobj)
python
def set_parent_on_new(self, parentrefobj): """Contextmanager that on close will get all new unwrapped refobjects, and for every refobject with no parent sets is to the given one. :returns: None :rtype: None :raises: None """ refobjinter = self.get_refobjinter() # to make sure we only get the new one # we get all current unwrapped first old = self.get_unwrapped(self.get_root(), refobjinter) yield new = self.get_unwrapped(self.get_root(), refobjinter) - old for refobj in new: if refobjinter.get_parent(refobj) is None: refobjinter.set_parent(refobj, parentrefobj)
[ "def", "set_parent_on_new", "(", "self", ",", "parentrefobj", ")", ":", "refobjinter", "=", "self", ".", "get_refobjinter", "(", ")", "# to make sure we only get the new one", "# we get all current unwrapped first", "old", "=", "self", ".", "get_unwrapped", "(", "self", ".", "get_root", "(", ")", ",", "refobjinter", ")", "yield", "new", "=", "self", ".", "get_unwrapped", "(", "self", ".", "get_root", "(", ")", ",", "refobjinter", ")", "-", "old", "for", "refobj", "in", "new", ":", "if", "refobjinter", ".", "get_parent", "(", "refobj", ")", "is", "None", ":", "refobjinter", ".", "set_parent", "(", "refobj", ",", "parentrefobj", ")" ]
Contextmanager that on close will get all new unwrapped refobjects, and for every refobject with no parent sets is to the given one. :returns: None :rtype: None :raises: None
[ "Contextmanager", "that", "on", "close", "will", "get", "all", "new", "unwrapped", "refobjects", "and", "for", "every", "refobject", "with", "no", "parent", "sets", "is", "to", "the", "given", "one", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1506-L1523
238,111
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.set_restricted
def set_restricted(self, obj, restricted): """Set the restriction on the given object. You can use this to signal that a certain function is restricted. Then you can query the restriction later with :meth:`Reftrack.is_restricted`. :param obj: a hashable object :param restricted: True, if you want to restrict the object. :type restricted: :class:`bool` :returns: None :rtype: None :raises: None """ if restricted: self._restricted.add(obj) elif obj in self._restricted: self._restricted.remove(obj)
python
def set_restricted(self, obj, restricted): """Set the restriction on the given object. You can use this to signal that a certain function is restricted. Then you can query the restriction later with :meth:`Reftrack.is_restricted`. :param obj: a hashable object :param restricted: True, if you want to restrict the object. :type restricted: :class:`bool` :returns: None :rtype: None :raises: None """ if restricted: self._restricted.add(obj) elif obj in self._restricted: self._restricted.remove(obj)
[ "def", "set_restricted", "(", "self", ",", "obj", ",", "restricted", ")", ":", "if", "restricted", ":", "self", ".", "_restricted", ".", "add", "(", "obj", ")", "elif", "obj", "in", "self", ".", "_restricted", ":", "self", ".", "_restricted", ".", "remove", "(", "obj", ")" ]
Set the restriction on the given object. You can use this to signal that a certain function is restricted. Then you can query the restriction later with :meth:`Reftrack.is_restricted`. :param obj: a hashable object :param restricted: True, if you want to restrict the object. :type restricted: :class:`bool` :returns: None :rtype: None :raises: None
[ "Set", "the", "restriction", "on", "the", "given", "object", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1537-L1553
238,112
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.fetch_reference_restriction
def fetch_reference_restriction(self, ): """Fetch whether referencing is restricted :returns: True, if referencing is restricted :rtype: :class:`bool` :raises: None """ inter = self.get_refobjinter() restricted = self.status() is not None return restricted or inter.fetch_action_restriction(self, 'reference')
python
def fetch_reference_restriction(self, ): """Fetch whether referencing is restricted :returns: True, if referencing is restricted :rtype: :class:`bool` :raises: None """ inter = self.get_refobjinter() restricted = self.status() is not None return restricted or inter.fetch_action_restriction(self, 'reference')
[ "def", "fetch_reference_restriction", "(", "self", ",", ")", ":", "inter", "=", "self", ".", "get_refobjinter", "(", ")", "restricted", "=", "self", ".", "status", "(", ")", "is", "not", "None", "return", "restricted", "or", "inter", ".", "fetch_action_restriction", "(", "self", ",", "'reference'", ")" ]
Fetch whether referencing is restricted :returns: True, if referencing is restricted :rtype: :class:`bool` :raises: None
[ "Fetch", "whether", "referencing", "is", "restricted" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1579-L1588
238,113
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.fetch_load_restriction
def fetch_load_restriction(self, ): """Fetch whether loading is restricted :returns: True, if loading is restricted :rtype: :class:`bool` :raises: None """ inter = self.get_refobjinter() restricted = self.status() != self.UNLOADED return restricted or inter.fetch_action_restriction(self, 'load')
python
def fetch_load_restriction(self, ): """Fetch whether loading is restricted :returns: True, if loading is restricted :rtype: :class:`bool` :raises: None """ inter = self.get_refobjinter() restricted = self.status() != self.UNLOADED return restricted or inter.fetch_action_restriction(self, 'load')
[ "def", "fetch_load_restriction", "(", "self", ",", ")", ":", "inter", "=", "self", ".", "get_refobjinter", "(", ")", "restricted", "=", "self", ".", "status", "(", ")", "!=", "self", ".", "UNLOADED", "return", "restricted", "or", "inter", ".", "fetch_action_restriction", "(", "self", ",", "'load'", ")" ]
Fetch whether loading is restricted :returns: True, if loading is restricted :rtype: :class:`bool` :raises: None
[ "Fetch", "whether", "loading", "is", "restricted" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1590-L1599
238,114
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.fetch_import_ref_restriction
def fetch_import_ref_restriction(self,): """Fetch whether importing the reference is restricted :returns: True, if importing the reference is restricted :rtype: :class:`bool` :raises: None """ inter = self.get_refobjinter() restricted = self.status() not in (self.LOADED, self.UNLOADED) return restricted or inter.fetch_action_restriction(self, 'import_reference')
python
def fetch_import_ref_restriction(self,): """Fetch whether importing the reference is restricted :returns: True, if importing the reference is restricted :rtype: :class:`bool` :raises: None """ inter = self.get_refobjinter() restricted = self.status() not in (self.LOADED, self.UNLOADED) return restricted or inter.fetch_action_restriction(self, 'import_reference')
[ "def", "fetch_import_ref_restriction", "(", "self", ",", ")", ":", "inter", "=", "self", ".", "get_refobjinter", "(", ")", "restricted", "=", "self", ".", "status", "(", ")", "not", "in", "(", "self", ".", "LOADED", ",", "self", ".", "UNLOADED", ")", "return", "restricted", "or", "inter", ".", "fetch_action_restriction", "(", "self", ",", "'import_reference'", ")" ]
Fetch whether importing the reference is restricted :returns: True, if importing the reference is restricted :rtype: :class:`bool` :raises: None
[ "Fetch", "whether", "importing", "the", "reference", "is", "restricted" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1612-L1621
238,115
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.fetch_import_f_restriction
def fetch_import_f_restriction(self,): """Fetch whether importing a file is restricted :returns: True, if import is restricted :rtype: :class:`bool` :raises: None """ inter = self.get_refobjinter() restricted = self.status() is not None return restricted or inter.fetch_action_restriction(self, 'import_taskfile')
python
def fetch_import_f_restriction(self,): """Fetch whether importing a file is restricted :returns: True, if import is restricted :rtype: :class:`bool` :raises: None """ inter = self.get_refobjinter() restricted = self.status() is not None return restricted or inter.fetch_action_restriction(self, 'import_taskfile')
[ "def", "fetch_import_f_restriction", "(", "self", ",", ")", ":", "inter", "=", "self", ".", "get_refobjinter", "(", ")", "restricted", "=", "self", ".", "status", "(", ")", "is", "not", "None", "return", "restricted", "or", "inter", ".", "fetch_action_restriction", "(", "self", ",", "'import_taskfile'", ")" ]
Fetch whether importing a file is restricted :returns: True, if import is restricted :rtype: :class:`bool` :raises: None
[ "Fetch", "whether", "importing", "a", "file", "is", "restricted" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1623-L1632
238,116
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
Reftrack.emit_data_changed
def emit_data_changed(self): """Emit the data changed signal on the model of the treeitem if the treeitem has a model. :returns: None :rtype: None :raises: None """ item = self.get_treeitem() m = item.get_model() if m: start = m.index_of_item(item) parent = start.parent() end = m.index(start.row(), item.column_count()-1, parent) m.dataChanged.emit(start, end)
python
def emit_data_changed(self): """Emit the data changed signal on the model of the treeitem if the treeitem has a model. :returns: None :rtype: None :raises: None """ item = self.get_treeitem() m = item.get_model() if m: start = m.index_of_item(item) parent = start.parent() end = m.index(start.row(), item.column_count()-1, parent) m.dataChanged.emit(start, end)
[ "def", "emit_data_changed", "(", "self", ")", ":", "item", "=", "self", ".", "get_treeitem", "(", ")", "m", "=", "item", ".", "get_model", "(", ")", "if", "m", ":", "start", "=", "m", ".", "index_of_item", "(", "item", ")", "parent", "=", "start", ".", "parent", "(", ")", "end", "=", "m", ".", "index", "(", "start", ".", "row", "(", ")", ",", "item", ".", "column_count", "(", ")", "-", "1", ",", "parent", ")", "m", ".", "dataChanged", ".", "emit", "(", "start", ",", "end", ")" ]
Emit the data changed signal on the model of the treeitem if the treeitem has a model. :returns: None :rtype: None :raises: None
[ "Emit", "the", "data", "changed", "signal", "on", "the", "model", "of", "the", "treeitem", "if", "the", "treeitem", "has", "a", "model", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1655-L1669
238,117
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
RefobjInterface.create
def create(self, typ, identifier, parent=None): """Create a new refobj with the given typ and parent :param typ: the entity type :type typ: str :param identifier: the refobj id. Used to identify refobjects of the same parent, element and type in the UI :type identifier: int :param parent: the parent refobject :type parent: refobj :returns: The created refobj :rtype: refobj :raises: None """ refobj = self.create_refobj() self.set_typ(refobj, typ) self.set_id(refobj, identifier) if parent: self.set_parent(refobj, parent) return refobj
python
def create(self, typ, identifier, parent=None): """Create a new refobj with the given typ and parent :param typ: the entity type :type typ: str :param identifier: the refobj id. Used to identify refobjects of the same parent, element and type in the UI :type identifier: int :param parent: the parent refobject :type parent: refobj :returns: The created refobj :rtype: refobj :raises: None """ refobj = self.create_refobj() self.set_typ(refobj, typ) self.set_id(refobj, identifier) if parent: self.set_parent(refobj, parent) return refobj
[ "def", "create", "(", "self", ",", "typ", ",", "identifier", ",", "parent", "=", "None", ")", ":", "refobj", "=", "self", ".", "create_refobj", "(", ")", "self", ".", "set_typ", "(", "refobj", ",", "typ", ")", "self", ".", "set_id", "(", "refobj", ",", "identifier", ")", "if", "parent", ":", "self", ".", "set_parent", "(", "refobj", ",", "parent", ")", "return", "refobj" ]
Create a new refobj with the given typ and parent :param typ: the entity type :type typ: str :param identifier: the refobj id. Used to identify refobjects of the same parent, element and type in the UI :type identifier: int :param parent: the parent refobject :type parent: refobj :returns: The created refobj :rtype: refobj :raises: None
[ "Create", "a", "new", "refobj", "with", "the", "given", "typ", "and", "parent" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1903-L1921
238,118
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
RefobjInterface.delete
def delete(self, refobj): """Delete the given refobj and the contents of the entity :param refobj: the refobj to delete :type refobj: refobj :returns: None :rtype: None :raises: None """ i = self.get_typ_interface(self.get_typ(refobj)) i.delete(refobj) self.delete_refobj(refobj)
python
def delete(self, refobj): """Delete the given refobj and the contents of the entity :param refobj: the refobj to delete :type refobj: refobj :returns: None :rtype: None :raises: None """ i = self.get_typ_interface(self.get_typ(refobj)) i.delete(refobj) self.delete_refobj(refobj)
[ "def", "delete", "(", "self", ",", "refobj", ")", ":", "i", "=", "self", ".", "get_typ_interface", "(", "self", ".", "get_typ", "(", "refobj", ")", ")", "i", ".", "delete", "(", "refobj", ")", "self", ".", "delete_refobj", "(", "refobj", ")" ]
Delete the given refobj and the contents of the entity :param refobj: the refobj to delete :type refobj: refobj :returns: None :rtype: None :raises: None
[ "Delete", "the", "given", "refobj", "and", "the", "contents", "of", "the", "entity" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1935-L1946
238,119
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
RefobjInterface.reference
def reference(self, taskfileinfo, refobj): """Reference the given taskfile info and set the created reference on the refobj This will call :meth:`ReftypeInterface.reference`, then :meth:`ReftypeInterface.set_reference`. :param taskfileinfo: The taskfileinfo that holds the information for what to reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :param refobj: the refobj that should represent the new reference :type refobj: refobj :returns: None :rtype: None :raises: None """ inter = self.get_typ_interface(self.get_typ(refobj)) ref = inter.reference(refobj, taskfileinfo) self.set_reference(refobj, ref)
python
def reference(self, taskfileinfo, refobj): """Reference the given taskfile info and set the created reference on the refobj This will call :meth:`ReftypeInterface.reference`, then :meth:`ReftypeInterface.set_reference`. :param taskfileinfo: The taskfileinfo that holds the information for what to reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :param refobj: the refobj that should represent the new reference :type refobj: refobj :returns: None :rtype: None :raises: None """ inter = self.get_typ_interface(self.get_typ(refobj)) ref = inter.reference(refobj, taskfileinfo) self.set_reference(refobj, ref)
[ "def", "reference", "(", "self", ",", "taskfileinfo", ",", "refobj", ")", ":", "inter", "=", "self", ".", "get_typ_interface", "(", "self", ".", "get_typ", "(", "refobj", ")", ")", "ref", "=", "inter", ".", "reference", "(", "refobj", ",", "taskfileinfo", ")", "self", ".", "set_reference", "(", "refobj", ",", "ref", ")" ]
Reference the given taskfile info and set the created reference on the refobj This will call :meth:`ReftypeInterface.reference`, then :meth:`ReftypeInterface.set_reference`. :param taskfileinfo: The taskfileinfo that holds the information for what to reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :param refobj: the refobj that should represent the new reference :type refobj: refobj :returns: None :rtype: None :raises: None
[ "Reference", "the", "given", "taskfile", "info", "and", "set", "the", "created", "reference", "on", "the", "refobj" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1999-L2015
238,120
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
RefobjInterface.replace
def replace(self, refobj, taskfileinfo): """Replace the given refobjs reference with the taskfileinfo This will call :meth:`ReftypeInterface.replace`. :param refobj: the refobject :type refobj: refobj :param taskfileinfo: the taskfileinfo that will replace the old entity :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: None """ inter = self.get_typ_interface(self.get_typ(refobj)) ref = self.get_reference(refobj) inter.replace(refobj, ref, taskfileinfo)
python
def replace(self, refobj, taskfileinfo): """Replace the given refobjs reference with the taskfileinfo This will call :meth:`ReftypeInterface.replace`. :param refobj: the refobject :type refobj: refobj :param taskfileinfo: the taskfileinfo that will replace the old entity :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: None """ inter = self.get_typ_interface(self.get_typ(refobj)) ref = self.get_reference(refobj) inter.replace(refobj, ref, taskfileinfo)
[ "def", "replace", "(", "self", ",", "refobj", ",", "taskfileinfo", ")", ":", "inter", "=", "self", ".", "get_typ_interface", "(", "self", ".", "get_typ", "(", "refobj", ")", ")", "ref", "=", "self", ".", "get_reference", "(", "refobj", ")", "inter", ".", "replace", "(", "refobj", ",", "ref", ",", "taskfileinfo", ")" ]
Replace the given refobjs reference with the taskfileinfo This will call :meth:`ReftypeInterface.replace`. :param refobj: the refobject :type refobj: refobj :param taskfileinfo: the taskfileinfo that will replace the old entity :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: None
[ "Replace", "the", "given", "refobjs", "reference", "with", "the", "taskfileinfo" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L2055-L2070
238,121
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
RefobjInterface.is_replaceable
def is_replaceable(self, refobj): """Return whether the given reference of the refobject is replaceable or if it should just get deleted and loaded again. This will call :meth:`ReftypeInterface.is_replaceable`. :param refobj: the refobject to query :type refobj: refobj :returns: True, if replaceable :rtype: bool :raises: None """ inter = self.get_typ_interface(self.get_typ(refobj)) return inter.is_replaceable(refobj)
python
def is_replaceable(self, refobj): """Return whether the given reference of the refobject is replaceable or if it should just get deleted and loaded again. This will call :meth:`ReftypeInterface.is_replaceable`. :param refobj: the refobject to query :type refobj: refobj :returns: True, if replaceable :rtype: bool :raises: None """ inter = self.get_typ_interface(self.get_typ(refobj)) return inter.is_replaceable(refobj)
[ "def", "is_replaceable", "(", "self", ",", "refobj", ")", ":", "inter", "=", "self", ".", "get_typ_interface", "(", "self", ".", "get_typ", "(", "refobj", ")", ")", "return", "inter", ".", "is_replaceable", "(", "refobj", ")" ]
Return whether the given reference of the refobject is replaceable or if it should just get deleted and loaded again. This will call :meth:`ReftypeInterface.is_replaceable`. :param refobj: the refobject to query :type refobj: refobj :returns: True, if replaceable :rtype: bool :raises: None
[ "Return", "whether", "the", "given", "reference", "of", "the", "refobject", "is", "replaceable", "or", "if", "it", "should", "just", "get", "deleted", "and", "loaded", "again", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L2072-L2085
238,122
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
RefobjInterface.import_reference
def import_reference(self, refobj): """Import the reference of the given refobj Here we assume, that the reference is already in the scene and we break the encapsulation and pull the data from the reference into the current scene. This will call :meth:`ReftypeInterface.import_reference` and set the reference on the refobj to None. :param refobj: the refobj with a reference :type refobj: refobj :returns: None :rtype: None :raises: None """ inter = self.get_typ_interface(self.get_typ(refobj)) ref = self.get_reference(refobj) inter.import_reference(refobj, ref) self.set_reference(refobj, None)
python
def import_reference(self, refobj): """Import the reference of the given refobj Here we assume, that the reference is already in the scene and we break the encapsulation and pull the data from the reference into the current scene. This will call :meth:`ReftypeInterface.import_reference` and set the reference on the refobj to None. :param refobj: the refobj with a reference :type refobj: refobj :returns: None :rtype: None :raises: None """ inter = self.get_typ_interface(self.get_typ(refobj)) ref = self.get_reference(refobj) inter.import_reference(refobj, ref) self.set_reference(refobj, None)
[ "def", "import_reference", "(", "self", ",", "refobj", ")", ":", "inter", "=", "self", ".", "get_typ_interface", "(", "self", ".", "get_typ", "(", "refobj", ")", ")", "ref", "=", "self", ".", "get_reference", "(", "refobj", ")", "inter", ".", "import_reference", "(", "refobj", ",", "ref", ")", "self", ".", "set_reference", "(", "refobj", ",", "None", ")" ]
Import the reference of the given refobj Here we assume, that the reference is already in the scene and we break the encapsulation and pull the data from the reference into the current scene. This will call :meth:`ReftypeInterface.import_reference` and set the reference on the refobj to None. :param refobj: the refobj with a reference :type refobj: refobj :returns: None :rtype: None :raises: None
[ "Import", "the", "reference", "of", "the", "given", "refobj" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L2087-L2105
238,123
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
RefobjInterface.get_element
def get_element(self, refobj): """Return the element the refobj represents. The element is either an Asset or a Shot. :param refobj: the refobject to query :type refobj: refobj :returns: The element the reftrack represents :rtype: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :raises: None """ tf = self.get_taskfile(refobj) return tf.task.element
python
def get_element(self, refobj): """Return the element the refobj represents. The element is either an Asset or a Shot. :param refobj: the refobject to query :type refobj: refobj :returns: The element the reftrack represents :rtype: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :raises: None """ tf = self.get_taskfile(refobj) return tf.task.element
[ "def", "get_element", "(", "self", ",", "refobj", ")", ":", "tf", "=", "self", ".", "get_taskfile", "(", "refobj", ")", "return", "tf", ".", "task", ".", "element" ]
Return the element the refobj represents. The element is either an Asset or a Shot. :param refobj: the refobject to query :type refobj: refobj :returns: The element the reftrack represents :rtype: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :raises: None
[ "Return", "the", "element", "the", "refobj", "represents", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L2162-L2174
238,124
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
RefobjInterface.get_option_labels
def get_option_labels(self, typ, element): """Return labels for each level of the option model. The options returned by :meth:`RefobjInterface.fetch_options` is a treemodel with ``n`` levels. Each level should get a label to describe what is displays. E.g. if you organize your options, so that the first level shows the tasks, the second level shows the descriptors and the third one shows the versions, then your labels should be: ``["Task", "Descriptor", "Version"]``. :param typ: the typ of options. E.g. Asset, Alembic, Camera etc :type typ: str :param element: The element for which the options should be fetched. :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :returns: label strings for all levels :rtype: list :raises: None """ inter = self.get_typ_interface(typ) return inter.get_option_labels(element)
python
def get_option_labels(self, typ, element): """Return labels for each level of the option model. The options returned by :meth:`RefobjInterface.fetch_options` is a treemodel with ``n`` levels. Each level should get a label to describe what is displays. E.g. if you organize your options, so that the first level shows the tasks, the second level shows the descriptors and the third one shows the versions, then your labels should be: ``["Task", "Descriptor", "Version"]``. :param typ: the typ of options. E.g. Asset, Alembic, Camera etc :type typ: str :param element: The element for which the options should be fetched. :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :returns: label strings for all levels :rtype: list :raises: None """ inter = self.get_typ_interface(typ) return inter.get_option_labels(element)
[ "def", "get_option_labels", "(", "self", ",", "typ", ",", "element", ")", ":", "inter", "=", "self", ".", "get_typ_interface", "(", "typ", ")", "return", "inter", ".", "get_option_labels", "(", "element", ")" ]
Return labels for each level of the option model. The options returned by :meth:`RefobjInterface.fetch_options` is a treemodel with ``n`` levels. Each level should get a label to describe what is displays. E.g. if you organize your options, so that the first level shows the tasks, the second level shows the descriptors and the third one shows the versions, then your labels should be: ``["Task", "Descriptor", "Version"]``. :param typ: the typ of options. E.g. Asset, Alembic, Camera etc :type typ: str :param element: The element for which the options should be fetched. :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :returns: label strings for all levels :rtype: list :raises: None
[ "Return", "labels", "for", "each", "level", "of", "the", "option", "model", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L2208-L2227
238,125
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
RefobjInterface.get_option_columns
def get_option_columns(self, typ, element): """Return the column of the model to show for each level Because each level might be displayed in a combobox. So you might want to provide the column to show. :param typ: the typ of options. E.g. Asset, Alembic, Camera etc :type typ: str :param element: The element for wich the options should be fetched. :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :returns: a list of columns :rtype: list :raises: None """ inter = self.get_typ_interface(typ) return inter.get_option_columns(element)
python
def get_option_columns(self, typ, element): """Return the column of the model to show for each level Because each level might be displayed in a combobox. So you might want to provide the column to show. :param typ: the typ of options. E.g. Asset, Alembic, Camera etc :type typ: str :param element: The element for wich the options should be fetched. :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :returns: a list of columns :rtype: list :raises: None """ inter = self.get_typ_interface(typ) return inter.get_option_columns(element)
[ "def", "get_option_columns", "(", "self", ",", "typ", ",", "element", ")", ":", "inter", "=", "self", ".", "get_typ_interface", "(", "typ", ")", "return", "inter", ".", "get_option_columns", "(", "element", ")" ]
Return the column of the model to show for each level Because each level might be displayed in a combobox. So you might want to provide the column to show. :param typ: the typ of options. E.g. Asset, Alembic, Camera etc :type typ: str :param element: The element for wich the options should be fetched. :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :returns: a list of columns :rtype: list :raises: None
[ "Return", "the", "column", "of", "the", "model", "to", "show", "for", "each", "level" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L2229-L2244
238,126
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
RefobjInterface.get_suggestions
def get_suggestions(self, reftrack): """Return a list with possible children for this reftrack Each Reftrack may want different children. E.g. a Asset wants to suggest a shader for itself and all assets that are linked in to it in the database. Suggestions only apply for enities with status other than None. A suggestion is a tuple of typ and element. It will be used to create a newlen :class:`Reftrack`. The parent will be this instance, root and interface will of course be the same. This will delegate the call to the appropriate :class:`ReftypeInterface`. So suggestions may vary for every typ and might depend on the status of the reftrack. :param reftrack: the reftrack which needs suggestions :type reftrack: :class:`Reftrack` :returns: list of suggestions, tuples of type and element. :rtype: list :raises: None """ inter = self.get_typ_interface(reftrack.get_typ()) return inter.get_suggestions(reftrack)
python
def get_suggestions(self, reftrack): """Return a list with possible children for this reftrack Each Reftrack may want different children. E.g. a Asset wants to suggest a shader for itself and all assets that are linked in to it in the database. Suggestions only apply for enities with status other than None. A suggestion is a tuple of typ and element. It will be used to create a newlen :class:`Reftrack`. The parent will be this instance, root and interface will of course be the same. This will delegate the call to the appropriate :class:`ReftypeInterface`. So suggestions may vary for every typ and might depend on the status of the reftrack. :param reftrack: the reftrack which needs suggestions :type reftrack: :class:`Reftrack` :returns: list of suggestions, tuples of type and element. :rtype: list :raises: None """ inter = self.get_typ_interface(reftrack.get_typ()) return inter.get_suggestions(reftrack)
[ "def", "get_suggestions", "(", "self", ",", "reftrack", ")", ":", "inter", "=", "self", ".", "get_typ_interface", "(", "reftrack", ".", "get_typ", "(", ")", ")", "return", "inter", ".", "get_suggestions", "(", "reftrack", ")" ]
Return a list with possible children for this reftrack Each Reftrack may want different children. E.g. a Asset wants to suggest a shader for itself and all assets that are linked in to it in the database. Suggestions only apply for enities with status other than None. A suggestion is a tuple of typ and element. It will be used to create a newlen :class:`Reftrack`. The parent will be this instance, root and interface will of course be the same. This will delegate the call to the appropriate :class:`ReftypeInterface`. So suggestions may vary for every typ and might depend on the status of the reftrack. :param reftrack: the reftrack which needs suggestions :type reftrack: :class:`Reftrack` :returns: list of suggestions, tuples of type and element. :rtype: list :raises: None
[ "Return", "a", "list", "with", "possible", "children", "for", "this", "reftrack" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L2246-L2269
238,127
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
RefobjInterface.get_available_types_for_scene
def get_available_types_for_scene(self, element): """Return a list of types that can be used in combination with the given element to add new reftracks to the scene. This allows for example the user, to add new reftracks (aliens) to the scene. So e.g. for a shader, it wouldn't make sense to make it available to be added to the scene, because one would use them only as children of let's say an asset or cache. Some types might only be available for shots or assets etc. :param element: the element that could be used in conjuction with the returned types to create new reftracks. :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :returns: a list of types :rtype: :class:`list` :raises: None """ available = [] for typ, inter in self.types.items(): if inter(self).is_available_for_scene(element): available.append(typ) return available
python
def get_available_types_for_scene(self, element): """Return a list of types that can be used in combination with the given element to add new reftracks to the scene. This allows for example the user, to add new reftracks (aliens) to the scene. So e.g. for a shader, it wouldn't make sense to make it available to be added to the scene, because one would use them only as children of let's say an asset or cache. Some types might only be available for shots or assets etc. :param element: the element that could be used in conjuction with the returned types to create new reftracks. :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :returns: a list of types :rtype: :class:`list` :raises: None """ available = [] for typ, inter in self.types.items(): if inter(self).is_available_for_scene(element): available.append(typ) return available
[ "def", "get_available_types_for_scene", "(", "self", ",", "element", ")", ":", "available", "=", "[", "]", "for", "typ", ",", "inter", "in", "self", ".", "types", ".", "items", "(", ")", ":", "if", "inter", "(", "self", ")", ".", "is_available_for_scene", "(", "element", ")", ":", "available", ".", "append", "(", "typ", ")", "return", "available" ]
Return a list of types that can be used in combination with the given element to add new reftracks to the scene. This allows for example the user, to add new reftracks (aliens) to the scene. So e.g. for a shader, it wouldn't make sense to make it available to be added to the scene, because one would use them only as children of let's say an asset or cache. Some types might only be available for shots or assets etc. :param element: the element that could be used in conjuction with the returned types to create new reftracks. :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :returns: a list of types :rtype: :class:`list` :raises: None
[ "Return", "a", "list", "of", "types", "that", "can", "be", "used", "in", "combination", "with", "the", "given", "element", "to", "add", "new", "reftracks", "to", "the", "scene", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L2330-L2349
238,128
SeabornGames/RequestClient
seaborn/request_client/connection_endpoint.py
ConnectionEndpoint._pre_process_call
def _pre_process_call(self, name="Unknown", endpoint_params=None): """ This is called by the method_decorator within the Endpoint. The point is to capture a slot for the endpoint.method to put it's final _calls. It also allows for some special new arguments that will be extracted before the endpoint is called :param name: str of the name of the endpoint calling function :param endpoint_params: dict of the arguments passed to the endpoint method """ call_temps = self._call_temps.get(self._get_thread_id(), None) call_params = call_temps and call_temps.pop() or {} default_params = dict(name=name, label='ID_' + str(self._count), base_uri=self.base_uri, timeout=self.timeout, headers={}, cookies={}, proxies=self.proxies, accepted_return=self.accepted_return or 'json') for k, v in default_params.items(): if call_params.get(k, None) is None: call_params[k] = v sub_base_uri = call_params.pop('sub_base_uri', None) if sub_base_uri: call_params['base_uri'] = self.clean_base_uri(sub_base_uri) endpoint_params = endpoint_params or {} for k, v in (call_temps and call_temps.pop().items() or []): if v is not None and k not in endpoint_params: endpoint_params.setdefault(k, v) for k, v in self.cookies.items(): call_params['cookies'].setdefault(k, v) for k, v in self.headers.items(): call_params['headers'].setdefault(k, v) api_call = self.ApiCall(**call_params) self._call_queue.setdefault(self._get_thread_id(), []).append(api_call) if self.max_history is not 0: self._count += 1 # count of _calls if len(self) > self.max_history: self._calls.popitem(0) self._calls[call_params['label']] = api_call return api_call
python
def _pre_process_call(self, name="Unknown", endpoint_params=None): """ This is called by the method_decorator within the Endpoint. The point is to capture a slot for the endpoint.method to put it's final _calls. It also allows for some special new arguments that will be extracted before the endpoint is called :param name: str of the name of the endpoint calling function :param endpoint_params: dict of the arguments passed to the endpoint method """ call_temps = self._call_temps.get(self._get_thread_id(), None) call_params = call_temps and call_temps.pop() or {} default_params = dict(name=name, label='ID_' + str(self._count), base_uri=self.base_uri, timeout=self.timeout, headers={}, cookies={}, proxies=self.proxies, accepted_return=self.accepted_return or 'json') for k, v in default_params.items(): if call_params.get(k, None) is None: call_params[k] = v sub_base_uri = call_params.pop('sub_base_uri', None) if sub_base_uri: call_params['base_uri'] = self.clean_base_uri(sub_base_uri) endpoint_params = endpoint_params or {} for k, v in (call_temps and call_temps.pop().items() or []): if v is not None and k not in endpoint_params: endpoint_params.setdefault(k, v) for k, v in self.cookies.items(): call_params['cookies'].setdefault(k, v) for k, v in self.headers.items(): call_params['headers'].setdefault(k, v) api_call = self.ApiCall(**call_params) self._call_queue.setdefault(self._get_thread_id(), []).append(api_call) if self.max_history is not 0: self._count += 1 # count of _calls if len(self) > self.max_history: self._calls.popitem(0) self._calls[call_params['label']] = api_call return api_call
[ "def", "_pre_process_call", "(", "self", ",", "name", "=", "\"Unknown\"", ",", "endpoint_params", "=", "None", ")", ":", "call_temps", "=", "self", ".", "_call_temps", ".", "get", "(", "self", ".", "_get_thread_id", "(", ")", ",", "None", ")", "call_params", "=", "call_temps", "and", "call_temps", ".", "pop", "(", ")", "or", "{", "}", "default_params", "=", "dict", "(", "name", "=", "name", ",", "label", "=", "'ID_'", "+", "str", "(", "self", ".", "_count", ")", ",", "base_uri", "=", "self", ".", "base_uri", ",", "timeout", "=", "self", ".", "timeout", ",", "headers", "=", "{", "}", ",", "cookies", "=", "{", "}", ",", "proxies", "=", "self", ".", "proxies", ",", "accepted_return", "=", "self", ".", "accepted_return", "or", "'json'", ")", "for", "k", ",", "v", "in", "default_params", ".", "items", "(", ")", ":", "if", "call_params", ".", "get", "(", "k", ",", "None", ")", "is", "None", ":", "call_params", "[", "k", "]", "=", "v", "sub_base_uri", "=", "call_params", ".", "pop", "(", "'sub_base_uri'", ",", "None", ")", "if", "sub_base_uri", ":", "call_params", "[", "'base_uri'", "]", "=", "self", ".", "clean_base_uri", "(", "sub_base_uri", ")", "endpoint_params", "=", "endpoint_params", "or", "{", "}", "for", "k", ",", "v", "in", "(", "call_temps", "and", "call_temps", ".", "pop", "(", ")", ".", "items", "(", ")", "or", "[", "]", ")", ":", "if", "v", "is", "not", "None", "and", "k", "not", "in", "endpoint_params", ":", "endpoint_params", ".", "setdefault", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "cookies", ".", "items", "(", ")", ":", "call_params", "[", "'cookies'", "]", ".", "setdefault", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "headers", ".", "items", "(", ")", ":", "call_params", "[", "'headers'", "]", ".", "setdefault", "(", "k", ",", "v", ")", "api_call", "=", "self", ".", "ApiCall", "(", "*", "*", "call_params", ")", "self", ".", "_call_queue", ".", "setdefault", "(", "self", ".", "_get_thread_id", "(", ")", ",", "[", "]", ")", ".", "append", "(", "api_call", ")", "if", "self", ".", "max_history", "is", "not", "0", ":", "self", ".", "_count", "+=", "1", "# count of _calls", "if", "len", "(", "self", ")", ">", "self", ".", "max_history", ":", "self", ".", "_calls", ".", "popitem", "(", "0", ")", "self", ".", "_calls", "[", "call_params", "[", "'label'", "]", "]", "=", "api_call", "return", "api_call" ]
This is called by the method_decorator within the Endpoint. The point is to capture a slot for the endpoint.method to put it's final _calls. It also allows for some special new arguments that will be extracted before the endpoint is called :param name: str of the name of the endpoint calling function :param endpoint_params: dict of the arguments passed to the endpoint method
[ "This", "is", "called", "by", "the", "method_decorator", "within", "the", "Endpoint", ".", "The", "point", "is", "to", "capture", "a", "slot", "for", "the", "endpoint", ".", "method", "to", "put", "it", "s", "final", "_calls", ".", "It", "also", "allows", "for", "some", "special", "new", "arguments", "that", "will", "be", "extracted", "before", "the", "endpoint", "is", "called" ]
21aeb951ddfdb6ee453ad0edc896ff224e06425d
https://github.com/SeabornGames/RequestClient/blob/21aeb951ddfdb6ee453ad0edc896ff224e06425d/seaborn/request_client/connection_endpoint.py#L70-L121
238,129
limodou/ido
ido/utils.py
function
def function(fname): """ Make a function to Function class """ def _f(func): class WrapFunction(Function): name = fname def __call__(self, *args, **kwargs): return func(*args, **kwargs) return WrapFunction return _f
python
def function(fname): """ Make a function to Function class """ def _f(func): class WrapFunction(Function): name = fname def __call__(self, *args, **kwargs): return func(*args, **kwargs) return WrapFunction return _f
[ "def", "function", "(", "fname", ")", ":", "def", "_f", "(", "func", ")", ":", "class", "WrapFunction", "(", "Function", ")", ":", "name", "=", "fname", "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "WrapFunction", "return", "_f" ]
Make a function to Function class
[ "Make", "a", "function", "to", "Function", "class" ]
7fcf5c20b47993b6c16eb6007f77ad1c868a6d68
https://github.com/limodou/ido/blob/7fcf5c20b47993b6c16eb6007f77ad1c868a6d68/ido/utils.py#L56-L69
238,130
ericflo/hurricane
hurricane/handlers/comet/utils.py
parse_cookie
def parse_cookie(header, charset='utf-8', errors='ignore'): """Parse a cookie. :param header: the header to be used to parse the cookie. :param charset: the charset for the cookie values. :param errors: the error behavior for the charset decoding. """ cookie = _ExtendedCookie() if header: cookie.load(header) result = {} # decode to unicode and skip broken items. Our extended morsel # and extended cookie will catch CookieErrors and convert them to # `None` items which we have to skip here. for key, value in cookie.iteritems(): if value.value is not None: result[key] = unquote_header_value(value.value) \ .decode(charset, errors) return result
python
def parse_cookie(header, charset='utf-8', errors='ignore'): """Parse a cookie. :param header: the header to be used to parse the cookie. :param charset: the charset for the cookie values. :param errors: the error behavior for the charset decoding. """ cookie = _ExtendedCookie() if header: cookie.load(header) result = {} # decode to unicode and skip broken items. Our extended morsel # and extended cookie will catch CookieErrors and convert them to # `None` items which we have to skip here. for key, value in cookie.iteritems(): if value.value is not None: result[key] = unquote_header_value(value.value) \ .decode(charset, errors) return result
[ "def", "parse_cookie", "(", "header", ",", "charset", "=", "'utf-8'", ",", "errors", "=", "'ignore'", ")", ":", "cookie", "=", "_ExtendedCookie", "(", ")", "if", "header", ":", "cookie", ".", "load", "(", "header", ")", "result", "=", "{", "}", "# decode to unicode and skip broken items. Our extended morsel", "# and extended cookie will catch CookieErrors and convert them to", "# `None` items which we have to skip here.", "for", "key", ",", "value", "in", "cookie", ".", "iteritems", "(", ")", ":", "if", "value", ".", "value", "is", "not", "None", ":", "result", "[", "key", "]", "=", "unquote_header_value", "(", "value", ".", "value", ")", ".", "decode", "(", "charset", ",", "errors", ")", "return", "result" ]
Parse a cookie. :param header: the header to be used to parse the cookie. :param charset: the charset for the cookie values. :param errors: the error behavior for the charset decoding.
[ "Parse", "a", "cookie", "." ]
c192b711b2b1c06a386d1a1a47f538b13a659cde
https://github.com/ericflo/hurricane/blob/c192b711b2b1c06a386d1a1a47f538b13a659cde/hurricane/handlers/comet/utils.py#L58-L78
238,131
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValue.py
AnyValue.equals_as
def equals_as(self, value_type, other): """ Compares this object value to specified specified value. When direct comparison gives negative results it converts values to type specified by type code and compare them again. :param value_type: the Typecode type that defined the type of the result :param other: the value to be compared with. :return: true when objects are equal and false otherwise. """ if other == None and self.value == None: return True if other == None or self.value == None: return False if isinstance(other, AnyValue): other = other._value if other == self.value: return True value1 = TypeConverter.to_type(value_type, self.value) value2 = TypeConverter.to_type(value_type, other) if value1 == None or value2 == None: return False return value1 == value2
python
def equals_as(self, value_type, other): """ Compares this object value to specified specified value. When direct comparison gives negative results it converts values to type specified by type code and compare them again. :param value_type: the Typecode type that defined the type of the result :param other: the value to be compared with. :return: true when objects are equal and false otherwise. """ if other == None and self.value == None: return True if other == None or self.value == None: return False if isinstance(other, AnyValue): other = other._value if other == self.value: return True value1 = TypeConverter.to_type(value_type, self.value) value2 = TypeConverter.to_type(value_type, other) if value1 == None or value2 == None: return False return value1 == value2
[ "def", "equals_as", "(", "self", ",", "value_type", ",", "other", ")", ":", "if", "other", "==", "None", "and", "self", ".", "value", "==", "None", ":", "return", "True", "if", "other", "==", "None", "or", "self", ".", "value", "==", "None", ":", "return", "False", "if", "isinstance", "(", "other", ",", "AnyValue", ")", ":", "other", "=", "other", ".", "_value", "if", "other", "==", "self", ".", "value", ":", "return", "True", "value1", "=", "TypeConverter", ".", "to_type", "(", "value_type", ",", "self", ".", "value", ")", "value2", "=", "TypeConverter", ".", "to_type", "(", "value_type", ",", "other", ")", "if", "value1", "==", "None", "or", "value2", "==", "None", ":", "return", "False", "return", "value1", "==", "value2" ]
Compares this object value to specified specified value. When direct comparison gives negative results it converts values to type specified by type code and compare them again. :param value_type: the Typecode type that defined the type of the result :param other: the value to be compared with. :return: true when objects are equal and false otherwise.
[ "Compares", "this", "object", "value", "to", "specified", "specified", "value", ".", "When", "direct", "comparison", "gives", "negative", "results", "it", "converts", "values", "to", "type", "specified", "by", "type", "code", "and", "compare", "them", "again", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValue.py#L296-L325
238,132
foliant-docs/foliantcontrib.mkdocs
foliant/preprocessors/mkdocs.py
Preprocessor._collect_images
def _collect_images(self, content: str, md_file_path: Path) -> str: '''Find images outside the source directory, copy them into the source directory, and replace the paths in the source. This is necessary because MkDocs can't deal with images outside the project's doc_dir. :param content: Markdown content :param md_file_path: Path to the Markdown file with content ``content`` :returns: Markdown content with image paths pointing within the source directory ''' self.logger.debug(f'Looking for images in {md_file_path}.') def _sub(image): image_caption = image.group('caption') image_path = (md_file_path.parent / Path(image.group('path'))).resolve() self.logger.debug(f'Detected image: caption="{image_caption}", path={image_path}') if self.working_dir.resolve() not in image_path.parents: self.logger.debug('Image outside source directory.') self._collected_imgs_path.mkdir(exist_ok=True) collected_img_path = ( self._collected_imgs_path/f'{image_path.stem}_{str(uuid1())}' ).with_suffix(image_path.suffix) copy(image_path, collected_img_path) self.logger.debug(f'Image copied to {collected_img_path}') rel_img_path = Path(relpath(collected_img_path, md_file_path.parent)).as_posix() else: self.logger.debug('Image inside source directory.') rel_img_path = Path(relpath(image_path, md_file_path.parent)).as_posix() img_ref = f'![{image_caption}]({rel_img_path})' self.logger.debug(f'Replacing with: {img_ref}') return img_ref return self._image_pattern.sub(_sub, content)
python
def _collect_images(self, content: str, md_file_path: Path) -> str: '''Find images outside the source directory, copy them into the source directory, and replace the paths in the source. This is necessary because MkDocs can't deal with images outside the project's doc_dir. :param content: Markdown content :param md_file_path: Path to the Markdown file with content ``content`` :returns: Markdown content with image paths pointing within the source directory ''' self.logger.debug(f'Looking for images in {md_file_path}.') def _sub(image): image_caption = image.group('caption') image_path = (md_file_path.parent / Path(image.group('path'))).resolve() self.logger.debug(f'Detected image: caption="{image_caption}", path={image_path}') if self.working_dir.resolve() not in image_path.parents: self.logger.debug('Image outside source directory.') self._collected_imgs_path.mkdir(exist_ok=True) collected_img_path = ( self._collected_imgs_path/f'{image_path.stem}_{str(uuid1())}' ).with_suffix(image_path.suffix) copy(image_path, collected_img_path) self.logger.debug(f'Image copied to {collected_img_path}') rel_img_path = Path(relpath(collected_img_path, md_file_path.parent)).as_posix() else: self.logger.debug('Image inside source directory.') rel_img_path = Path(relpath(image_path, md_file_path.parent)).as_posix() img_ref = f'![{image_caption}]({rel_img_path})' self.logger.debug(f'Replacing with: {img_ref}') return img_ref return self._image_pattern.sub(_sub, content)
[ "def", "_collect_images", "(", "self", ",", "content", ":", "str", ",", "md_file_path", ":", "Path", ")", "->", "str", ":", "self", ".", "logger", ".", "debug", "(", "f'Looking for images in {md_file_path}.'", ")", "def", "_sub", "(", "image", ")", ":", "image_caption", "=", "image", ".", "group", "(", "'caption'", ")", "image_path", "=", "(", "md_file_path", ".", "parent", "/", "Path", "(", "image", ".", "group", "(", "'path'", ")", ")", ")", ".", "resolve", "(", ")", "self", ".", "logger", ".", "debug", "(", "f'Detected image: caption=\"{image_caption}\", path={image_path}'", ")", "if", "self", ".", "working_dir", ".", "resolve", "(", ")", "not", "in", "image_path", ".", "parents", ":", "self", ".", "logger", ".", "debug", "(", "'Image outside source directory.'", ")", "self", ".", "_collected_imgs_path", ".", "mkdir", "(", "exist_ok", "=", "True", ")", "collected_img_path", "=", "(", "self", ".", "_collected_imgs_path", "/", "f'{image_path.stem}_{str(uuid1())}'", ")", ".", "with_suffix", "(", "image_path", ".", "suffix", ")", "copy", "(", "image_path", ",", "collected_img_path", ")", "self", ".", "logger", ".", "debug", "(", "f'Image copied to {collected_img_path}'", ")", "rel_img_path", "=", "Path", "(", "relpath", "(", "collected_img_path", ",", "md_file_path", ".", "parent", ")", ")", ".", "as_posix", "(", ")", "else", ":", "self", ".", "logger", ".", "debug", "(", "'Image inside source directory.'", ")", "rel_img_path", "=", "Path", "(", "relpath", "(", "image_path", ",", "md_file_path", ".", "parent", ")", ")", ".", "as_posix", "(", ")", "img_ref", "=", "f'![{image_caption}]({rel_img_path})'", "self", ".", "logger", ".", "debug", "(", "f'Replacing with: {img_ref}'", ")", "return", "img_ref", "return", "self", ".", "_image_pattern", ".", "sub", "(", "_sub", ",", "content", ")" ]
Find images outside the source directory, copy them into the source directory, and replace the paths in the source. This is necessary because MkDocs can't deal with images outside the project's doc_dir. :param content: Markdown content :param md_file_path: Path to the Markdown file with content ``content`` :returns: Markdown content with image paths pointing within the source directory
[ "Find", "images", "outside", "the", "source", "directory", "copy", "them", "into", "the", "source", "directory", "and", "replace", "the", "paths", "in", "the", "source", "." ]
5f71a47139ab1cb630f1b61d4cef1c0657001272
https://github.com/foliant-docs/foliantcontrib.mkdocs/blob/5f71a47139ab1cb630f1b61d4cef1c0657001272/foliant/preprocessors/mkdocs.py#L15-L60
238,133
roboogle/gtkmvc3
gtkmvco/gtkmvc3/support/metaclasses.py
PropertyMeta.has_prop_attribute
def has_prop_attribute(cls, prop_name): # @NoSelf """This methods returns True if there exists a class attribute for the given property. The attribute is searched locally only""" return (prop_name in cls.__dict__ and not isinstance(cls.__dict__[prop_name], types.FunctionType))
python
def has_prop_attribute(cls, prop_name): # @NoSelf """This methods returns True if there exists a class attribute for the given property. The attribute is searched locally only""" return (prop_name in cls.__dict__ and not isinstance(cls.__dict__[prop_name], types.FunctionType))
[ "def", "has_prop_attribute", "(", "cls", ",", "prop_name", ")", ":", "# @NoSelf", "return", "(", "prop_name", "in", "cls", ".", "__dict__", "and", "not", "isinstance", "(", "cls", ".", "__dict__", "[", "prop_name", "]", ",", "types", ".", "FunctionType", ")", ")" ]
This methods returns True if there exists a class attribute for the given property. The attribute is searched locally only
[ "This", "methods", "returns", "True", "if", "there", "exists", "a", "class", "attribute", "for", "the", "given", "property", ".", "The", "attribute", "is", "searched", "locally", "only" ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/support/metaclasses.py#L421-L426
238,134
roboogle/gtkmvc3
gtkmvco/gtkmvc3/support/metaclasses.py
PropertyMeta.check_value_change
def check_value_change(cls, old, new): # @NoSelf """Checks whether the value of the property changed in type or if the instance has been changed to a different instance. If true, a call to model._reset_property_notification should be called in order to re-register the new property instance or type""" return (type(old) != type(new) or isinstance(old, wrappers.ObsWrapperBase) and old != new)
python
def check_value_change(cls, old, new): # @NoSelf """Checks whether the value of the property changed in type or if the instance has been changed to a different instance. If true, a call to model._reset_property_notification should be called in order to re-register the new property instance or type""" return (type(old) != type(new) or isinstance(old, wrappers.ObsWrapperBase) and old != new)
[ "def", "check_value_change", "(", "cls", ",", "old", ",", "new", ")", ":", "# @NoSelf", "return", "(", "type", "(", "old", ")", "!=", "type", "(", "new", ")", "or", "isinstance", "(", "old", ",", "wrappers", ".", "ObsWrapperBase", ")", "and", "old", "!=", "new", ")" ]
Checks whether the value of the property changed in type or if the instance has been changed to a different instance. If true, a call to model._reset_property_notification should be called in order to re-register the new property instance or type
[ "Checks", "whether", "the", "value", "of", "the", "property", "changed", "in", "type", "or", "if", "the", "instance", "has", "been", "changed", "to", "a", "different", "instance", ".", "If", "true", "a", "call", "to", "model", ".", "_reset_property_notification", "should", "be", "called", "in", "order", "to", "re", "-", "register", "the", "new", "property", "instance", "or", "type" ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/support/metaclasses.py#L428-L435
238,135
roboogle/gtkmvc3
gtkmvco/gtkmvc3/support/metaclasses.py
PropertyMeta.get_getter
def get_getter(cls, prop_name, # @NoSelf user_getter=None, getter_takes_name=False): """Returns a function wich is a getter for a property. prop_name is the name off the property. user_getter is an optional function doing the work. If specified, that function will be called instead of getting the attribute whose name is in 'prop_name'. If user_getter is specified with a False value for getter_takes_name (default), than the method is used to get the value of the property. If True is specified for getter_takes_name, then the user_getter is called by passing the property name (i.e. it is considered a general method which receive the property name whose value has to be returned.) """ if user_getter: if getter_takes_name: # wraps the property name _deps = type(cls)._get_old_style_getter_deps(cls, prop_name, user_getter) def _getter(self, deps=_deps): return user_getter(self, prop_name) else: _getter = user_getter return _getter def _getter(self): # @DuplicatedSignature return getattr(self, PROP_NAME % {'prop_name' : prop_name}) return _getter
python
def get_getter(cls, prop_name, # @NoSelf user_getter=None, getter_takes_name=False): """Returns a function wich is a getter for a property. prop_name is the name off the property. user_getter is an optional function doing the work. If specified, that function will be called instead of getting the attribute whose name is in 'prop_name'. If user_getter is specified with a False value for getter_takes_name (default), than the method is used to get the value of the property. If True is specified for getter_takes_name, then the user_getter is called by passing the property name (i.e. it is considered a general method which receive the property name whose value has to be returned.) """ if user_getter: if getter_takes_name: # wraps the property name _deps = type(cls)._get_old_style_getter_deps(cls, prop_name, user_getter) def _getter(self, deps=_deps): return user_getter(self, prop_name) else: _getter = user_getter return _getter def _getter(self): # @DuplicatedSignature return getattr(self, PROP_NAME % {'prop_name' : prop_name}) return _getter
[ "def", "get_getter", "(", "cls", ",", "prop_name", ",", "# @NoSelf", "user_getter", "=", "None", ",", "getter_takes_name", "=", "False", ")", ":", "if", "user_getter", ":", "if", "getter_takes_name", ":", "# wraps the property name", "_deps", "=", "type", "(", "cls", ")", ".", "_get_old_style_getter_deps", "(", "cls", ",", "prop_name", ",", "user_getter", ")", "def", "_getter", "(", "self", ",", "deps", "=", "_deps", ")", ":", "return", "user_getter", "(", "self", ",", "prop_name", ")", "else", ":", "_getter", "=", "user_getter", "return", "_getter", "def", "_getter", "(", "self", ")", ":", "# @DuplicatedSignature", "return", "getattr", "(", "self", ",", "PROP_NAME", "%", "{", "'prop_name'", ":", "prop_name", "}", ")", "return", "_getter" ]
Returns a function wich is a getter for a property. prop_name is the name off the property. user_getter is an optional function doing the work. If specified, that function will be called instead of getting the attribute whose name is in 'prop_name'. If user_getter is specified with a False value for getter_takes_name (default), than the method is used to get the value of the property. If True is specified for getter_takes_name, then the user_getter is called by passing the property name (i.e. it is considered a general method which receive the property name whose value has to be returned.)
[ "Returns", "a", "function", "wich", "is", "a", "getter", "for", "a", "property", ".", "prop_name", "is", "the", "name", "off", "the", "property", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/support/metaclasses.py#L489-L519
238,136
zkbt/the-friendly-stars
thefriendlystars/constellations/others.py
GALEX.coneSearch
def coneSearch(self, center, radius=3*u.arcmin, magnitudelimit=25): ''' Run a cone search of the GALEX archive ''' self.magnitudelimit = magnitudelimit # run the query self.speak('querying GALEX, centered on {} with radius {}'.format(center, radius, magnitudelimit)) coordinatetosearch = '{0.ra.deg} {0.dec.deg}'.format(center) table = astroquery.mast.Catalogs.query_region(coordinates=center, radius=radius, catalog='GALEX') # the gaia DR2 epoch is 2015.5 epoch = 2005#??? # create skycoord objects self.coordinates = coord.SkyCoord( ra=table['ra'].data*u.deg, dec=table['dec'].data*u.deg, obstime=Time(epoch, format='decimalyear')) self.magnitudes = dict(NUV=table['nuv_mag'].data, FUV=table['fuv_mag'].data) self.magnitude = self.magnitudes['NUV']
python
def coneSearch(self, center, radius=3*u.arcmin, magnitudelimit=25): ''' Run a cone search of the GALEX archive ''' self.magnitudelimit = magnitudelimit # run the query self.speak('querying GALEX, centered on {} with radius {}'.format(center, radius, magnitudelimit)) coordinatetosearch = '{0.ra.deg} {0.dec.deg}'.format(center) table = astroquery.mast.Catalogs.query_region(coordinates=center, radius=radius, catalog='GALEX') # the gaia DR2 epoch is 2015.5 epoch = 2005#??? # create skycoord objects self.coordinates = coord.SkyCoord( ra=table['ra'].data*u.deg, dec=table['dec'].data*u.deg, obstime=Time(epoch, format='decimalyear')) self.magnitudes = dict(NUV=table['nuv_mag'].data, FUV=table['fuv_mag'].data) self.magnitude = self.magnitudes['NUV']
[ "def", "coneSearch", "(", "self", ",", "center", ",", "radius", "=", "3", "*", "u", ".", "arcmin", ",", "magnitudelimit", "=", "25", ")", ":", "self", ".", "magnitudelimit", "=", "magnitudelimit", "# run the query", "self", ".", "speak", "(", "'querying GALEX, centered on {} with radius {}'", ".", "format", "(", "center", ",", "radius", ",", "magnitudelimit", ")", ")", "coordinatetosearch", "=", "'{0.ra.deg} {0.dec.deg}'", ".", "format", "(", "center", ")", "table", "=", "astroquery", ".", "mast", ".", "Catalogs", ".", "query_region", "(", "coordinates", "=", "center", ",", "radius", "=", "radius", ",", "catalog", "=", "'GALEX'", ")", "# the gaia DR2 epoch is 2015.5", "epoch", "=", "2005", "#???", "# create skycoord objects", "self", ".", "coordinates", "=", "coord", ".", "SkyCoord", "(", "ra", "=", "table", "[", "'ra'", "]", ".", "data", "*", "u", ".", "deg", ",", "dec", "=", "table", "[", "'dec'", "]", ".", "data", "*", "u", ".", "deg", ",", "obstime", "=", "Time", "(", "epoch", ",", "format", "=", "'decimalyear'", ")", ")", "self", ".", "magnitudes", "=", "dict", "(", "NUV", "=", "table", "[", "'nuv_mag'", "]", ".", "data", ",", "FUV", "=", "table", "[", "'fuv_mag'", "]", ".", "data", ")", "self", ".", "magnitude", "=", "self", ".", "magnitudes", "[", "'NUV'", "]" ]
Run a cone search of the GALEX archive
[ "Run", "a", "cone", "search", "of", "the", "GALEX", "archive" ]
50d3f979e79e63c66629065c75595696dc79802e
https://github.com/zkbt/the-friendly-stars/blob/50d3f979e79e63c66629065c75595696dc79802e/thefriendlystars/constellations/others.py#L10-L35
238,137
mlavin/argyle
argyle/nginx.py
upload_nginx_site_conf
def upload_nginx_site_conf(site_name, template_name=None, context=None, enable=True): """Upload Nginx site configuration from a template.""" template_name = template_name or [u'nginx/%s.conf' % site_name, u'nginx/site.conf'] site_available = u'/etc/nginx/sites-available/%s' % site_name upload_template(template_name, site_available, context=context, use_sudo=True) if enable: enable_site(site_name)
python
def upload_nginx_site_conf(site_name, template_name=None, context=None, enable=True): """Upload Nginx site configuration from a template.""" template_name = template_name or [u'nginx/%s.conf' % site_name, u'nginx/site.conf'] site_available = u'/etc/nginx/sites-available/%s' % site_name upload_template(template_name, site_available, context=context, use_sudo=True) if enable: enable_site(site_name)
[ "def", "upload_nginx_site_conf", "(", "site_name", ",", "template_name", "=", "None", ",", "context", "=", "None", ",", "enable", "=", "True", ")", ":", "template_name", "=", "template_name", "or", "[", "u'nginx/%s.conf'", "%", "site_name", ",", "u'nginx/site.conf'", "]", "site_available", "=", "u'/etc/nginx/sites-available/%s'", "%", "site_name", "upload_template", "(", "template_name", ",", "site_available", ",", "context", "=", "context", ",", "use_sudo", "=", "True", ")", "if", "enable", ":", "enable_site", "(", "site_name", ")" ]
Upload Nginx site configuration from a template.
[ "Upload", "Nginx", "site", "configuration", "from", "a", "template", "." ]
92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72
https://github.com/mlavin/argyle/blob/92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72/argyle/nginx.py#L15-L22
238,138
mlavin/argyle
argyle/nginx.py
enable_site
def enable_site(site_name): """Enable an available Nginx site.""" site_available = u'/etc/nginx/sites-available/%s' % site_name site_enabled = u'/etc/nginx/sites-enabled/%s' % site_name if files.exists(site_available): sudo(u'ln -s -f %s %s' % (site_available, site_enabled)) restart_service(u'nginx') else: abort(u'%s site configuration is not available' % site_name)
python
def enable_site(site_name): """Enable an available Nginx site.""" site_available = u'/etc/nginx/sites-available/%s' % site_name site_enabled = u'/etc/nginx/sites-enabled/%s' % site_name if files.exists(site_available): sudo(u'ln -s -f %s %s' % (site_available, site_enabled)) restart_service(u'nginx') else: abort(u'%s site configuration is not available' % site_name)
[ "def", "enable_site", "(", "site_name", ")", ":", "site_available", "=", "u'/etc/nginx/sites-available/%s'", "%", "site_name", "site_enabled", "=", "u'/etc/nginx/sites-enabled/%s'", "%", "site_name", "if", "files", ".", "exists", "(", "site_available", ")", ":", "sudo", "(", "u'ln -s -f %s %s'", "%", "(", "site_available", ",", "site_enabled", ")", ")", "restart_service", "(", "u'nginx'", ")", "else", ":", "abort", "(", "u'%s site configuration is not available'", "%", "site_name", ")" ]
Enable an available Nginx site.
[ "Enable", "an", "available", "Nginx", "site", "." ]
92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72
https://github.com/mlavin/argyle/blob/92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72/argyle/nginx.py#L26-L35
238,139
mlavin/argyle
argyle/nginx.py
disable_site
def disable_site(site_name): """Disables Nginx site configuration.""" site = u'/etc/nginx/sites-enabled/%s' % site_name if files.exists(site): sudo(u'rm %s' % site) restart_service(u'nginx')
python
def disable_site(site_name): """Disables Nginx site configuration.""" site = u'/etc/nginx/sites-enabled/%s' % site_name if files.exists(site): sudo(u'rm %s' % site) restart_service(u'nginx')
[ "def", "disable_site", "(", "site_name", ")", ":", "site", "=", "u'/etc/nginx/sites-enabled/%s'", "%", "site_name", "if", "files", ".", "exists", "(", "site", ")", ":", "sudo", "(", "u'rm %s'", "%", "site", ")", "restart_service", "(", "u'nginx'", ")" ]
Disables Nginx site configuration.
[ "Disables", "Nginx", "site", "configuration", "." ]
92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72
https://github.com/mlavin/argyle/blob/92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72/argyle/nginx.py#L39-L45
238,140
host-anshu/simpleInterceptor
example/call_graph/utils.py
suppressConsoleOut
def suppressConsoleOut(meth): """Disable console output during the method is run.""" @wraps(meth) def decorate(*args, **kwargs): """Decorate""" # Disable ansible console output _stdout = sys.stdout fptr = open(os.devnull, 'w') sys.stdout = fptr try: return meth(*args, **kwargs) except Exception as e: raise e finally: # Enable console output sys.stdout = _stdout return decorate
python
def suppressConsoleOut(meth): """Disable console output during the method is run.""" @wraps(meth) def decorate(*args, **kwargs): """Decorate""" # Disable ansible console output _stdout = sys.stdout fptr = open(os.devnull, 'w') sys.stdout = fptr try: return meth(*args, **kwargs) except Exception as e: raise e finally: # Enable console output sys.stdout = _stdout return decorate
[ "def", "suppressConsoleOut", "(", "meth", ")", ":", "@", "wraps", "(", "meth", ")", "def", "decorate", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Decorate\"\"\"", "# Disable ansible console output", "_stdout", "=", "sys", ".", "stdout", "fptr", "=", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "sys", ".", "stdout", "=", "fptr", "try", ":", "return", "meth", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":", "raise", "e", "finally", ":", "# Enable console output", "sys", ".", "stdout", "=", "_stdout", "return", "decorate" ]
Disable console output during the method is run.
[ "Disable", "console", "output", "during", "the", "method", "is", "run", "." ]
71238fed57c62b5f77ce32d0c9b98acad73ab6a8
https://github.com/host-anshu/simpleInterceptor/blob/71238fed57c62b5f77ce32d0c9b98acad73ab6a8/example/call_graph/utils.py#L8-L24
238,141
ravenac95/overlay4u
overlay4u/overlay.py
OverlayFS.mount
def mount(cls, mount_point, lower_dir, upper_dir, mount_table=None): """Execute the mount. This requires root""" ensure_directories(mount_point, lower_dir, upper_dir) # Load the mount table if it isn't given if not mount_table: mount_table = MountTable.load() # Check if the mount_point is in use if mount_table.is_mounted(mount_point): # Throw an error if it is raise AlreadyMounted() # Build mount options options = "rw,lowerdir=%s,upperdir=%s" % (lower_dir, upper_dir) # Run the actual mount subwrap.run(['mount', '-t', 'overlayfs', '-o', options, 'olyfs%s' % random_name(), mount_point]) return cls(mount_point, lower_dir, upper_dir)
python
def mount(cls, mount_point, lower_dir, upper_dir, mount_table=None): """Execute the mount. This requires root""" ensure_directories(mount_point, lower_dir, upper_dir) # Load the mount table if it isn't given if not mount_table: mount_table = MountTable.load() # Check if the mount_point is in use if mount_table.is_mounted(mount_point): # Throw an error if it is raise AlreadyMounted() # Build mount options options = "rw,lowerdir=%s,upperdir=%s" % (lower_dir, upper_dir) # Run the actual mount subwrap.run(['mount', '-t', 'overlayfs', '-o', options, 'olyfs%s' % random_name(), mount_point]) return cls(mount_point, lower_dir, upper_dir)
[ "def", "mount", "(", "cls", ",", "mount_point", ",", "lower_dir", ",", "upper_dir", ",", "mount_table", "=", "None", ")", ":", "ensure_directories", "(", "mount_point", ",", "lower_dir", ",", "upper_dir", ")", "# Load the mount table if it isn't given", "if", "not", "mount_table", ":", "mount_table", "=", "MountTable", ".", "load", "(", ")", "# Check if the mount_point is in use", "if", "mount_table", ".", "is_mounted", "(", "mount_point", ")", ":", "# Throw an error if it is", "raise", "AlreadyMounted", "(", ")", "# Build mount options", "options", "=", "\"rw,lowerdir=%s,upperdir=%s\"", "%", "(", "lower_dir", ",", "upper_dir", ")", "# Run the actual mount", "subwrap", ".", "run", "(", "[", "'mount'", ",", "'-t'", ",", "'overlayfs'", ",", "'-o'", ",", "options", ",", "'olyfs%s'", "%", "random_name", "(", ")", ",", "mount_point", "]", ")", "return", "cls", "(", "mount_point", ",", "lower_dir", ",", "upper_dir", ")" ]
Execute the mount. This requires root
[ "Execute", "the", "mount", ".", "This", "requires", "root" ]
621eecc0d4d40951aa8afcb533b5eec5d91c73cc
https://github.com/ravenac95/overlay4u/blob/621eecc0d4d40951aa8afcb533b5eec5d91c73cc/overlay4u/overlay.py#L21-L36
238,142
pip-services3-python/pip-services3-commons-python
pip_services3_commons/run/Opener.py
Opener.is_opened
def is_opened(components): """ Checks if all components are opened. To be checked components must implement [[IOpenable]] interface. If they don't the call to this method returns true. :param components: a list of components that are to be checked. :return: true if all components are opened and false if at least one component is closed. """ if components == None: return True result = True for component in components: result = result and Opener.is_opened_one(component) return result
python
def is_opened(components): """ Checks if all components are opened. To be checked components must implement [[IOpenable]] interface. If they don't the call to this method returns true. :param components: a list of components that are to be checked. :return: true if all components are opened and false if at least one component is closed. """ if components == None: return True result = True for component in components: result = result and Opener.is_opened_one(component) return result
[ "def", "is_opened", "(", "components", ")", ":", "if", "components", "==", "None", ":", "return", "True", "result", "=", "True", "for", "component", "in", "components", ":", "result", "=", "result", "and", "Opener", ".", "is_opened_one", "(", "component", ")", "return", "result" ]
Checks if all components are opened. To be checked components must implement [[IOpenable]] interface. If they don't the call to this method returns true. :param components: a list of components that are to be checked. :return: true if all components are opened and false if at least one component is closed.
[ "Checks", "if", "all", "components", "are", "opened", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/run/Opener.py#L36-L54
238,143
pip-services3-python/pip-services3-commons-python
pip_services3_commons/run/Opener.py
Opener.open
def open(correlation_id, components): """ Opens multiple components. To be opened components must implement [[IOpenable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param components: the list of components that are to be closed. """ if components == None: return for component in components: Opener.open_one(correlation_id, component)
python
def open(correlation_id, components): """ Opens multiple components. To be opened components must implement [[IOpenable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param components: the list of components that are to be closed. """ if components == None: return for component in components: Opener.open_one(correlation_id, component)
[ "def", "open", "(", "correlation_id", ",", "components", ")", ":", "if", "components", "==", "None", ":", "return", "for", "component", "in", "components", ":", "Opener", ".", "open_one", "(", "correlation_id", ",", "component", ")" ]
Opens multiple components. To be opened components must implement [[IOpenable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param components: the list of components that are to be closed.
[ "Opens", "multiple", "components", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/run/Opener.py#L72-L87
238,144
kervi/kervi-devices
kervi/devices/sensors/BMP085.py
BMP085DeviceDriver.read_temperature
def read_temperature(self): """Gets the compensated temperature in degrees celsius.""" UT = self.read_raw_temp() # Datasheet value for debugging: #UT = 27898 # Calculations below are taken straight from section 3.5 of the datasheet. X1 = ((UT - self.cal_AC6) * self.cal_AC5) >> 15 X2 = (self.cal_MC << 11) // (X1 + self.cal_MD) B5 = X1 + X2 temp = ((B5 + 8) >> 4) / 10.0 self.logger.debug('Calibrated temperature {0} C', temp) return temp
python
def read_temperature(self): """Gets the compensated temperature in degrees celsius.""" UT = self.read_raw_temp() # Datasheet value for debugging: #UT = 27898 # Calculations below are taken straight from section 3.5 of the datasheet. X1 = ((UT - self.cal_AC6) * self.cal_AC5) >> 15 X2 = (self.cal_MC << 11) // (X1 + self.cal_MD) B5 = X1 + X2 temp = ((B5 + 8) >> 4) / 10.0 self.logger.debug('Calibrated temperature {0} C', temp) return temp
[ "def", "read_temperature", "(", "self", ")", ":", "UT", "=", "self", ".", "read_raw_temp", "(", ")", "# Datasheet value for debugging:", "#UT = 27898", "# Calculations below are taken straight from section 3.5 of the datasheet.", "X1", "=", "(", "(", "UT", "-", "self", ".", "cal_AC6", ")", "*", "self", ".", "cal_AC5", ")", ">>", "15", "X2", "=", "(", "self", ".", "cal_MC", "<<", "11", ")", "//", "(", "X1", "+", "self", ".", "cal_MD", ")", "B5", "=", "X1", "+", "X2", "temp", "=", "(", "(", "B5", "+", "8", ")", ">>", "4", ")", "/", "10.0", "self", ".", "logger", ".", "debug", "(", "'Calibrated temperature {0} C'", ",", "temp", ")", "return", "temp" ]
Gets the compensated temperature in degrees celsius.
[ "Gets", "the", "compensated", "temperature", "in", "degrees", "celsius", "." ]
c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56
https://github.com/kervi/kervi-devices/blob/c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56/kervi/devices/sensors/BMP085.py#L130-L141
238,145
kervi/kervi-devices
kervi/devices/sensors/BMP085.py
BMP085DeviceDriver.read_pressure
def read_pressure(self): """Gets the compensated pressure in Pascals.""" UT = self.read_raw_temp() UP = self.read_raw_pressure() # Datasheet values for debugging: #UT = 27898 #UP = 23843 # Calculations below are taken straight from section 3.5 of the datasheet. # Calculate true temperature coefficient B5. X1 = ((UT - self.cal_AC6) * self.cal_AC5) >> 15 X2 = (self.cal_MC << 11) // (X1 + self.cal_MD) B5 = X1 + X2 self.logger.debug('B5 = {0}', B5) # Pressure Calculations B6 = B5 - 4000 self.logger.debug('B6 = {0}', B6) X1 = (self.cal_B2 * (B6 * B6) >> 12) >> 11 X2 = (self.cal_AC2 * B6) >> 11 X3 = X1 + X2 B3 = (((self.cal_AC1 * 4 + X3) << self._mode) + 2) // 4 self.logger.debug('B3 = {0}', B3) X1 = (self.cal_AC3 * B6) >> 13 X2 = (self.cal_B1 * ((B6 * B6) >> 12)) >> 16 X3 = ((X1 + X2) + 2) >> 2 B4 = (self.cal_AC4 * (X3 + 32768)) >> 15 self.logger.debug('B4 = {0}', B4) B7 = (UP - B3) * (50000 >> self._mode) self.logger.debug('B7 = {0}', B7) if B7 < 0x80000000: p = (B7 * 2) // B4 else: p = (B7 // B4) * 2 X1 = (p >> 8) * (p >> 8) X1 = (X1 * 3038) >> 16 X2 = (-7357 * p) >> 16 p = p + ((X1 + X2 + 3791) >> 4) self.logger.debug('Pressure {0} Pa', p) return p/100
python
def read_pressure(self): """Gets the compensated pressure in Pascals.""" UT = self.read_raw_temp() UP = self.read_raw_pressure() # Datasheet values for debugging: #UT = 27898 #UP = 23843 # Calculations below are taken straight from section 3.5 of the datasheet. # Calculate true temperature coefficient B5. X1 = ((UT - self.cal_AC6) * self.cal_AC5) >> 15 X2 = (self.cal_MC << 11) // (X1 + self.cal_MD) B5 = X1 + X2 self.logger.debug('B5 = {0}', B5) # Pressure Calculations B6 = B5 - 4000 self.logger.debug('B6 = {0}', B6) X1 = (self.cal_B2 * (B6 * B6) >> 12) >> 11 X2 = (self.cal_AC2 * B6) >> 11 X3 = X1 + X2 B3 = (((self.cal_AC1 * 4 + X3) << self._mode) + 2) // 4 self.logger.debug('B3 = {0}', B3) X1 = (self.cal_AC3 * B6) >> 13 X2 = (self.cal_B1 * ((B6 * B6) >> 12)) >> 16 X3 = ((X1 + X2) + 2) >> 2 B4 = (self.cal_AC4 * (X3 + 32768)) >> 15 self.logger.debug('B4 = {0}', B4) B7 = (UP - B3) * (50000 >> self._mode) self.logger.debug('B7 = {0}', B7) if B7 < 0x80000000: p = (B7 * 2) // B4 else: p = (B7 // B4) * 2 X1 = (p >> 8) * (p >> 8) X1 = (X1 * 3038) >> 16 X2 = (-7357 * p) >> 16 p = p + ((X1 + X2 + 3791) >> 4) self.logger.debug('Pressure {0} Pa', p) return p/100
[ "def", "read_pressure", "(", "self", ")", ":", "UT", "=", "self", ".", "read_raw_temp", "(", ")", "UP", "=", "self", ".", "read_raw_pressure", "(", ")", "# Datasheet values for debugging:", "#UT = 27898", "#UP = 23843", "# Calculations below are taken straight from section 3.5 of the datasheet.", "# Calculate true temperature coefficient B5.", "X1", "=", "(", "(", "UT", "-", "self", ".", "cal_AC6", ")", "*", "self", ".", "cal_AC5", ")", ">>", "15", "X2", "=", "(", "self", ".", "cal_MC", "<<", "11", ")", "//", "(", "X1", "+", "self", ".", "cal_MD", ")", "B5", "=", "X1", "+", "X2", "self", ".", "logger", ".", "debug", "(", "'B5 = {0}'", ",", "B5", ")", "# Pressure Calculations", "B6", "=", "B5", "-", "4000", "self", ".", "logger", ".", "debug", "(", "'B6 = {0}'", ",", "B6", ")", "X1", "=", "(", "self", ".", "cal_B2", "*", "(", "B6", "*", "B6", ")", ">>", "12", ")", ">>", "11", "X2", "=", "(", "self", ".", "cal_AC2", "*", "B6", ")", ">>", "11", "X3", "=", "X1", "+", "X2", "B3", "=", "(", "(", "(", "self", ".", "cal_AC1", "*", "4", "+", "X3", ")", "<<", "self", ".", "_mode", ")", "+", "2", ")", "//", "4", "self", ".", "logger", ".", "debug", "(", "'B3 = {0}'", ",", "B3", ")", "X1", "=", "(", "self", ".", "cal_AC3", "*", "B6", ")", ">>", "13", "X2", "=", "(", "self", ".", "cal_B1", "*", "(", "(", "B6", "*", "B6", ")", ">>", "12", ")", ")", ">>", "16", "X3", "=", "(", "(", "X1", "+", "X2", ")", "+", "2", ")", ">>", "2", "B4", "=", "(", "self", ".", "cal_AC4", "*", "(", "X3", "+", "32768", ")", ")", ">>", "15", "self", ".", "logger", ".", "debug", "(", "'B4 = {0}'", ",", "B4", ")", "B7", "=", "(", "UP", "-", "B3", ")", "*", "(", "50000", ">>", "self", ".", "_mode", ")", "self", ".", "logger", ".", "debug", "(", "'B7 = {0}'", ",", "B7", ")", "if", "B7", "<", "0x80000000", ":", "p", "=", "(", "B7", "*", "2", ")", "//", "B4", "else", ":", "p", "=", "(", "B7", "//", "B4", ")", "*", "2", "X1", "=", "(", "p", ">>", "8", ")", "*", "(", "p", ">>", "8", ")", "X1", "=", "(", "X1", "*", "3038", ")", ">>", "16", "X2", "=", "(", "-", "7357", "*", "p", ")", ">>", "16", "p", "=", "p", "+", "(", "(", "X1", "+", "X2", "+", "3791", ")", ">>", "4", ")", "self", ".", "logger", ".", "debug", "(", "'Pressure {0} Pa'", ",", "p", ")", "return", "p", "/", "100" ]
Gets the compensated pressure in Pascals.
[ "Gets", "the", "compensated", "pressure", "in", "Pascals", "." ]
c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56
https://github.com/kervi/kervi-devices/blob/c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56/kervi/devices/sensors/BMP085.py#L143-L180
238,146
rouk1/django-image-renderer
renderer/views.py
get_rendition_url
def get_rendition_url(request, image_id, target_width=0, target_height=0): ''' get a rendition url if the rendition does nto exist it will be created in the storage if dimensions do not fit master's aspect ratio then image will be cropped with a centered anchor if one dimensions is omitted (0) the other one will be generated accordind to master's aspect ratio :param request: http GET request /renderer/rendition/url/<image_id>/<target_width>/<target_height>/ :param image_id: the master image primary key :param target_width: target image width if 0 renderer will use target_height to generate a image with correct aspect ratio :param target_height: target image height if 0 renderer will use target_width to generate a image height correct aspect ratio :return: rendition url in a json dictionary ''' im = get_object_or_404(MasterImage, pk=image_id) return JsonResponse({ 'url': im.get_rendition_url(target_width, target_height) })
python
def get_rendition_url(request, image_id, target_width=0, target_height=0): ''' get a rendition url if the rendition does nto exist it will be created in the storage if dimensions do not fit master's aspect ratio then image will be cropped with a centered anchor if one dimensions is omitted (0) the other one will be generated accordind to master's aspect ratio :param request: http GET request /renderer/rendition/url/<image_id>/<target_width>/<target_height>/ :param image_id: the master image primary key :param target_width: target image width if 0 renderer will use target_height to generate a image with correct aspect ratio :param target_height: target image height if 0 renderer will use target_width to generate a image height correct aspect ratio :return: rendition url in a json dictionary ''' im = get_object_or_404(MasterImage, pk=image_id) return JsonResponse({ 'url': im.get_rendition_url(target_width, target_height) })
[ "def", "get_rendition_url", "(", "request", ",", "image_id", ",", "target_width", "=", "0", ",", "target_height", "=", "0", ")", ":", "im", "=", "get_object_or_404", "(", "MasterImage", ",", "pk", "=", "image_id", ")", "return", "JsonResponse", "(", "{", "'url'", ":", "im", ".", "get_rendition_url", "(", "target_width", ",", "target_height", ")", "}", ")" ]
get a rendition url if the rendition does nto exist it will be created in the storage if dimensions do not fit master's aspect ratio then image will be cropped with a centered anchor if one dimensions is omitted (0) the other one will be generated accordind to master's aspect ratio :param request: http GET request /renderer/rendition/url/<image_id>/<target_width>/<target_height>/ :param image_id: the master image primary key :param target_width: target image width if 0 renderer will use target_height to generate a image with correct aspect ratio :param target_height: target image height if 0 renderer will use target_width to generate a image height correct aspect ratio :return: rendition url in a json dictionary
[ "get", "a", "rendition", "url" ]
6a4326b77709601e18ee04f5626cf475c5ea0bb5
https://github.com/rouk1/django-image-renderer/blob/6a4326b77709601e18ee04f5626cf475c5ea0bb5/renderer/views.py#L13-L39
238,147
rouk1/django-image-renderer
renderer/views.py
get_master_url
def get_master_url(request, image_id): ''' get image's master url ... :param request: http GET request /renderer/master/url/<image_id>/ :param image_id: the master image primary key :return: master url in a json dictionary ''' im = get_object_or_404(MasterImage, pk=image_id) return JsonResponse({'url': im.get_master_url()})
python
def get_master_url(request, image_id): ''' get image's master url ... :param request: http GET request /renderer/master/url/<image_id>/ :param image_id: the master image primary key :return: master url in a json dictionary ''' im = get_object_or_404(MasterImage, pk=image_id) return JsonResponse({'url': im.get_master_url()})
[ "def", "get_master_url", "(", "request", ",", "image_id", ")", ":", "im", "=", "get_object_or_404", "(", "MasterImage", ",", "pk", "=", "image_id", ")", "return", "JsonResponse", "(", "{", "'url'", ":", "im", ".", "get_master_url", "(", ")", "}", ")" ]
get image's master url ... :param request: http GET request /renderer/master/url/<image_id>/ :param image_id: the master image primary key :return: master url in a json dictionary
[ "get", "image", "s", "master", "url" ]
6a4326b77709601e18ee04f5626cf475c5ea0bb5
https://github.com/rouk1/django-image-renderer/blob/6a4326b77709601e18ee04f5626cf475c5ea0bb5/renderer/views.py#L43-L55
238,148
adsabs/adsutils
adsutils/utils.py
Resolver.__parse_results
def __parse_results(self,results): """ The resolve server responds with some basic HTML formatting, where the actual results are listed as an HTML list. The regular expression RE_RESULT captures each entry """ reslist = [] cursor = 0 match = RE_RESULTS.search(results,cursor) while match: doc = {} doc['bibcode'] = match.group('bibcode') doc['confidence'] = self.__get_confidence_level(match.group('confidence')) doc['refstring'] = match.group('refstring') reslist.append(doc) cursor = match.end() match = RE_RESULTS.search(results,cursor) return reslist
python
def __parse_results(self,results): """ The resolve server responds with some basic HTML formatting, where the actual results are listed as an HTML list. The regular expression RE_RESULT captures each entry """ reslist = [] cursor = 0 match = RE_RESULTS.search(results,cursor) while match: doc = {} doc['bibcode'] = match.group('bibcode') doc['confidence'] = self.__get_confidence_level(match.group('confidence')) doc['refstring'] = match.group('refstring') reslist.append(doc) cursor = match.end() match = RE_RESULTS.search(results,cursor) return reslist
[ "def", "__parse_results", "(", "self", ",", "results", ")", ":", "reslist", "=", "[", "]", "cursor", "=", "0", "match", "=", "RE_RESULTS", ".", "search", "(", "results", ",", "cursor", ")", "while", "match", ":", "doc", "=", "{", "}", "doc", "[", "'bibcode'", "]", "=", "match", ".", "group", "(", "'bibcode'", ")", "doc", "[", "'confidence'", "]", "=", "self", ".", "__get_confidence_level", "(", "match", ".", "group", "(", "'confidence'", ")", ")", "doc", "[", "'refstring'", "]", "=", "match", ".", "group", "(", "'refstring'", ")", "reslist", ".", "append", "(", "doc", ")", "cursor", "=", "match", ".", "end", "(", ")", "match", "=", "RE_RESULTS", ".", "search", "(", "results", ",", "cursor", ")", "return", "reslist" ]
The resolve server responds with some basic HTML formatting, where the actual results are listed as an HTML list. The regular expression RE_RESULT captures each entry
[ "The", "resolve", "server", "responds", "with", "some", "basic", "HTML", "formatting", "where", "the", "actual", "results", "are", "listed", "as", "an", "HTML", "list", ".", "The", "regular", "expression", "RE_RESULT", "captures", "each", "entry" ]
fb9d6b4f6ed5e6ca19c552efc3cdd6466c587fdb
https://github.com/adsabs/adsutils/blob/fb9d6b4f6ed5e6ca19c552efc3cdd6466c587fdb/adsutils/utils.py#L205-L222
238,149
pawel-kow/domainconnect_python
domainconnect/domainconnect.py
DomainConnect.get_domain_config
def get_domain_config(self, domain): """Makes a discovery of domain name and resolves configuration of DNS provider :param domain: str domain name :return: DomainConnectConfig domain connect config :raises: NoDomainConnectRecordException when no _domainconnect record found :raises: NoDomainConnectSettingsException when settings are not found """ domain_root = self.identify_domain_root(domain) host = '' if len(domain_root) != len(domain): host = domain.replace('.' + domain_root, '') domain_connect_api = self._identify_domain_connect_api(domain_root) ret = self._get_domain_config_for_root(domain_root, domain_connect_api) return DomainConnectConfig(domain, domain_root, host, ret)
python
def get_domain_config(self, domain): """Makes a discovery of domain name and resolves configuration of DNS provider :param domain: str domain name :return: DomainConnectConfig domain connect config :raises: NoDomainConnectRecordException when no _domainconnect record found :raises: NoDomainConnectSettingsException when settings are not found """ domain_root = self.identify_domain_root(domain) host = '' if len(domain_root) != len(domain): host = domain.replace('.' + domain_root, '') domain_connect_api = self._identify_domain_connect_api(domain_root) ret = self._get_domain_config_for_root(domain_root, domain_connect_api) return DomainConnectConfig(domain, domain_root, host, ret)
[ "def", "get_domain_config", "(", "self", ",", "domain", ")", ":", "domain_root", "=", "self", ".", "identify_domain_root", "(", "domain", ")", "host", "=", "''", "if", "len", "(", "domain_root", ")", "!=", "len", "(", "domain", ")", ":", "host", "=", "domain", ".", "replace", "(", "'.'", "+", "domain_root", ",", "''", ")", "domain_connect_api", "=", "self", ".", "_identify_domain_connect_api", "(", "domain_root", ")", "ret", "=", "self", ".", "_get_domain_config_for_root", "(", "domain_root", ",", "domain_connect_api", ")", "return", "DomainConnectConfig", "(", "domain", ",", "domain_root", ",", "host", ",", "ret", ")" ]
Makes a discovery of domain name and resolves configuration of DNS provider :param domain: str domain name :return: DomainConnectConfig domain connect config :raises: NoDomainConnectRecordException when no _domainconnect record found :raises: NoDomainConnectSettingsException when settings are not found
[ "Makes", "a", "discovery", "of", "domain", "name", "and", "resolves", "configuration", "of", "DNS", "provider" ]
2467093cc4e997234e0fb5c55e71f76b856c1ab1
https://github.com/pawel-kow/domainconnect_python/blob/2467093cc4e997234e0fb5c55e71f76b856c1ab1/domainconnect/domainconnect.py#L218-L239
238,150
pawel-kow/domainconnect_python
domainconnect/domainconnect.py
DomainConnect.get_domain_connect_template_sync_url
def get_domain_connect_template_sync_url(self, domain, provider_id, service_id, redirect_uri=None, params=None, state=None, group_ids=None): """Makes full Domain Connect discovery of a domain and returns full url to request sync consent. :param domain: str :param provider_id: str :param service_id: str :param redirect_uri: str :param params: dict :param state: str :param group_ids: list(str) :return: (str, str) first field is an url which shall be used to redirect the browser to second field is an indication of error :raises: NoDomainConnectRecordException when no _domainconnect record found :raises: NoDomainConnectSettingsException when settings are not found :raises: InvalidDomainConnectSettingsException when settings contain missing fields """ # TODO: support for signatures # TODO: support for provider_name (for shared templates) if params is None: params = {} config = self.get_domain_config(domain) self.check_template_supported(config, provider_id, service_id) if config.urlSyncUX is None: raise InvalidDomainConnectSettingsException("No sync URL in config") sync_url_format = '{}/v2/domainTemplates/providers/{}/services/{}/' \ 'apply?domain={}&host={}&{}' if redirect_uri is not None: params["redirect_uri"] = redirect_uri if state is not None: params["state"] = state if group_ids is not None: params["groupId"] = ",".join(group_ids) return sync_url_format.format(config.urlSyncUX, provider_id, service_id, config.domain_root, config.host, urllib.parse.urlencode(sorted(params.items(), key=lambda val: val[0])))
python
def get_domain_connect_template_sync_url(self, domain, provider_id, service_id, redirect_uri=None, params=None, state=None, group_ids=None): """Makes full Domain Connect discovery of a domain and returns full url to request sync consent. :param domain: str :param provider_id: str :param service_id: str :param redirect_uri: str :param params: dict :param state: str :param group_ids: list(str) :return: (str, str) first field is an url which shall be used to redirect the browser to second field is an indication of error :raises: NoDomainConnectRecordException when no _domainconnect record found :raises: NoDomainConnectSettingsException when settings are not found :raises: InvalidDomainConnectSettingsException when settings contain missing fields """ # TODO: support for signatures # TODO: support for provider_name (for shared templates) if params is None: params = {} config = self.get_domain_config(domain) self.check_template_supported(config, provider_id, service_id) if config.urlSyncUX is None: raise InvalidDomainConnectSettingsException("No sync URL in config") sync_url_format = '{}/v2/domainTemplates/providers/{}/services/{}/' \ 'apply?domain={}&host={}&{}' if redirect_uri is not None: params["redirect_uri"] = redirect_uri if state is not None: params["state"] = state if group_ids is not None: params["groupId"] = ",".join(group_ids) return sync_url_format.format(config.urlSyncUX, provider_id, service_id, config.domain_root, config.host, urllib.parse.urlencode(sorted(params.items(), key=lambda val: val[0])))
[ "def", "get_domain_connect_template_sync_url", "(", "self", ",", "domain", ",", "provider_id", ",", "service_id", ",", "redirect_uri", "=", "None", ",", "params", "=", "None", ",", "state", "=", "None", ",", "group_ids", "=", "None", ")", ":", "# TODO: support for signatures", "# TODO: support for provider_name (for shared templates)", "if", "params", "is", "None", ":", "params", "=", "{", "}", "config", "=", "self", ".", "get_domain_config", "(", "domain", ")", "self", ".", "check_template_supported", "(", "config", ",", "provider_id", ",", "service_id", ")", "if", "config", ".", "urlSyncUX", "is", "None", ":", "raise", "InvalidDomainConnectSettingsException", "(", "\"No sync URL in config\"", ")", "sync_url_format", "=", "'{}/v2/domainTemplates/providers/{}/services/{}/'", "'apply?domain={}&host={}&{}'", "if", "redirect_uri", "is", "not", "None", ":", "params", "[", "\"redirect_uri\"", "]", "=", "redirect_uri", "if", "state", "is", "not", "None", ":", "params", "[", "\"state\"", "]", "=", "state", "if", "group_ids", "is", "not", "None", ":", "params", "[", "\"groupId\"", "]", "=", "\",\"", ".", "join", "(", "group_ids", ")", "return", "sync_url_format", ".", "format", "(", "config", ".", "urlSyncUX", ",", "provider_id", ",", "service_id", ",", "config", ".", "domain_root", ",", "config", ".", "host", ",", "urllib", ".", "parse", ".", "urlencode", "(", "sorted", "(", "params", ".", "items", "(", ")", ",", "key", "=", "lambda", "val", ":", "val", "[", "0", "]", ")", ")", ")" ]
Makes full Domain Connect discovery of a domain and returns full url to request sync consent. :param domain: str :param provider_id: str :param service_id: str :param redirect_uri: str :param params: dict :param state: str :param group_ids: list(str) :return: (str, str) first field is an url which shall be used to redirect the browser to second field is an indication of error :raises: NoDomainConnectRecordException when no _domainconnect record found :raises: NoDomainConnectSettingsException when settings are not found :raises: InvalidDomainConnectSettingsException when settings contain missing fields
[ "Makes", "full", "Domain", "Connect", "discovery", "of", "a", "domain", "and", "returns", "full", "url", "to", "request", "sync", "consent", "." ]
2467093cc4e997234e0fb5c55e71f76b856c1ab1
https://github.com/pawel-kow/domainconnect_python/blob/2467093cc4e997234e0fb5c55e71f76b856c1ab1/domainconnect/domainconnect.py#L297-L342
238,151
pawel-kow/domainconnect_python
domainconnect/domainconnect.py
DomainConnect.get_domain_connect_template_async_context
def get_domain_connect_template_async_context(self, domain, provider_id, service_id, redirect_uri, params=None, state=None, service_id_in_path=False): """Makes full Domain Connect discovery of a domain and returns full context to request async consent. :param domain: str :param provider_id: str :param service_id: str :param redirect_uri: str :param params: dict :param state: str :param service_id_in_path: bool :return: (DomainConnectAsyncContext, str) asyncConsentUrl field of returned context shall be used to redirect the browser to second field is an indication of error :raises: NoDomainConnectRecordException when no _domainconnect record found :raises: NoDomainConnectSettingsException when settings are not found :raises: TemplateNotSupportedException when template is not found :raises: InvalidDomainConnectSettingsException when parts of the settings are missing :raises: DomainConnectException on other domain connect issues """ if params is None: params = {} config = self.get_domain_config(domain) self.check_template_supported(config, provider_id, service_id) if config.urlAsyncUX is None: raise InvalidDomainConnectSettingsException("No asynch UX URL in config") if service_id_in_path: if type(service_id) is list: raise DomainConnectException("Multiple services are only supported with service_id_in_path=false") async_url_format = '{0}/v2/domainTemplates/providers/{1}/services/{2}' \ '?client_id={1}&scope={2}&domain={3}&host={4}&{5}' else: if type(service_id) is list: service_id = '+'.join(service_id) async_url_format = '{0}/v2/domainTemplates/providers/{1}' \ '?client_id={1}&scope={2}&domain={3}&host={4}&{5}' if redirect_uri is not None: params["redirect_uri"] = redirect_uri if state is not None: params["state"] = state ret = DomainConnectAsyncContext(config, provider_id, service_id, redirect_uri, params) ret.asyncConsentUrl = async_url_format.format(config.urlAsyncUX, provider_id, service_id, config.domain_root, config.host, urllib.parse.urlencode( sorted(params.items(), key=lambda val: val[0]))) return ret
python
def get_domain_connect_template_async_context(self, domain, provider_id, service_id, redirect_uri, params=None, state=None, service_id_in_path=False): """Makes full Domain Connect discovery of a domain and returns full context to request async consent. :param domain: str :param provider_id: str :param service_id: str :param redirect_uri: str :param params: dict :param state: str :param service_id_in_path: bool :return: (DomainConnectAsyncContext, str) asyncConsentUrl field of returned context shall be used to redirect the browser to second field is an indication of error :raises: NoDomainConnectRecordException when no _domainconnect record found :raises: NoDomainConnectSettingsException when settings are not found :raises: TemplateNotSupportedException when template is not found :raises: InvalidDomainConnectSettingsException when parts of the settings are missing :raises: DomainConnectException on other domain connect issues """ if params is None: params = {} config = self.get_domain_config(domain) self.check_template_supported(config, provider_id, service_id) if config.urlAsyncUX is None: raise InvalidDomainConnectSettingsException("No asynch UX URL in config") if service_id_in_path: if type(service_id) is list: raise DomainConnectException("Multiple services are only supported with service_id_in_path=false") async_url_format = '{0}/v2/domainTemplates/providers/{1}/services/{2}' \ '?client_id={1}&scope={2}&domain={3}&host={4}&{5}' else: if type(service_id) is list: service_id = '+'.join(service_id) async_url_format = '{0}/v2/domainTemplates/providers/{1}' \ '?client_id={1}&scope={2}&domain={3}&host={4}&{5}' if redirect_uri is not None: params["redirect_uri"] = redirect_uri if state is not None: params["state"] = state ret = DomainConnectAsyncContext(config, provider_id, service_id, redirect_uri, params) ret.asyncConsentUrl = async_url_format.format(config.urlAsyncUX, provider_id, service_id, config.domain_root, config.host, urllib.parse.urlencode( sorted(params.items(), key=lambda val: val[0]))) return ret
[ "def", "get_domain_connect_template_async_context", "(", "self", ",", "domain", ",", "provider_id", ",", "service_id", ",", "redirect_uri", ",", "params", "=", "None", ",", "state", "=", "None", ",", "service_id_in_path", "=", "False", ")", ":", "if", "params", "is", "None", ":", "params", "=", "{", "}", "config", "=", "self", ".", "get_domain_config", "(", "domain", ")", "self", ".", "check_template_supported", "(", "config", ",", "provider_id", ",", "service_id", ")", "if", "config", ".", "urlAsyncUX", "is", "None", ":", "raise", "InvalidDomainConnectSettingsException", "(", "\"No asynch UX URL in config\"", ")", "if", "service_id_in_path", ":", "if", "type", "(", "service_id", ")", "is", "list", ":", "raise", "DomainConnectException", "(", "\"Multiple services are only supported with service_id_in_path=false\"", ")", "async_url_format", "=", "'{0}/v2/domainTemplates/providers/{1}/services/{2}'", "'?client_id={1}&scope={2}&domain={3}&host={4}&{5}'", "else", ":", "if", "type", "(", "service_id", ")", "is", "list", ":", "service_id", "=", "'+'", ".", "join", "(", "service_id", ")", "async_url_format", "=", "'{0}/v2/domainTemplates/providers/{1}'", "'?client_id={1}&scope={2}&domain={3}&host={4}&{5}'", "if", "redirect_uri", "is", "not", "None", ":", "params", "[", "\"redirect_uri\"", "]", "=", "redirect_uri", "if", "state", "is", "not", "None", ":", "params", "[", "\"state\"", "]", "=", "state", "ret", "=", "DomainConnectAsyncContext", "(", "config", ",", "provider_id", ",", "service_id", ",", "redirect_uri", ",", "params", ")", "ret", ".", "asyncConsentUrl", "=", "async_url_format", ".", "format", "(", "config", ".", "urlAsyncUX", ",", "provider_id", ",", "service_id", ",", "config", ".", "domain_root", ",", "config", ".", "host", ",", "urllib", ".", "parse", ".", "urlencode", "(", "sorted", "(", "params", ".", "items", "(", ")", ",", "key", "=", "lambda", "val", ":", "val", "[", "0", "]", ")", ")", ")", "return", "ret" ]
Makes full Domain Connect discovery of a domain and returns full context to request async consent. :param domain: str :param provider_id: str :param service_id: str :param redirect_uri: str :param params: dict :param state: str :param service_id_in_path: bool :return: (DomainConnectAsyncContext, str) asyncConsentUrl field of returned context shall be used to redirect the browser to second field is an indication of error :raises: NoDomainConnectRecordException when no _domainconnect record found :raises: NoDomainConnectSettingsException when settings are not found :raises: TemplateNotSupportedException when template is not found :raises: InvalidDomainConnectSettingsException when parts of the settings are missing :raises: DomainConnectException on other domain connect issues
[ "Makes", "full", "Domain", "Connect", "discovery", "of", "a", "domain", "and", "returns", "full", "context", "to", "request", "async", "consent", "." ]
2467093cc4e997234e0fb5c55e71f76b856c1ab1
https://github.com/pawel-kow/domainconnect_python/blob/2467093cc4e997234e0fb5c55e71f76b856c1ab1/domainconnect/domainconnect.py#L344-L400
238,152
pawel-kow/domainconnect_python
domainconnect/domainconnect.py
DomainConnect.get_async_token
def get_async_token(self, context, credentials): """Gets access_token in async process :param context: DomainConnectAsyncContext :param credentials: DomainConnectAsyncCredentials :return: DomainConnectAsyncContext context enriched with access_token and refresh_token if existing :raises: AsyncTokenException """ params = {'code': context.code, 'grant_type': 'authorization_code'} if getattr(context, 'iat', None) and getattr(context, 'access_token_expires_in', None) and \ getattr(context, 'refresh_token', None): now = int(time.time()) + 60 if now > context.iat + context.access_token_expires_in: params = {'refresh_token': context.refresh_token, 'grant_type': 'refresh_token', 'client_id': credentials.client_id, 'client_secret': credentials.client_secret } else: logger.debug('Context has a valid access token') return context params['redirect_uri'] = context.return_url url_get_access_token = '{}/v2/oauth/access_token?{}'.format(context.config.urlAPI, urllib.parse.urlencode( sorted(params.items(), key=lambda val: val[0]))) try: # this has to be checked to avoid secret leakage by spoofed "settings" end-point if credentials.api_url != context.config.urlAPI: raise AsyncTokenException("URL API for provider does not match registered one with credentials") data, status = http_request_json(self._networkContext, method='POST', content_type='application/json', body=json.dumps({ 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, }), url=url_get_access_token ) except Exception as ex: logger.debug('Cannot get async token: {}'.format(ex)) raise AsyncTokenException('Cannot get async token: {}'.format(ex)) if 'access_token' not in data \ or 'expires_in' not in data \ or 'token_type' not in data \ or data['token_type'].lower() != 'bearer': logger.debug('Token not complete: {}'.format(data)) raise AsyncTokenException('Token not complete: {}'.format(data)) context.access_token = data['access_token'] context.access_token_expires_in = data['expires_in'] context.iat = int(time.time()) if 'refresh_token' in data: context.refresh_token = data['refresh_token'] return context
python
def get_async_token(self, context, credentials): """Gets access_token in async process :param context: DomainConnectAsyncContext :param credentials: DomainConnectAsyncCredentials :return: DomainConnectAsyncContext context enriched with access_token and refresh_token if existing :raises: AsyncTokenException """ params = {'code': context.code, 'grant_type': 'authorization_code'} if getattr(context, 'iat', None) and getattr(context, 'access_token_expires_in', None) and \ getattr(context, 'refresh_token', None): now = int(time.time()) + 60 if now > context.iat + context.access_token_expires_in: params = {'refresh_token': context.refresh_token, 'grant_type': 'refresh_token', 'client_id': credentials.client_id, 'client_secret': credentials.client_secret } else: logger.debug('Context has a valid access token') return context params['redirect_uri'] = context.return_url url_get_access_token = '{}/v2/oauth/access_token?{}'.format(context.config.urlAPI, urllib.parse.urlencode( sorted(params.items(), key=lambda val: val[0]))) try: # this has to be checked to avoid secret leakage by spoofed "settings" end-point if credentials.api_url != context.config.urlAPI: raise AsyncTokenException("URL API for provider does not match registered one with credentials") data, status = http_request_json(self._networkContext, method='POST', content_type='application/json', body=json.dumps({ 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, }), url=url_get_access_token ) except Exception as ex: logger.debug('Cannot get async token: {}'.format(ex)) raise AsyncTokenException('Cannot get async token: {}'.format(ex)) if 'access_token' not in data \ or 'expires_in' not in data \ or 'token_type' not in data \ or data['token_type'].lower() != 'bearer': logger.debug('Token not complete: {}'.format(data)) raise AsyncTokenException('Token not complete: {}'.format(data)) context.access_token = data['access_token'] context.access_token_expires_in = data['expires_in'] context.iat = int(time.time()) if 'refresh_token' in data: context.refresh_token = data['refresh_token'] return context
[ "def", "get_async_token", "(", "self", ",", "context", ",", "credentials", ")", ":", "params", "=", "{", "'code'", ":", "context", ".", "code", ",", "'grant_type'", ":", "'authorization_code'", "}", "if", "getattr", "(", "context", ",", "'iat'", ",", "None", ")", "and", "getattr", "(", "context", ",", "'access_token_expires_in'", ",", "None", ")", "and", "getattr", "(", "context", ",", "'refresh_token'", ",", "None", ")", ":", "now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "+", "60", "if", "now", ">", "context", ".", "iat", "+", "context", ".", "access_token_expires_in", ":", "params", "=", "{", "'refresh_token'", ":", "context", ".", "refresh_token", ",", "'grant_type'", ":", "'refresh_token'", ",", "'client_id'", ":", "credentials", ".", "client_id", ",", "'client_secret'", ":", "credentials", ".", "client_secret", "}", "else", ":", "logger", ".", "debug", "(", "'Context has a valid access token'", ")", "return", "context", "params", "[", "'redirect_uri'", "]", "=", "context", ".", "return_url", "url_get_access_token", "=", "'{}/v2/oauth/access_token?{}'", ".", "format", "(", "context", ".", "config", ".", "urlAPI", ",", "urllib", ".", "parse", ".", "urlencode", "(", "sorted", "(", "params", ".", "items", "(", ")", ",", "key", "=", "lambda", "val", ":", "val", "[", "0", "]", ")", ")", ")", "try", ":", "# this has to be checked to avoid secret leakage by spoofed \"settings\" end-point", "if", "credentials", ".", "api_url", "!=", "context", ".", "config", ".", "urlAPI", ":", "raise", "AsyncTokenException", "(", "\"URL API for provider does not match registered one with credentials\"", ")", "data", ",", "status", "=", "http_request_json", "(", "self", ".", "_networkContext", ",", "method", "=", "'POST'", ",", "content_type", "=", "'application/json'", ",", "body", "=", "json", ".", "dumps", "(", "{", "'client_id'", ":", "credentials", ".", "client_id", ",", "'client_secret'", ":", "credentials", ".", "client_secret", ",", "}", ")", ",", "url", "=", "url_get_access_token", ")", "except", "Exception", "as", "ex", ":", "logger", ".", "debug", "(", "'Cannot get async token: {}'", ".", "format", "(", "ex", ")", ")", "raise", "AsyncTokenException", "(", "'Cannot get async token: {}'", ".", "format", "(", "ex", ")", ")", "if", "'access_token'", "not", "in", "data", "or", "'expires_in'", "not", "in", "data", "or", "'token_type'", "not", "in", "data", "or", "data", "[", "'token_type'", "]", ".", "lower", "(", ")", "!=", "'bearer'", ":", "logger", ".", "debug", "(", "'Token not complete: {}'", ".", "format", "(", "data", ")", ")", "raise", "AsyncTokenException", "(", "'Token not complete: {}'", ".", "format", "(", "data", ")", ")", "context", ".", "access_token", "=", "data", "[", "'access_token'", "]", "context", ".", "access_token_expires_in", "=", "data", "[", "'expires_in'", "]", "context", ".", "iat", "=", "int", "(", "time", ".", "time", "(", ")", ")", "if", "'refresh_token'", "in", "data", ":", "context", ".", "refresh_token", "=", "data", "[", "'refresh_token'", "]", "return", "context" ]
Gets access_token in async process :param context: DomainConnectAsyncContext :param credentials: DomainConnectAsyncCredentials :return: DomainConnectAsyncContext context enriched with access_token and refresh_token if existing :raises: AsyncTokenException
[ "Gets", "access_token", "in", "async", "process" ]
2467093cc4e997234e0fb5c55e71f76b856c1ab1
https://github.com/pawel-kow/domainconnect_python/blob/2467093cc4e997234e0fb5c55e71f76b856c1ab1/domainconnect/domainconnect.py#L438-L494
238,153
TestInABox/stackInABox
stackinabox/util/httpretty/core.py
httpretty_callback
def httpretty_callback(request, uri, headers): """httpretty request handler. converts a call intercepted by httpretty to the stack-in-a-box infrastructure :param request: request object :param uri: the uri of the request :param headers: headers for the response :returns: tuple - (int, dict, string) containing: int - the http response status code dict - the headers for the http response string - http string response """ method = request.method response_headers = CaseInsensitiveDict() response_headers.update(headers) request_headers = CaseInsensitiveDict() request_headers.update(request.headers) request.headers = request_headers return StackInABox.call_into(method, request, uri, response_headers)
python
def httpretty_callback(request, uri, headers): """httpretty request handler. converts a call intercepted by httpretty to the stack-in-a-box infrastructure :param request: request object :param uri: the uri of the request :param headers: headers for the response :returns: tuple - (int, dict, string) containing: int - the http response status code dict - the headers for the http response string - http string response """ method = request.method response_headers = CaseInsensitiveDict() response_headers.update(headers) request_headers = CaseInsensitiveDict() request_headers.update(request.headers) request.headers = request_headers return StackInABox.call_into(method, request, uri, response_headers)
[ "def", "httpretty_callback", "(", "request", ",", "uri", ",", "headers", ")", ":", "method", "=", "request", ".", "method", "response_headers", "=", "CaseInsensitiveDict", "(", ")", "response_headers", ".", "update", "(", "headers", ")", "request_headers", "=", "CaseInsensitiveDict", "(", ")", "request_headers", ".", "update", "(", "request", ".", "headers", ")", "request", ".", "headers", "=", "request_headers", "return", "StackInABox", ".", "call_into", "(", "method", ",", "request", ",", "uri", ",", "response_headers", ")" ]
httpretty request handler. converts a call intercepted by httpretty to the stack-in-a-box infrastructure :param request: request object :param uri: the uri of the request :param headers: headers for the response :returns: tuple - (int, dict, string) containing: int - the http response status code dict - the headers for the http response string - http string response
[ "httpretty", "request", "handler", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/httpretty/core.py#L22-L47
238,154
TestInABox/stackInABox
stackinabox/util/httpretty/core.py
registration
def registration(uri): """httpretty handler registration. registers a handler for a given uri with httpretty so that it can be intercepted and handed to stack-in-a-box. :param uri: uri used for the base of the http requests :returns: n/a """ # add the stack-in-a-box specific response codes to # http's status information status_data = { 595: 'StackInABoxService - Unknown Route', 596: 'StackInABox - Exception in Service Handler', 597: 'StackInABox - Unknown Service' } for k, v in six.iteritems(status_data): if k not in httpretty.http.STATUSES: httpretty.http.STATUSES[k] = v # log the uri that is used to access the stack-in-a-box services logger.debug('Registering Stack-In-A-Box at {0} under Python HTTPretty' .format(uri)) # tell stack-in-a-box what uri to match with StackInABox.update_uri(uri) # build the regex for the uri and register all http verbs # with httpretty regex = re.compile('(http)?s?(://)?{0}:?(\d+)?/'.format(uri), re.I) for method in HttpBaseClass.METHODS: register_uri(method, regex, body=httpretty_callback)
python
def registration(uri): """httpretty handler registration. registers a handler for a given uri with httpretty so that it can be intercepted and handed to stack-in-a-box. :param uri: uri used for the base of the http requests :returns: n/a """ # add the stack-in-a-box specific response codes to # http's status information status_data = { 595: 'StackInABoxService - Unknown Route', 596: 'StackInABox - Exception in Service Handler', 597: 'StackInABox - Unknown Service' } for k, v in six.iteritems(status_data): if k not in httpretty.http.STATUSES: httpretty.http.STATUSES[k] = v # log the uri that is used to access the stack-in-a-box services logger.debug('Registering Stack-In-A-Box at {0} under Python HTTPretty' .format(uri)) # tell stack-in-a-box what uri to match with StackInABox.update_uri(uri) # build the regex for the uri and register all http verbs # with httpretty regex = re.compile('(http)?s?(://)?{0}:?(\d+)?/'.format(uri), re.I) for method in HttpBaseClass.METHODS: register_uri(method, regex, body=httpretty_callback)
[ "def", "registration", "(", "uri", ")", ":", "# add the stack-in-a-box specific response codes to", "# http's status information", "status_data", "=", "{", "595", ":", "'StackInABoxService - Unknown Route'", ",", "596", ":", "'StackInABox - Exception in Service Handler'", ",", "597", ":", "'StackInABox - Unknown Service'", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "status_data", ")", ":", "if", "k", "not", "in", "httpretty", ".", "http", ".", "STATUSES", ":", "httpretty", ".", "http", ".", "STATUSES", "[", "k", "]", "=", "v", "# log the uri that is used to access the stack-in-a-box services", "logger", ".", "debug", "(", "'Registering Stack-In-A-Box at {0} under Python HTTPretty'", ".", "format", "(", "uri", ")", ")", "# tell stack-in-a-box what uri to match with", "StackInABox", ".", "update_uri", "(", "uri", ")", "# build the regex for the uri and register all http verbs", "# with httpretty", "regex", "=", "re", ".", "compile", "(", "'(http)?s?(://)?{0}:?(\\d+)?/'", ".", "format", "(", "uri", ")", ",", "re", ".", "I", ")", "for", "method", "in", "HttpBaseClass", ".", "METHODS", ":", "register_uri", "(", "method", ",", "regex", ",", "body", "=", "httpretty_callback", ")" ]
httpretty handler registration. registers a handler for a given uri with httpretty so that it can be intercepted and handed to stack-in-a-box. :param uri: uri used for the base of the http requests :returns: n/a
[ "httpretty", "handler", "registration", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/httpretty/core.py#L50-L85
238,155
FujiMakoto/AgentML
agentml/parser/tags/redirect.py
Redirect.value
def value(self): """ Return the value of the redirect response """ user = self.trigger.agentml.request_log.most_recent().user groups = self.trigger.agentml.request_log.most_recent().groups # Does the redirect statement have tags to parse? if len(self._element): message = ''.join(map(str, self.trigger.agentml.parse_tags(self._element, self.trigger))) else: message = self._element.text # Is there a default value defined? default = attribute(self._element, 'default', '') response = self.trigger.agentml.get_reply(user.id, message, groups) return response or default
python
def value(self): """ Return the value of the redirect response """ user = self.trigger.agentml.request_log.most_recent().user groups = self.trigger.agentml.request_log.most_recent().groups # Does the redirect statement have tags to parse? if len(self._element): message = ''.join(map(str, self.trigger.agentml.parse_tags(self._element, self.trigger))) else: message = self._element.text # Is there a default value defined? default = attribute(self._element, 'default', '') response = self.trigger.agentml.get_reply(user.id, message, groups) return response or default
[ "def", "value", "(", "self", ")", ":", "user", "=", "self", ".", "trigger", ".", "agentml", ".", "request_log", ".", "most_recent", "(", ")", ".", "user", "groups", "=", "self", ".", "trigger", ".", "agentml", ".", "request_log", ".", "most_recent", "(", ")", ".", "groups", "# Does the redirect statement have tags to parse?", "if", "len", "(", "self", ".", "_element", ")", ":", "message", "=", "''", ".", "join", "(", "map", "(", "str", ",", "self", ".", "trigger", ".", "agentml", ".", "parse_tags", "(", "self", ".", "_element", ",", "self", ".", "trigger", ")", ")", ")", "else", ":", "message", "=", "self", ".", "_element", ".", "text", "# Is there a default value defined?", "default", "=", "attribute", "(", "self", ".", "_element", ",", "'default'", ",", "''", ")", "response", "=", "self", ".", "trigger", ".", "agentml", ".", "get_reply", "(", "user", ".", "id", ",", "message", ",", "groups", ")", "return", "response", "or", "default" ]
Return the value of the redirect response
[ "Return", "the", "value", "of", "the", "redirect", "response" ]
c8cb64b460d876666bf29ea2c682189874c7c403
https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/parser/tags/redirect.py#L24-L41
238,156
lgfausak/sqlauth
sqlauth/scripts/sqlauthrouter.py
MyRouterSession.onHello
def onHello(self, realm, details): """ Callback fired when client wants to attach session. """ log.msg("onHello: {} {}".format(realm, details)) self._pending_auth = None if details.authmethods: for authmethod in details.authmethods: if authmethod == u"wampcra": ## lookup user in user DB salt, key, role, uid = yield self.factory.userdb.get(details.authid) log.msg("salt, key, role: {} {} {} {}".format(salt, key, role, uid)) ## if user found .. if key: log.msg("found key") ## setup pending auth self._pending_auth = PendingAuth(key, details.pending_session, details.authid, role, authmethod, u"userdb", uid) log.msg("setting challenge") ## send challenge to client extra = { u'challenge': self._pending_auth.challenge } ## when using salted passwords, provide the client with ## the salt and then PBKDF2 parameters used if salt: extra[u'salt'] = salt extra[u'iterations'] = 1000 extra[u'keylen'] = 32 defer.returnValue(types.Challenge(u'wampcra', extra)) ## deny client defer.returnValue(types.Deny())
python
def onHello(self, realm, details): """ Callback fired when client wants to attach session. """ log.msg("onHello: {} {}".format(realm, details)) self._pending_auth = None if details.authmethods: for authmethod in details.authmethods: if authmethod == u"wampcra": ## lookup user in user DB salt, key, role, uid = yield self.factory.userdb.get(details.authid) log.msg("salt, key, role: {} {} {} {}".format(salt, key, role, uid)) ## if user found .. if key: log.msg("found key") ## setup pending auth self._pending_auth = PendingAuth(key, details.pending_session, details.authid, role, authmethod, u"userdb", uid) log.msg("setting challenge") ## send challenge to client extra = { u'challenge': self._pending_auth.challenge } ## when using salted passwords, provide the client with ## the salt and then PBKDF2 parameters used if salt: extra[u'salt'] = salt extra[u'iterations'] = 1000 extra[u'keylen'] = 32 defer.returnValue(types.Challenge(u'wampcra', extra)) ## deny client defer.returnValue(types.Deny())
[ "def", "onHello", "(", "self", ",", "realm", ",", "details", ")", ":", "log", ".", "msg", "(", "\"onHello: {} {}\"", ".", "format", "(", "realm", ",", "details", ")", ")", "self", ".", "_pending_auth", "=", "None", "if", "details", ".", "authmethods", ":", "for", "authmethod", "in", "details", ".", "authmethods", ":", "if", "authmethod", "==", "u\"wampcra\"", ":", "## lookup user in user DB", "salt", ",", "key", ",", "role", ",", "uid", "=", "yield", "self", ".", "factory", ".", "userdb", ".", "get", "(", "details", ".", "authid", ")", "log", ".", "msg", "(", "\"salt, key, role: {} {} {} {}\"", ".", "format", "(", "salt", ",", "key", ",", "role", ",", "uid", ")", ")", "## if user found ..", "if", "key", ":", "log", ".", "msg", "(", "\"found key\"", ")", "## setup pending auth", "self", ".", "_pending_auth", "=", "PendingAuth", "(", "key", ",", "details", ".", "pending_session", ",", "details", ".", "authid", ",", "role", ",", "authmethod", ",", "u\"userdb\"", ",", "uid", ")", "log", ".", "msg", "(", "\"setting challenge\"", ")", "## send challenge to client", "extra", "=", "{", "u'challenge'", ":", "self", ".", "_pending_auth", ".", "challenge", "}", "## when using salted passwords, provide the client with", "## the salt and then PBKDF2 parameters used", "if", "salt", ":", "extra", "[", "u'salt'", "]", "=", "salt", "extra", "[", "u'iterations'", "]", "=", "1000", "extra", "[", "u'keylen'", "]", "=", "32", "defer", ".", "returnValue", "(", "types", ".", "Challenge", "(", "u'wampcra'", ",", "extra", ")", ")", "## deny client", "defer", ".", "returnValue", "(", "types", ".", "Deny", "(", ")", ")" ]
Callback fired when client wants to attach session.
[ "Callback", "fired", "when", "client", "wants", "to", "attach", "session", "." ]
e79237e5790b989ad327c17698b295d14d25b63f
https://github.com/lgfausak/sqlauth/blob/e79237e5790b989ad327c17698b295d14d25b63f/sqlauth/scripts/sqlauthrouter.py#L151-L192
238,157
lgfausak/sqlauth
sqlauth/scripts/sqlauthrouter.py
MyRouterSession.onAuthenticate
def onAuthenticate(self, signature, extra): """ Callback fired when a client responds to an authentication challenge. """ log.msg("onAuthenticate: {} {}".format(signature, extra)) ## if there is a pending auth, and the signature provided by client matches .. if self._pending_auth: if signature == self._pending_auth.signature: ## accept the client return types.Accept(authid = self._pending_auth.uid, authrole = self._pending_auth.authrole, authmethod = self._pending_auth.authmethod, authprovider = self._pending_auth.authprovider) else: ## deny client return types.Deny(message = u"signature is invalid") else: ## deny client return types.Deny(message = u"no pending authentication")
python
def onAuthenticate(self, signature, extra): """ Callback fired when a client responds to an authentication challenge. """ log.msg("onAuthenticate: {} {}".format(signature, extra)) ## if there is a pending auth, and the signature provided by client matches .. if self._pending_auth: if signature == self._pending_auth.signature: ## accept the client return types.Accept(authid = self._pending_auth.uid, authrole = self._pending_auth.authrole, authmethod = self._pending_auth.authmethod, authprovider = self._pending_auth.authprovider) else: ## deny client return types.Deny(message = u"signature is invalid") else: ## deny client return types.Deny(message = u"no pending authentication")
[ "def", "onAuthenticate", "(", "self", ",", "signature", ",", "extra", ")", ":", "log", ".", "msg", "(", "\"onAuthenticate: {} {}\"", ".", "format", "(", "signature", ",", "extra", ")", ")", "## if there is a pending auth, and the signature provided by client matches ..", "if", "self", ".", "_pending_auth", ":", "if", "signature", "==", "self", ".", "_pending_auth", ".", "signature", ":", "## accept the client", "return", "types", ".", "Accept", "(", "authid", "=", "self", ".", "_pending_auth", ".", "uid", ",", "authrole", "=", "self", ".", "_pending_auth", ".", "authrole", ",", "authmethod", "=", "self", ".", "_pending_auth", ".", "authmethod", ",", "authprovider", "=", "self", ".", "_pending_auth", ".", "authprovider", ")", "else", ":", "## deny client", "return", "types", ".", "Deny", "(", "message", "=", "u\"signature is invalid\"", ")", "else", ":", "## deny client", "return", "types", ".", "Deny", "(", "message", "=", "u\"no pending authentication\"", ")" ]
Callback fired when a client responds to an authentication challenge.
[ "Callback", "fired", "when", "a", "client", "responds", "to", "an", "authentication", "challenge", "." ]
e79237e5790b989ad327c17698b295d14d25b63f
https://github.com/lgfausak/sqlauth/blob/e79237e5790b989ad327c17698b295d14d25b63f/sqlauth/scripts/sqlauthrouter.py#L195-L218
238,158
cltrudeau/wrench
wrench/logtools/utils.py
configure_stdout_logger
def configure_stdout_logger(log_level=logging.DEBUG): """Configures logging to use STDOUT""" root = logging.getLogger() root.setLevel(log_level) handler = logging.StreamHandler() handler.setLevel(log_level) handler.setFormatter(logging.Formatter(LOG_FORMAT_ESCAPED)) root.addHandler(handler)
python
def configure_stdout_logger(log_level=logging.DEBUG): """Configures logging to use STDOUT""" root = logging.getLogger() root.setLevel(log_level) handler = logging.StreamHandler() handler.setLevel(log_level) handler.setFormatter(logging.Formatter(LOG_FORMAT_ESCAPED)) root.addHandler(handler)
[ "def", "configure_stdout_logger", "(", "log_level", "=", "logging", ".", "DEBUG", ")", ":", "root", "=", "logging", ".", "getLogger", "(", ")", "root", ".", "setLevel", "(", "log_level", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "handler", ".", "setLevel", "(", "log_level", ")", "handler", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "LOG_FORMAT_ESCAPED", ")", ")", "root", ".", "addHandler", "(", "handler", ")" ]
Configures logging to use STDOUT
[ "Configures", "logging", "to", "use", "STDOUT" ]
bc231dd085050a63a87ff3eb8f0a863928f65a41
https://github.com/cltrudeau/wrench/blob/bc231dd085050a63a87ff3eb8f0a863928f65a41/wrench/logtools/utils.py#L32-L41
238,159
cltrudeau/wrench
wrench/logtools/utils.py
silence_logging
def silence_logging(method): """Disables logging for the duration of what is being wrapped. This is particularly useful when testing if a test method is supposed to issue an error message which is confusing that the error shows for a successful test. """ @wraps(method) def wrapper(*args, **kwargs): logging.disable(logging.ERROR) result = method(*args, **kwargs) logging.disable(logging.NOTSET) return result return wrapper
python
def silence_logging(method): """Disables logging for the duration of what is being wrapped. This is particularly useful when testing if a test method is supposed to issue an error message which is confusing that the error shows for a successful test. """ @wraps(method) def wrapper(*args, **kwargs): logging.disable(logging.ERROR) result = method(*args, **kwargs) logging.disable(logging.NOTSET) return result return wrapper
[ "def", "silence_logging", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logging", ".", "disable", "(", "logging", ".", "ERROR", ")", "result", "=", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")", "logging", ".", "disable", "(", "logging", ".", "NOTSET", ")", "return", "result", "return", "wrapper" ]
Disables logging for the duration of what is being wrapped. This is particularly useful when testing if a test method is supposed to issue an error message which is confusing that the error shows for a successful test.
[ "Disables", "logging", "for", "the", "duration", "of", "what", "is", "being", "wrapped", ".", "This", "is", "particularly", "useful", "when", "testing", "if", "a", "test", "method", "is", "supposed", "to", "issue", "an", "error", "message", "which", "is", "confusing", "that", "the", "error", "shows", "for", "a", "successful", "test", "." ]
bc231dd085050a63a87ff3eb8f0a863928f65a41
https://github.com/cltrudeau/wrench/blob/bc231dd085050a63a87ff3eb8f0a863928f65a41/wrench/logtools/utils.py#L96-L108
238,160
roboogle/gtkmvc3
gtkmvco/examples/uimanager/subviews/spintool.py
SpinToolAction.do_create_tool_item
def do_create_tool_item(self): """This is called by the UIManager when it is time to instantiate the proxy""" proxy = SpinToolItem(*self._args_for_toolitem) self.connect_proxy(proxy) return proxy
python
def do_create_tool_item(self): """This is called by the UIManager when it is time to instantiate the proxy""" proxy = SpinToolItem(*self._args_for_toolitem) self.connect_proxy(proxy) return proxy
[ "def", "do_create_tool_item", "(", "self", ")", ":", "proxy", "=", "SpinToolItem", "(", "*", "self", ".", "_args_for_toolitem", ")", "self", ".", "connect_proxy", "(", "proxy", ")", "return", "proxy" ]
This is called by the UIManager when it is time to instantiate the proxy
[ "This", "is", "called", "by", "the", "UIManager", "when", "it", "is", "time", "to", "instantiate", "the", "proxy" ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/examples/uimanager/subviews/spintool.py#L109-L114
238,161
roboogle/gtkmvc3
gtkmvco/examples/uimanager/subviews/spintool.py
SpinToolAction.set_value
def set_value(self, value): """Set value to action.""" self._value = value for proxy in self.get_proxies(): proxy.handler_block(self._changed_handlers[proxy]) proxy.set_value(self._value) proxy.handler_unblock(self._changed_handlers[proxy]) pass self.emit('changed') return
python
def set_value(self, value): """Set value to action.""" self._value = value for proxy in self.get_proxies(): proxy.handler_block(self._changed_handlers[proxy]) proxy.set_value(self._value) proxy.handler_unblock(self._changed_handlers[proxy]) pass self.emit('changed') return
[ "def", "set_value", "(", "self", ",", "value", ")", ":", "self", ".", "_value", "=", "value", "for", "proxy", "in", "self", ".", "get_proxies", "(", ")", ":", "proxy", ".", "handler_block", "(", "self", ".", "_changed_handlers", "[", "proxy", "]", ")", "proxy", ".", "set_value", "(", "self", ".", "_value", ")", "proxy", ".", "handler_unblock", "(", "self", ".", "_changed_handlers", "[", "proxy", "]", ")", "pass", "self", ".", "emit", "(", "'changed'", ")", "return" ]
Set value to action.
[ "Set", "value", "to", "action", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/examples/uimanager/subviews/spintool.py#L129-L140
238,162
samuel-phan/mssh-copy-id
tasks.py
clean
def clean(ctx): """ clean generated project files """ os.chdir(PROJECT_DIR) patterns = ['.cache', '.coverage', '.eggs', 'build', 'dist'] ctx.run('rm -vrf {0}'.format(' '.join(patterns))) ctx.run('''find . \( -name '*,cover' -o -name '__pycache__' -o -name '*.py[co]' -o -name '_work' \) ''' '''-exec rm -vrf '{}' \; || true''')
python
def clean(ctx): """ clean generated project files """ os.chdir(PROJECT_DIR) patterns = ['.cache', '.coverage', '.eggs', 'build', 'dist'] ctx.run('rm -vrf {0}'.format(' '.join(patterns))) ctx.run('''find . \( -name '*,cover' -o -name '__pycache__' -o -name '*.py[co]' -o -name '_work' \) ''' '''-exec rm -vrf '{}' \; || true''')
[ "def", "clean", "(", "ctx", ")", ":", "os", ".", "chdir", "(", "PROJECT_DIR", ")", "patterns", "=", "[", "'.cache'", ",", "'.coverage'", ",", "'.eggs'", ",", "'build'", ",", "'dist'", "]", "ctx", ".", "run", "(", "'rm -vrf {0}'", ".", "format", "(", "' '", ".", "join", "(", "patterns", ")", ")", ")", "ctx", ".", "run", "(", "'''find . \\( -name '*,cover' -o -name '__pycache__' -o -name '*.py[co]' -o -name '_work' \\) '''", "'''-exec rm -vrf '{}' \\; || true'''", ")" ]
clean generated project files
[ "clean", "generated", "project", "files" ]
59c50eabb74c4e0eeb729266df57c285e6661b0b
https://github.com/samuel-phan/mssh-copy-id/blob/59c50eabb74c4e0eeb729266df57c285e6661b0b/tasks.py#L36-L48
238,163
samuel-phan/mssh-copy-id
tasks.py
build_docker_sshd
def build_docker_sshd(ctx): """ build docker image sshd-mssh-copy-id """ dinfo = DOCKER_SSHD_IMG ctx.run('docker rmi -f {0}'.format(dinfo['name']), warn=True) ctx.run('docker build -t {0} {1}'.format(dinfo['name'], dinfo['path']))
python
def build_docker_sshd(ctx): """ build docker image sshd-mssh-copy-id """ dinfo = DOCKER_SSHD_IMG ctx.run('docker rmi -f {0}'.format(dinfo['name']), warn=True) ctx.run('docker build -t {0} {1}'.format(dinfo['name'], dinfo['path']))
[ "def", "build_docker_sshd", "(", "ctx", ")", ":", "dinfo", "=", "DOCKER_SSHD_IMG", "ctx", ".", "run", "(", "'docker rmi -f {0}'", ".", "format", "(", "dinfo", "[", "'name'", "]", ")", ",", "warn", "=", "True", ")", "ctx", ".", "run", "(", "'docker build -t {0} {1}'", ".", "format", "(", "dinfo", "[", "'name'", "]", ",", "dinfo", "[", "'path'", "]", ")", ")" ]
build docker image sshd-mssh-copy-id
[ "build", "docker", "image", "sshd", "-", "mssh", "-", "copy", "-", "id" ]
59c50eabb74c4e0eeb729266df57c285e6661b0b
https://github.com/samuel-phan/mssh-copy-id/blob/59c50eabb74c4e0eeb729266df57c285e6661b0b/tasks.py#L52-L58
238,164
samuel-phan/mssh-copy-id
tasks.py
build_docker
def build_docker(ctx, image): """ build docker images """ if image not in DOCKER_IMGS: print('Error: unknown docker image "{0}"!'.format(image), file=sys.stderr) sys.exit(1) dinfo = DOCKER_IMGS[image] ctx.run('docker rmi -f {0}'.format(dinfo['name']), warn=True) dinfo_work_dir = os.path.join(dinfo['path'], '_work') ctx.run('mkdir -p {0}'.format(dinfo_work_dir)) ctx.run('cp {0} {1}'.format(os.path.join(DOCKER_COMMON_DIR, 'sudo-as-user.sh'), dinfo_work_dir)) ctx.run('docker build -t {0} {1}'.format(dinfo['name'], dinfo['path']))
python
def build_docker(ctx, image): """ build docker images """ if image not in DOCKER_IMGS: print('Error: unknown docker image "{0}"!'.format(image), file=sys.stderr) sys.exit(1) dinfo = DOCKER_IMGS[image] ctx.run('docker rmi -f {0}'.format(dinfo['name']), warn=True) dinfo_work_dir = os.path.join(dinfo['path'], '_work') ctx.run('mkdir -p {0}'.format(dinfo_work_dir)) ctx.run('cp {0} {1}'.format(os.path.join(DOCKER_COMMON_DIR, 'sudo-as-user.sh'), dinfo_work_dir)) ctx.run('docker build -t {0} {1}'.format(dinfo['name'], dinfo['path']))
[ "def", "build_docker", "(", "ctx", ",", "image", ")", ":", "if", "image", "not", "in", "DOCKER_IMGS", ":", "print", "(", "'Error: unknown docker image \"{0}\"!'", ".", "format", "(", "image", ")", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "dinfo", "=", "DOCKER_IMGS", "[", "image", "]", "ctx", ".", "run", "(", "'docker rmi -f {0}'", ".", "format", "(", "dinfo", "[", "'name'", "]", ")", ",", "warn", "=", "True", ")", "dinfo_work_dir", "=", "os", ".", "path", ".", "join", "(", "dinfo", "[", "'path'", "]", ",", "'_work'", ")", "ctx", ".", "run", "(", "'mkdir -p {0}'", ".", "format", "(", "dinfo_work_dir", ")", ")", "ctx", ".", "run", "(", "'cp {0} {1}'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "DOCKER_COMMON_DIR", ",", "'sudo-as-user.sh'", ")", ",", "dinfo_work_dir", ")", ")", "ctx", ".", "run", "(", "'docker build -t {0} {1}'", ".", "format", "(", "dinfo", "[", "'name'", "]", ",", "dinfo", "[", "'path'", "]", ")", ")" ]
build docker images
[ "build", "docker", "images" ]
59c50eabb74c4e0eeb729266df57c285e6661b0b
https://github.com/samuel-phan/mssh-copy-id/blob/59c50eabb74c4e0eeb729266df57c285e6661b0b/tasks.py#L62-L75
238,165
samuel-phan/mssh-copy-id
tasks.py
build_deb
def build_deb(ctx, target): """ build a deb package """ if target not in ('ubuntu-trusty',): print('Error: unknown target "{0}"!'.format(target), file=sys.stderr) sys.exit(1) os.chdir(PROJECT_DIR) debbuild_dir = os.path.join(DIST_DIR, 'deb') # Create directories layout ctx.run('mkdir -p {0}'.format(debbuild_dir)) # Copy the sources build_src(ctx, dest=debbuild_dir) src_archive = glob.glob(os.path.join(debbuild_dir, 'mssh-copy-id-*.tar.gz'))[0] ctx.run('tar -xvf {0} -C {1}'.format(src_archive, debbuild_dir)) src_dir = src_archive[:-7] # uncompressed directory ctx.run('cp -r {0} {1}'.format(os.path.join(PROJECT_DIR, 'deb/debian'), src_dir)) # Build the deb ctx.run('docker run -e LOCAL_USER_ID={local_user_id} -v {local}:{cont} {img}' .format(local_user_id=os.getuid(), local=debbuild_dir, cont='/deb', img=DOCKER_IMGS[target]['name'])) ctx.run('mv -f {0} {1}'.format(os.path.join(debbuild_dir, 'mssh-copy-id_*.deb'), DIST_DIR))
python
def build_deb(ctx, target): """ build a deb package """ if target not in ('ubuntu-trusty',): print('Error: unknown target "{0}"!'.format(target), file=sys.stderr) sys.exit(1) os.chdir(PROJECT_DIR) debbuild_dir = os.path.join(DIST_DIR, 'deb') # Create directories layout ctx.run('mkdir -p {0}'.format(debbuild_dir)) # Copy the sources build_src(ctx, dest=debbuild_dir) src_archive = glob.glob(os.path.join(debbuild_dir, 'mssh-copy-id-*.tar.gz'))[0] ctx.run('tar -xvf {0} -C {1}'.format(src_archive, debbuild_dir)) src_dir = src_archive[:-7] # uncompressed directory ctx.run('cp -r {0} {1}'.format(os.path.join(PROJECT_DIR, 'deb/debian'), src_dir)) # Build the deb ctx.run('docker run -e LOCAL_USER_ID={local_user_id} -v {local}:{cont} {img}' .format(local_user_id=os.getuid(), local=debbuild_dir, cont='/deb', img=DOCKER_IMGS[target]['name'])) ctx.run('mv -f {0} {1}'.format(os.path.join(debbuild_dir, 'mssh-copy-id_*.deb'), DIST_DIR))
[ "def", "build_deb", "(", "ctx", ",", "target", ")", ":", "if", "target", "not", "in", "(", "'ubuntu-trusty'", ",", ")", ":", "print", "(", "'Error: unknown target \"{0}\"!'", ".", "format", "(", "target", ")", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "os", ".", "chdir", "(", "PROJECT_DIR", ")", "debbuild_dir", "=", "os", ".", "path", ".", "join", "(", "DIST_DIR", ",", "'deb'", ")", "# Create directories layout", "ctx", ".", "run", "(", "'mkdir -p {0}'", ".", "format", "(", "debbuild_dir", ")", ")", "# Copy the sources", "build_src", "(", "ctx", ",", "dest", "=", "debbuild_dir", ")", "src_archive", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "debbuild_dir", ",", "'mssh-copy-id-*.tar.gz'", ")", ")", "[", "0", "]", "ctx", ".", "run", "(", "'tar -xvf {0} -C {1}'", ".", "format", "(", "src_archive", ",", "debbuild_dir", ")", ")", "src_dir", "=", "src_archive", "[", ":", "-", "7", "]", "# uncompressed directory", "ctx", ".", "run", "(", "'cp -r {0} {1}'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "PROJECT_DIR", ",", "'deb/debian'", ")", ",", "src_dir", ")", ")", "# Build the deb", "ctx", ".", "run", "(", "'docker run -e LOCAL_USER_ID={local_user_id} -v {local}:{cont} {img}'", ".", "format", "(", "local_user_id", "=", "os", ".", "getuid", "(", ")", ",", "local", "=", "debbuild_dir", ",", "cont", "=", "'/deb'", ",", "img", "=", "DOCKER_IMGS", "[", "target", "]", "[", "'name'", "]", ")", ")", "ctx", ".", "run", "(", "'mv -f {0} {1}'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "debbuild_dir", ",", "'mssh-copy-id_*.deb'", ")", ",", "DIST_DIR", ")", ")" ]
build a deb package
[ "build", "a", "deb", "package" ]
59c50eabb74c4e0eeb729266df57c285e6661b0b
https://github.com/samuel-phan/mssh-copy-id/blob/59c50eabb74c4e0eeb729266df57c285e6661b0b/tasks.py#L79-L107
238,166
samuel-phan/mssh-copy-id
tasks.py
build_rpm
def build_rpm(ctx, target): """ build an RPM package """ if target not in ('centos6', 'centos7'): print('Error: unknown target "{0}"!'.format(target), file=sys.stderr) sys.exit(1) os.chdir(PROJECT_DIR) rpmbuild_dir = os.path.join(DIST_DIR, 'rpmbuild') # Create directories layout ctx.run('mkdir -p {0}'.format(' '.join(os.path.join(rpmbuild_dir, d) for d in ('BUILD', 'RPMS', 'SOURCES', 'SPECS', 'SRPMS')))) # Copy the sources & spec file build_src(ctx, dest=os.path.join(rpmbuild_dir, 'SOURCES')) ctx.run('cp -f {0} {1}'.format(os.path.join(PROJECT_DIR, 'rpm/centos/mssh-copy-id.spec'), os.path.join(rpmbuild_dir, 'SPECS'))) # Build the RPM ctx.run('docker run -e LOCAL_USER_ID={local_user_id} -v {local}:{cont} {img}' .format(local_user_id=os.getuid(), local=rpmbuild_dir, cont='/rpmbuild', img=DOCKER_IMGS[target]['name'])) ctx.run('mv -f {0} {1}'.format(os.path.join(rpmbuild_dir, 'RPMS/noarch/mssh-copy-id-*.rpm'), DIST_DIR))
python
def build_rpm(ctx, target): """ build an RPM package """ if target not in ('centos6', 'centos7'): print('Error: unknown target "{0}"!'.format(target), file=sys.stderr) sys.exit(1) os.chdir(PROJECT_DIR) rpmbuild_dir = os.path.join(DIST_DIR, 'rpmbuild') # Create directories layout ctx.run('mkdir -p {0}'.format(' '.join(os.path.join(rpmbuild_dir, d) for d in ('BUILD', 'RPMS', 'SOURCES', 'SPECS', 'SRPMS')))) # Copy the sources & spec file build_src(ctx, dest=os.path.join(rpmbuild_dir, 'SOURCES')) ctx.run('cp -f {0} {1}'.format(os.path.join(PROJECT_DIR, 'rpm/centos/mssh-copy-id.spec'), os.path.join(rpmbuild_dir, 'SPECS'))) # Build the RPM ctx.run('docker run -e LOCAL_USER_ID={local_user_id} -v {local}:{cont} {img}' .format(local_user_id=os.getuid(), local=rpmbuild_dir, cont='/rpmbuild', img=DOCKER_IMGS[target]['name'])) ctx.run('mv -f {0} {1}'.format(os.path.join(rpmbuild_dir, 'RPMS/noarch/mssh-copy-id-*.rpm'), DIST_DIR))
[ "def", "build_rpm", "(", "ctx", ",", "target", ")", ":", "if", "target", "not", "in", "(", "'centos6'", ",", "'centos7'", ")", ":", "print", "(", "'Error: unknown target \"{0}\"!'", ".", "format", "(", "target", ")", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "os", ".", "chdir", "(", "PROJECT_DIR", ")", "rpmbuild_dir", "=", "os", ".", "path", ".", "join", "(", "DIST_DIR", ",", "'rpmbuild'", ")", "# Create directories layout", "ctx", ".", "run", "(", "'mkdir -p {0}'", ".", "format", "(", "' '", ".", "join", "(", "os", ".", "path", ".", "join", "(", "rpmbuild_dir", ",", "d", ")", "for", "d", "in", "(", "'BUILD'", ",", "'RPMS'", ",", "'SOURCES'", ",", "'SPECS'", ",", "'SRPMS'", ")", ")", ")", ")", "# Copy the sources & spec file", "build_src", "(", "ctx", ",", "dest", "=", "os", ".", "path", ".", "join", "(", "rpmbuild_dir", ",", "'SOURCES'", ")", ")", "ctx", ".", "run", "(", "'cp -f {0} {1}'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "PROJECT_DIR", ",", "'rpm/centos/mssh-copy-id.spec'", ")", ",", "os", ".", "path", ".", "join", "(", "rpmbuild_dir", ",", "'SPECS'", ")", ")", ")", "# Build the RPM", "ctx", ".", "run", "(", "'docker run -e LOCAL_USER_ID={local_user_id} -v {local}:{cont} {img}'", ".", "format", "(", "local_user_id", "=", "os", ".", "getuid", "(", ")", ",", "local", "=", "rpmbuild_dir", ",", "cont", "=", "'/rpmbuild'", ",", "img", "=", "DOCKER_IMGS", "[", "target", "]", "[", "'name'", "]", ")", ")", "ctx", ".", "run", "(", "'mv -f {0} {1}'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "rpmbuild_dir", ",", "'RPMS/noarch/mssh-copy-id-*.rpm'", ")", ",", "DIST_DIR", ")", ")" ]
build an RPM package
[ "build", "an", "RPM", "package" ]
59c50eabb74c4e0eeb729266df57c285e6661b0b
https://github.com/samuel-phan/mssh-copy-id/blob/59c50eabb74c4e0eeb729266df57c285e6661b0b/tasks.py#L111-L138
238,167
samuel-phan/mssh-copy-id
tasks.py
build_src
def build_src(ctx, dest=None): """ build source archive """ if dest: if not dest.startswith('/'): # Relative dest = os.path.join(os.getcwd(), dest) os.chdir(PROJECT_DIR) ctx.run('python setup.py sdist --dist-dir {0}'.format(dest)) else: os.chdir(PROJECT_DIR) ctx.run('python setup.py sdist')
python
def build_src(ctx, dest=None): """ build source archive """ if dest: if not dest.startswith('/'): # Relative dest = os.path.join(os.getcwd(), dest) os.chdir(PROJECT_DIR) ctx.run('python setup.py sdist --dist-dir {0}'.format(dest)) else: os.chdir(PROJECT_DIR) ctx.run('python setup.py sdist')
[ "def", "build_src", "(", "ctx", ",", "dest", "=", "None", ")", ":", "if", "dest", ":", "if", "not", "dest", ".", "startswith", "(", "'/'", ")", ":", "# Relative", "dest", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "dest", ")", "os", ".", "chdir", "(", "PROJECT_DIR", ")", "ctx", ".", "run", "(", "'python setup.py sdist --dist-dir {0}'", ".", "format", "(", "dest", ")", ")", "else", ":", "os", ".", "chdir", "(", "PROJECT_DIR", ")", "ctx", ".", "run", "(", "'python setup.py sdist'", ")" ]
build source archive
[ "build", "source", "archive" ]
59c50eabb74c4e0eeb729266df57c285e6661b0b
https://github.com/samuel-phan/mssh-copy-id/blob/59c50eabb74c4e0eeb729266df57c285e6661b0b/tasks.py#L142-L155
238,168
JukeboxPipeline/jukebox-core
docs/updatedoc.py
run_gendoc
def run_gendoc(source, dest, args): """Starts gendoc which reads source and creates rst files in dest with the given args. :param source: The python source directory for gendoc. Can be a relative path. :type source: str :param dest: The destination for the rst files. Can be a relative path. :type dest: str :param args: Arguments for gendoc. See gendoc for more information. :type args: list :returns: None :rtype: None :raises: SystemExit """ args.insert(0, 'gendoc.py') args.append(dest) args.append(source) print 'Running gendoc.main with: %s' % args gendoc.main(args)
python
def run_gendoc(source, dest, args): """Starts gendoc which reads source and creates rst files in dest with the given args. :param source: The python source directory for gendoc. Can be a relative path. :type source: str :param dest: The destination for the rst files. Can be a relative path. :type dest: str :param args: Arguments for gendoc. See gendoc for more information. :type args: list :returns: None :rtype: None :raises: SystemExit """ args.insert(0, 'gendoc.py') args.append(dest) args.append(source) print 'Running gendoc.main with: %s' % args gendoc.main(args)
[ "def", "run_gendoc", "(", "source", ",", "dest", ",", "args", ")", ":", "args", ".", "insert", "(", "0", ",", "'gendoc.py'", ")", "args", ".", "append", "(", "dest", ")", "args", ".", "append", "(", "source", ")", "print", "'Running gendoc.main with: %s'", "%", "args", "gendoc", ".", "main", "(", "args", ")" ]
Starts gendoc which reads source and creates rst files in dest with the given args. :param source: The python source directory for gendoc. Can be a relative path. :type source: str :param dest: The destination for the rst files. Can be a relative path. :type dest: str :param args: Arguments for gendoc. See gendoc for more information. :type args: list :returns: None :rtype: None :raises: SystemExit
[ "Starts", "gendoc", "which", "reads", "source", "and", "creates", "rst", "files", "in", "dest", "with", "the", "given", "args", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/docs/updatedoc.py#L84-L101
238,169
JukeboxPipeline/jukebox-core
docs/updatedoc.py
main
def main(argv=sys.argv[1:]): """Parse commandline arguments and run the tool :param argv: the commandline arguments. :type argv: list :returns: None :rtype: None :raises: None """ parser = setup_argparse() args = parser.parse_args(argv) if args.gendochelp: sys.argv[0] = 'gendoc.py' genparser = gendoc.setup_parser() genparser.print_help() sys.exit(0) print 'Preparing output directories' print '='*80 for odir in args.output: prepare_dir(odir, not args.nodelete) print '\nRunning gendoc' print '='*80 for i, idir in enumerate(args.input): if i >= len(args.output): odir = args.output[-1] else: odir = args.output[i] run_gendoc(idir, odir, args.gendocargs)
python
def main(argv=sys.argv[1:]): """Parse commandline arguments and run the tool :param argv: the commandline arguments. :type argv: list :returns: None :rtype: None :raises: None """ parser = setup_argparse() args = parser.parse_args(argv) if args.gendochelp: sys.argv[0] = 'gendoc.py' genparser = gendoc.setup_parser() genparser.print_help() sys.exit(0) print 'Preparing output directories' print '='*80 for odir in args.output: prepare_dir(odir, not args.nodelete) print '\nRunning gendoc' print '='*80 for i, idir in enumerate(args.input): if i >= len(args.output): odir = args.output[-1] else: odir = args.output[i] run_gendoc(idir, odir, args.gendocargs)
[ "def", "main", "(", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", ")", ":", "parser", "=", "setup_argparse", "(", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "if", "args", ".", "gendochelp", ":", "sys", ".", "argv", "[", "0", "]", "=", "'gendoc.py'", "genparser", "=", "gendoc", ".", "setup_parser", "(", ")", "genparser", ".", "print_help", "(", ")", "sys", ".", "exit", "(", "0", ")", "print", "'Preparing output directories'", "print", "'='", "*", "80", "for", "odir", "in", "args", ".", "output", ":", "prepare_dir", "(", "odir", ",", "not", "args", ".", "nodelete", ")", "print", "'\\nRunning gendoc'", "print", "'='", "*", "80", "for", "i", ",", "idir", "in", "enumerate", "(", "args", ".", "input", ")", ":", "if", "i", ">=", "len", "(", "args", ".", "output", ")", ":", "odir", "=", "args", ".", "output", "[", "-", "1", "]", "else", ":", "odir", "=", "args", ".", "output", "[", "i", "]", "run_gendoc", "(", "idir", ",", "odir", ",", "args", ".", "gendocargs", ")" ]
Parse commandline arguments and run the tool :param argv: the commandline arguments. :type argv: list :returns: None :rtype: None :raises: None
[ "Parse", "commandline", "arguments", "and", "run", "the", "tool" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/docs/updatedoc.py#L104-L131
238,170
Checksum/landfill
landfill.py
get_migrations
def get_migrations(path): ''' In the specified directory, get all the files which match the pattern 0001_migration.py ''' pattern = re.compile(r"\d+_[\w\d]+") modules = [name for _, name, _ in pkgutil.iter_modules([path]) if pattern.match(name) ] return sorted(modules, key=lambda name: int(name.split("_")[0]))
python
def get_migrations(path): ''' In the specified directory, get all the files which match the pattern 0001_migration.py ''' pattern = re.compile(r"\d+_[\w\d]+") modules = [name for _, name, _ in pkgutil.iter_modules([path]) if pattern.match(name) ] return sorted(modules, key=lambda name: int(name.split("_")[0]))
[ "def", "get_migrations", "(", "path", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r\"\\d+_[\\w\\d]+\"", ")", "modules", "=", "[", "name", "for", "_", ",", "name", ",", "_", "in", "pkgutil", ".", "iter_modules", "(", "[", "path", "]", ")", "if", "pattern", ".", "match", "(", "name", ")", "]", "return", "sorted", "(", "modules", ",", "key", "=", "lambda", "name", ":", "int", "(", "name", ".", "split", "(", "\"_\"", ")", "[", "0", "]", ")", ")" ]
In the specified directory, get all the files which match the pattern 0001_migration.py
[ "In", "the", "specified", "directory", "get", "all", "the", "files", "which", "match", "the", "pattern", "0001_migration", ".", "py" ]
bf1ea36042a00dc848e1380b8dc0153bb7e89fea
https://github.com/Checksum/landfill/blob/bf1ea36042a00dc848e1380b8dc0153bb7e89fea/landfill.py#L398-L408
238,171
Checksum/landfill
landfill.py
migrate
def migrate(engine, database, module, **kwargs): ''' Execute the migrations. Pass in kwargs ''' validate_args(engine, database, module) options = { 'direction': kwargs.get('direction', 'up'), 'fake': kwargs.get('fake', False), 'force': kwargs.get('force', False), 'migration': kwargs.get('migration', None), 'transaction': kwargs.get('transaction', True), } Migration._meta.database = database migrator = DATABASE_MAP[engine](database, module, **options) migrator.run()
python
def migrate(engine, database, module, **kwargs): ''' Execute the migrations. Pass in kwargs ''' validate_args(engine, database, module) options = { 'direction': kwargs.get('direction', 'up'), 'fake': kwargs.get('fake', False), 'force': kwargs.get('force', False), 'migration': kwargs.get('migration', None), 'transaction': kwargs.get('transaction', True), } Migration._meta.database = database migrator = DATABASE_MAP[engine](database, module, **options) migrator.run()
[ "def", "migrate", "(", "engine", ",", "database", ",", "module", ",", "*", "*", "kwargs", ")", ":", "validate_args", "(", "engine", ",", "database", ",", "module", ")", "options", "=", "{", "'direction'", ":", "kwargs", ".", "get", "(", "'direction'", ",", "'up'", ")", ",", "'fake'", ":", "kwargs", ".", "get", "(", "'fake'", ",", "False", ")", ",", "'force'", ":", "kwargs", ".", "get", "(", "'force'", ",", "False", ")", ",", "'migration'", ":", "kwargs", ".", "get", "(", "'migration'", ",", "None", ")", ",", "'transaction'", ":", "kwargs", ".", "get", "(", "'transaction'", ",", "True", ")", ",", "}", "Migration", ".", "_meta", ".", "database", "=", "database", "migrator", "=", "DATABASE_MAP", "[", "engine", "]", "(", "database", ",", "module", ",", "*", "*", "options", ")", "migrator", ".", "run", "(", ")" ]
Execute the migrations. Pass in kwargs
[ "Execute", "the", "migrations", ".", "Pass", "in", "kwargs" ]
bf1ea36042a00dc848e1380b8dc0153bb7e89fea
https://github.com/Checksum/landfill/blob/bf1ea36042a00dc848e1380b8dc0153bb7e89fea/landfill.py#L423-L439
238,172
Checksum/landfill
landfill.py
generate
def generate(engine, database, models, **kwargs): ''' Generate the migrations by introspecting the db ''' validate_args(engine, database, models) generator = Generator(engine, database, models) generator.run()
python
def generate(engine, database, models, **kwargs): ''' Generate the migrations by introspecting the db ''' validate_args(engine, database, models) generator = Generator(engine, database, models) generator.run()
[ "def", "generate", "(", "engine", ",", "database", ",", "models", ",", "*", "*", "kwargs", ")", ":", "validate_args", "(", "engine", ",", "database", ",", "models", ")", "generator", "=", "Generator", "(", "engine", ",", "database", ",", "models", ")", "generator", ".", "run", "(", ")" ]
Generate the migrations by introspecting the db
[ "Generate", "the", "migrations", "by", "introspecting", "the", "db" ]
bf1ea36042a00dc848e1380b8dc0153bb7e89fea
https://github.com/Checksum/landfill/blob/bf1ea36042a00dc848e1380b8dc0153bb7e89fea/landfill.py#L441-L447
238,173
Checksum/landfill
landfill.py
CustomMigrator.apply_migration
def apply_migration(self, migration, **kwargs): ''' Apply a particular migration ''' cprint("\nAttempting to run %s" % migration, "cyan") # First check if the migration has already been applied exists = Migration.select().where(Migration.name == migration).limit(1).first() if exists and self.direction == 'up': cprint("This migration has already been run on this server", "red") if not self.force or self.fake: return False else: cprint("Force running this migration again", "yellow") # Load the module module_name = "%s.%s" % (self.module_name, migration) try: module = importlib.import_module(module_name) if not hasattr(module, self.direction): raise MigrationException("%s doesn't have %s migration defined" % (migration, self.direction) ) # Actually execute the direction method # Note that this doesn't actually run the migrations in the DB yet. # This merely collects the steps in the migration, so that if needed # we can just fake it and print out the SQL query as well. getattr(module, self.direction)(self) # Print out each migration and execute it for op in self.operations: self.execute_operation(op) if not self.fake: # If successful, create the entry in our log if self.direction == 'up' and not exists: Migration.create(name=migration) elif self.direction == 'down' and exists: exists.delete_instance() cprint("Done", "green") except ImportError: raise MigrationException("%s migration not found" % migration)
python
def apply_migration(self, migration, **kwargs): ''' Apply a particular migration ''' cprint("\nAttempting to run %s" % migration, "cyan") # First check if the migration has already been applied exists = Migration.select().where(Migration.name == migration).limit(1).first() if exists and self.direction == 'up': cprint("This migration has already been run on this server", "red") if not self.force or self.fake: return False else: cprint("Force running this migration again", "yellow") # Load the module module_name = "%s.%s" % (self.module_name, migration) try: module = importlib.import_module(module_name) if not hasattr(module, self.direction): raise MigrationException("%s doesn't have %s migration defined" % (migration, self.direction) ) # Actually execute the direction method # Note that this doesn't actually run the migrations in the DB yet. # This merely collects the steps in the migration, so that if needed # we can just fake it and print out the SQL query as well. getattr(module, self.direction)(self) # Print out each migration and execute it for op in self.operations: self.execute_operation(op) if not self.fake: # If successful, create the entry in our log if self.direction == 'up' and not exists: Migration.create(name=migration) elif self.direction == 'down' and exists: exists.delete_instance() cprint("Done", "green") except ImportError: raise MigrationException("%s migration not found" % migration)
[ "def", "apply_migration", "(", "self", ",", "migration", ",", "*", "*", "kwargs", ")", ":", "cprint", "(", "\"\\nAttempting to run %s\"", "%", "migration", ",", "\"cyan\"", ")", "# First check if the migration has already been applied", "exists", "=", "Migration", ".", "select", "(", ")", ".", "where", "(", "Migration", ".", "name", "==", "migration", ")", ".", "limit", "(", "1", ")", ".", "first", "(", ")", "if", "exists", "and", "self", ".", "direction", "==", "'up'", ":", "cprint", "(", "\"This migration has already been run on this server\"", ",", "\"red\"", ")", "if", "not", "self", ".", "force", "or", "self", ".", "fake", ":", "return", "False", "else", ":", "cprint", "(", "\"Force running this migration again\"", ",", "\"yellow\"", ")", "# Load the module", "module_name", "=", "\"%s.%s\"", "%", "(", "self", ".", "module_name", ",", "migration", ")", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "if", "not", "hasattr", "(", "module", ",", "self", ".", "direction", ")", ":", "raise", "MigrationException", "(", "\"%s doesn't have %s migration defined\"", "%", "(", "migration", ",", "self", ".", "direction", ")", ")", "# Actually execute the direction method", "# Note that this doesn't actually run the migrations in the DB yet.", "# This merely collects the steps in the migration, so that if needed", "# we can just fake it and print out the SQL query as well.", "getattr", "(", "module", ",", "self", ".", "direction", ")", "(", "self", ")", "# Print out each migration and execute it", "for", "op", "in", "self", ".", "operations", ":", "self", ".", "execute_operation", "(", "op", ")", "if", "not", "self", ".", "fake", ":", "# If successful, create the entry in our log", "if", "self", ".", "direction", "==", "'up'", "and", "not", "exists", ":", "Migration", ".", "create", "(", "name", "=", "migration", ")", "elif", "self", ".", "direction", "==", "'down'", "and", "exists", ":", "exists", ".", "delete_instance", "(", ")", "cprint", "(", "\"Done\"", ",", "\"green\"", ")", "except", "ImportError", ":", "raise", "MigrationException", "(", "\"%s migration not found\"", "%", "migration", ")" ]
Apply a particular migration
[ "Apply", "a", "particular", "migration" ]
bf1ea36042a00dc848e1380b8dc0153bb7e89fea
https://github.com/Checksum/landfill/blob/bf1ea36042a00dc848e1380b8dc0153bb7e89fea/landfill.py#L162-L203
238,174
Checksum/landfill
landfill.py
Generator.get_tables
def get_tables(self, models): ''' Extract all peewee models from the passed in module ''' return { obj._meta.db_table : obj for obj in models.__dict__.itervalues() if isinstance(obj, peewee.BaseModel) and len(obj._meta.fields) > 1 }
python
def get_tables(self, models): ''' Extract all peewee models from the passed in module ''' return { obj._meta.db_table : obj for obj in models.__dict__.itervalues() if isinstance(obj, peewee.BaseModel) and len(obj._meta.fields) > 1 }
[ "def", "get_tables", "(", "self", ",", "models", ")", ":", "return", "{", "obj", ".", "_meta", ".", "db_table", ":", "obj", "for", "obj", "in", "models", ".", "__dict__", ".", "itervalues", "(", ")", "if", "isinstance", "(", "obj", ",", "peewee", ".", "BaseModel", ")", "and", "len", "(", "obj", ".", "_meta", ".", "fields", ")", ">", "1", "}" ]
Extract all peewee models from the passed in module
[ "Extract", "all", "peewee", "models", "from", "the", "passed", "in", "module" ]
bf1ea36042a00dc848e1380b8dc0153bb7e89fea
https://github.com/Checksum/landfill/blob/bf1ea36042a00dc848e1380b8dc0153bb7e89fea/landfill.py#L274-L282
238,175
Checksum/landfill
landfill.py
Generator.get_pwiz_tables
def get_pwiz_tables(self, engine, database): ''' Run the pwiz introspector and get the models defined in the DB. ''' introspector = pwiz.make_introspector(engine, database.database, **database.connect_kwargs) out_file = '/tmp/db_models.py' with Capturing() as code: pwiz.print_models(introspector) code = '\n'.join(code) # Unfortunately, introspect.getsource doesn't seem to work # with dynamically created classes unless it is written out # to a file. So write it out to a temporary file with open(out_file, 'w') as file_: file_.write(code) # Load up the DB models as a new module so that we can # compare them with those in the model definition return imp.load_source('db_models', out_file)
python
def get_pwiz_tables(self, engine, database): ''' Run the pwiz introspector and get the models defined in the DB. ''' introspector = pwiz.make_introspector(engine, database.database, **database.connect_kwargs) out_file = '/tmp/db_models.py' with Capturing() as code: pwiz.print_models(introspector) code = '\n'.join(code) # Unfortunately, introspect.getsource doesn't seem to work # with dynamically created classes unless it is written out # to a file. So write it out to a temporary file with open(out_file, 'w') as file_: file_.write(code) # Load up the DB models as a new module so that we can # compare them with those in the model definition return imp.load_source('db_models', out_file)
[ "def", "get_pwiz_tables", "(", "self", ",", "engine", ",", "database", ")", ":", "introspector", "=", "pwiz", ".", "make_introspector", "(", "engine", ",", "database", ".", "database", ",", "*", "*", "database", ".", "connect_kwargs", ")", "out_file", "=", "'/tmp/db_models.py'", "with", "Capturing", "(", ")", "as", "code", ":", "pwiz", ".", "print_models", "(", "introspector", ")", "code", "=", "'\\n'", ".", "join", "(", "code", ")", "# Unfortunately, introspect.getsource doesn't seem to work", "# with dynamically created classes unless it is written out", "# to a file. So write it out to a temporary file", "with", "open", "(", "out_file", ",", "'w'", ")", "as", "file_", ":", "file_", ".", "write", "(", "code", ")", "# Load up the DB models as a new module so that we can", "# compare them with those in the model definition", "return", "imp", ".", "load_source", "(", "'db_models'", ",", "out_file", ")" ]
Run the pwiz introspector and get the models defined in the DB.
[ "Run", "the", "pwiz", "introspector", "and", "get", "the", "models", "defined", "in", "the", "DB", "." ]
bf1ea36042a00dc848e1380b8dc0153bb7e89fea
https://github.com/Checksum/landfill/blob/bf1ea36042a00dc848e1380b8dc0153bb7e89fea/landfill.py#L284-L303
238,176
botswana-harvard/edc-registration
edc_registration/model_mixins/registered_subject_model_mixin.py
RegisteredSubjectModelMixin.update_subject_identifier_on_save
def update_subject_identifier_on_save(self): """Overridden to not set the subject identifier on save. """ if not self.subject_identifier: self.subject_identifier = self.subject_identifier_as_pk.hex elif re.match(UUID_PATTERN, self.subject_identifier): pass return self.subject_identifier
python
def update_subject_identifier_on_save(self): """Overridden to not set the subject identifier on save. """ if not self.subject_identifier: self.subject_identifier = self.subject_identifier_as_pk.hex elif re.match(UUID_PATTERN, self.subject_identifier): pass return self.subject_identifier
[ "def", "update_subject_identifier_on_save", "(", "self", ")", ":", "if", "not", "self", ".", "subject_identifier", ":", "self", ".", "subject_identifier", "=", "self", ".", "subject_identifier_as_pk", ".", "hex", "elif", "re", ".", "match", "(", "UUID_PATTERN", ",", "self", ".", "subject_identifier", ")", ":", "pass", "return", "self", ".", "subject_identifier" ]
Overridden to not set the subject identifier on save.
[ "Overridden", "to", "not", "set", "the", "subject", "identifier", "on", "save", "." ]
3daca624a496945fd4536488f6f80790bbecc081
https://github.com/botswana-harvard/edc-registration/blob/3daca624a496945fd4536488f6f80790bbecc081/edc_registration/model_mixins/registered_subject_model_mixin.py#L186-L193
238,177
botswana-harvard/edc-registration
edc_registration/model_mixins/registered_subject_model_mixin.py
RegisteredSubjectModelMixin.raise_on_changed_subject_identifier
def raise_on_changed_subject_identifier(self): """Raises an exception if there is an attempt to change the subject identifier for an existing instance if the subject identifier is already set. """ if self.id and self.subject_identifier_is_set(): with transaction.atomic(): obj = self.__class__.objects.get(pk=self.id) if obj.subject_identifier != self.subject_identifier_as_pk.hex: if self.subject_identifier != obj.subject_identifier: raise RegisteredSubjectError( 'Subject identifier cannot be changed for ' 'existing registered subject. Got {} <> {}.'.format( self.subject_identifier, obj.subject_identifier))
python
def raise_on_changed_subject_identifier(self): """Raises an exception if there is an attempt to change the subject identifier for an existing instance if the subject identifier is already set. """ if self.id and self.subject_identifier_is_set(): with transaction.atomic(): obj = self.__class__.objects.get(pk=self.id) if obj.subject_identifier != self.subject_identifier_as_pk.hex: if self.subject_identifier != obj.subject_identifier: raise RegisteredSubjectError( 'Subject identifier cannot be changed for ' 'existing registered subject. Got {} <> {}.'.format( self.subject_identifier, obj.subject_identifier))
[ "def", "raise_on_changed_subject_identifier", "(", "self", ")", ":", "if", "self", ".", "id", "and", "self", ".", "subject_identifier_is_set", "(", ")", ":", "with", "transaction", ".", "atomic", "(", ")", ":", "obj", "=", "self", ".", "__class__", ".", "objects", ".", "get", "(", "pk", "=", "self", ".", "id", ")", "if", "obj", ".", "subject_identifier", "!=", "self", ".", "subject_identifier_as_pk", ".", "hex", ":", "if", "self", ".", "subject_identifier", "!=", "obj", ".", "subject_identifier", ":", "raise", "RegisteredSubjectError", "(", "'Subject identifier cannot be changed for '", "'existing registered subject. Got {} <> {}.'", ".", "format", "(", "self", ".", "subject_identifier", ",", "obj", ".", "subject_identifier", ")", ")" ]
Raises an exception if there is an attempt to change the subject identifier for an existing instance if the subject identifier is already set.
[ "Raises", "an", "exception", "if", "there", "is", "an", "attempt", "to", "change", "the", "subject", "identifier", "for", "an", "existing", "instance", "if", "the", "subject", "identifier", "is", "already", "set", "." ]
3daca624a496945fd4536488f6f80790bbecc081
https://github.com/botswana-harvard/edc-registration/blob/3daca624a496945fd4536488f6f80790bbecc081/edc_registration/model_mixins/registered_subject_model_mixin.py#L209-L222
238,178
pip-services3-python/pip-services3-commons-python
pip_services3_commons/config/NameResolver.py
NameResolver.resolve
def resolve(config, default_name = None): """ Resolves a component name from configuration parameters. The name can be stored in "id", "name" fields or inside a component descriptor. If name cannot be determined it returns a defaultName. :param config: configuration parameters that may contain a component name. :param default_name: (optional) a default component name. :return: resolved name or default name if the name cannot be determined. """ name = config.get_as_nullable_string("name") name = name if name != None else config.get_as_nullable_string("id") if name == None: descriptor_str = config.get_as_nullable_string("descriptor") descriptor = Descriptor.from_string(descriptor_str) if descriptor != None: name = descriptor.get_name() return name if name != None else default_name
python
def resolve(config, default_name = None): """ Resolves a component name from configuration parameters. The name can be stored in "id", "name" fields or inside a component descriptor. If name cannot be determined it returns a defaultName. :param config: configuration parameters that may contain a component name. :param default_name: (optional) a default component name. :return: resolved name or default name if the name cannot be determined. """ name = config.get_as_nullable_string("name") name = name if name != None else config.get_as_nullable_string("id") if name == None: descriptor_str = config.get_as_nullable_string("descriptor") descriptor = Descriptor.from_string(descriptor_str) if descriptor != None: name = descriptor.get_name() return name if name != None else default_name
[ "def", "resolve", "(", "config", ",", "default_name", "=", "None", ")", ":", "name", "=", "config", ".", "get_as_nullable_string", "(", "\"name\"", ")", "name", "=", "name", "if", "name", "!=", "None", "else", "config", ".", "get_as_nullable_string", "(", "\"id\"", ")", "if", "name", "==", "None", ":", "descriptor_str", "=", "config", ".", "get_as_nullable_string", "(", "\"descriptor\"", ")", "descriptor", "=", "Descriptor", ".", "from_string", "(", "descriptor_str", ")", "if", "descriptor", "!=", "None", ":", "name", "=", "descriptor", ".", "get_name", "(", ")", "return", "name", "if", "name", "!=", "None", "else", "default_name" ]
Resolves a component name from configuration parameters. The name can be stored in "id", "name" fields or inside a component descriptor. If name cannot be determined it returns a defaultName. :param config: configuration parameters that may contain a component name. :param default_name: (optional) a default component name. :return: resolved name or default name if the name cannot be determined.
[ "Resolves", "a", "component", "name", "from", "configuration", "parameters", ".", "The", "name", "can", "be", "stored", "in", "id", "name", "fields", "or", "inside", "a", "component", "descriptor", ".", "If", "name", "cannot", "be", "determined", "it", "returns", "a", "defaultName", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/config/NameResolver.py#L30-L51
238,179
mikicz/arca
arca/backend/current_environment.py
CurrentEnvironmentBackend.get_or_create_environment
def get_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str: """ Returns the path to the current Python executable. """ return sys.executable
python
def get_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str: """ Returns the path to the current Python executable. """ return sys.executable
[ "def", "get_or_create_environment", "(", "self", ",", "repo", ":", "str", ",", "branch", ":", "str", ",", "git_repo", ":", "Repo", ",", "repo_path", ":", "Path", ")", "->", "str", ":", "return", "sys", ".", "executable" ]
Returns the path to the current Python executable.
[ "Returns", "the", "path", "to", "the", "current", "Python", "executable", "." ]
e67fdc00be473ecf8ec16d024e1a3f2c47ca882c
https://github.com/mikicz/arca/blob/e67fdc00be473ecf8ec16d024e1a3f2c47ca882c/arca/backend/current_environment.py#L15-L18
238,180
roboogle/gtkmvc3
gtkmvco/gtkmvc3/model.py
count_leaves
def count_leaves(x): """ Return the number of non-sequence items in a given recursive sequence. """ if hasattr(x, 'keys'): x = list(x.values()) if hasattr(x, '__getitem__'): return sum(map(count_leaves, x)) return 1
python
def count_leaves(x): """ Return the number of non-sequence items in a given recursive sequence. """ if hasattr(x, 'keys'): x = list(x.values()) if hasattr(x, '__getitem__'): return sum(map(count_leaves, x)) return 1
[ "def", "count_leaves", "(", "x", ")", ":", "if", "hasattr", "(", "x", ",", "'keys'", ")", ":", "x", "=", "list", "(", "x", ".", "values", "(", ")", ")", "if", "hasattr", "(", "x", ",", "'__getitem__'", ")", ":", "return", "sum", "(", "map", "(", "count_leaves", ",", "x", ")", ")", "return", "1" ]
Return the number of non-sequence items in a given recursive sequence.
[ "Return", "the", "number", "of", "non", "-", "sequence", "items", "in", "a", "given", "recursive", "sequence", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/model.py#L46-L55
238,181
ask/literal.py
literal/__init__.py
reprkwargs
def reprkwargs(kwargs, sep=', ', fmt="{0!s}={1!r}"): """Display kwargs.""" return sep.join(fmt.format(k, v) for k, v in kwargs.iteritems())
python
def reprkwargs(kwargs, sep=', ', fmt="{0!s}={1!r}"): """Display kwargs.""" return sep.join(fmt.format(k, v) for k, v in kwargs.iteritems())
[ "def", "reprkwargs", "(", "kwargs", ",", "sep", "=", "', '", ",", "fmt", "=", "\"{0!s}={1!r}\"", ")", ":", "return", "sep", ".", "join", "(", "fmt", ".", "format", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "kwargs", ".", "iteritems", "(", ")", ")" ]
Display kwargs.
[ "Display", "kwargs", "." ]
b3c48b4b82edf408ce3bdf2639dae6daec483b24
https://github.com/ask/literal.py/blob/b3c48b4b82edf408ce3bdf2639dae6daec483b24/literal/__init__.py#L62-L64
238,182
ask/literal.py
literal/__init__.py
reprcall
def reprcall(name, args=(), kwargs=(), keywords='', sep=', ', argfilter=repr): """Format a function call for display.""" if keywords: keywords = ((', ' if (args or kwargs) else '') + '**' + keywords) argfilter = argfilter or repr return "{name}({args}{sep}{kwargs}{keywords})".format( name=name, args=reprargs(args, filter=argfilter), sep=(args and kwargs) and sep or "", kwargs=reprkwargs(kwargs, sep), keywords=keywords or '')
python
def reprcall(name, args=(), kwargs=(), keywords='', sep=', ', argfilter=repr): """Format a function call for display.""" if keywords: keywords = ((', ' if (args or kwargs) else '') + '**' + keywords) argfilter = argfilter or repr return "{name}({args}{sep}{kwargs}{keywords})".format( name=name, args=reprargs(args, filter=argfilter), sep=(args and kwargs) and sep or "", kwargs=reprkwargs(kwargs, sep), keywords=keywords or '')
[ "def", "reprcall", "(", "name", ",", "args", "=", "(", ")", ",", "kwargs", "=", "(", ")", ",", "keywords", "=", "''", ",", "sep", "=", "', '", ",", "argfilter", "=", "repr", ")", ":", "if", "keywords", ":", "keywords", "=", "(", "(", "', '", "if", "(", "args", "or", "kwargs", ")", "else", "''", ")", "+", "'**'", "+", "keywords", ")", "argfilter", "=", "argfilter", "or", "repr", "return", "\"{name}({args}{sep}{kwargs}{keywords})\"", ".", "format", "(", "name", "=", "name", ",", "args", "=", "reprargs", "(", "args", ",", "filter", "=", "argfilter", ")", ",", "sep", "=", "(", "args", "and", "kwargs", ")", "and", "sep", "or", "\"\"", ",", "kwargs", "=", "reprkwargs", "(", "kwargs", ",", "sep", ")", ",", "keywords", "=", "keywords", "or", "''", ")" ]
Format a function call for display.
[ "Format", "a", "function", "call", "for", "display", "." ]
b3c48b4b82edf408ce3bdf2639dae6daec483b24
https://github.com/ask/literal.py/blob/b3c48b4b82edf408ce3bdf2639dae6daec483b24/literal/__init__.py#L71-L81
238,183
ask/literal.py
literal/__init__.py
reprsig
def reprsig(fun, name=None, method=False): """Format a methods signature for display.""" args, varargs, keywords, defs, kwargs = [], [], None, [], {} argspec = fun if callable(fun): name = fun.__name__ if name is None else name argspec = getargspec(fun) try: args = argspec[0] varargs = argspec[1] keywords = argspec[2] defs = argspec[3] except IndexError: pass if defs: args, kwkeys = args[:-len(defs)], args[-len(defs):] kwargs = dict(zip(kwkeys, defs)) if varargs: args.append('*' + varargs) if method: args.insert(0, 'self') return reprcall(name, map(str, args), kwargs, keywords, argfilter=str)
python
def reprsig(fun, name=None, method=False): """Format a methods signature for display.""" args, varargs, keywords, defs, kwargs = [], [], None, [], {} argspec = fun if callable(fun): name = fun.__name__ if name is None else name argspec = getargspec(fun) try: args = argspec[0] varargs = argspec[1] keywords = argspec[2] defs = argspec[3] except IndexError: pass if defs: args, kwkeys = args[:-len(defs)], args[-len(defs):] kwargs = dict(zip(kwkeys, defs)) if varargs: args.append('*' + varargs) if method: args.insert(0, 'self') return reprcall(name, map(str, args), kwargs, keywords, argfilter=str)
[ "def", "reprsig", "(", "fun", ",", "name", "=", "None", ",", "method", "=", "False", ")", ":", "args", ",", "varargs", ",", "keywords", ",", "defs", ",", "kwargs", "=", "[", "]", ",", "[", "]", ",", "None", ",", "[", "]", ",", "{", "}", "argspec", "=", "fun", "if", "callable", "(", "fun", ")", ":", "name", "=", "fun", ".", "__name__", "if", "name", "is", "None", "else", "name", "argspec", "=", "getargspec", "(", "fun", ")", "try", ":", "args", "=", "argspec", "[", "0", "]", "varargs", "=", "argspec", "[", "1", "]", "keywords", "=", "argspec", "[", "2", "]", "defs", "=", "argspec", "[", "3", "]", "except", "IndexError", ":", "pass", "if", "defs", ":", "args", ",", "kwkeys", "=", "args", "[", ":", "-", "len", "(", "defs", ")", "]", ",", "args", "[", "-", "len", "(", "defs", ")", ":", "]", "kwargs", "=", "dict", "(", "zip", "(", "kwkeys", ",", "defs", ")", ")", "if", "varargs", ":", "args", ".", "append", "(", "'*'", "+", "varargs", ")", "if", "method", ":", "args", ".", "insert", "(", "0", ",", "'self'", ")", "return", "reprcall", "(", "name", ",", "map", "(", "str", ",", "args", ")", ",", "kwargs", ",", "keywords", ",", "argfilter", "=", "str", ")" ]
Format a methods signature for display.
[ "Format", "a", "methods", "signature", "for", "display", "." ]
b3c48b4b82edf408ce3bdf2639dae6daec483b24
https://github.com/ask/literal.py/blob/b3c48b4b82edf408ce3bdf2639dae6daec483b24/literal/__init__.py#L84-L106
238,184
mapmyfitness/jtime
jtime/utils.py
get_input
def get_input(input_func, input_str): """ Get input from the user given an input function and an input string """ val = input_func("Please enter your {0}: ".format(input_str)) while not val or not len(val.strip()): val = input_func("You didn't enter a valid {0}, please try again: ".format(input_str)) return val
python
def get_input(input_func, input_str): """ Get input from the user given an input function and an input string """ val = input_func("Please enter your {0}: ".format(input_str)) while not val or not len(val.strip()): val = input_func("You didn't enter a valid {0}, please try again: ".format(input_str)) return val
[ "def", "get_input", "(", "input_func", ",", "input_str", ")", ":", "val", "=", "input_func", "(", "\"Please enter your {0}: \"", ".", "format", "(", "input_str", ")", ")", "while", "not", "val", "or", "not", "len", "(", "val", ".", "strip", "(", ")", ")", ":", "val", "=", "input_func", "(", "\"You didn't enter a valid {0}, please try again: \"", ".", "format", "(", "input_str", ")", ")", "return", "val" ]
Get input from the user given an input function and an input string
[ "Get", "input", "from", "the", "user", "given", "an", "input", "function", "and", "an", "input", "string" ]
402fb6b40ac7a78c23fd02fac50c6dbe49e5ebfd
https://github.com/mapmyfitness/jtime/blob/402fb6b40ac7a78c23fd02fac50c6dbe49e5ebfd/jtime/utils.py#L6-L13
238,185
mapmyfitness/jtime
jtime/utils.py
working_cycletime
def working_cycletime(start, end, workday_start=datetime.timedelta(hours=0), workday_end=datetime.timedelta(hours=24)): """ Get the working time between a beginning and an end point subtracting out non-office time """ def clamp(t, start, end): "Return 't' clamped to the range ['start', 'end']" return max(start, min(end, t)) def day_part(t): "Return timedelta between midnight and 't'." return t - t.replace(hour=0, minute=0, second=0) if not start: return None if not end: end = datetime.datetime.now() zero = datetime.timedelta(0) # Make sure that the work day is valid assert(zero <= workday_start <= workday_end <= datetime.timedelta(1)) # Get the workday delta workday = workday_end - workday_start # Get the number of days it took days = (end - start).days + 1 # Number of weeks weeks = days // 7 # Get the number of days in addition to weeks extra = (max(0, 5 - start.weekday()) + min(5, 1 + end.weekday())) % 5 # Get the number of working days weekdays = weeks * 5 + extra # Get the total time spent accounting for the workday total = workday * weekdays if start.weekday() < 5: # Figuring out how much time it wasn't being worked on and subtracting total -= clamp(day_part(start) - workday_start, zero, workday) if end.weekday() < 5: # Figuring out how much time it wasn't being worked on and subtracting total -= clamp(workday_end - day_part(end), zero, workday) cycle_time = timedelta_total_seconds(total) / timedelta_total_seconds(workday) return cycle_time
python
def working_cycletime(start, end, workday_start=datetime.timedelta(hours=0), workday_end=datetime.timedelta(hours=24)): """ Get the working time between a beginning and an end point subtracting out non-office time """ def clamp(t, start, end): "Return 't' clamped to the range ['start', 'end']" return max(start, min(end, t)) def day_part(t): "Return timedelta between midnight and 't'." return t - t.replace(hour=0, minute=0, second=0) if not start: return None if not end: end = datetime.datetime.now() zero = datetime.timedelta(0) # Make sure that the work day is valid assert(zero <= workday_start <= workday_end <= datetime.timedelta(1)) # Get the workday delta workday = workday_end - workday_start # Get the number of days it took days = (end - start).days + 1 # Number of weeks weeks = days // 7 # Get the number of days in addition to weeks extra = (max(0, 5 - start.weekday()) + min(5, 1 + end.weekday())) % 5 # Get the number of working days weekdays = weeks * 5 + extra # Get the total time spent accounting for the workday total = workday * weekdays if start.weekday() < 5: # Figuring out how much time it wasn't being worked on and subtracting total -= clamp(day_part(start) - workday_start, zero, workday) if end.weekday() < 5: # Figuring out how much time it wasn't being worked on and subtracting total -= clamp(workday_end - day_part(end), zero, workday) cycle_time = timedelta_total_seconds(total) / timedelta_total_seconds(workday) return cycle_time
[ "def", "working_cycletime", "(", "start", ",", "end", ",", "workday_start", "=", "datetime", ".", "timedelta", "(", "hours", "=", "0", ")", ",", "workday_end", "=", "datetime", ".", "timedelta", "(", "hours", "=", "24", ")", ")", ":", "def", "clamp", "(", "t", ",", "start", ",", "end", ")", ":", "\"Return 't' clamped to the range ['start', 'end']\"", "return", "max", "(", "start", ",", "min", "(", "end", ",", "t", ")", ")", "def", "day_part", "(", "t", ")", ":", "\"Return timedelta between midnight and 't'.\"", "return", "t", "-", "t", ".", "replace", "(", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ")", "if", "not", "start", ":", "return", "None", "if", "not", "end", ":", "end", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "zero", "=", "datetime", ".", "timedelta", "(", "0", ")", "# Make sure that the work day is valid", "assert", "(", "zero", "<=", "workday_start", "<=", "workday_end", "<=", "datetime", ".", "timedelta", "(", "1", ")", ")", "# Get the workday delta", "workday", "=", "workday_end", "-", "workday_start", "# Get the number of days it took", "days", "=", "(", "end", "-", "start", ")", ".", "days", "+", "1", "# Number of weeks", "weeks", "=", "days", "//", "7", "# Get the number of days in addition to weeks", "extra", "=", "(", "max", "(", "0", ",", "5", "-", "start", ".", "weekday", "(", ")", ")", "+", "min", "(", "5", ",", "1", "+", "end", ".", "weekday", "(", ")", ")", ")", "%", "5", "# Get the number of working days", "weekdays", "=", "weeks", "*", "5", "+", "extra", "# Get the total time spent accounting for the workday", "total", "=", "workday", "*", "weekdays", "if", "start", ".", "weekday", "(", ")", "<", "5", ":", "# Figuring out how much time it wasn't being worked on and subtracting", "total", "-=", "clamp", "(", "day_part", "(", "start", ")", "-", "workday_start", ",", "zero", ",", "workday", ")", "if", "end", ".", "weekday", "(", ")", "<", "5", ":", "# Figuring out how much time it wasn't being worked on and subtracting", "total", "-=", "clamp", "(", "workday_end", "-", "day_part", "(", "end", ")", ",", "zero", ",", "workday", ")", "cycle_time", "=", "timedelta_total_seconds", "(", "total", ")", "/", "timedelta_total_seconds", "(", "workday", ")", "return", "cycle_time" ]
Get the working time between a beginning and an end point subtracting out non-office time
[ "Get", "the", "working", "time", "between", "a", "beginning", "and", "an", "end", "point", "subtracting", "out", "non", "-", "office", "time" ]
402fb6b40ac7a78c23fd02fac50c6dbe49e5ebfd
https://github.com/mapmyfitness/jtime/blob/402fb6b40ac7a78c23fd02fac50c6dbe49e5ebfd/jtime/utils.py#L16-L56
238,186
gorakhargosh/pepe
pepe/__init__.py
parse_definition_expr
def parse_definition_expr(expr, default_value=None): """ Parses a definition expression and returns a key-value pair as a tuple. Each definition expression should be in one of these two formats: * <variable>=<value> * <variable> :param expr: String expression to be parsed. :param default_value: (Default None) When a definition is encountered that has no value, this will be used as its value. :return: A (define, value) tuple or raises a ``ValueError`` if an invalid definition expression is provided. or raises ``AttributeError`` if None is provided for ``expr``. Usage: >>> parse_definition_expr('DEBUG=1') ('DEBUG', 1) >>> parse_definition_expr('FOOBAR=0x40') ('FOOBAR', 64) >>> parse_definition_expr('FOOBAR=whatever') ('FOOBAR', 'whatever') >>> parse_definition_expr('FOOBAR=false') ('FOOBAR', False) >>> parse_definition_expr('FOOBAR=TRUE') ('FOOBAR', True) >>> parse_definition_expr('FOOBAR', default_value=None) ('FOOBAR', None) >>> parse_definition_expr('FOOBAR', default_value=1) ('FOOBAR', 1) >>> parse_definition_expr('FOOBAR=ah=3') ('FOOBAR', 'ah=3') >>> parse_definition_expr(' FOOBAR=ah=3 ') ('FOOBAR', 'ah=3 ') >>> parse_definition_expr(' FOOBAR =ah=3 ') ('FOOBAR', 'ah=3 ') >>> parse_definition_expr(' FOOBAR = ah=3 ') ('FOOBAR', ' ah=3 ') >>> parse_definition_expr(" ") Traceback (most recent call last): ... ValueError: Invalid definition symbol ` ` >>> parse_definition_expr(None) Traceback (most recent call last): ... AttributeError: 'NoneType' object has no attribute 'split' """ try: define, value = expr.split('=', 1) try: value = parse_number_token(value) except ValueError: value = parse_bool_token(value) except ValueError: if expr: define, value = expr, default_value else: raise ValueError("Invalid definition expression `%s`" % str(expr)) d = define.strip() if d: return d, value else: raise ValueError("Invalid definition symbol `%s`" % str(define))
python
def parse_definition_expr(expr, default_value=None): """ Parses a definition expression and returns a key-value pair as a tuple. Each definition expression should be in one of these two formats: * <variable>=<value> * <variable> :param expr: String expression to be parsed. :param default_value: (Default None) When a definition is encountered that has no value, this will be used as its value. :return: A (define, value) tuple or raises a ``ValueError`` if an invalid definition expression is provided. or raises ``AttributeError`` if None is provided for ``expr``. Usage: >>> parse_definition_expr('DEBUG=1') ('DEBUG', 1) >>> parse_definition_expr('FOOBAR=0x40') ('FOOBAR', 64) >>> parse_definition_expr('FOOBAR=whatever') ('FOOBAR', 'whatever') >>> parse_definition_expr('FOOBAR=false') ('FOOBAR', False) >>> parse_definition_expr('FOOBAR=TRUE') ('FOOBAR', True) >>> parse_definition_expr('FOOBAR', default_value=None) ('FOOBAR', None) >>> parse_definition_expr('FOOBAR', default_value=1) ('FOOBAR', 1) >>> parse_definition_expr('FOOBAR=ah=3') ('FOOBAR', 'ah=3') >>> parse_definition_expr(' FOOBAR=ah=3 ') ('FOOBAR', 'ah=3 ') >>> parse_definition_expr(' FOOBAR =ah=3 ') ('FOOBAR', 'ah=3 ') >>> parse_definition_expr(' FOOBAR = ah=3 ') ('FOOBAR', ' ah=3 ') >>> parse_definition_expr(" ") Traceback (most recent call last): ... ValueError: Invalid definition symbol ` ` >>> parse_definition_expr(None) Traceback (most recent call last): ... AttributeError: 'NoneType' object has no attribute 'split' """ try: define, value = expr.split('=', 1) try: value = parse_number_token(value) except ValueError: value = parse_bool_token(value) except ValueError: if expr: define, value = expr, default_value else: raise ValueError("Invalid definition expression `%s`" % str(expr)) d = define.strip() if d: return d, value else: raise ValueError("Invalid definition symbol `%s`" % str(define))
[ "def", "parse_definition_expr", "(", "expr", ",", "default_value", "=", "None", ")", ":", "try", ":", "define", ",", "value", "=", "expr", ".", "split", "(", "'='", ",", "1", ")", "try", ":", "value", "=", "parse_number_token", "(", "value", ")", "except", "ValueError", ":", "value", "=", "parse_bool_token", "(", "value", ")", "except", "ValueError", ":", "if", "expr", ":", "define", ",", "value", "=", "expr", ",", "default_value", "else", ":", "raise", "ValueError", "(", "\"Invalid definition expression `%s`\"", "%", "str", "(", "expr", ")", ")", "d", "=", "define", ".", "strip", "(", ")", "if", "d", ":", "return", "d", ",", "value", "else", ":", "raise", "ValueError", "(", "\"Invalid definition symbol `%s`\"", "%", "str", "(", "define", ")", ")" ]
Parses a definition expression and returns a key-value pair as a tuple. Each definition expression should be in one of these two formats: * <variable>=<value> * <variable> :param expr: String expression to be parsed. :param default_value: (Default None) When a definition is encountered that has no value, this will be used as its value. :return: A (define, value) tuple or raises a ``ValueError`` if an invalid definition expression is provided. or raises ``AttributeError`` if None is provided for ``expr``. Usage: >>> parse_definition_expr('DEBUG=1') ('DEBUG', 1) >>> parse_definition_expr('FOOBAR=0x40') ('FOOBAR', 64) >>> parse_definition_expr('FOOBAR=whatever') ('FOOBAR', 'whatever') >>> parse_definition_expr('FOOBAR=false') ('FOOBAR', False) >>> parse_definition_expr('FOOBAR=TRUE') ('FOOBAR', True) >>> parse_definition_expr('FOOBAR', default_value=None) ('FOOBAR', None) >>> parse_definition_expr('FOOBAR', default_value=1) ('FOOBAR', 1) >>> parse_definition_expr('FOOBAR=ah=3') ('FOOBAR', 'ah=3') >>> parse_definition_expr(' FOOBAR=ah=3 ') ('FOOBAR', 'ah=3 ') >>> parse_definition_expr(' FOOBAR =ah=3 ') ('FOOBAR', 'ah=3 ') >>> parse_definition_expr(' FOOBAR = ah=3 ') ('FOOBAR', ' ah=3 ') >>> parse_definition_expr(" ") Traceback (most recent call last): ... ValueError: Invalid definition symbol ` ` >>> parse_definition_expr(None) Traceback (most recent call last): ... AttributeError: 'NoneType' object has no attribute 'split'
[ "Parses", "a", "definition", "expression", "and", "returns", "a", "key", "-", "value", "pair", "as", "a", "tuple", "." ]
1e40853378d515c99f03b3f59efa9b943d26eb62
https://github.com/gorakhargosh/pepe/blob/1e40853378d515c99f03b3f59efa9b943d26eb62/pepe/__init__.py#L550-L621
238,187
gorakhargosh/pepe
pepe/__init__.py
parse_definitions
def parse_definitions(definitions): """ Parses a list of macro definitions and returns a "symbol table" as a dictionary. :params definitions: A list of command line macro definitions. Each item in the list should be in one of these two formats: * <variable>=<value> * <variable> :return: ``dict`` as symbol table or raises an exception thrown by :func:``parse_definition_expr``. Usage:: >>> parse_definitions(['DEBUG=1']) {'DEBUG': 1} >>> parse_definitions(['FOOBAR=0x40', 'DEBUG=false']) {'DEBUG': False, 'FOOBAR': 64} >>> parse_definitions(['FOOBAR=whatever']) {'FOOBAR': 'whatever'} >>> parse_definitions(['FOOBAR']) {'FOOBAR': None} >>> parse_definitions(['FOOBAR=ah=3']) {'FOOBAR': 'ah=3'} >>> parse_definitions(None) {} >>> parse_definitions([]) {} """ defines = {} if definitions: for definition in definitions: define, value = parse_definition_expr(definition, default_value=None) defines[define] = value return defines
python
def parse_definitions(definitions): """ Parses a list of macro definitions and returns a "symbol table" as a dictionary. :params definitions: A list of command line macro definitions. Each item in the list should be in one of these two formats: * <variable>=<value> * <variable> :return: ``dict`` as symbol table or raises an exception thrown by :func:``parse_definition_expr``. Usage:: >>> parse_definitions(['DEBUG=1']) {'DEBUG': 1} >>> parse_definitions(['FOOBAR=0x40', 'DEBUG=false']) {'DEBUG': False, 'FOOBAR': 64} >>> parse_definitions(['FOOBAR=whatever']) {'FOOBAR': 'whatever'} >>> parse_definitions(['FOOBAR']) {'FOOBAR': None} >>> parse_definitions(['FOOBAR=ah=3']) {'FOOBAR': 'ah=3'} >>> parse_definitions(None) {} >>> parse_definitions([]) {} """ defines = {} if definitions: for definition in definitions: define, value = parse_definition_expr(definition, default_value=None) defines[define] = value return defines
[ "def", "parse_definitions", "(", "definitions", ")", ":", "defines", "=", "{", "}", "if", "definitions", ":", "for", "definition", "in", "definitions", ":", "define", ",", "value", "=", "parse_definition_expr", "(", "definition", ",", "default_value", "=", "None", ")", "defines", "[", "define", "]", "=", "value", "return", "defines" ]
Parses a list of macro definitions and returns a "symbol table" as a dictionary. :params definitions: A list of command line macro definitions. Each item in the list should be in one of these two formats: * <variable>=<value> * <variable> :return: ``dict`` as symbol table or raises an exception thrown by :func:``parse_definition_expr``. Usage:: >>> parse_definitions(['DEBUG=1']) {'DEBUG': 1} >>> parse_definitions(['FOOBAR=0x40', 'DEBUG=false']) {'DEBUG': False, 'FOOBAR': 64} >>> parse_definitions(['FOOBAR=whatever']) {'FOOBAR': 'whatever'} >>> parse_definitions(['FOOBAR']) {'FOOBAR': None} >>> parse_definitions(['FOOBAR=ah=3']) {'FOOBAR': 'ah=3'} >>> parse_definitions(None) {} >>> parse_definitions([]) {}
[ "Parses", "a", "list", "of", "macro", "definitions", "and", "returns", "a", "symbol", "table", "as", "a", "dictionary", "." ]
1e40853378d515c99f03b3f59efa9b943d26eb62
https://github.com/gorakhargosh/pepe/blob/1e40853378d515c99f03b3f59efa9b943d26eb62/pepe/__init__.py#L624-L662
238,188
gorakhargosh/pepe
pepe/__init__.py
set_up_logging
def set_up_logging(logger, level, should_be_quiet): """ Sets up logging for pepe. :param logger: The logger object to update. :param level: Logging level specified at command line. :param should_be_quiet: Boolean value for the -q option. :return: logging level ``int`` or None """ LOGGING_LEVELS = { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL, 'NONE': None, } logging_level = LOGGING_LEVELS.get(level) if should_be_quiet or logging_level is None: logging_handler = NullLoggingHandler() else: logger.setLevel(logging_level) logging_handler = logging.StreamHandler() logging_handler.setLevel(logging_level) logging_handler.setFormatter( logging.Formatter( "%(asctime)s:%(name)s:%(levelname)s: %(message)s" ) ) logger.addHandler(logging_handler) return logging_level
python
def set_up_logging(logger, level, should_be_quiet): """ Sets up logging for pepe. :param logger: The logger object to update. :param level: Logging level specified at command line. :param should_be_quiet: Boolean value for the -q option. :return: logging level ``int`` or None """ LOGGING_LEVELS = { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL, 'NONE': None, } logging_level = LOGGING_LEVELS.get(level) if should_be_quiet or logging_level is None: logging_handler = NullLoggingHandler() else: logger.setLevel(logging_level) logging_handler = logging.StreamHandler() logging_handler.setLevel(logging_level) logging_handler.setFormatter( logging.Formatter( "%(asctime)s:%(name)s:%(levelname)s: %(message)s" ) ) logger.addHandler(logging_handler) return logging_level
[ "def", "set_up_logging", "(", "logger", ",", "level", ",", "should_be_quiet", ")", ":", "LOGGING_LEVELS", "=", "{", "'DEBUG'", ":", "logging", ".", "DEBUG", ",", "'INFO'", ":", "logging", ".", "INFO", ",", "'WARNING'", ":", "logging", ".", "WARNING", ",", "'ERROR'", ":", "logging", ".", "ERROR", ",", "'CRITICAL'", ":", "logging", ".", "CRITICAL", ",", "'NONE'", ":", "None", ",", "}", "logging_level", "=", "LOGGING_LEVELS", ".", "get", "(", "level", ")", "if", "should_be_quiet", "or", "logging_level", "is", "None", ":", "logging_handler", "=", "NullLoggingHandler", "(", ")", "else", ":", "logger", ".", "setLevel", "(", "logging_level", ")", "logging_handler", "=", "logging", ".", "StreamHandler", "(", ")", "logging_handler", ".", "setLevel", "(", "logging_level", ")", "logging_handler", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "\"%(asctime)s:%(name)s:%(levelname)s: %(message)s\"", ")", ")", "logger", ".", "addHandler", "(", "logging_handler", ")", "return", "logging_level" ]
Sets up logging for pepe. :param logger: The logger object to update. :param level: Logging level specified at command line. :param should_be_quiet: Boolean value for the -q option. :return: logging level ``int`` or None
[ "Sets", "up", "logging", "for", "pepe", "." ]
1e40853378d515c99f03b3f59efa9b943d26eb62
https://github.com/gorakhargosh/pepe/blob/1e40853378d515c99f03b3f59efa9b943d26eb62/pepe/__init__.py#L793-L829
238,189
gorakhargosh/pepe
pepe/__init__.py
main
def main(): """ Entry-point function. """ args = parse_command_line() logging_level = set_up_logging(logger, args.logging_level, args.should_be_quiet) defines = parse_definitions(args.definitions) try: content_types_db = ContentTypesDatabase(DEFAULT_CONTENT_TYPES_FILE) for config_file in args.content_types_config_files: content_types_db.add_config_file(config_file) output_filename = args.output_filename with open(args.input_filename, 'rb') as input_file: if output_filename is None: # No output file specified. Will output to stdout. preprocess(input_file=input_file, output_file=sys.stdout, defines=defines, options=args, content_types_db=content_types_db) else: if os.path.exists(output_filename): if args.should_force_overwrite: # Overwrite existing file. with open(output_filename, 'wb') as output_file: preprocess(input_file=input_file, output_file=output_file, defines=defines, options=args, content_types_db=content_types_db) else: raise IOError("File `%s` exists - cannot overwrite. (Use -f to force overwrite.)" % args.output_filename) else: # File doesn't exist and output file is provided, so write. with open(output_filename, 'wb') as output_file: preprocess(input_file=input_file, output_file=output_file, defines=defines, options=args, content_types_db=content_types_db) except PreprocessorError, ex: if logging_level == logging.DEBUG: import traceback traceback.print_exc(file=sys.stderr) else: sys.stderr.write("pepe: error: %s\n" % str(ex)) return 1 return 0
python
def main(): """ Entry-point function. """ args = parse_command_line() logging_level = set_up_logging(logger, args.logging_level, args.should_be_quiet) defines = parse_definitions(args.definitions) try: content_types_db = ContentTypesDatabase(DEFAULT_CONTENT_TYPES_FILE) for config_file in args.content_types_config_files: content_types_db.add_config_file(config_file) output_filename = args.output_filename with open(args.input_filename, 'rb') as input_file: if output_filename is None: # No output file specified. Will output to stdout. preprocess(input_file=input_file, output_file=sys.stdout, defines=defines, options=args, content_types_db=content_types_db) else: if os.path.exists(output_filename): if args.should_force_overwrite: # Overwrite existing file. with open(output_filename, 'wb') as output_file: preprocess(input_file=input_file, output_file=output_file, defines=defines, options=args, content_types_db=content_types_db) else: raise IOError("File `%s` exists - cannot overwrite. (Use -f to force overwrite.)" % args.output_filename) else: # File doesn't exist and output file is provided, so write. with open(output_filename, 'wb') as output_file: preprocess(input_file=input_file, output_file=output_file, defines=defines, options=args, content_types_db=content_types_db) except PreprocessorError, ex: if logging_level == logging.DEBUG: import traceback traceback.print_exc(file=sys.stderr) else: sys.stderr.write("pepe: error: %s\n" % str(ex)) return 1 return 0
[ "def", "main", "(", ")", ":", "args", "=", "parse_command_line", "(", ")", "logging_level", "=", "set_up_logging", "(", "logger", ",", "args", ".", "logging_level", ",", "args", ".", "should_be_quiet", ")", "defines", "=", "parse_definitions", "(", "args", ".", "definitions", ")", "try", ":", "content_types_db", "=", "ContentTypesDatabase", "(", "DEFAULT_CONTENT_TYPES_FILE", ")", "for", "config_file", "in", "args", ".", "content_types_config_files", ":", "content_types_db", ".", "add_config_file", "(", "config_file", ")", "output_filename", "=", "args", ".", "output_filename", "with", "open", "(", "args", ".", "input_filename", ",", "'rb'", ")", "as", "input_file", ":", "if", "output_filename", "is", "None", ":", "# No output file specified. Will output to stdout.", "preprocess", "(", "input_file", "=", "input_file", ",", "output_file", "=", "sys", ".", "stdout", ",", "defines", "=", "defines", ",", "options", "=", "args", ",", "content_types_db", "=", "content_types_db", ")", "else", ":", "if", "os", ".", "path", ".", "exists", "(", "output_filename", ")", ":", "if", "args", ".", "should_force_overwrite", ":", "# Overwrite existing file.", "with", "open", "(", "output_filename", ",", "'wb'", ")", "as", "output_file", ":", "preprocess", "(", "input_file", "=", "input_file", ",", "output_file", "=", "output_file", ",", "defines", "=", "defines", ",", "options", "=", "args", ",", "content_types_db", "=", "content_types_db", ")", "else", ":", "raise", "IOError", "(", "\"File `%s` exists - cannot overwrite. (Use -f to force overwrite.)\"", "%", "args", ".", "output_filename", ")", "else", ":", "# File doesn't exist and output file is provided, so write.", "with", "open", "(", "output_filename", ",", "'wb'", ")", "as", "output_file", ":", "preprocess", "(", "input_file", "=", "input_file", ",", "output_file", "=", "output_file", ",", "defines", "=", "defines", ",", "options", "=", "args", ",", "content_types_db", "=", "content_types_db", ")", "except", "PreprocessorError", ",", "ex", ":", "if", "logging_level", "==", "logging", ".", "DEBUG", ":", "import", "traceback", "traceback", ".", "print_exc", "(", "file", "=", "sys", ".", "stderr", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "\"pepe: error: %s\\n\"", "%", "str", "(", "ex", ")", ")", "return", "1", "return", "0" ]
Entry-point function.
[ "Entry", "-", "point", "function", "." ]
1e40853378d515c99f03b3f59efa9b943d26eb62
https://github.com/gorakhargosh/pepe/blob/1e40853378d515c99f03b3f59efa9b943d26eb62/pepe/__init__.py#L832-L884
238,190
jammycakes/pyfactoryfactory
factoryfactory/__init__.py
ServiceLocator.register
def register(self, service, provider, singleton=False): """ Registers a service provider for a given service. @param service A key that identifies the service being registered. @param provider This is either the service being registered, or a callable that will either instantiate it or return it. @param singleton Indicates that the service is to be registered as a singleton. This is only relevant if the provider is a callable. Services that are not callable will always be registered as singletons. """ def get_singleton(*args, **kwargs): result = self._get_singleton(service) if not result: instantiator = self._get_instantiator(provider) result = instantiator(*args, **kwargs) self._set_singleton(service, result) return result # Providers are always registered in self.providers as callable methods if not callable(provider): self._set_provider(service, lambda *args, **kwargs: provider) elif singleton: self._set_provider(service, get_singleton) else: self._set_provider(service, self._get_instantiator(provider))
python
def register(self, service, provider, singleton=False): """ Registers a service provider for a given service. @param service A key that identifies the service being registered. @param provider This is either the service being registered, or a callable that will either instantiate it or return it. @param singleton Indicates that the service is to be registered as a singleton. This is only relevant if the provider is a callable. Services that are not callable will always be registered as singletons. """ def get_singleton(*args, **kwargs): result = self._get_singleton(service) if not result: instantiator = self._get_instantiator(provider) result = instantiator(*args, **kwargs) self._set_singleton(service, result) return result # Providers are always registered in self.providers as callable methods if not callable(provider): self._set_provider(service, lambda *args, **kwargs: provider) elif singleton: self._set_provider(service, get_singleton) else: self._set_provider(service, self._get_instantiator(provider))
[ "def", "register", "(", "self", ",", "service", ",", "provider", ",", "singleton", "=", "False", ")", ":", "def", "get_singleton", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "self", ".", "_get_singleton", "(", "service", ")", "if", "not", "result", ":", "instantiator", "=", "self", ".", "_get_instantiator", "(", "provider", ")", "result", "=", "instantiator", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_set_singleton", "(", "service", ",", "result", ")", "return", "result", "# Providers are always registered in self.providers as callable methods", "if", "not", "callable", "(", "provider", ")", ":", "self", ".", "_set_provider", "(", "service", ",", "lambda", "*", "args", ",", "*", "*", "kwargs", ":", "provider", ")", "elif", "singleton", ":", "self", ".", "_set_provider", "(", "service", ",", "get_singleton", ")", "else", ":", "self", ".", "_set_provider", "(", "service", ",", "self", ".", "_get_instantiator", "(", "provider", ")", ")" ]
Registers a service provider for a given service. @param service A key that identifies the service being registered. @param provider This is either the service being registered, or a callable that will either instantiate it or return it. @param singleton Indicates that the service is to be registered as a singleton. This is only relevant if the provider is a callable. Services that are not callable will always be registered as singletons.
[ "Registers", "a", "service", "provider", "for", "a", "given", "service", "." ]
64bfbd37f7aee4a710c4a8b750a971f88efdb7eb
https://github.com/jammycakes/pyfactoryfactory/blob/64bfbd37f7aee4a710c4a8b750a971f88efdb7eb/factoryfactory/__init__.py#L63-L93
238,191
avanwyk/cipy
cipy/algorithms/core.py
dictionary_based_metrics
def dictionary_based_metrics(metrics): """ Higher order function creating a result type and collection function from the given metrics. Args: metrics (iterable): Sequence of callable metrics, each accepting the algorithm state as parameter and returning the measured value with its label: measurement(state) -> (label, value). Returns: tuple(dict, callable): dictionary result type and a collection function accepting the current results and the state as arguments and returning updated result. Examples: >>> state = State() >>> metrics = [lambda state_: state_.iterations] >>> (results, collect) = dictionary_based_metrics(metrics) >>> results = collect(results, state) """ def collect(results, state): """ Measurement collection function for dictionary based metrics. Args: results (dict): Storing results of metrics. state (cipy.algorithms.core.State): Current state of the algorithm. Returns: dict: Updated results containing new metrics. """ for measurement in metrics: (label, value) = measurement(state) iteration_dict = results.get(state.iterations, {}) iteration_dict[label] = str(value) results[state.iterations] = iteration_dict return results return {}, collect
python
def dictionary_based_metrics(metrics): """ Higher order function creating a result type and collection function from the given metrics. Args: metrics (iterable): Sequence of callable metrics, each accepting the algorithm state as parameter and returning the measured value with its label: measurement(state) -> (label, value). Returns: tuple(dict, callable): dictionary result type and a collection function accepting the current results and the state as arguments and returning updated result. Examples: >>> state = State() >>> metrics = [lambda state_: state_.iterations] >>> (results, collect) = dictionary_based_metrics(metrics) >>> results = collect(results, state) """ def collect(results, state): """ Measurement collection function for dictionary based metrics. Args: results (dict): Storing results of metrics. state (cipy.algorithms.core.State): Current state of the algorithm. Returns: dict: Updated results containing new metrics. """ for measurement in metrics: (label, value) = measurement(state) iteration_dict = results.get(state.iterations, {}) iteration_dict[label] = str(value) results[state.iterations] = iteration_dict return results return {}, collect
[ "def", "dictionary_based_metrics", "(", "metrics", ")", ":", "def", "collect", "(", "results", ",", "state", ")", ":", "\"\"\"\n Measurement collection function for dictionary based metrics.\n\n Args:\n results (dict): Storing results of metrics.\n state (cipy.algorithms.core.State): Current state of the algorithm.\n\n Returns:\n dict: Updated results containing new metrics.\n \"\"\"", "for", "measurement", "in", "metrics", ":", "(", "label", ",", "value", ")", "=", "measurement", "(", "state", ")", "iteration_dict", "=", "results", ".", "get", "(", "state", ".", "iterations", ",", "{", "}", ")", "iteration_dict", "[", "label", "]", "=", "str", "(", "value", ")", "results", "[", "state", ".", "iterations", "]", "=", "iteration_dict", "return", "results", "return", "{", "}", ",", "collect" ]
Higher order function creating a result type and collection function from the given metrics. Args: metrics (iterable): Sequence of callable metrics, each accepting the algorithm state as parameter and returning the measured value with its label: measurement(state) -> (label, value). Returns: tuple(dict, callable): dictionary result type and a collection function accepting the current results and the state as arguments and returning updated result. Examples: >>> state = State() >>> metrics = [lambda state_: state_.iterations] >>> (results, collect) = dictionary_based_metrics(metrics) >>> results = collect(results, state)
[ "Higher", "order", "function", "creating", "a", "result", "type", "and", "collection", "function", "from", "the", "given", "metrics", "." ]
98450dd01767b3615c113e50dc396f135e177b29
https://github.com/avanwyk/cipy/blob/98450dd01767b3615c113e50dc396f135e177b29/cipy/algorithms/core.py#L52-L94
238,192
avanwyk/cipy
cipy/algorithms/core.py
comparator
def comparator(objective): """ Higher order function creating a compare function for objectives. Args: objective (cipy.algorithms.core.Objective): The objective to create a compare for. Returns: callable: Function accepting two objectives to compare. Examples: >>> a = Minimum(0.1) >>> b = Minimum(0.2) >>> compare = comparator(a) >>> comparison = compare(a, b) # False """ if isinstance(objective, Minimum): return lambda l, r: l < r else: return lambda l, r: l > r
python
def comparator(objective): """ Higher order function creating a compare function for objectives. Args: objective (cipy.algorithms.core.Objective): The objective to create a compare for. Returns: callable: Function accepting two objectives to compare. Examples: >>> a = Minimum(0.1) >>> b = Minimum(0.2) >>> compare = comparator(a) >>> comparison = compare(a, b) # False """ if isinstance(objective, Minimum): return lambda l, r: l < r else: return lambda l, r: l > r
[ "def", "comparator", "(", "objective", ")", ":", "if", "isinstance", "(", "objective", ",", "Minimum", ")", ":", "return", "lambda", "l", ",", "r", ":", "l", "<", "r", "else", ":", "return", "lambda", "l", ",", "r", ":", "l", ">", "r" ]
Higher order function creating a compare function for objectives. Args: objective (cipy.algorithms.core.Objective): The objective to create a compare for. Returns: callable: Function accepting two objectives to compare. Examples: >>> a = Minimum(0.1) >>> b = Minimum(0.2) >>> compare = comparator(a) >>> comparison = compare(a, b) # False
[ "Higher", "order", "function", "creating", "a", "compare", "function", "for", "objectives", "." ]
98450dd01767b3615c113e50dc396f135e177b29
https://github.com/avanwyk/cipy/blob/98450dd01767b3615c113e50dc396f135e177b29/cipy/algorithms/core.py#L145-L166
238,193
toumorokoshi/jenks
jenks/__init__.py
_get_jenks_config
def _get_jenks_config(): """ retrieve the jenks configuration object """ config_file = (get_configuration_file() or os.path.expanduser(os.path.join("~", CONFIG_FILE_NAME))) if not os.path.exists(config_file): open(config_file, 'w').close() with open(config_file, 'r') as fh: return JenksData( yaml.load(fh.read()), write_method=generate_write_yaml_to_file(config_file) )
python
def _get_jenks_config(): """ retrieve the jenks configuration object """ config_file = (get_configuration_file() or os.path.expanduser(os.path.join("~", CONFIG_FILE_NAME))) if not os.path.exists(config_file): open(config_file, 'w').close() with open(config_file, 'r') as fh: return JenksData( yaml.load(fh.read()), write_method=generate_write_yaml_to_file(config_file) )
[ "def", "_get_jenks_config", "(", ")", ":", "config_file", "=", "(", "get_configuration_file", "(", ")", "or", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "\"~\"", ",", "CONFIG_FILE_NAME", ")", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "config_file", ")", ":", "open", "(", "config_file", ",", "'w'", ")", ".", "close", "(", ")", "with", "open", "(", "config_file", ",", "'r'", ")", "as", "fh", ":", "return", "JenksData", "(", "yaml", ".", "load", "(", "fh", ".", "read", "(", ")", ")", ",", "write_method", "=", "generate_write_yaml_to_file", "(", "config_file", ")", ")" ]
retrieve the jenks configuration object
[ "retrieve", "the", "jenks", "configuration", "object" ]
d3333a7b86ba290b7185aa5b8da75e76a28124f5
https://github.com/toumorokoshi/jenks/blob/d3333a7b86ba290b7185aa5b8da75e76a28124f5/jenks/__init__.py#L59-L71
238,194
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/textedit.py
JB_PlainTextEdit.set_placeholder
def set_placeholder(self, text): """Set the placeholder text that will be displayed when the text is empty and the widget is out of focus :param text: The text for the placeholder :type text: str :raises: None """ if self._placeholder != text: self._placeholder = text if not self.hasFocus(): self.update()
python
def set_placeholder(self, text): """Set the placeholder text that will be displayed when the text is empty and the widget is out of focus :param text: The text for the placeholder :type text: str :raises: None """ if self._placeholder != text: self._placeholder = text if not self.hasFocus(): self.update()
[ "def", "set_placeholder", "(", "self", ",", "text", ")", ":", "if", "self", ".", "_placeholder", "!=", "text", ":", "self", ".", "_placeholder", "=", "text", "if", "not", "self", ".", "hasFocus", "(", ")", ":", "self", ".", "update", "(", ")" ]
Set the placeholder text that will be displayed when the text is empty and the widget is out of focus :param text: The text for the placeholder :type text: str :raises: None
[ "Set", "the", "placeholder", "text", "that", "will", "be", "displayed", "when", "the", "text", "is", "empty", "and", "the", "widget", "is", "out", "of", "focus" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/textedit.py#L30-L41
238,195
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/textedit.py
JB_PlainTextEdit.paintEvent
def paintEvent(self, event): """Paint the widget :param event: :type event: :returns: None :rtype: None :raises: None """ if not self.toPlainText() and not self.hasFocus() and self._placeholder: p = QtGui.QPainter(self.viewport()) p.setClipping(False) col = self.palette().text().color() col.setAlpha(128) oldpen = p.pen() p.setPen(col) p.drawText(self.viewport().geometry(), QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop, self._placeholder) p.setPen(oldpen) else: return super(JB_PlainTextEdit, self).paintEvent(event)
python
def paintEvent(self, event): """Paint the widget :param event: :type event: :returns: None :rtype: None :raises: None """ if not self.toPlainText() and not self.hasFocus() and self._placeholder: p = QtGui.QPainter(self.viewport()) p.setClipping(False) col = self.palette().text().color() col.setAlpha(128) oldpen = p.pen() p.setPen(col) p.drawText(self.viewport().geometry(), QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop, self._placeholder) p.setPen(oldpen) else: return super(JB_PlainTextEdit, self).paintEvent(event)
[ "def", "paintEvent", "(", "self", ",", "event", ")", ":", "if", "not", "self", ".", "toPlainText", "(", ")", "and", "not", "self", ".", "hasFocus", "(", ")", "and", "self", ".", "_placeholder", ":", "p", "=", "QtGui", ".", "QPainter", "(", "self", ".", "viewport", "(", ")", ")", "p", ".", "setClipping", "(", "False", ")", "col", "=", "self", ".", "palette", "(", ")", ".", "text", "(", ")", ".", "color", "(", ")", "col", ".", "setAlpha", "(", "128", ")", "oldpen", "=", "p", ".", "pen", "(", ")", "p", ".", "setPen", "(", "col", ")", "p", ".", "drawText", "(", "self", ".", "viewport", "(", ")", ".", "geometry", "(", ")", ",", "QtCore", ".", "Qt", ".", "AlignLeft", "|", "QtCore", ".", "Qt", ".", "AlignTop", ",", "self", ".", "_placeholder", ")", "p", ".", "setPen", "(", "oldpen", ")", "else", ":", "return", "super", "(", "JB_PlainTextEdit", ",", "self", ")", ".", "paintEvent", "(", "event", ")" ]
Paint the widget :param event: :type event: :returns: None :rtype: None :raises: None
[ "Paint", "the", "widget" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/textedit.py#L43-L62
238,196
emilydolson/avida-spatial-tools
avidaspatial/environment_file_components.py
calcEvenAnchors
def calcEvenAnchors(args): """ Calculates anchor points evenly spaced across the world, given user-specified parameters. Note: May not be exactly even if world size is not divisible by patches+1. Note: Eveness is based on bounded world, not toroidal. """ anchors = [] dist = int((args.worldSize)/(args.patchesPerSide+1)) for i in range(dist, args.worldSize, dist): for j in range(dist, args.worldSize, dist): anchors.append((i, j)) return anchors
python
def calcEvenAnchors(args): """ Calculates anchor points evenly spaced across the world, given user-specified parameters. Note: May not be exactly even if world size is not divisible by patches+1. Note: Eveness is based on bounded world, not toroidal. """ anchors = [] dist = int((args.worldSize)/(args.patchesPerSide+1)) for i in range(dist, args.worldSize, dist): for j in range(dist, args.worldSize, dist): anchors.append((i, j)) return anchors
[ "def", "calcEvenAnchors", "(", "args", ")", ":", "anchors", "=", "[", "]", "dist", "=", "int", "(", "(", "args", ".", "worldSize", ")", "/", "(", "args", ".", "patchesPerSide", "+", "1", ")", ")", "for", "i", "in", "range", "(", "dist", ",", "args", ".", "worldSize", ",", "dist", ")", ":", "for", "j", "in", "range", "(", "dist", ",", "args", ".", "worldSize", ",", "dist", ")", ":", "anchors", ".", "append", "(", "(", "i", ",", "j", ")", ")", "return", "anchors" ]
Calculates anchor points evenly spaced across the world, given user-specified parameters. Note: May not be exactly even if world size is not divisible by patches+1. Note: Eveness is based on bounded world, not toroidal.
[ "Calculates", "anchor", "points", "evenly", "spaced", "across", "the", "world", "given", "user", "-", "specified", "parameters", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/environment_file_components.py#L63-L77
238,197
emilydolson/avida-spatial-tools
avidaspatial/environment_file_components.py
calcRandomAnchors
def calcRandomAnchors(args, inworld=True): """ Generates a list of random anchor points such that all circles will fit in the world, given the specified radius and worldsize. The number of anchors to generate is given by nPatches """ anchors = [] rng = (args.patchRadius, args.worldSize - args.patchRadius) if not inworld: rng = (0, args.worldSize) for i in range(args.nPatches): anchors.append((random.randrange(rng[0], rng[1]), random.randrange(rng[0], rng[1]))) return anchors
python
def calcRandomAnchors(args, inworld=True): """ Generates a list of random anchor points such that all circles will fit in the world, given the specified radius and worldsize. The number of anchors to generate is given by nPatches """ anchors = [] rng = (args.patchRadius, args.worldSize - args.patchRadius) if not inworld: rng = (0, args.worldSize) for i in range(args.nPatches): anchors.append((random.randrange(rng[0], rng[1]), random.randrange(rng[0], rng[1]))) return anchors
[ "def", "calcRandomAnchors", "(", "args", ",", "inworld", "=", "True", ")", ":", "anchors", "=", "[", "]", "rng", "=", "(", "args", ".", "patchRadius", ",", "args", ".", "worldSize", "-", "args", ".", "patchRadius", ")", "if", "not", "inworld", ":", "rng", "=", "(", "0", ",", "args", ".", "worldSize", ")", "for", "i", "in", "range", "(", "args", ".", "nPatches", ")", ":", "anchors", ".", "append", "(", "(", "random", ".", "randrange", "(", "rng", "[", "0", "]", ",", "rng", "[", "1", "]", ")", ",", "random", ".", "randrange", "(", "rng", "[", "0", "]", ",", "rng", "[", "1", "]", ")", ")", ")", "return", "anchors" ]
Generates a list of random anchor points such that all circles will fit in the world, given the specified radius and worldsize. The number of anchors to generate is given by nPatches
[ "Generates", "a", "list", "of", "random", "anchor", "points", "such", "that", "all", "circles", "will", "fit", "in", "the", "world", "given", "the", "specified", "radius", "and", "worldsize", ".", "The", "number", "of", "anchors", "to", "generate", "is", "given", "by", "nPatches" ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/environment_file_components.py#L80-L94
238,198
emilydolson/avida-spatial-tools
avidaspatial/environment_file_components.py
pairwise_point_combinations
def pairwise_point_combinations(xs, ys, anchors): """ Does an in-place addition of the four points that can be composed by combining coordinates from the two lists to the given list of anchors """ for i in xs: anchors.append((i, max(ys))) anchors.append((i, min(ys))) for i in ys: anchors.append((max(xs), i)) anchors.append((min(xs), i))
python
def pairwise_point_combinations(xs, ys, anchors): """ Does an in-place addition of the four points that can be composed by combining coordinates from the two lists to the given list of anchors """ for i in xs: anchors.append((i, max(ys))) anchors.append((i, min(ys))) for i in ys: anchors.append((max(xs), i)) anchors.append((min(xs), i))
[ "def", "pairwise_point_combinations", "(", "xs", ",", "ys", ",", "anchors", ")", ":", "for", "i", "in", "xs", ":", "anchors", ".", "append", "(", "(", "i", ",", "max", "(", "ys", ")", ")", ")", "anchors", ".", "append", "(", "(", "i", ",", "min", "(", "ys", ")", ")", ")", "for", "i", "in", "ys", ":", "anchors", ".", "append", "(", "(", "max", "(", "xs", ")", ",", "i", ")", ")", "anchors", ".", "append", "(", "(", "min", "(", "xs", ")", ",", "i", ")", ")" ]
Does an in-place addition of the four points that can be composed by combining coordinates from the two lists to the given list of anchors
[ "Does", "an", "in", "-", "place", "addition", "of", "the", "four", "points", "that", "can", "be", "composed", "by", "combining", "coordinates", "from", "the", "two", "lists", "to", "the", "given", "list", "of", "anchors" ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/environment_file_components.py#L97-L107
238,199
emilydolson/avida-spatial-tools
avidaspatial/environment_file_components.py
calcTightAnchors
def calcTightAnchors(args, d, patches): """ Recursively generates the number of anchor points specified in the patches argument, such that all patches are d cells away from their nearest neighbors. """ centerPoint = (int(args.worldSize/2), int(args.worldSize/2)) anchors = [] if patches == 0: pass elif patches == 1: anchors.append(centerPoint) elif patches % 2 == 0: dsout = int((patches-2)//2) + 1 add_anchors(centerPoint, d, dsout, anchors, True) if d != 0: anchors = list(set(anchors)) anchors.sort() if dsout != 1: return (anchors + calcTightAnchors(args, d, patches-2) )[:patches*patches] # to cut off the extras in the case where d=0 else: # Note - an odd number of args.patchesPerSide requires that there be # a patch at the centerpoint dsout = int((patches-1)//2) add_anchors(centerPoint, d, dsout, anchors, False) if dsout != 1: return anchors + calcTightAnchors(d, patches-2) return anchors
python
def calcTightAnchors(args, d, patches): """ Recursively generates the number of anchor points specified in the patches argument, such that all patches are d cells away from their nearest neighbors. """ centerPoint = (int(args.worldSize/2), int(args.worldSize/2)) anchors = [] if patches == 0: pass elif patches == 1: anchors.append(centerPoint) elif patches % 2 == 0: dsout = int((patches-2)//2) + 1 add_anchors(centerPoint, d, dsout, anchors, True) if d != 0: anchors = list(set(anchors)) anchors.sort() if dsout != 1: return (anchors + calcTightAnchors(args, d, patches-2) )[:patches*patches] # to cut off the extras in the case where d=0 else: # Note - an odd number of args.patchesPerSide requires that there be # a patch at the centerpoint dsout = int((patches-1)//2) add_anchors(centerPoint, d, dsout, anchors, False) if dsout != 1: return anchors + calcTightAnchors(d, patches-2) return anchors
[ "def", "calcTightAnchors", "(", "args", ",", "d", ",", "patches", ")", ":", "centerPoint", "=", "(", "int", "(", "args", ".", "worldSize", "/", "2", ")", ",", "int", "(", "args", ".", "worldSize", "/", "2", ")", ")", "anchors", "=", "[", "]", "if", "patches", "==", "0", ":", "pass", "elif", "patches", "==", "1", ":", "anchors", ".", "append", "(", "centerPoint", ")", "elif", "patches", "%", "2", "==", "0", ":", "dsout", "=", "int", "(", "(", "patches", "-", "2", ")", "//", "2", ")", "+", "1", "add_anchors", "(", "centerPoint", ",", "d", ",", "dsout", ",", "anchors", ",", "True", ")", "if", "d", "!=", "0", ":", "anchors", "=", "list", "(", "set", "(", "anchors", ")", ")", "anchors", ".", "sort", "(", ")", "if", "dsout", "!=", "1", ":", "return", "(", "anchors", "+", "calcTightAnchors", "(", "args", ",", "d", ",", "patches", "-", "2", ")", ")", "[", ":", "patches", "*", "patches", "]", "# to cut off the extras in the case where d=0", "else", ":", "# Note - an odd number of args.patchesPerSide requires that there be", "# a patch at the centerpoint", "dsout", "=", "int", "(", "(", "patches", "-", "1", ")", "//", "2", ")", "add_anchors", "(", "centerPoint", ",", "d", ",", "dsout", ",", "anchors", ",", "False", ")", "if", "dsout", "!=", "1", ":", "return", "anchors", "+", "calcTightAnchors", "(", "d", ",", "patches", "-", "2", ")", "return", "anchors" ]
Recursively generates the number of anchor points specified in the patches argument, such that all patches are d cells away from their nearest neighbors.
[ "Recursively", "generates", "the", "number", "of", "anchor", "points", "specified", "in", "the", "patches", "argument", "such", "that", "all", "patches", "are", "d", "cells", "away", "from", "their", "nearest", "neighbors", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/environment_file_components.py#L133-L167