repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
sequencelengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
sequencelengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
KelSolaar/Manager
manager/QObject_component.py
QObjectComponent.initialized
def initialized(self, value): """ Setter for **self.__initialized** attribute. :param value: Attribute value. :type value: bool """ if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("initialized", value) self.component_initialized.emit() if value else self.component_uninitialized.emit() self.__initialized = value
python
def initialized(self, value): """ Setter for **self.__initialized** attribute. :param value: Attribute value. :type value: bool """ if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("initialized", value) self.component_initialized.emit() if value else self.component_uninitialized.emit() self.__initialized = value
[ "def", "initialized", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "bool", ",", "\"'{0}' attribute: '{1}' type is not 'bool'!\"", ".", "format", "(", "\"initialized\"", ",", "value", ")", "self", ".", "component_initialized", ".", "emit", "(", ")", "if", "value", "else", "self", ".", "component_uninitialized", ".", "emit", "(", ")", "self", ".", "__initialized", "=", "value" ]
Setter for **self.__initialized** attribute. :param value: Attribute value. :type value: bool
[ "Setter", "for", "**", "self", ".", "__initialized", "**", "attribute", "." ]
train
https://github.com/KelSolaar/Manager/blob/39c8153fc021fc8a76e345a6e336ec2644f089d1/manager/QObject_component.py#L172-L183
KelSolaar/Manager
manager/QObject_component.py
QObjectComponent.deactivatable
def deactivatable(self, value): """ Setter for **self.__deactivatable** attribute. :param value: Attribute value. :type value: bool """ if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("deactivatable", value) self.__deactivatable = value
python
def deactivatable(self, value): """ Setter for **self.__deactivatable** attribute. :param value: Attribute value. :type value: bool """ if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("deactivatable", value) self.__deactivatable = value
[ "def", "deactivatable", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "bool", ",", "\"'{0}' attribute: '{1}' type is not 'bool'!\"", ".", "format", "(", "\"deactivatable\"", ",", "value", ")", "self", ".", "__deactivatable", "=", "value" ]
Setter for **self.__deactivatable** attribute. :param value: Attribute value. :type value: bool
[ "Setter", "for", "**", "self", ".", "__deactivatable", "**", "attribute", "." ]
train
https://github.com/KelSolaar/Manager/blob/39c8153fc021fc8a76e345a6e336ec2644f089d1/manager/QObject_component.py#L208-L218
Capitains/Nautilus
capitains_nautilus/apis/cts.py
CTSApi.r_cts
def r_cts(self): """ Actual main route of CTS APIs. Transfer typical requests through the ?request=REQUESTNAME route :return: Response """ _request = request.args.get("request", None) if _request is not None: try: if _request.lower() == "getcapabilities": return self._get_capabilities( urn=request.args.get("urn", None) ) elif _request.lower() == "getpassage": return self._get_passage( urn=request.args.get("urn", None) ) elif _request.lower() == "getpassageplus": return self._get_passage_plus( urn=request.args.get("urn", None) ) elif _request.lower() == "getlabel": return self._get_label( urn=request.args.get("urn", None) ) elif _request.lower() == "getfirsturn": return self._get_first_urn( urn=request.args.get("urn", None) ) elif _request.lower() == "getprevnexturn": return self._get_prev_next( urn=request.args.get("urn", None) ) elif _request.lower() == "getvalidreff": return self._get_valid_reff( urn=request.args.get("urn", None), level=request.args.get("level", 1, type=int) ) except NautilusError as E: return self.cts_error(error_name=E.__class__.__name__, message=E.__doc__) return self.cts_error(MissingParameter.__name__, message=MissingParameter.__doc__)
python
def r_cts(self): """ Actual main route of CTS APIs. Transfer typical requests through the ?request=REQUESTNAME route :return: Response """ _request = request.args.get("request", None) if _request is not None: try: if _request.lower() == "getcapabilities": return self._get_capabilities( urn=request.args.get("urn", None) ) elif _request.lower() == "getpassage": return self._get_passage( urn=request.args.get("urn", None) ) elif _request.lower() == "getpassageplus": return self._get_passage_plus( urn=request.args.get("urn", None) ) elif _request.lower() == "getlabel": return self._get_label( urn=request.args.get("urn", None) ) elif _request.lower() == "getfirsturn": return self._get_first_urn( urn=request.args.get("urn", None) ) elif _request.lower() == "getprevnexturn": return self._get_prev_next( urn=request.args.get("urn", None) ) elif _request.lower() == "getvalidreff": return self._get_valid_reff( urn=request.args.get("urn", None), level=request.args.get("level", 1, type=int) ) except NautilusError as E: return self.cts_error(error_name=E.__class__.__name__, message=E.__doc__) return self.cts_error(MissingParameter.__name__, message=MissingParameter.__doc__)
[ "def", "r_cts", "(", "self", ")", ":", "_request", "=", "request", ".", "args", ".", "get", "(", "\"request\"", ",", "None", ")", "if", "_request", "is", "not", "None", ":", "try", ":", "if", "_request", ".", "lower", "(", ")", "==", "\"getcapabilities\"", ":", "return", "self", ".", "_get_capabilities", "(", "urn", "=", "request", ".", "args", ".", "get", "(", "\"urn\"", ",", "None", ")", ")", "elif", "_request", ".", "lower", "(", ")", "==", "\"getpassage\"", ":", "return", "self", ".", "_get_passage", "(", "urn", "=", "request", ".", "args", ".", "get", "(", "\"urn\"", ",", "None", ")", ")", "elif", "_request", ".", "lower", "(", ")", "==", "\"getpassageplus\"", ":", "return", "self", ".", "_get_passage_plus", "(", "urn", "=", "request", ".", "args", ".", "get", "(", "\"urn\"", ",", "None", ")", ")", "elif", "_request", ".", "lower", "(", ")", "==", "\"getlabel\"", ":", "return", "self", ".", "_get_label", "(", "urn", "=", "request", ".", "args", ".", "get", "(", "\"urn\"", ",", "None", ")", ")", "elif", "_request", ".", "lower", "(", ")", "==", "\"getfirsturn\"", ":", "return", "self", ".", "_get_first_urn", "(", "urn", "=", "request", ".", "args", ".", "get", "(", "\"urn\"", ",", "None", ")", ")", "elif", "_request", ".", "lower", "(", ")", "==", "\"getprevnexturn\"", ":", "return", "self", ".", "_get_prev_next", "(", "urn", "=", "request", ".", "args", ".", "get", "(", "\"urn\"", ",", "None", ")", ")", "elif", "_request", ".", "lower", "(", ")", "==", "\"getvalidreff\"", ":", "return", "self", ".", "_get_valid_reff", "(", "urn", "=", "request", ".", "args", ".", "get", "(", "\"urn\"", ",", "None", ")", ",", "level", "=", "request", ".", "args", ".", "get", "(", "\"level\"", ",", "1", ",", "type", "=", "int", ")", ")", "except", "NautilusError", "as", "E", ":", "return", "self", ".", "cts_error", "(", "error_name", "=", "E", ".", "__class__", ".", "__name__", ",", "message", "=", "E", ".", "__doc__", ")", "return", "self", ".", "cts_error", "(", "MissingParameter", ".", "__name__", ",", "message", "=", "MissingParameter", ".", "__doc__", ")" ]
Actual main route of CTS APIs. Transfer typical requests through the ?request=REQUESTNAME route :return: Response
[ "Actual", "main", "route", "of", "CTS", "APIs", ".", "Transfer", "typical", "requests", "through", "the", "?request", "=", "REQUESTNAME", "route" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L25-L64
Capitains/Nautilus
capitains_nautilus/apis/cts.py
CTSApi.cts_error
def cts_error(self, error_name, message=None): """ Create a CTS Error reply :param error_name: Name of the error :param message: Message of the Error :return: CTS Error Response with information (XML) """ self.nautilus_extension.logger.info( "CTS error thrown {} for {} ({})".format( error_name, request.query_string.decode(), message) ) return render_template( "cts/Error.xml", errorType=error_name, message=message ), 404, {"content-type": "application/xml"}
python
def cts_error(self, error_name, message=None): """ Create a CTS Error reply :param error_name: Name of the error :param message: Message of the Error :return: CTS Error Response with information (XML) """ self.nautilus_extension.logger.info( "CTS error thrown {} for {} ({})".format( error_name, request.query_string.decode(), message) ) return render_template( "cts/Error.xml", errorType=error_name, message=message ), 404, {"content-type": "application/xml"}
[ "def", "cts_error", "(", "self", ",", "error_name", ",", "message", "=", "None", ")", ":", "self", ".", "nautilus_extension", ".", "logger", ".", "info", "(", "\"CTS error thrown {} for {} ({})\"", ".", "format", "(", "error_name", ",", "request", ".", "query_string", ".", "decode", "(", ")", ",", "message", ")", ")", "return", "render_template", "(", "\"cts/Error.xml\"", ",", "errorType", "=", "error_name", ",", "message", "=", "message", ")", ",", "404", ",", "{", "\"content-type\"", ":", "\"application/xml\"", "}" ]
Create a CTS Error reply :param error_name: Name of the error :param message: Message of the Error :return: CTS Error Response with information (XML)
[ "Create", "a", "CTS", "Error", "reply" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L66-L83
Capitains/Nautilus
capitains_nautilus/apis/cts.py
CTSApi._get_capabilities
def _get_capabilities(self, urn=None): """ Provisional route for GetCapabilities request :param urn: URN to filter the resource :param inv: Inventory Identifier :return: GetCapabilities response """ r = self.resolver.getMetadata(objectId=urn) if len(r.parents) > 0: r = r.parents[-1] r = render_template( "cts/GetCapabilities.xml", filters="urn={}".format(urn), inventory=Markup(r.export(Mimetypes.XML.CTS)) ) return r, 200, {"content-type": "application/xml"}
python
def _get_capabilities(self, urn=None): """ Provisional route for GetCapabilities request :param urn: URN to filter the resource :param inv: Inventory Identifier :return: GetCapabilities response """ r = self.resolver.getMetadata(objectId=urn) if len(r.parents) > 0: r = r.parents[-1] r = render_template( "cts/GetCapabilities.xml", filters="urn={}".format(urn), inventory=Markup(r.export(Mimetypes.XML.CTS)) ) return r, 200, {"content-type": "application/xml"}
[ "def", "_get_capabilities", "(", "self", ",", "urn", "=", "None", ")", ":", "r", "=", "self", ".", "resolver", ".", "getMetadata", "(", "objectId", "=", "urn", ")", "if", "len", "(", "r", ".", "parents", ")", ">", "0", ":", "r", "=", "r", ".", "parents", "[", "-", "1", "]", "r", "=", "render_template", "(", "\"cts/GetCapabilities.xml\"", ",", "filters", "=", "\"urn={}\"", ".", "format", "(", "urn", ")", ",", "inventory", "=", "Markup", "(", "r", ".", "export", "(", "Mimetypes", ".", "XML", ".", "CTS", ")", ")", ")", "return", "r", ",", "200", ",", "{", "\"content-type\"", ":", "\"application/xml\"", "}" ]
Provisional route for GetCapabilities request :param urn: URN to filter the resource :param inv: Inventory Identifier :return: GetCapabilities response
[ "Provisional", "route", "for", "GetCapabilities", "request" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L85-L100
Capitains/Nautilus
capitains_nautilus/apis/cts.py
CTSApi._get_passage
def _get_passage(self, urn): """ Provisional route for GetPassage request :param urn: URN to filter the resource :return: GetPassage response """ urn = URN(urn) subreference = None if len(urn) < 4: raise InvalidURN if urn.reference is not None: subreference = str(urn.reference) node = self.resolver.getTextualNode(textId=urn.upTo(URN.NO_PASSAGE), subreference=subreference) r = render_template( "cts/GetPassage.xml", filters="urn={}".format(urn), request_urn=str(urn), full_urn=node.urn, passage=Markup(node.export(Mimetypes.XML.TEI)) ) return r, 200, {"content-type": "application/xml"}
python
def _get_passage(self, urn): """ Provisional route for GetPassage request :param urn: URN to filter the resource :return: GetPassage response """ urn = URN(urn) subreference = None if len(urn) < 4: raise InvalidURN if urn.reference is not None: subreference = str(urn.reference) node = self.resolver.getTextualNode(textId=urn.upTo(URN.NO_PASSAGE), subreference=subreference) r = render_template( "cts/GetPassage.xml", filters="urn={}".format(urn), request_urn=str(urn), full_urn=node.urn, passage=Markup(node.export(Mimetypes.XML.TEI)) ) return r, 200, {"content-type": "application/xml"}
[ "def", "_get_passage", "(", "self", ",", "urn", ")", ":", "urn", "=", "URN", "(", "urn", ")", "subreference", "=", "None", "if", "len", "(", "urn", ")", "<", "4", ":", "raise", "InvalidURN", "if", "urn", ".", "reference", "is", "not", "None", ":", "subreference", "=", "str", "(", "urn", ".", "reference", ")", "node", "=", "self", ".", "resolver", ".", "getTextualNode", "(", "textId", "=", "urn", ".", "upTo", "(", "URN", ".", "NO_PASSAGE", ")", ",", "subreference", "=", "subreference", ")", "r", "=", "render_template", "(", "\"cts/GetPassage.xml\"", ",", "filters", "=", "\"urn={}\"", ".", "format", "(", "urn", ")", ",", "request_urn", "=", "str", "(", "urn", ")", ",", "full_urn", "=", "node", ".", "urn", ",", "passage", "=", "Markup", "(", "node", ".", "export", "(", "Mimetypes", ".", "XML", ".", "TEI", ")", ")", ")", "return", "r", ",", "200", ",", "{", "\"content-type\"", ":", "\"application/xml\"", "}" ]
Provisional route for GetPassage request :param urn: URN to filter the resource :return: GetPassage response
[ "Provisional", "route", "for", "GetPassage", "request" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L102-L123
Capitains/Nautilus
capitains_nautilus/apis/cts.py
CTSApi._get_passage_plus
def _get_passage_plus(self, urn): """ Provisional route for GetPassagePlus request :param urn: URN to filter the resource :return: GetPassagePlus response """ urn = URN(urn) subreference = None if len(urn) < 4: raise InvalidURN if urn.reference is not None: subreference = str(urn.reference) node = self.resolver.getTextualNode(textId=urn.upTo(URN.NO_PASSAGE), subreference=subreference) r = render_template( "cts/GetPassagePlus.xml", filters="urn={}".format(urn), request_urn=str(urn), full_urn=node.urn, prev_urn=node.prevId, next_urn=node.nextId, metadata={ "groupname": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.groupname)], "title": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.title)], "description": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.description)], "label": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.label)] }, citation=Markup(node.citation.export(Mimetypes.XML.CTS)), passage=Markup(node.export(Mimetypes.XML.TEI)) ) return r, 200, {"content-type": "application/xml"}
python
def _get_passage_plus(self, urn): """ Provisional route for GetPassagePlus request :param urn: URN to filter the resource :return: GetPassagePlus response """ urn = URN(urn) subreference = None if len(urn) < 4: raise InvalidURN if urn.reference is not None: subreference = str(urn.reference) node = self.resolver.getTextualNode(textId=urn.upTo(URN.NO_PASSAGE), subreference=subreference) r = render_template( "cts/GetPassagePlus.xml", filters="urn={}".format(urn), request_urn=str(urn), full_urn=node.urn, prev_urn=node.prevId, next_urn=node.nextId, metadata={ "groupname": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.groupname)], "title": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.title)], "description": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.description)], "label": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.label)] }, citation=Markup(node.citation.export(Mimetypes.XML.CTS)), passage=Markup(node.export(Mimetypes.XML.TEI)) ) return r, 200, {"content-type": "application/xml"}
[ "def", "_get_passage_plus", "(", "self", ",", "urn", ")", ":", "urn", "=", "URN", "(", "urn", ")", "subreference", "=", "None", "if", "len", "(", "urn", ")", "<", "4", ":", "raise", "InvalidURN", "if", "urn", ".", "reference", "is", "not", "None", ":", "subreference", "=", "str", "(", "urn", ".", "reference", ")", "node", "=", "self", ".", "resolver", ".", "getTextualNode", "(", "textId", "=", "urn", ".", "upTo", "(", "URN", ".", "NO_PASSAGE", ")", ",", "subreference", "=", "subreference", ")", "r", "=", "render_template", "(", "\"cts/GetPassagePlus.xml\"", ",", "filters", "=", "\"urn={}\"", ".", "format", "(", "urn", ")", ",", "request_urn", "=", "str", "(", "urn", ")", ",", "full_urn", "=", "node", ".", "urn", ",", "prev_urn", "=", "node", ".", "prevId", ",", "next_urn", "=", "node", ".", "nextId", ",", "metadata", "=", "{", "\"groupname\"", ":", "[", "(", "literal", ".", "language", ",", "str", "(", "literal", ")", ")", "for", "literal", "in", "node", ".", "metadata", ".", "get", "(", "RDF_NAMESPACES", ".", "CTS", ".", "groupname", ")", "]", ",", "\"title\"", ":", "[", "(", "literal", ".", "language", ",", "str", "(", "literal", ")", ")", "for", "literal", "in", "node", ".", "metadata", ".", "get", "(", "RDF_NAMESPACES", ".", "CTS", ".", "title", ")", "]", ",", "\"description\"", ":", "[", "(", "literal", ".", "language", ",", "str", "(", "literal", ")", ")", "for", "literal", "in", "node", ".", "metadata", ".", "get", "(", "RDF_NAMESPACES", ".", "CTS", ".", "description", ")", "]", ",", "\"label\"", ":", "[", "(", "literal", ".", "language", ",", "str", "(", "literal", ")", ")", "for", "literal", "in", "node", ".", "metadata", ".", "get", "(", "RDF_NAMESPACES", ".", "CTS", ".", "label", ")", "]", "}", ",", "citation", "=", "Markup", "(", "node", ".", "citation", ".", "export", "(", "Mimetypes", ".", "XML", ".", "CTS", ")", ")", ",", "passage", "=", "Markup", "(", "node", ".", "export", "(", "Mimetypes", ".", "XML", ".", "TEI", ")", ")", ")", "return", "r", ",", "200", ",", "{", "\"content-type\"", ":", "\"application/xml\"", "}" ]
Provisional route for GetPassagePlus request :param urn: URN to filter the resource :return: GetPassagePlus response
[ "Provisional", "route", "for", "GetPassagePlus", "request" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L125-L154
Capitains/Nautilus
capitains_nautilus/apis/cts.py
CTSApi._get_valid_reff
def _get_valid_reff(self, urn, level): """ Provisional route for GetValidReff request :param urn: URN to filter the resource :return: GetValidReff response """ urn = URN(urn) subreference = None textId=urn.upTo(URN.NO_PASSAGE) if urn.reference is not None: subreference = str(urn.reference) reffs = self.resolver.getReffs(textId=textId, subreference=subreference, level=level) r = render_template( "cts/GetValidReff.xml", reffs=reffs, urn=textId, level=level, request_urn=str(urn) ) return r, 200, {"content-type": "application/xml"}
python
def _get_valid_reff(self, urn, level): """ Provisional route for GetValidReff request :param urn: URN to filter the resource :return: GetValidReff response """ urn = URN(urn) subreference = None textId=urn.upTo(URN.NO_PASSAGE) if urn.reference is not None: subreference = str(urn.reference) reffs = self.resolver.getReffs(textId=textId, subreference=subreference, level=level) r = render_template( "cts/GetValidReff.xml", reffs=reffs, urn=textId, level=level, request_urn=str(urn) ) return r, 200, {"content-type": "application/xml"}
[ "def", "_get_valid_reff", "(", "self", ",", "urn", ",", "level", ")", ":", "urn", "=", "URN", "(", "urn", ")", "subreference", "=", "None", "textId", "=", "urn", ".", "upTo", "(", "URN", ".", "NO_PASSAGE", ")", "if", "urn", ".", "reference", "is", "not", "None", ":", "subreference", "=", "str", "(", "urn", ".", "reference", ")", "reffs", "=", "self", ".", "resolver", ".", "getReffs", "(", "textId", "=", "textId", ",", "subreference", "=", "subreference", ",", "level", "=", "level", ")", "r", "=", "render_template", "(", "\"cts/GetValidReff.xml\"", ",", "reffs", "=", "reffs", ",", "urn", "=", "textId", ",", "level", "=", "level", ",", "request_urn", "=", "str", "(", "urn", ")", ")", "return", "r", ",", "200", ",", "{", "\"content-type\"", ":", "\"application/xml\"", "}" ]
Provisional route for GetValidReff request :param urn: URN to filter the resource :return: GetValidReff response
[ "Provisional", "route", "for", "GetValidReff", "request" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L156-L175
Capitains/Nautilus
capitains_nautilus/apis/cts.py
CTSApi._get_prev_next
def _get_prev_next(self, urn): """ Provisional route for GetPrevNext request :param urn: URN to filter the resource :param inv: Inventory Identifier :return: GetPrevNext response """ urn = URN(urn) subreference = None textId = urn.upTo(URN.NO_PASSAGE) if urn.reference is not None: subreference = str(urn.reference) previous, nextious = self.resolver.getSiblings(textId=textId, subreference=subreference) r = render_template( "cts/GetPrevNext.xml", prev_urn=previous, next_urn=nextious, urn=textId, request_urn=str(urn) ) return r, 200, {"content-type": "application/xml"}
python
def _get_prev_next(self, urn): """ Provisional route for GetPrevNext request :param urn: URN to filter the resource :param inv: Inventory Identifier :return: GetPrevNext response """ urn = URN(urn) subreference = None textId = urn.upTo(URN.NO_PASSAGE) if urn.reference is not None: subreference = str(urn.reference) previous, nextious = self.resolver.getSiblings(textId=textId, subreference=subreference) r = render_template( "cts/GetPrevNext.xml", prev_urn=previous, next_urn=nextious, urn=textId, request_urn=str(urn) ) return r, 200, {"content-type": "application/xml"}
[ "def", "_get_prev_next", "(", "self", ",", "urn", ")", ":", "urn", "=", "URN", "(", "urn", ")", "subreference", "=", "None", "textId", "=", "urn", ".", "upTo", "(", "URN", ".", "NO_PASSAGE", ")", "if", "urn", ".", "reference", "is", "not", "None", ":", "subreference", "=", "str", "(", "urn", ".", "reference", ")", "previous", ",", "nextious", "=", "self", ".", "resolver", ".", "getSiblings", "(", "textId", "=", "textId", ",", "subreference", "=", "subreference", ")", "r", "=", "render_template", "(", "\"cts/GetPrevNext.xml\"", ",", "prev_urn", "=", "previous", ",", "next_urn", "=", "nextious", ",", "urn", "=", "textId", ",", "request_urn", "=", "str", "(", "urn", ")", ")", "return", "r", ",", "200", ",", "{", "\"content-type\"", ":", "\"application/xml\"", "}" ]
Provisional route for GetPrevNext request :param urn: URN to filter the resource :param inv: Inventory Identifier :return: GetPrevNext response
[ "Provisional", "route", "for", "GetPrevNext", "request" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L177-L197
Capitains/Nautilus
capitains_nautilus/apis/cts.py
CTSApi._get_first_urn
def _get_first_urn(self, urn): """ Provisional route for GetFirstUrn request :param urn: URN to filter the resource :param inv: Inventory Identifier :return: GetFirstUrn response """ urn = URN(urn) subreference = None textId = urn.upTo(URN.NO_PASSAGE) if urn.reference is not None: subreference = str(urn.reference) firstId = self.resolver.getTextualNode(textId=textId, subreference=subreference).firstId r = render_template( "cts/GetFirstUrn.xml", firstId=firstId, full_urn=textId, request_urn=str(urn) ) return r, 200, {"content-type": "application/xml"}
python
def _get_first_urn(self, urn): """ Provisional route for GetFirstUrn request :param urn: URN to filter the resource :param inv: Inventory Identifier :return: GetFirstUrn response """ urn = URN(urn) subreference = None textId = urn.upTo(URN.NO_PASSAGE) if urn.reference is not None: subreference = str(urn.reference) firstId = self.resolver.getTextualNode(textId=textId, subreference=subreference).firstId r = render_template( "cts/GetFirstUrn.xml", firstId=firstId, full_urn=textId, request_urn=str(urn) ) return r, 200, {"content-type": "application/xml"}
[ "def", "_get_first_urn", "(", "self", ",", "urn", ")", ":", "urn", "=", "URN", "(", "urn", ")", "subreference", "=", "None", "textId", "=", "urn", ".", "upTo", "(", "URN", ".", "NO_PASSAGE", ")", "if", "urn", ".", "reference", "is", "not", "None", ":", "subreference", "=", "str", "(", "urn", ".", "reference", ")", "firstId", "=", "self", ".", "resolver", ".", "getTextualNode", "(", "textId", "=", "textId", ",", "subreference", "=", "subreference", ")", ".", "firstId", "r", "=", "render_template", "(", "\"cts/GetFirstUrn.xml\"", ",", "firstId", "=", "firstId", ",", "full_urn", "=", "textId", ",", "request_urn", "=", "str", "(", "urn", ")", ")", "return", "r", ",", "200", ",", "{", "\"content-type\"", ":", "\"application/xml\"", "}" ]
Provisional route for GetFirstUrn request :param urn: URN to filter the resource :param inv: Inventory Identifier :return: GetFirstUrn response
[ "Provisional", "route", "for", "GetFirstUrn", "request" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L199-L218
Capitains/Nautilus
capitains_nautilus/apis/cts.py
CTSApi._get_label
def _get_label(self, urn): """ Provisional route for GetLabel request :param urn: URN to filter the resource :param inv: Inventory Identifier :return: GetLabel response """ node = self.resolver.getTextualNode(textId=urn) r = render_template( "cts/GetLabel.xml", request_urn=str(urn), full_urn=node.urn, metadata={ "groupname": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.groupname)], "title": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.title)], "description": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.description)], "label": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.label)] }, citation=Markup(node.citation.export(Mimetypes.XML.CTS)) ) return r, 200, {"content-type": "application/xml"}
python
def _get_label(self, urn): """ Provisional route for GetLabel request :param urn: URN to filter the resource :param inv: Inventory Identifier :return: GetLabel response """ node = self.resolver.getTextualNode(textId=urn) r = render_template( "cts/GetLabel.xml", request_urn=str(urn), full_urn=node.urn, metadata={ "groupname": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.groupname)], "title": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.title)], "description": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.description)], "label": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.label)] }, citation=Markup(node.citation.export(Mimetypes.XML.CTS)) ) return r, 200, {"content-type": "application/xml"}
[ "def", "_get_label", "(", "self", ",", "urn", ")", ":", "node", "=", "self", ".", "resolver", ".", "getTextualNode", "(", "textId", "=", "urn", ")", "r", "=", "render_template", "(", "\"cts/GetLabel.xml\"", ",", "request_urn", "=", "str", "(", "urn", ")", ",", "full_urn", "=", "node", ".", "urn", ",", "metadata", "=", "{", "\"groupname\"", ":", "[", "(", "literal", ".", "language", ",", "str", "(", "literal", ")", ")", "for", "literal", "in", "node", ".", "metadata", ".", "get", "(", "RDF_NAMESPACES", ".", "CTS", ".", "groupname", ")", "]", ",", "\"title\"", ":", "[", "(", "literal", ".", "language", ",", "str", "(", "literal", ")", ")", "for", "literal", "in", "node", ".", "metadata", ".", "get", "(", "RDF_NAMESPACES", ".", "CTS", ".", "title", ")", "]", ",", "\"description\"", ":", "[", "(", "literal", ".", "language", ",", "str", "(", "literal", ")", ")", "for", "literal", "in", "node", ".", "metadata", ".", "get", "(", "RDF_NAMESPACES", ".", "CTS", ".", "description", ")", "]", ",", "\"label\"", ":", "[", "(", "literal", ".", "language", ",", "str", "(", "literal", ")", ")", "for", "literal", "in", "node", ".", "metadata", ".", "get", "(", "RDF_NAMESPACES", ".", "CTS", ".", "label", ")", "]", "}", ",", "citation", "=", "Markup", "(", "node", ".", "citation", ".", "export", "(", "Mimetypes", ".", "XML", ".", "CTS", ")", ")", ")", "return", "r", ",", "200", ",", "{", "\"content-type\"", ":", "\"application/xml\"", "}" ]
Provisional route for GetLabel request :param urn: URN to filter the resource :param inv: Inventory Identifier :return: GetLabel response
[ "Provisional", "route", "for", "GetLabel", "request" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L220-L240
OzymandiasTheGreat/python-libinput
libinput/__init__.py
LibInput.events
def events(self): """Yield events from the internal libinput's queue. Yields device events that are subclasses of :class:`~libinput.event.Event`. Yields: :class:`~libinput.event.Event`: Device event. """ while True: events = self._selector.select() for nevent in range(len(events) + 1): self._libinput.libinput_dispatch(self._li) hevent = self._libinput.libinput_get_event(self._li) if hevent: type_ = self._libinput.libinput_event_get_type(hevent) self._libinput.libinput_dispatch(self._li) if type_.is_pointer(): yield PointerEvent(hevent, self._libinput) elif type_.is_keyboard(): yield KeyboardEvent(hevent, self._libinput) elif type_.is_touch(): yield TouchEvent(hevent, self._libinput) elif type_.is_gesture(): yield GestureEvent(hevent, self._libinput) elif type_.is_tablet_tool(): yield TabletToolEvent(hevent, self._libinput) elif type_.is_tablet_pad(): yield TabletPadEvent(hevent, self._libinput) elif type_.is_switch(): yield SwitchEvent(hevent, self._libinput) elif type_.is_device(): yield DeviceNotifyEvent(hevent, self._libinput)
python
def events(self): """Yield events from the internal libinput's queue. Yields device events that are subclasses of :class:`~libinput.event.Event`. Yields: :class:`~libinput.event.Event`: Device event. """ while True: events = self._selector.select() for nevent in range(len(events) + 1): self._libinput.libinput_dispatch(self._li) hevent = self._libinput.libinput_get_event(self._li) if hevent: type_ = self._libinput.libinput_event_get_type(hevent) self._libinput.libinput_dispatch(self._li) if type_.is_pointer(): yield PointerEvent(hevent, self._libinput) elif type_.is_keyboard(): yield KeyboardEvent(hevent, self._libinput) elif type_.is_touch(): yield TouchEvent(hevent, self._libinput) elif type_.is_gesture(): yield GestureEvent(hevent, self._libinput) elif type_.is_tablet_tool(): yield TabletToolEvent(hevent, self._libinput) elif type_.is_tablet_pad(): yield TabletPadEvent(hevent, self._libinput) elif type_.is_switch(): yield SwitchEvent(hevent, self._libinput) elif type_.is_device(): yield DeviceNotifyEvent(hevent, self._libinput)
[ "def", "events", "(", "self", ")", ":", "while", "True", ":", "events", "=", "self", ".", "_selector", ".", "select", "(", ")", "for", "nevent", "in", "range", "(", "len", "(", "events", ")", "+", "1", ")", ":", "self", ".", "_libinput", ".", "libinput_dispatch", "(", "self", ".", "_li", ")", "hevent", "=", "self", ".", "_libinput", ".", "libinput_get_event", "(", "self", ".", "_li", ")", "if", "hevent", ":", "type_", "=", "self", ".", "_libinput", ".", "libinput_event_get_type", "(", "hevent", ")", "self", ".", "_libinput", ".", "libinput_dispatch", "(", "self", ".", "_li", ")", "if", "type_", ".", "is_pointer", "(", ")", ":", "yield", "PointerEvent", "(", "hevent", ",", "self", ".", "_libinput", ")", "elif", "type_", ".", "is_keyboard", "(", ")", ":", "yield", "KeyboardEvent", "(", "hevent", ",", "self", ".", "_libinput", ")", "elif", "type_", ".", "is_touch", "(", ")", ":", "yield", "TouchEvent", "(", "hevent", ",", "self", ".", "_libinput", ")", "elif", "type_", ".", "is_gesture", "(", ")", ":", "yield", "GestureEvent", "(", "hevent", ",", "self", ".", "_libinput", ")", "elif", "type_", ".", "is_tablet_tool", "(", ")", ":", "yield", "TabletToolEvent", "(", "hevent", ",", "self", ".", "_libinput", ")", "elif", "type_", ".", "is_tablet_pad", "(", ")", ":", "yield", "TabletPadEvent", "(", "hevent", ",", "self", ".", "_libinput", ")", "elif", "type_", ".", "is_switch", "(", ")", ":", "yield", "SwitchEvent", "(", "hevent", ",", "self", ".", "_libinput", ")", "elif", "type_", ".", "is_device", "(", ")", ":", "yield", "DeviceNotifyEvent", "(", "hevent", ",", "self", ".", "_libinput", ")" ]
Yield events from the internal libinput's queue. Yields device events that are subclasses of :class:`~libinput.event.Event`. Yields: :class:`~libinput.event.Event`: Device event.
[ "Yield", "events", "from", "the", "internal", "libinput", "s", "queue", "." ]
train
https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/__init__.py#L186-L219
OzymandiasTheGreat/python-libinput
libinput/__init__.py
LibInput.next_event_type
def next_event_type(self): """Return the type of the next event in the internal queue. This method does not pop the event off the queue and the next call to :attr:`events` returns that event. Returns: ~libinput.constant.EventType: The event type of the next available event or :obj:`None` if no event is available. """ type_ = self._libinput.libinput_next_event_type(self._li) if type_ == 0: return None else: return EventType(type_)
python
def next_event_type(self): """Return the type of the next event in the internal queue. This method does not pop the event off the queue and the next call to :attr:`events` returns that event. Returns: ~libinput.constant.EventType: The event type of the next available event or :obj:`None` if no event is available. """ type_ = self._libinput.libinput_next_event_type(self._li) if type_ == 0: return None else: return EventType(type_)
[ "def", "next_event_type", "(", "self", ")", ":", "type_", "=", "self", ".", "_libinput", ".", "libinput_next_event_type", "(", "self", ".", "_li", ")", "if", "type_", "==", "0", ":", "return", "None", "else", ":", "return", "EventType", "(", "type_", ")" ]
Return the type of the next event in the internal queue. This method does not pop the event off the queue and the next call to :attr:`events` returns that event. Returns: ~libinput.constant.EventType: The event type of the next available event or :obj:`None` if no event is available.
[ "Return", "the", "type", "of", "the", "next", "event", "in", "the", "internal", "queue", "." ]
train
https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/__init__.py#L221-L236
OzymandiasTheGreat/python-libinput
libinput/__init__.py
LibInputPath.add_device
def add_device(self, path): """Add a device to a libinput context. If successful, the device will be added to the internal list and re-opened on :meth:`~libinput.LibInput.resume`. The device can be removed with :meth:`remove_device`. If the device was successfully initialized, it is returned. Args: path (str): Path to an input device. Returns: ~libinput.define.Device: A device object or :obj:`None`. """ hdevice = self._libinput.libinput_path_add_device( self._li, path.encode()) if hdevice: return Device(hdevice, self._libinput) return None
python
def add_device(self, path): """Add a device to a libinput context. If successful, the device will be added to the internal list and re-opened on :meth:`~libinput.LibInput.resume`. The device can be removed with :meth:`remove_device`. If the device was successfully initialized, it is returned. Args: path (str): Path to an input device. Returns: ~libinput.define.Device: A device object or :obj:`None`. """ hdevice = self._libinput.libinput_path_add_device( self._li, path.encode()) if hdevice: return Device(hdevice, self._libinput) return None
[ "def", "add_device", "(", "self", ",", "path", ")", ":", "hdevice", "=", "self", ".", "_libinput", ".", "libinput_path_add_device", "(", "self", ".", "_li", ",", "path", ".", "encode", "(", ")", ")", "if", "hdevice", ":", "return", "Device", "(", "hdevice", ",", "self", ".", "_libinput", ")", "return", "None" ]
Add a device to a libinput context. If successful, the device will be added to the internal list and re-opened on :meth:`~libinput.LibInput.resume`. The device can be removed with :meth:`remove_device`. If the device was successfully initialized, it is returned. Args: path (str): Path to an input device. Returns: ~libinput.define.Device: A device object or :obj:`None`.
[ "Add", "a", "device", "to", "a", "libinput", "context", "." ]
train
https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/__init__.py#L258-L276
OzymandiasTheGreat/python-libinput
libinput/__init__.py
LibInputUdev.assign_seat
def assign_seat(self, seat): """Assign a seat to this libinput context. New devices or the removal of existing devices will appear as events when iterating over :meth:`~libinput.LibInput.get_event`. :meth:`assign_seat` succeeds even if no input devices are currently available on this seat, or if devices are available but fail to open. Devices that do not have the minimum capabilities to be recognized as pointer, keyboard or touch device are ignored. Such devices and those that failed to open are ignored until the next call to :meth:`~libinput.LibInput.resume`. Warning: This method may only be called once per context. Args: seat (str): A seat identifier. """ rc = self._libinput.libinput_udev_assign_seat(self._li, seat.encode()) assert rc == 0, 'Failed to assign {}'.format(seat)
python
def assign_seat(self, seat): """Assign a seat to this libinput context. New devices or the removal of existing devices will appear as events when iterating over :meth:`~libinput.LibInput.get_event`. :meth:`assign_seat` succeeds even if no input devices are currently available on this seat, or if devices are available but fail to open. Devices that do not have the minimum capabilities to be recognized as pointer, keyboard or touch device are ignored. Such devices and those that failed to open are ignored until the next call to :meth:`~libinput.LibInput.resume`. Warning: This method may only be called once per context. Args: seat (str): A seat identifier. """ rc = self._libinput.libinput_udev_assign_seat(self._li, seat.encode()) assert rc == 0, 'Failed to assign {}'.format(seat)
[ "def", "assign_seat", "(", "self", ",", "seat", ")", ":", "rc", "=", "self", ".", "_libinput", ".", "libinput_udev_assign_seat", "(", "self", ".", "_li", ",", "seat", ".", "encode", "(", ")", ")", "assert", "rc", "==", "0", ",", "'Failed to assign {}'", ".", "format", "(", "seat", ")" ]
Assign a seat to this libinput context. New devices or the removal of existing devices will appear as events when iterating over :meth:`~libinput.LibInput.get_event`. :meth:`assign_seat` succeeds even if no input devices are currently available on this seat, or if devices are available but fail to open. Devices that do not have the minimum capabilities to be recognized as pointer, keyboard or touch device are ignored. Such devices and those that failed to open are ignored until the next call to :meth:`~libinput.LibInput.resume`. Warning: This method may only be called once per context. Args: seat (str): A seat identifier.
[ "Assign", "a", "seat", "to", "this", "libinput", "context", "." ]
train
https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/__init__.py#L317-L337
BlueBrain/hpcbench
hpcbench/api.py
MetricsExtractor.context
def context(self, outdir, log_prefix): """Setup instance to extract metrics from the proper run :param outdir: run directory :param log_prefix: log filenames prefix """ try: self._outdir = outdir self._log_prefix = log_prefix yield finally: self._log_prefix = None self._outdir = None
python
def context(self, outdir, log_prefix): """Setup instance to extract metrics from the proper run :param outdir: run directory :param log_prefix: log filenames prefix """ try: self._outdir = outdir self._log_prefix = log_prefix yield finally: self._log_prefix = None self._outdir = None
[ "def", "context", "(", "self", ",", "outdir", ",", "log_prefix", ")", ":", "try", ":", "self", ".", "_outdir", "=", "outdir", "self", ".", "_log_prefix", "=", "log_prefix", "yield", "finally", ":", "self", ".", "_log_prefix", "=", "None", "self", ".", "_outdir", "=", "None" ]
Setup instance to extract metrics from the proper run :param outdir: run directory :param log_prefix: log filenames prefix
[ "Setup", "instance", "to", "extract", "metrics", "from", "the", "proper", "run" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/api.py#L117-L129
BlueBrain/hpcbench
hpcbench/api.py
Benchmark.get_subclass
def get_subclass(cls, name): """Get Benchmark subclass by name :param name: name returned by ``Benchmark.name`` property :return: instance of ``Benchmark`` class """ for subclass in cls.__subclasses__(): if subclass.name == name: return subclass raise NameError("Not a valid Benchmark class: " + name)
python
def get_subclass(cls, name): """Get Benchmark subclass by name :param name: name returned by ``Benchmark.name`` property :return: instance of ``Benchmark`` class """ for subclass in cls.__subclasses__(): if subclass.name == name: return subclass raise NameError("Not a valid Benchmark class: " + name)
[ "def", "get_subclass", "(", "cls", ",", "name", ")", ":", "for", "subclass", "in", "cls", ".", "__subclasses__", "(", ")", ":", "if", "subclass", ".", "name", "==", "name", ":", "return", "subclass", "raise", "NameError", "(", "\"Not a valid Benchmark class: \"", "+", "name", ")" ]
Get Benchmark subclass by name :param name: name returned by ``Benchmark.name`` property :return: instance of ``Benchmark`` class
[ "Get", "Benchmark", "subclass", "by", "name", ":", "param", "name", ":", "name", "returned", "by", "Benchmark", ".", "name", "property", ":", "return", ":", "instance", "of", "Benchmark", "class" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/api.py#L355-L363
sci-bots/svg-model
svg_model/detect_connections.py
auto_detect_adjacent_shapes
def auto_detect_adjacent_shapes(svg_source, shape_i_attr='id', layer_name='Connections', shapes_xpath='//svg:path | //svg:polygon', extend=1.5): ''' Attempt to automatically find "adjacent" shapes in a SVG layer. In a layer within a new SVG document, draw each detected connection between the center points of the corresponding shapes. Parameters ---------- svg_source : str Input SVG file as a filepath (or file-like object). shape_i_attr : str, optional Attribute of each shape SVG element that uniquely identifies the shape. layer_name : str, optional Name to use for the output layer where detected connections are drawn. .. note:: Any existing layer with the same name will be overwritten. shapes_xpath : str, optional XPath path expression to select shape nodes. By default, all ``svg:path`` and ``svg:polygon`` elements are selected. extend : float, optional Extend ``x``/``y`` coords by the specified number of absolute units from the center point of each shape. Each shape is stretched independently in the ``x`` and ``y`` direction. In each direction, a shape is considered adjacent to all other shapes that are overlapped by the extended shape. Returns ------- StringIO.StringIO File-like object containing SVG document with layer named according to :data:`layer_name` with the detected connections drawn as ``svg:line`` instances. ''' # Read SVG polygons into dataframe, one row per polygon vertex. df_shapes = svg_shapes_to_df(svg_source, xpath=shapes_xpath) df_shapes = compute_shape_centers(df_shapes, shape_i_attr) df_shape_connections = extract_adjacent_shapes(df_shapes, shape_i_attr, extend=extend) # Parse input file. xml_root = etree.parse(svg_source) svg_root = xml_root.xpath('/svg:svg', namespaces=INKSCAPE_NSMAP)[0] # Get the center coordinate of each shape. df_shape_centers = (df_shapes.drop_duplicates(subset=[shape_i_attr]) [[shape_i_attr] + ['x_center', 'y_center']] .set_index(shape_i_attr)) # Get the center coordinate of the shapes corresponding to the two # endpoints of each connection. df_connection_centers = (df_shape_centers.loc[df_shape_connections.source] .reset_index(drop=True) .join(df_shape_centers.loc[df_shape_connections .target] .reset_index(drop=True), lsuffix='_source', rsuffix='_target')) # Remove existing connections layer from source, in-memory XML (source file # remains unmodified). A new connections layer will be added below. connections_xpath = '//svg:g[@inkscape:label="%s"]' % layer_name connections_groups = svg_root.xpath(connections_xpath, namespaces=INKSCAPE_NSMAP) if connections_groups: for g in connections_groups: g.getparent().remove(g) # Create in-memory SVG svg_output = \ draw_lines_svg_layer(df_connection_centers .rename(columns={'x_center_source': 'x_source', 'y_center_source': 'y_source', 'x_center_target': 'x_target', 'y_center_target': 'y_target'}), layer_name=layer_name) return svg_output
python
def auto_detect_adjacent_shapes(svg_source, shape_i_attr='id', layer_name='Connections', shapes_xpath='//svg:path | //svg:polygon', extend=1.5): ''' Attempt to automatically find "adjacent" shapes in a SVG layer. In a layer within a new SVG document, draw each detected connection between the center points of the corresponding shapes. Parameters ---------- svg_source : str Input SVG file as a filepath (or file-like object). shape_i_attr : str, optional Attribute of each shape SVG element that uniquely identifies the shape. layer_name : str, optional Name to use for the output layer where detected connections are drawn. .. note:: Any existing layer with the same name will be overwritten. shapes_xpath : str, optional XPath path expression to select shape nodes. By default, all ``svg:path`` and ``svg:polygon`` elements are selected. extend : float, optional Extend ``x``/``y`` coords by the specified number of absolute units from the center point of each shape. Each shape is stretched independently in the ``x`` and ``y`` direction. In each direction, a shape is considered adjacent to all other shapes that are overlapped by the extended shape. Returns ------- StringIO.StringIO File-like object containing SVG document with layer named according to :data:`layer_name` with the detected connections drawn as ``svg:line`` instances. ''' # Read SVG polygons into dataframe, one row per polygon vertex. df_shapes = svg_shapes_to_df(svg_source, xpath=shapes_xpath) df_shapes = compute_shape_centers(df_shapes, shape_i_attr) df_shape_connections = extract_adjacent_shapes(df_shapes, shape_i_attr, extend=extend) # Parse input file. xml_root = etree.parse(svg_source) svg_root = xml_root.xpath('/svg:svg', namespaces=INKSCAPE_NSMAP)[0] # Get the center coordinate of each shape. df_shape_centers = (df_shapes.drop_duplicates(subset=[shape_i_attr]) [[shape_i_attr] + ['x_center', 'y_center']] .set_index(shape_i_attr)) # Get the center coordinate of the shapes corresponding to the two # endpoints of each connection. df_connection_centers = (df_shape_centers.loc[df_shape_connections.source] .reset_index(drop=True) .join(df_shape_centers.loc[df_shape_connections .target] .reset_index(drop=True), lsuffix='_source', rsuffix='_target')) # Remove existing connections layer from source, in-memory XML (source file # remains unmodified). A new connections layer will be added below. connections_xpath = '//svg:g[@inkscape:label="%s"]' % layer_name connections_groups = svg_root.xpath(connections_xpath, namespaces=INKSCAPE_NSMAP) if connections_groups: for g in connections_groups: g.getparent().remove(g) # Create in-memory SVG svg_output = \ draw_lines_svg_layer(df_connection_centers .rename(columns={'x_center_source': 'x_source', 'y_center_source': 'y_source', 'x_center_target': 'x_target', 'y_center_target': 'y_target'}), layer_name=layer_name) return svg_output
[ "def", "auto_detect_adjacent_shapes", "(", "svg_source", ",", "shape_i_attr", "=", "'id'", ",", "layer_name", "=", "'Connections'", ",", "shapes_xpath", "=", "'//svg:path | //svg:polygon'", ",", "extend", "=", "1.5", ")", ":", "# Read SVG polygons into dataframe, one row per polygon vertex.", "df_shapes", "=", "svg_shapes_to_df", "(", "svg_source", ",", "xpath", "=", "shapes_xpath", ")", "df_shapes", "=", "compute_shape_centers", "(", "df_shapes", ",", "shape_i_attr", ")", "df_shape_connections", "=", "extract_adjacent_shapes", "(", "df_shapes", ",", "shape_i_attr", ",", "extend", "=", "extend", ")", "# Parse input file.", "xml_root", "=", "etree", ".", "parse", "(", "svg_source", ")", "svg_root", "=", "xml_root", ".", "xpath", "(", "'/svg:svg'", ",", "namespaces", "=", "INKSCAPE_NSMAP", ")", "[", "0", "]", "# Get the center coordinate of each shape.", "df_shape_centers", "=", "(", "df_shapes", ".", "drop_duplicates", "(", "subset", "=", "[", "shape_i_attr", "]", ")", "[", "[", "shape_i_attr", "]", "+", "[", "'x_center'", ",", "'y_center'", "]", "]", ".", "set_index", "(", "shape_i_attr", ")", ")", "# Get the center coordinate of the shapes corresponding to the two", "# endpoints of each connection.", "df_connection_centers", "=", "(", "df_shape_centers", ".", "loc", "[", "df_shape_connections", ".", "source", "]", ".", "reset_index", "(", "drop", "=", "True", ")", ".", "join", "(", "df_shape_centers", ".", "loc", "[", "df_shape_connections", ".", "target", "]", ".", "reset_index", "(", "drop", "=", "True", ")", ",", "lsuffix", "=", "'_source'", ",", "rsuffix", "=", "'_target'", ")", ")", "# Remove existing connections layer from source, in-memory XML (source file", "# remains unmodified). A new connections layer will be added below.", "connections_xpath", "=", "'//svg:g[@inkscape:label=\"%s\"]'", "%", "layer_name", "connections_groups", "=", "svg_root", ".", "xpath", "(", "connections_xpath", ",", "namespaces", "=", "INKSCAPE_NSMAP", ")", "if", "connections_groups", ":", "for", "g", "in", "connections_groups", ":", "g", ".", "getparent", "(", ")", ".", "remove", "(", "g", ")", "# Create in-memory SVG", "svg_output", "=", "draw_lines_svg_layer", "(", "df_connection_centers", ".", "rename", "(", "columns", "=", "{", "'x_center_source'", ":", "'x_source'", ",", "'y_center_source'", ":", "'y_source'", ",", "'x_center_target'", ":", "'x_target'", ",", "'y_center_target'", ":", "'y_target'", "}", ")", ",", "layer_name", "=", "layer_name", ")", "return", "svg_output" ]
Attempt to automatically find "adjacent" shapes in a SVG layer. In a layer within a new SVG document, draw each detected connection between the center points of the corresponding shapes. Parameters ---------- svg_source : str Input SVG file as a filepath (or file-like object). shape_i_attr : str, optional Attribute of each shape SVG element that uniquely identifies the shape. layer_name : str, optional Name to use for the output layer where detected connections are drawn. .. note:: Any existing layer with the same name will be overwritten. shapes_xpath : str, optional XPath path expression to select shape nodes. By default, all ``svg:path`` and ``svg:polygon`` elements are selected. extend : float, optional Extend ``x``/``y`` coords by the specified number of absolute units from the center point of each shape. Each shape is stretched independently in the ``x`` and ``y`` direction. In each direction, a shape is considered adjacent to all other shapes that are overlapped by the extended shape. Returns ------- StringIO.StringIO File-like object containing SVG document with layer named according to :data:`layer_name` with the detected connections drawn as ``svg:line`` instances.
[ "Attempt", "to", "automatically", "find", "adjacent", "shapes", "in", "a", "SVG", "layer", "." ]
train
https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/detect_connections.py#L13-L95
BlueBrain/hpcbench
hpcbench/toolbox/collections_ext.py
flatten_dict
def flatten_dict(dic, parent_key='', sep='.'): """Flatten sub-keys of a dictionary """ items = [] for key, value in dic.items(): new_key = parent_key + sep + key if parent_key else key if isinstance(value, collections.MutableMapping): items.extend(flatten_dict(value, new_key, sep=sep).items()) elif isinstance(value, list): for idx, elt in enumerate(value): items.extend( flatten_dict(elt, new_key + sep + str(idx), sep=sep).items() ) else: items.append((new_key, value)) return dict(items)
python
def flatten_dict(dic, parent_key='', sep='.'): """Flatten sub-keys of a dictionary """ items = [] for key, value in dic.items(): new_key = parent_key + sep + key if parent_key else key if isinstance(value, collections.MutableMapping): items.extend(flatten_dict(value, new_key, sep=sep).items()) elif isinstance(value, list): for idx, elt in enumerate(value): items.extend( flatten_dict(elt, new_key + sep + str(idx), sep=sep).items() ) else: items.append((new_key, value)) return dict(items)
[ "def", "flatten_dict", "(", "dic", ",", "parent_key", "=", "''", ",", "sep", "=", "'.'", ")", ":", "items", "=", "[", "]", "for", "key", ",", "value", "in", "dic", ".", "items", "(", ")", ":", "new_key", "=", "parent_key", "+", "sep", "+", "key", "if", "parent_key", "else", "key", "if", "isinstance", "(", "value", ",", "collections", ".", "MutableMapping", ")", ":", "items", ".", "extend", "(", "flatten_dict", "(", "value", ",", "new_key", ",", "sep", "=", "sep", ")", ".", "items", "(", ")", ")", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "for", "idx", ",", "elt", "in", "enumerate", "(", "value", ")", ":", "items", ".", "extend", "(", "flatten_dict", "(", "elt", ",", "new_key", "+", "sep", "+", "str", "(", "idx", ")", ",", "sep", "=", "sep", ")", ".", "items", "(", ")", ")", "else", ":", "items", ".", "append", "(", "(", "new_key", ",", "value", ")", ")", "return", "dict", "(", "items", ")" ]
Flatten sub-keys of a dictionary
[ "Flatten", "sub", "-", "keys", "of", "a", "dictionary" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/collections_ext.py#L103-L118
BlueBrain/hpcbench
hpcbench/toolbox/collections_ext.py
dict_merge
def dict_merge(dct, merge_dct): """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``merge_dct`` is merged into ``dct``. :param dct: dict onto which the merge is executed :param merge_dct: dct merged into dct :return: None """ for key in merge_dct.keys(): if ( key in dct and isinstance(dct[key], dict) and isinstance(merge_dct[key], collections.Mapping) ): dict_merge(dct[key], merge_dct[key]) else: dct[key] = merge_dct[key]
python
def dict_merge(dct, merge_dct): """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``merge_dct`` is merged into ``dct``. :param dct: dict onto which the merge is executed :param merge_dct: dct merged into dct :return: None """ for key in merge_dct.keys(): if ( key in dct and isinstance(dct[key], dict) and isinstance(merge_dct[key], collections.Mapping) ): dict_merge(dct[key], merge_dct[key]) else: dct[key] = merge_dct[key]
[ "def", "dict_merge", "(", "dct", ",", "merge_dct", ")", ":", "for", "key", "in", "merge_dct", ".", "keys", "(", ")", ":", "if", "(", "key", "in", "dct", "and", "isinstance", "(", "dct", "[", "key", "]", ",", "dict", ")", "and", "isinstance", "(", "merge_dct", "[", "key", "]", ",", "collections", ".", "Mapping", ")", ")", ":", "dict_merge", "(", "dct", "[", "key", "]", ",", "merge_dct", "[", "key", "]", ")", "else", ":", "dct", "[", "key", "]", "=", "merge_dct", "[", "key", "]" ]
Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``merge_dct`` is merged into ``dct``. :param dct: dict onto which the merge is executed :param merge_dct: dct merged into dct :return: None
[ "Recursive", "dict", "merge", ".", "Inspired", "by", ":", "meth", ":", "dict", ".", "update", "()", "instead", "of", "updating", "only", "top", "-", "level", "keys", "dict_merge", "recurses", "down", "into", "dicts", "nested", "to", "an", "arbitrary", "depth", "updating", "keys", ".", "The", "merge_dct", "is", "merged", "into", "dct", ".", ":", "param", "dct", ":", "dict", "onto", "which", "the", "merge", "is", "executed", ":", "param", "merge_dct", ":", "dct", "merged", "into", "dct", ":", "return", ":", "None" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/collections_ext.py#L121-L138
BlueBrain/hpcbench
hpcbench/toolbox/collections_ext.py
freeze
def freeze(obj): """Transform tree of dict and list in read-only data structure. dict instances are transformed to FrozenDict, lists in FrozenList. """ if isinstance(obj, collections.Mapping): return FrozenDict({freeze(k): freeze(v) for k, v in six.iteritems(obj)}) elif isinstance(obj, list): return FrozenList([freeze(e) for e in obj]) else: return obj
python
def freeze(obj): """Transform tree of dict and list in read-only data structure. dict instances are transformed to FrozenDict, lists in FrozenList. """ if isinstance(obj, collections.Mapping): return FrozenDict({freeze(k): freeze(v) for k, v in six.iteritems(obj)}) elif isinstance(obj, list): return FrozenList([freeze(e) for e in obj]) else: return obj
[ "def", "freeze", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "collections", ".", "Mapping", ")", ":", "return", "FrozenDict", "(", "{", "freeze", "(", "k", ")", ":", "freeze", "(", "v", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "obj", ")", "}", ")", "elif", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "FrozenList", "(", "[", "freeze", "(", "e", ")", "for", "e", "in", "obj", "]", ")", "else", ":", "return", "obj" ]
Transform tree of dict and list in read-only data structure. dict instances are transformed to FrozenDict, lists in FrozenList.
[ "Transform", "tree", "of", "dict", "and", "list", "in", "read", "-", "only", "data", "structure", ".", "dict", "instances", "are", "transformed", "to", "FrozenDict", "lists", "in", "FrozenList", "." ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/collections_ext.py#L232-L243
BlueBrain/hpcbench
hpcbench/toolbox/collections_ext.py
Configuration.from_file
def from_file(cls, path): """Create a ``Configuration`` from a file :param path: path to YAML file :return: new configuration :rtype: ``Configuration`` """ if path == '-': return Configuration(yaml.safe_load(sys.stdin)) if not osp.exists(path) and not osp.isabs(path): path = osp.join(osp.dirname(osp.abspath(__file__)), path) with open(path, 'r') as istr: return Configuration(yaml.safe_load(istr))
python
def from_file(cls, path): """Create a ``Configuration`` from a file :param path: path to YAML file :return: new configuration :rtype: ``Configuration`` """ if path == '-': return Configuration(yaml.safe_load(sys.stdin)) if not osp.exists(path) and not osp.isabs(path): path = osp.join(osp.dirname(osp.abspath(__file__)), path) with open(path, 'r') as istr: return Configuration(yaml.safe_load(istr))
[ "def", "from_file", "(", "cls", ",", "path", ")", ":", "if", "path", "==", "'-'", ":", "return", "Configuration", "(", "yaml", ".", "safe_load", "(", "sys", ".", "stdin", ")", ")", "if", "not", "osp", ".", "exists", "(", "path", ")", "and", "not", "osp", ".", "isabs", "(", "path", ")", ":", "path", "=", "osp", ".", "join", "(", "osp", ".", "dirname", "(", "osp", ".", "abspath", "(", "__file__", ")", ")", ",", "path", ")", "with", "open", "(", "path", ",", "'r'", ")", "as", "istr", ":", "return", "Configuration", "(", "yaml", ".", "safe_load", "(", "istr", ")", ")" ]
Create a ``Configuration`` from a file :param path: path to YAML file :return: new configuration :rtype: ``Configuration``
[ "Create", "a", "Configuration", "from", "a", "file" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/collections_ext.py#L59-L71
sci-bots/svg-model
svg_model/color.py
hex_color_to_rgba
def hex_color_to_rgba(hex_color, normalize_to=255): ''' Convert a hex-formatted number (i.e., `"#RGB[A]"` or `"#RRGGBB[AA]"`) to an RGBA tuple (i.e., `(<r>, <g>, <b>, <a>)`). Args: hex_color (str) : hex-formatted number (e.g., `"#2fc"`, `"#3c2f8611"`) normalize_to (int, float) : Factor to normalize each channel by Returns: (tuple) : RGBA tuple (i.e., `(<r>, <g>, <b>, <a>)`), where range of each channel in tuple is `[0, normalize_to]`. ''' color_pattern_one_digit = (r'#(?P<R>[\da-fA-F])(?P<G>[\da-fA-F])' r'(?P<B>[\da-fA-F])(?P<A>[\da-fA-F])?') color_pattern_two_digit = (r'#(?P<R>[\da-fA-F]{2})(?P<G>[\da-fA-F]{2})' r'(?P<B>[\da-fA-F]{2})(?P<A>[\da-fA-F]{2})?') # First try to match `#rrggbb[aa]`. match = re.match(color_pattern_two_digit, hex_color) if match: channels = match.groupdict() channel_scale = 255 else: # Try to match `#rgb[a]`. match = re.match(color_pattern_one_digit, hex_color) if match: channels = match.groupdict() channel_scale = 15 else: raise ValueError('Color string must be in format #RGB[A] or ' '#RRGGBB[AA] (i.e., alpha channel is optional)') scale = normalize_to / channel_scale return tuple(type(normalize_to)(int(channels[k], 16) * scale) if channels[k] is not None else None for k in 'RGBA')
python
def hex_color_to_rgba(hex_color, normalize_to=255): ''' Convert a hex-formatted number (i.e., `"#RGB[A]"` or `"#RRGGBB[AA]"`) to an RGBA tuple (i.e., `(<r>, <g>, <b>, <a>)`). Args: hex_color (str) : hex-formatted number (e.g., `"#2fc"`, `"#3c2f8611"`) normalize_to (int, float) : Factor to normalize each channel by Returns: (tuple) : RGBA tuple (i.e., `(<r>, <g>, <b>, <a>)`), where range of each channel in tuple is `[0, normalize_to]`. ''' color_pattern_one_digit = (r'#(?P<R>[\da-fA-F])(?P<G>[\da-fA-F])' r'(?P<B>[\da-fA-F])(?P<A>[\da-fA-F])?') color_pattern_two_digit = (r'#(?P<R>[\da-fA-F]{2})(?P<G>[\da-fA-F]{2})' r'(?P<B>[\da-fA-F]{2})(?P<A>[\da-fA-F]{2})?') # First try to match `#rrggbb[aa]`. match = re.match(color_pattern_two_digit, hex_color) if match: channels = match.groupdict() channel_scale = 255 else: # Try to match `#rgb[a]`. match = re.match(color_pattern_one_digit, hex_color) if match: channels = match.groupdict() channel_scale = 15 else: raise ValueError('Color string must be in format #RGB[A] or ' '#RRGGBB[AA] (i.e., alpha channel is optional)') scale = normalize_to / channel_scale return tuple(type(normalize_to)(int(channels[k], 16) * scale) if channels[k] is not None else None for k in 'RGBA')
[ "def", "hex_color_to_rgba", "(", "hex_color", ",", "normalize_to", "=", "255", ")", ":", "color_pattern_one_digit", "=", "(", "r'#(?P<R>[\\da-fA-F])(?P<G>[\\da-fA-F])'", "r'(?P<B>[\\da-fA-F])(?P<A>[\\da-fA-F])?'", ")", "color_pattern_two_digit", "=", "(", "r'#(?P<R>[\\da-fA-F]{2})(?P<G>[\\da-fA-F]{2})'", "r'(?P<B>[\\da-fA-F]{2})(?P<A>[\\da-fA-F]{2})?'", ")", "# First try to match `#rrggbb[aa]`.", "match", "=", "re", ".", "match", "(", "color_pattern_two_digit", ",", "hex_color", ")", "if", "match", ":", "channels", "=", "match", ".", "groupdict", "(", ")", "channel_scale", "=", "255", "else", ":", "# Try to match `#rgb[a]`.", "match", "=", "re", ".", "match", "(", "color_pattern_one_digit", ",", "hex_color", ")", "if", "match", ":", "channels", "=", "match", ".", "groupdict", "(", ")", "channel_scale", "=", "15", "else", ":", "raise", "ValueError", "(", "'Color string must be in format #RGB[A] or '", "'#RRGGBB[AA] (i.e., alpha channel is optional)'", ")", "scale", "=", "normalize_to", "/", "channel_scale", "return", "tuple", "(", "type", "(", "normalize_to", ")", "(", "int", "(", "channels", "[", "k", "]", ",", "16", ")", "*", "scale", ")", "if", "channels", "[", "k", "]", "is", "not", "None", "else", "None", "for", "k", "in", "'RGBA'", ")" ]
Convert a hex-formatted number (i.e., `"#RGB[A]"` or `"#RRGGBB[AA]"`) to an RGBA tuple (i.e., `(<r>, <g>, <b>, <a>)`). Args: hex_color (str) : hex-formatted number (e.g., `"#2fc"`, `"#3c2f8611"`) normalize_to (int, float) : Factor to normalize each channel by Returns: (tuple) : RGBA tuple (i.e., `(<r>, <g>, <b>, <a>)`), where range of each channel in tuple is `[0, normalize_to]`.
[ "Convert", "a", "hex", "-", "formatted", "number", "(", "i", ".", "e", ".", "#RGB", "[", "A", "]", "or", "#RRGGBB", "[", "AA", "]", ")", "to", "an", "RGBA", "tuple", "(", "i", ".", "e", ".", "(", "<r", ">", "<g", ">", "<b", ">", "<a", ">", ")", ")", "." ]
train
https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/color.py#L7-L46
Metatab/metatab
metatab/terms.py
Term.split_term
def split_term(cls, term): """ Split a term in to parent and record term components :param term: combined term text :return: Tuple of parent and record term """ if '.' in term: parent_term, record_term = term.split('.') parent_term, record_term = parent_term.strip(), record_term.strip() if parent_term == '': parent_term = ELIDED_TERM else: parent_term, record_term = ROOT_TERM, term.strip() return parent_term, record_term
python
def split_term(cls, term): """ Split a term in to parent and record term components :param term: combined term text :return: Tuple of parent and record term """ if '.' in term: parent_term, record_term = term.split('.') parent_term, record_term = parent_term.strip(), record_term.strip() if parent_term == '': parent_term = ELIDED_TERM else: parent_term, record_term = ROOT_TERM, term.strip() return parent_term, record_term
[ "def", "split_term", "(", "cls", ",", "term", ")", ":", "if", "'.'", "in", "term", ":", "parent_term", ",", "record_term", "=", "term", ".", "split", "(", "'.'", ")", "parent_term", ",", "record_term", "=", "parent_term", ".", "strip", "(", ")", ",", "record_term", ".", "strip", "(", ")", "if", "parent_term", "==", "''", ":", "parent_term", "=", "ELIDED_TERM", "else", ":", "parent_term", ",", "record_term", "=", "ROOT_TERM", ",", "term", ".", "strip", "(", ")", "return", "parent_term", ",", "record_term" ]
Split a term in to parent and record term components :param term: combined term text :return: Tuple of parent and record term
[ "Split", "a", "term", "in", "to", "parent", "and", "record", "term", "components", ":", "param", "term", ":", "combined", "term", "text", ":", "return", ":", "Tuple", "of", "parent", "and", "record", "term" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L122-L139
Metatab/metatab
metatab/terms.py
Term.split_term_lower
def split_term_lower(cls, term): """ Like split_term, but also lowercases both parent and record term :param term: combined term text :return: Tuple of parent and record term """ return tuple(e.lower() for e in Term.split_term(term))
python
def split_term_lower(cls, term): """ Like split_term, but also lowercases both parent and record term :param term: combined term text :return: Tuple of parent and record term """ return tuple(e.lower() for e in Term.split_term(term))
[ "def", "split_term_lower", "(", "cls", ",", "term", ")", ":", "return", "tuple", "(", "e", ".", "lower", "(", ")", "for", "e", "in", "Term", ".", "split_term", "(", "term", ")", ")" ]
Like split_term, but also lowercases both parent and record term :param term: combined term text :return: Tuple of parent and record term
[ "Like", "split_term", "but", "also", "lowercases", "both", "parent", "and", "record", "term", ":", "param", "term", ":", "combined", "term", "text", ":", "return", ":", "Tuple", "of", "parent", "and", "record", "term" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L142-L150
Metatab/metatab
metatab/terms.py
Term.file_ref
def file_ref(self): """Return a string for the file, row and column of the term.""" from metatab.util import slugify assert self.file_name is None or isinstance(self.file_name, str) if self.file_name is not None and self.row is not None: parts = split(self.file_name); return "{} {}:{} ".format(parts[-1], self.row, self.col) elif self.row is not None: return " {}:{} ".format(self.row, self.col) else: return ''
python
def file_ref(self): """Return a string for the file, row and column of the term.""" from metatab.util import slugify assert self.file_name is None or isinstance(self.file_name, str) if self.file_name is not None and self.row is not None: parts = split(self.file_name); return "{} {}:{} ".format(parts[-1], self.row, self.col) elif self.row is not None: return " {}:{} ".format(self.row, self.col) else: return ''
[ "def", "file_ref", "(", "self", ")", ":", "from", "metatab", ".", "util", "import", "slugify", "assert", "self", ".", "file_name", "is", "None", "or", "isinstance", "(", "self", ".", "file_name", ",", "str", ")", "if", "self", ".", "file_name", "is", "not", "None", "and", "self", ".", "row", "is", "not", "None", ":", "parts", "=", "split", "(", "self", ".", "file_name", ")", "return", "\"{} {}:{} \"", ".", "format", "(", "parts", "[", "-", "1", "]", ",", "self", ".", "row", ",", "self", ".", "col", ")", "elif", "self", ".", "row", "is", "not", "None", ":", "return", "\" {}:{} \"", ".", "format", "(", "self", ".", "row", ",", "self", ".", "col", ")", "else", ":", "return", "''" ]
Return a string for the file, row and column of the term.
[ "Return", "a", "string", "for", "the", "file", "row", "and", "column", "of", "the", "term", "." ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L152-L164
Metatab/metatab
metatab/terms.py
Term.add_child
def add_child(self, child): """Add a term to this term's children. Also sets the child term's parent""" assert isinstance(child, Term) self.children.append(child) child.parent = self assert not child.term_is("Datafile.Section")
python
def add_child(self, child): """Add a term to this term's children. Also sets the child term's parent""" assert isinstance(child, Term) self.children.append(child) child.parent = self assert not child.term_is("Datafile.Section")
[ "def", "add_child", "(", "self", ",", "child", ")", ":", "assert", "isinstance", "(", "child", ",", "Term", ")", "self", ".", "children", ".", "append", "(", "child", ")", "child", ".", "parent", "=", "self", "assert", "not", "child", ".", "term_is", "(", "\"Datafile.Section\"", ")" ]
Add a term to this term's children. Also sets the child term's parent
[ "Add", "a", "term", "to", "this", "term", "s", "children", ".", "Also", "sets", "the", "child", "term", "s", "parent" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L166-L171
Metatab/metatab
metatab/terms.py
Term.new_child
def new_child(self, term, value, **kwargs): """Create a new term and add it to this term as a child. Creates grandchildren from the kwargs. :param term: term name. Just the record term :param term: Value to assign to the term :param term: Term properties, which create children of the child term. """ tc = self.doc.get_term_class(term.lower()) c = tc(term, str(value) if value is not None else None, parent=self, doc=self.doc, section=self.section).new_children(**kwargs) c.term_value_name = self.doc.decl_terms.get(c.join, {}).get('termvaluename', c.term_value_name) assert not c.term_is("*.Section") self.children.append(c) return c
python
def new_child(self, term, value, **kwargs): """Create a new term and add it to this term as a child. Creates grandchildren from the kwargs. :param term: term name. Just the record term :param term: Value to assign to the term :param term: Term properties, which create children of the child term. """ tc = self.doc.get_term_class(term.lower()) c = tc(term, str(value) if value is not None else None, parent=self, doc=self.doc, section=self.section).new_children(**kwargs) c.term_value_name = self.doc.decl_terms.get(c.join, {}).get('termvaluename', c.term_value_name) assert not c.term_is("*.Section") self.children.append(c) return c
[ "def", "new_child", "(", "self", ",", "term", ",", "value", ",", "*", "*", "kwargs", ")", ":", "tc", "=", "self", ".", "doc", ".", "get_term_class", "(", "term", ".", "lower", "(", ")", ")", "c", "=", "tc", "(", "term", ",", "str", "(", "value", ")", "if", "value", "is", "not", "None", "else", "None", ",", "parent", "=", "self", ",", "doc", "=", "self", ".", "doc", ",", "section", "=", "self", ".", "section", ")", ".", "new_children", "(", "*", "*", "kwargs", ")", "c", ".", "term_value_name", "=", "self", ".", "doc", ".", "decl_terms", ".", "get", "(", "c", ".", "join", ",", "{", "}", ")", ".", "get", "(", "'termvaluename'", ",", "c", ".", "term_value_name", ")", "assert", "not", "c", ".", "term_is", "(", "\"*.Section\"", ")", "self", ".", "children", ".", "append", "(", "c", ")", "return", "c" ]
Create a new term and add it to this term as a child. Creates grandchildren from the kwargs. :param term: term name. Just the record term :param term: Value to assign to the term :param term: Term properties, which create children of the child term.
[ "Create", "a", "new", "term", "and", "add", "it", "to", "this", "term", "as", "a", "child", ".", "Creates", "grandchildren", "from", "the", "kwargs", "." ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L173-L191
Metatab/metatab
metatab/terms.py
Term.remove_child
def remove_child(self, child): """Remove the term from this term's children. """ assert isinstance(child, Term) self.children.remove(child) self.doc.remove_term(child)
python
def remove_child(self, child): """Remove the term from this term's children. """ assert isinstance(child, Term) self.children.remove(child) self.doc.remove_term(child)
[ "def", "remove_child", "(", "self", ",", "child", ")", ":", "assert", "isinstance", "(", "child", ",", "Term", ")", "self", ".", "children", ".", "remove", "(", "child", ")", "self", ".", "doc", ".", "remove_term", "(", "child", ")" ]
Remove the term from this term's children.
[ "Remove", "the", "term", "from", "this", "term", "s", "children", "." ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L193-L197
Metatab/metatab
metatab/terms.py
Term.new_children
def new_children(self, **kwargs): """Create new children from kwargs""" for k, v in kwargs.items(): self.new_child(k, v) return self
python
def new_children(self, **kwargs): """Create new children from kwargs""" for k, v in kwargs.items(): self.new_child(k, v) return self
[ "def", "new_children", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "self", ".", "new_child", "(", "k", ",", "v", ")", "return", "self" ]
Create new children from kwargs
[ "Create", "new", "children", "from", "kwargs" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L199-L204
Metatab/metatab
metatab/terms.py
Term.set_ownership
def set_ownership(self): """Recursivelt set the parent, section and doc for a children""" assert self.section is not None for t in self.children: t.parent = self t._section = self.section t.doc = self.doc t.set_ownership()
python
def set_ownership(self): """Recursivelt set the parent, section and doc for a children""" assert self.section is not None for t in self.children: t.parent = self t._section = self.section t.doc = self.doc t.set_ownership()
[ "def", "set_ownership", "(", "self", ")", ":", "assert", "self", ".", "section", "is", "not", "None", "for", "t", "in", "self", ".", "children", ":", "t", ".", "parent", "=", "self", "t", ".", "_section", "=", "self", ".", "section", "t", ".", "doc", "=", "self", ".", "doc", "t", ".", "set_ownership", "(", ")" ]
Recursivelt set the parent, section and doc for a children
[ "Recursivelt", "set", "the", "parent", "section", "and", "doc", "for", "a", "children" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L206-L214
Metatab/metatab
metatab/terms.py
Term.find
def find(self, term, value=False): """Return a terms by name. If the name is not qualified, use this term's record name for the parent. The method will yield all terms with a matching qualified name. """ if '.' in term: parent, term = term.split('.') assert parent.lower() == self.record_term_lc, (parent.lower(), self.record_term_lc) for c in self.children: if c.record_term_lc == term.lower(): if value is False or c.value == value: yield c
python
def find(self, term, value=False): """Return a terms by name. If the name is not qualified, use this term's record name for the parent. The method will yield all terms with a matching qualified name. """ if '.' in term: parent, term = term.split('.') assert parent.lower() == self.record_term_lc, (parent.lower(), self.record_term_lc) for c in self.children: if c.record_term_lc == term.lower(): if value is False or c.value == value: yield c
[ "def", "find", "(", "self", ",", "term", ",", "value", "=", "False", ")", ":", "if", "'.'", "in", "term", ":", "parent", ",", "term", "=", "term", ".", "split", "(", "'.'", ")", "assert", "parent", ".", "lower", "(", ")", "==", "self", ".", "record_term_lc", ",", "(", "parent", ".", "lower", "(", ")", ",", "self", ".", "record_term_lc", ")", "for", "c", "in", "self", ".", "children", ":", "if", "c", ".", "record_term_lc", "==", "term", ".", "lower", "(", ")", ":", "if", "value", "is", "False", "or", "c", ".", "value", "==", "value", ":", "yield", "c" ]
Return a terms by name. If the name is not qualified, use this term's record name for the parent. The method will yield all terms with a matching qualified name.
[ "Return", "a", "terms", "by", "name", ".", "If", "the", "name", "is", "not", "qualified", "use", "this", "term", "s", "record", "name", "for", "the", "parent", ".", "The", "method", "will", "yield", "all", "terms", "with", "a", "matching", "qualified", "name", "." ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L216-L226
Metatab/metatab
metatab/terms.py
Term.get_or_new_child
def get_or_new_child(self, term, value=False, **kwargs): """Find a term, using find_first, and set it's value and properties, if it exists. If it does not, create a new term and children. """ pt, rt = self.split_term(term) term = self.record_term + '.' + rt c = self.find_first(rt) if c is None: tc = self.doc.get_term_class(term.lower()) c = tc(term, value, parent=self, doc=self.doc, section=self.section).new_children(**kwargs) assert not c.term_is("Datafile.Section"), (self, c) self.children.append(c) else: if value is not False: c.value = value for k, v in kwargs.items(): c.get_or_new_child(k, v) # Check that the term was inserted and can be found. assert self.find_first(rt) assert self.find_first(rt) == c return c
python
def get_or_new_child(self, term, value=False, **kwargs): """Find a term, using find_first, and set it's value and properties, if it exists. If it does not, create a new term and children. """ pt, rt = self.split_term(term) term = self.record_term + '.' + rt c = self.find_first(rt) if c is None: tc = self.doc.get_term_class(term.lower()) c = tc(term, value, parent=self, doc=self.doc, section=self.section).new_children(**kwargs) assert not c.term_is("Datafile.Section"), (self, c) self.children.append(c) else: if value is not False: c.value = value for k, v in kwargs.items(): c.get_or_new_child(k, v) # Check that the term was inserted and can be found. assert self.find_first(rt) assert self.find_first(rt) == c return c
[ "def", "get_or_new_child", "(", "self", ",", "term", ",", "value", "=", "False", ",", "*", "*", "kwargs", ")", ":", "pt", ",", "rt", "=", "self", ".", "split_term", "(", "term", ")", "term", "=", "self", ".", "record_term", "+", "'.'", "+", "rt", "c", "=", "self", ".", "find_first", "(", "rt", ")", "if", "c", "is", "None", ":", "tc", "=", "self", ".", "doc", ".", "get_term_class", "(", "term", ".", "lower", "(", ")", ")", "c", "=", "tc", "(", "term", ",", "value", ",", "parent", "=", "self", ",", "doc", "=", "self", ".", "doc", ",", "section", "=", "self", ".", "section", ")", ".", "new_children", "(", "*", "*", "kwargs", ")", "assert", "not", "c", ".", "term_is", "(", "\"Datafile.Section\"", ")", ",", "(", "self", ",", "c", ")", "self", ".", "children", ".", "append", "(", "c", ")", "else", ":", "if", "value", "is", "not", "False", ":", "c", ".", "value", "=", "value", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "c", ".", "get_or_new_child", "(", "k", ",", "v", ")", "# Check that the term was inserted and can be found.", "assert", "self", ".", "find_first", "(", "rt", ")", "assert", "self", ".", "find_first", "(", "rt", ")", "==", "c", "return", "c" ]
Find a term, using find_first, and set it's value and properties, if it exists. If it does not, create a new term and children.
[ "Find", "a", "term", "using", "find_first", "and", "set", "it", "s", "value", "and", "properties", "if", "it", "exists", ".", "If", "it", "does", "not", "create", "a", "new", "term", "and", "children", "." ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L254-L281
Metatab/metatab
metatab/terms.py
Term.get_value
def get_value(self, item, default=None): """Get the value of a child""" try: return self[item].value except (AttributeError, KeyError) as e: return default
python
def get_value(self, item, default=None): """Get the value of a child""" try: return self[item].value except (AttributeError, KeyError) as e: return default
[ "def", "get_value", "(", "self", ",", "item", ",", "default", "=", "None", ")", ":", "try", ":", "return", "self", "[", "item", "]", ".", "value", "except", "(", "AttributeError", ",", "KeyError", ")", "as", "e", ":", "return", "default" ]
Get the value of a child
[ "Get", "the", "value", "of", "a", "child" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L390-L395
Metatab/metatab
metatab/terms.py
Term.qualified_term
def qualified_term(self): """Return the fully qualified term name. The parent will be 'root' if there is no parent term defined. """ assert self.parent is not None or self.parent_term_lc == 'root' if self.parent: return self.parent.record_term_lc + '.' + self.record_term_lc else: return 'root.' + self.record_term_lc
python
def qualified_term(self): """Return the fully qualified term name. The parent will be 'root' if there is no parent term defined. """ assert self.parent is not None or self.parent_term_lc == 'root' if self.parent: return self.parent.record_term_lc + '.' + self.record_term_lc else: return 'root.' + self.record_term_lc
[ "def", "qualified_term", "(", "self", ")", ":", "assert", "self", ".", "parent", "is", "not", "None", "or", "self", ".", "parent_term_lc", "==", "'root'", "if", "self", ".", "parent", ":", "return", "self", ".", "parent", ".", "record_term_lc", "+", "'.'", "+", "self", ".", "record_term_lc", "else", ":", "return", "'root.'", "+", "self", ".", "record_term_lc" ]
Return the fully qualified term name. The parent will be 'root' if there is no parent term defined.
[ "Return", "the", "fully", "qualified", "term", "name", ".", "The", "parent", "will", "be", "root", "if", "there", "is", "no", "parent", "term", "defined", "." ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L437-L445
Metatab/metatab
metatab/terms.py
Term.term_is
def term_is(self, v): """Return True if the fully qualified name of the term is the same as the argument. If the argument is a list or tuple, return True if any of the term names match. Either the parent or the record term can be '*' ( 'Table.*' or '*.Name' ) to match any value for either the parent or record term. """ if isinstance(v, str): if '.' not in v: v = 'root.' + v v_p, v_r = self.split_term_lower(v) if self.join_lc == v.lower(): return True elif v_r == '*' and v_p == self.parent_term_lc: return True elif v_p == '*' and v_r == self.record_term_lc: return True elif v_p == '*' and v_r == '*': return True else: return False else: return any(self.term_is(e) for e in v)
python
def term_is(self, v): """Return True if the fully qualified name of the term is the same as the argument. If the argument is a list or tuple, return True if any of the term names match. Either the parent or the record term can be '*' ( 'Table.*' or '*.Name' ) to match any value for either the parent or record term. """ if isinstance(v, str): if '.' not in v: v = 'root.' + v v_p, v_r = self.split_term_lower(v) if self.join_lc == v.lower(): return True elif v_r == '*' and v_p == self.parent_term_lc: return True elif v_p == '*' and v_r == self.record_term_lc: return True elif v_p == '*' and v_r == '*': return True else: return False else: return any(self.term_is(e) for e in v)
[ "def", "term_is", "(", "self", ",", "v", ")", ":", "if", "isinstance", "(", "v", ",", "str", ")", ":", "if", "'.'", "not", "in", "v", ":", "v", "=", "'root.'", "+", "v", "v_p", ",", "v_r", "=", "self", ".", "split_term_lower", "(", "v", ")", "if", "self", ".", "join_lc", "==", "v", ".", "lower", "(", ")", ":", "return", "True", "elif", "v_r", "==", "'*'", "and", "v_p", "==", "self", ".", "parent_term_lc", ":", "return", "True", "elif", "v_p", "==", "'*'", "and", "v_r", "==", "self", ".", "record_term_lc", ":", "return", "True", "elif", "v_p", "==", "'*'", "and", "v_r", "==", "'*'", ":", "return", "True", "else", ":", "return", "False", "else", ":", "return", "any", "(", "self", ".", "term_is", "(", "e", ")", "for", "e", "in", "v", ")" ]
Return True if the fully qualified name of the term is the same as the argument. If the argument is a list or tuple, return True if any of the term names match. Either the parent or the record term can be '*' ( 'Table.*' or '*.Name' ) to match any value for either the parent or record term.
[ "Return", "True", "if", "the", "fully", "qualified", "name", "of", "the", "term", "is", "the", "same", "as", "the", "argument", ".", "If", "the", "argument", "is", "a", "list", "or", "tuple", "return", "True", "if", "any", "of", "the", "term", "names", "match", "." ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L447-L476
Metatab/metatab
metatab/terms.py
Term.arg_props
def arg_props(self): """Return the value and scalar properties as a dictionary. Returns only argumnet properties, properties declared on the same row as a term. It will return an entry for all of the args declared by the term's section. Use props to get values of all children and arg props combined""" d = dict(zip([str(e).lower() for e in self.section.property_names], self.args)) # print({ c.record_term_lc:c.value for c in self.children}) d[self.term_value_name.lower()] = self.value return d
python
def arg_props(self): """Return the value and scalar properties as a dictionary. Returns only argumnet properties, properties declared on the same row as a term. It will return an entry for all of the args declared by the term's section. Use props to get values of all children and arg props combined""" d = dict(zip([str(e).lower() for e in self.section.property_names], self.args)) # print({ c.record_term_lc:c.value for c in self.children}) d[self.term_value_name.lower()] = self.value return d
[ "def", "arg_props", "(", "self", ")", ":", "d", "=", "dict", "(", "zip", "(", "[", "str", "(", "e", ")", ".", "lower", "(", ")", "for", "e", "in", "self", ".", "section", ".", "property_names", "]", ",", "self", ".", "args", ")", ")", "# print({ c.record_term_lc:c.value for c in self.children})", "d", "[", "self", ".", "term_value_name", ".", "lower", "(", ")", "]", "=", "self", ".", "value", "return", "d" ]
Return the value and scalar properties as a dictionary. Returns only argumnet properties, properties declared on the same row as a term. It will return an entry for all of the args declared by the term's section. Use props to get values of all children and arg props combined
[ "Return", "the", "value", "and", "scalar", "properties", "as", "a", "dictionary", ".", "Returns", "only", "argumnet", "properties", "properties", "declared", "on", "the", "same", "row", "as", "a", "term", ".", "It", "will", "return", "an", "entry", "for", "all", "of", "the", "args", "declared", "by", "the", "term", "s", "section", ".", "Use", "props", "to", "get", "values", "of", "all", "children", "and", "arg", "props", "combined" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L516-L527
Metatab/metatab
metatab/terms.py
Term.all_props
def all_props(self): """Return a dictionary with the values of all children, and place holders for all of the section argumemts. It combines props and arg_props""" d = self.arg_props d.update(self.props) return d
python
def all_props(self): """Return a dictionary with the values of all children, and place holders for all of the section argumemts. It combines props and arg_props""" d = self.arg_props d.update(self.props) return d
[ "def", "all_props", "(", "self", ")", ":", "d", "=", "self", ".", "arg_props", "d", ".", "update", "(", "self", ".", "props", ")", "return", "d" ]
Return a dictionary with the values of all children, and place holders for all of the section argumemts. It combines props and arg_props
[ "Return", "a", "dictionary", "with", "the", "values", "of", "all", "children", "and", "place", "holders", "for", "all", "of", "the", "section", "argumemts", ".", "It", "combines", "props", "and", "arg_props" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L530-L537
Metatab/metatab
metatab/terms.py
Term._convert_to_dict
def _convert_to_dict(cls, term, replace_value_names=True): """Converts a record heirarchy to nested dicts. :param term: Root term at which to start conversion """ from collections import OrderedDict if not term: return None if term.children: d = OrderedDict() for c in term.children: if c.child_property_type == 'scalar': d[c.record_term_lc] = cls._convert_to_dict(c, replace_value_names) elif c.child_property_type == 'sequence': try: d[c.record_term_lc].append(cls._convert_to_dict(c, replace_value_names)) except (KeyError, AttributeError): # The c.term property doesn't exist, so add a list d[c.record_term_lc] = [cls._convert_to_dict(c, replace_value_names)] elif c.child_property_type == 'sconcat': # Concat with a space if c.record_term_lc in d: s = d[c.record_term_lc] + ' ' else: s = '' d[c.record_term_lc] =s + (cls._convert_to_dict(c, replace_value_names) or '') elif c.child_property_type == 'bconcat': # Concat with a blank d[c.record_term_lc] = d.get(c.record_term_lc, '') + (cls._convert_to_dict(c, replace_value_names) or '') else: try: d[c.record_term_lc].append(cls._convert_to_dict(c, replace_value_names)) except KeyError: # The c.term property doesn't exist, so add a scalar or a map d[c.record_term_lc] = cls._convert_to_dict(c, replace_value_names) except AttributeError as e: # d[c.term] exists, but is a scalar, so convert it to a list d[c.record_term_lc] = [d[c.record_term]] + [cls._convert_to_dict(c, replace_value_names)] if term.value: if replace_value_names: d[term.term_value_name.lower()] = term.value else: d['@value'] = term.value return d else: return term.value
python
def _convert_to_dict(cls, term, replace_value_names=True): """Converts a record heirarchy to nested dicts. :param term: Root term at which to start conversion """ from collections import OrderedDict if not term: return None if term.children: d = OrderedDict() for c in term.children: if c.child_property_type == 'scalar': d[c.record_term_lc] = cls._convert_to_dict(c, replace_value_names) elif c.child_property_type == 'sequence': try: d[c.record_term_lc].append(cls._convert_to_dict(c, replace_value_names)) except (KeyError, AttributeError): # The c.term property doesn't exist, so add a list d[c.record_term_lc] = [cls._convert_to_dict(c, replace_value_names)] elif c.child_property_type == 'sconcat': # Concat with a space if c.record_term_lc in d: s = d[c.record_term_lc] + ' ' else: s = '' d[c.record_term_lc] =s + (cls._convert_to_dict(c, replace_value_names) or '') elif c.child_property_type == 'bconcat': # Concat with a blank d[c.record_term_lc] = d.get(c.record_term_lc, '') + (cls._convert_to_dict(c, replace_value_names) or '') else: try: d[c.record_term_lc].append(cls._convert_to_dict(c, replace_value_names)) except KeyError: # The c.term property doesn't exist, so add a scalar or a map d[c.record_term_lc] = cls._convert_to_dict(c, replace_value_names) except AttributeError as e: # d[c.term] exists, but is a scalar, so convert it to a list d[c.record_term_lc] = [d[c.record_term]] + [cls._convert_to_dict(c, replace_value_names)] if term.value: if replace_value_names: d[term.term_value_name.lower()] = term.value else: d['@value'] = term.value return d else: return term.value
[ "def", "_convert_to_dict", "(", "cls", ",", "term", ",", "replace_value_names", "=", "True", ")", ":", "from", "collections", "import", "OrderedDict", "if", "not", "term", ":", "return", "None", "if", "term", ".", "children", ":", "d", "=", "OrderedDict", "(", ")", "for", "c", "in", "term", ".", "children", ":", "if", "c", ".", "child_property_type", "==", "'scalar'", ":", "d", "[", "c", ".", "record_term_lc", "]", "=", "cls", ".", "_convert_to_dict", "(", "c", ",", "replace_value_names", ")", "elif", "c", ".", "child_property_type", "==", "'sequence'", ":", "try", ":", "d", "[", "c", ".", "record_term_lc", "]", ".", "append", "(", "cls", ".", "_convert_to_dict", "(", "c", ",", "replace_value_names", ")", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "# The c.term property doesn't exist, so add a list", "d", "[", "c", ".", "record_term_lc", "]", "=", "[", "cls", ".", "_convert_to_dict", "(", "c", ",", "replace_value_names", ")", "]", "elif", "c", ".", "child_property_type", "==", "'sconcat'", ":", "# Concat with a space", "if", "c", ".", "record_term_lc", "in", "d", ":", "s", "=", "d", "[", "c", ".", "record_term_lc", "]", "+", "' '", "else", ":", "s", "=", "''", "d", "[", "c", ".", "record_term_lc", "]", "=", "s", "+", "(", "cls", ".", "_convert_to_dict", "(", "c", ",", "replace_value_names", ")", "or", "''", ")", "elif", "c", ".", "child_property_type", "==", "'bconcat'", ":", "# Concat with a blank", "d", "[", "c", ".", "record_term_lc", "]", "=", "d", ".", "get", "(", "c", ".", "record_term_lc", ",", "''", ")", "+", "(", "cls", ".", "_convert_to_dict", "(", "c", ",", "replace_value_names", ")", "or", "''", ")", "else", ":", "try", ":", "d", "[", "c", ".", "record_term_lc", "]", ".", "append", "(", "cls", ".", "_convert_to_dict", "(", "c", ",", "replace_value_names", ")", ")", "except", "KeyError", ":", "# The c.term property doesn't exist, so add a scalar or a map", "d", "[", "c", ".", "record_term_lc", "]", "=", "cls", ".", "_convert_to_dict", "(", "c", ",", "replace_value_names", ")", "except", "AttributeError", "as", "e", ":", "# d[c.term] exists, but is a scalar, so convert it to a list", "d", "[", "c", ".", "record_term_lc", "]", "=", "[", "d", "[", "c", ".", "record_term", "]", "]", "+", "[", "cls", ".", "_convert_to_dict", "(", "c", ",", "replace_value_names", ")", "]", "if", "term", ".", "value", ":", "if", "replace_value_names", ":", "d", "[", "term", ".", "term_value_name", ".", "lower", "(", ")", "]", "=", "term", ".", "value", "else", ":", "d", "[", "'@value'", "]", "=", "term", ".", "value", "return", "d", "else", ":", "return", "term", ".", "value" ]
Converts a record heirarchy to nested dicts. :param term: Root term at which to start conversion
[ "Converts", "a", "record", "heirarchy", "to", "nested", "dicts", "." ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L546-L609
Metatab/metatab
metatab/terms.py
Term.rows
def rows(self): """Yield rows for the term, for writing terms to a CSV file. """ # Translate the term value name so it can be assigned to a parameter. tvm = self.section.doc.decl_terms.get(self.qualified_term, {}).get('termvaluename', '@value') assert tvm # Terminal children have no arguments, just a value. Here we put the terminal children # in a property array, so they can be written to the parent's arg-children columns # if the section has any. properties = {tvm: self.value} for c in self.children: if c.is_terminal: if c.record_term_lc: # This is rare, but can happen if a property child is not given # a property name by the section -- the "Section" term has a blank column. properties[c.record_term_lc] = c.value yield (self.qualified_term, properties) # The non-terminal children have to get yielded normally -- they can't be arg-children for c in self.children: if not c.is_terminal: for row in c.rows: yield row
python
def rows(self): """Yield rows for the term, for writing terms to a CSV file. """ # Translate the term value name so it can be assigned to a parameter. tvm = self.section.doc.decl_terms.get(self.qualified_term, {}).get('termvaluename', '@value') assert tvm # Terminal children have no arguments, just a value. Here we put the terminal children # in a property array, so they can be written to the parent's arg-children columns # if the section has any. properties = {tvm: self.value} for c in self.children: if c.is_terminal: if c.record_term_lc: # This is rare, but can happen if a property child is not given # a property name by the section -- the "Section" term has a blank column. properties[c.record_term_lc] = c.value yield (self.qualified_term, properties) # The non-terminal children have to get yielded normally -- they can't be arg-children for c in self.children: if not c.is_terminal: for row in c.rows: yield row
[ "def", "rows", "(", "self", ")", ":", "# Translate the term value name so it can be assigned to a parameter.", "tvm", "=", "self", ".", "section", ".", "doc", ".", "decl_terms", ".", "get", "(", "self", ".", "qualified_term", ",", "{", "}", ")", ".", "get", "(", "'termvaluename'", ",", "'@value'", ")", "assert", "tvm", "# Terminal children have no arguments, just a value. Here we put the terminal children", "# in a property array, so they can be written to the parent's arg-children columns", "# if the section has any.", "properties", "=", "{", "tvm", ":", "self", ".", "value", "}", "for", "c", "in", "self", ".", "children", ":", "if", "c", ".", "is_terminal", ":", "if", "c", ".", "record_term_lc", ":", "# This is rare, but can happen if a property child is not given", "# a property name by the section -- the \"Section\" term has a blank column.", "properties", "[", "c", ".", "record_term_lc", "]", "=", "c", ".", "value", "yield", "(", "self", ".", "qualified_term", ",", "properties", ")", "# The non-terminal children have to get yielded normally -- they can't be arg-children", "for", "c", "in", "self", ".", "children", ":", "if", "not", "c", ".", "is_terminal", ":", "for", "row", "in", "c", ".", "rows", ":", "yield", "row" ]
Yield rows for the term, for writing terms to a CSV file.
[ "Yield", "rows", "for", "the", "term", "for", "writing", "terms", "to", "a", "CSV", "file", "." ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L612-L637
Metatab/metatab
metatab/terms.py
Term.descendents
def descendents(self): """Iterate over all descendent terms""" for c in self.children: yield c for d in c.descendents: yield d
python
def descendents(self): """Iterate over all descendent terms""" for c in self.children: yield c for d in c.descendents: yield d
[ "def", "descendents", "(", "self", ")", ":", "for", "c", "in", "self", ".", "children", ":", "yield", "c", "for", "d", "in", "c", ".", "descendents", ":", "yield", "d" ]
Iterate over all descendent terms
[ "Iterate", "over", "all", "descendent", "terms" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L640-L647
Metatab/metatab
metatab/terms.py
SectionTerm.subclass
def subclass(cls, t): """Change a term into a Section Term""" t.doc = None t.terms = [] t.__class__ = SectionTerm return t
python
def subclass(cls, t): """Change a term into a Section Term""" t.doc = None t.terms = [] t.__class__ = SectionTerm return t
[ "def", "subclass", "(", "cls", ",", "t", ")", ":", "t", ".", "doc", "=", "None", "t", ".", "terms", "=", "[", "]", "t", ".", "__class__", "=", "SectionTerm", "return", "t" ]
Change a term into a Section Term
[ "Change", "a", "term", "into", "a", "Section", "Term" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L704-L709
Metatab/metatab
metatab/terms.py
SectionTerm.add_arg
def add_arg(self,arg, prepend=False): """Append an arg to the arg list""" self.args = [arg_.strip() for arg_ in self.args if arg_.strip()] if arg.title() not in self.args: if prepend: self.args = [arg.title()] + self.args else: self.args.append(arg.title())
python
def add_arg(self,arg, prepend=False): """Append an arg to the arg list""" self.args = [arg_.strip() for arg_ in self.args if arg_.strip()] if arg.title() not in self.args: if prepend: self.args = [arg.title()] + self.args else: self.args.append(arg.title())
[ "def", "add_arg", "(", "self", ",", "arg", ",", "prepend", "=", "False", ")", ":", "self", ".", "args", "=", "[", "arg_", ".", "strip", "(", ")", "for", "arg_", "in", "self", ".", "args", "if", "arg_", ".", "strip", "(", ")", "]", "if", "arg", ".", "title", "(", ")", "not", "in", "self", ".", "args", ":", "if", "prepend", ":", "self", ".", "args", "=", "[", "arg", ".", "title", "(", ")", "]", "+", "self", ".", "args", "else", ":", "self", ".", "args", ".", "append", "(", "arg", ".", "title", "(", ")", ")" ]
Append an arg to the arg list
[ "Append", "an", "arg", "to", "the", "arg", "list" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L724-L733
Metatab/metatab
metatab/terms.py
SectionTerm.remove_arg
def remove_arg(self, arg): """Remove an arg to the arg list""" self.args = [arg_.strip() for arg_ in self.args if arg_.strip()] for arg_ in list(self.args): if arg_.lower() == arg.lower(): self.args.remove(arg_)
python
def remove_arg(self, arg): """Remove an arg to the arg list""" self.args = [arg_.strip() for arg_ in self.args if arg_.strip()] for arg_ in list(self.args): if arg_.lower() == arg.lower(): self.args.remove(arg_)
[ "def", "remove_arg", "(", "self", ",", "arg", ")", ":", "self", ".", "args", "=", "[", "arg_", ".", "strip", "(", ")", "for", "arg_", "in", "self", ".", "args", "if", "arg_", ".", "strip", "(", ")", "]", "for", "arg_", "in", "list", "(", "self", ".", "args", ")", ":", "if", "arg_", ".", "lower", "(", ")", "==", "arg", ".", "lower", "(", ")", ":", "self", ".", "args", ".", "remove", "(", "arg_", ")" ]
Remove an arg to the arg list
[ "Remove", "an", "arg", "to", "the", "arg", "list" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L735-L742
Metatab/metatab
metatab/terms.py
SectionTerm.add_term
def add_term(self, t): """Add a term to this section and set it's ownership. Should only be used on root level terms""" if t not in self.terms: if t.parent_term_lc == 'root': self.terms.append(t) self.doc.add_term(t, add_section=False) t.set_ownership() else: raise GenerateError("Can only add or move root-level terms. Term '{}' parent is '{}' " .format(t, t.parent_term_lc)) assert t.section or t.join_lc == 'root.root', t
python
def add_term(self, t): """Add a term to this section and set it's ownership. Should only be used on root level terms""" if t not in self.terms: if t.parent_term_lc == 'root': self.terms.append(t) self.doc.add_term(t, add_section=False) t.set_ownership() else: raise GenerateError("Can only add or move root-level terms. Term '{}' parent is '{}' " .format(t, t.parent_term_lc)) assert t.section or t.join_lc == 'root.root', t
[ "def", "add_term", "(", "self", ",", "t", ")", ":", "if", "t", "not", "in", "self", ".", "terms", ":", "if", "t", ".", "parent_term_lc", "==", "'root'", ":", "self", ".", "terms", ".", "append", "(", "t", ")", "self", ".", "doc", ".", "add_term", "(", "t", ",", "add_section", "=", "False", ")", "t", ".", "set_ownership", "(", ")", "else", ":", "raise", "GenerateError", "(", "\"Can only add or move root-level terms. Term '{}' parent is '{}' \"", ".", "format", "(", "t", ",", "t", ".", "parent_term_lc", ")", ")", "assert", "t", ".", "section", "or", "t", ".", "join_lc", "==", "'root.root'", ",", "t" ]
Add a term to this section and set it's ownership. Should only be used on root level terms
[ "Add", "a", "term", "to", "this", "section", "and", "set", "it", "s", "ownership", ".", "Should", "only", "be", "used", "on", "root", "level", "terms" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L744-L758
Metatab/metatab
metatab/terms.py
SectionTerm.new_term
def new_term(self, term, value, **kwargs): """Create a new root-level term in this section""" tc = self.doc.get_term_class(term.lower()) t = tc(term, value, doc=self.doc, parent=None, section=self).new_children(**kwargs) self.doc.add_term(t) return t
python
def new_term(self, term, value, **kwargs): """Create a new root-level term in this section""" tc = self.doc.get_term_class(term.lower()) t = tc(term, value, doc=self.doc, parent=None, section=self).new_children(**kwargs) self.doc.add_term(t) return t
[ "def", "new_term", "(", "self", ",", "term", ",", "value", ",", "*", "*", "kwargs", ")", ":", "tc", "=", "self", ".", "doc", ".", "get_term_class", "(", "term", ".", "lower", "(", ")", ")", "t", "=", "tc", "(", "term", ",", "value", ",", "doc", "=", "self", ".", "doc", ",", "parent", "=", "None", ",", "section", "=", "self", ")", ".", "new_children", "(", "*", "*", "kwargs", ")", "self", ".", "doc", ".", "add_term", "(", "t", ")", "return", "t" ]
Create a new root-level term in this section
[ "Create", "a", "new", "root", "-", "level", "term", "in", "this", "section" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L764-L772
Metatab/metatab
metatab/terms.py
SectionTerm.get_term
def get_term(self, term, value=False): """Synonym for find_first, restructed to this section""" return self.doc.find_first(term, value=value, section=self.name)
python
def get_term(self, term, value=False): """Synonym for find_first, restructed to this section""" return self.doc.find_first(term, value=value, section=self.name)
[ "def", "get_term", "(", "self", ",", "term", ",", "value", "=", "False", ")", ":", "return", "self", ".", "doc", ".", "find_first", "(", "term", ",", "value", "=", "value", ",", "section", "=", "self", ".", "name", ")" ]
Synonym for find_first, restructed to this section
[ "Synonym", "for", "find_first", "restructed", "to", "this", "section" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L774-L776
Metatab/metatab
metatab/terms.py
SectionTerm.set_terms
def set_terms(self,*terms, **kw_terms): """ Create or set top level terms in the section. After python 3.6.0, the terms entries should maintain the same order as the argument list. The term arguments can have any of these forms: * For position argument, a Term object * For kw arguments: - 'TermName=TermValue' - 'TermName=(TermValue, PropertyDict) Positional arguments are processed before keyword arguments, and are passed into .add_term() :param terms: Term arguments :return: """ for t in terms: self.add_term(t) for k,v in kw_terms.items(): try: value, props = v except (ValueError, TypeError) as e: value, props = v,{} self.new_term(k,value,**props)
python
def set_terms(self,*terms, **kw_terms): """ Create or set top level terms in the section. After python 3.6.0, the terms entries should maintain the same order as the argument list. The term arguments can have any of these forms: * For position argument, a Term object * For kw arguments: - 'TermName=TermValue' - 'TermName=(TermValue, PropertyDict) Positional arguments are processed before keyword arguments, and are passed into .add_term() :param terms: Term arguments :return: """ for t in terms: self.add_term(t) for k,v in kw_terms.items(): try: value, props = v except (ValueError, TypeError) as e: value, props = v,{} self.new_term(k,value,**props)
[ "def", "set_terms", "(", "self", ",", "*", "terms", ",", "*", "*", "kw_terms", ")", ":", "for", "t", "in", "terms", ":", "self", ".", "add_term", "(", "t", ")", "for", "k", ",", "v", "in", "kw_terms", ".", "items", "(", ")", ":", "try", ":", "value", ",", "props", "=", "v", "except", "(", "ValueError", ",", "TypeError", ")", "as", "e", ":", "value", ",", "props", "=", "v", ",", "{", "}", "self", ".", "new_term", "(", "k", ",", "value", ",", "*", "*", "props", ")" ]
Create or set top level terms in the section. After python 3.6.0, the terms entries should maintain the same order as the argument list. The term arguments can have any of these forms: * For position argument, a Term object * For kw arguments: - 'TermName=TermValue' - 'TermName=(TermValue, PropertyDict) Positional arguments are processed before keyword arguments, and are passed into .add_term() :param terms: Term arguments :return:
[ "Create", "or", "set", "top", "level", "terms", "in", "the", "section", ".", "After", "python", "3", ".", "6", ".", "0", "the", "terms", "entries", "should", "maintain", "the", "same", "order", "as", "the", "argument", "list", ".", "The", "term", "arguments", "can", "have", "any", "of", "these", "forms", ":" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L805-L830
Metatab/metatab
metatab/terms.py
SectionTerm.remove_term
def remove_term(self, term, remove_from_doc=True): """Remove a term from the terms. Must be the identical term, the same object""" try: self.terms.remove(term) except ValueError: pass if remove_from_doc: self.doc.remove_term(term)
python
def remove_term(self, term, remove_from_doc=True): """Remove a term from the terms. Must be the identical term, the same object""" try: self.terms.remove(term) except ValueError: pass if remove_from_doc: self.doc.remove_term(term)
[ "def", "remove_term", "(", "self", ",", "term", ",", "remove_from_doc", "=", "True", ")", ":", "try", ":", "self", ".", "terms", ".", "remove", "(", "term", ")", "except", "ValueError", ":", "pass", "if", "remove_from_doc", ":", "self", ".", "doc", ".", "remove_term", "(", "term", ")" ]
Remove a term from the terms. Must be the identical term, the same object
[ "Remove", "a", "term", "from", "the", "terms", ".", "Must", "be", "the", "identical", "term", "the", "same", "object" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L833-L842
Metatab/metatab
metatab/terms.py
SectionTerm.clean
def clean(self): """Remove all of the terms from the section, and also remove them from the document""" terms = list(self) for t in terms: self.doc.remove_term(t)
python
def clean(self): """Remove all of the terms from the section, and also remove them from the document""" terms = list(self) for t in terms: self.doc.remove_term(t)
[ "def", "clean", "(", "self", ")", ":", "terms", "=", "list", "(", "self", ")", "for", "t", "in", "terms", ":", "self", ".", "doc", ".", "remove_term", "(", "t", ")" ]
Remove all of the terms from the section, and also remove them from the document
[ "Remove", "all", "of", "the", "terms", "from", "the", "section", "and", "also", "remove", "them", "from", "the", "document" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L844-L849
Metatab/metatab
metatab/terms.py
SectionTerm.sort_by_term
def sort_by_term(self, order=None): """ Sort the terms in the section. :param order: If specified, a list of qualified, lowercased term names. These names will appear first in the section, and the remaining terms will be sorted alphabetically. If not specified, all terms are alphabetized. :return: """ if order is None: self.terms = sorted(self.terms, key=lambda e: e.join_lc) else: all_terms = list(self.terms) sorted_terms = [] for tn in order: for t in list(all_terms): if t.term_is(tn): all_terms.remove(t) sorted_terms.append(t) sorted_terms.extend(sorted(all_terms, key=lambda e: e.join_lc)) self.terms = sorted_terms
python
def sort_by_term(self, order=None): """ Sort the terms in the section. :param order: If specified, a list of qualified, lowercased term names. These names will appear first in the section, and the remaining terms will be sorted alphabetically. If not specified, all terms are alphabetized. :return: """ if order is None: self.terms = sorted(self.terms, key=lambda e: e.join_lc) else: all_terms = list(self.terms) sorted_terms = [] for tn in order: for t in list(all_terms): if t.term_is(tn): all_terms.remove(t) sorted_terms.append(t) sorted_terms.extend(sorted(all_terms, key=lambda e: e.join_lc)) self.terms = sorted_terms
[ "def", "sort_by_term", "(", "self", ",", "order", "=", "None", ")", ":", "if", "order", "is", "None", ":", "self", ".", "terms", "=", "sorted", "(", "self", ".", "terms", ",", "key", "=", "lambda", "e", ":", "e", ".", "join_lc", ")", "else", ":", "all_terms", "=", "list", "(", "self", ".", "terms", ")", "sorted_terms", "=", "[", "]", "for", "tn", "in", "order", ":", "for", "t", "in", "list", "(", "all_terms", ")", ":", "if", "t", ".", "term_is", "(", "tn", ")", ":", "all_terms", ".", "remove", "(", "t", ")", "sorted_terms", ".", "append", "(", "t", ")", "sorted_terms", ".", "extend", "(", "sorted", "(", "all_terms", ",", "key", "=", "lambda", "e", ":", "e", ".", "join_lc", ")", ")", "self", ".", "terms", "=", "sorted_terms" ]
Sort the terms in the section. :param order: If specified, a list of qualified, lowercased term names. These names will appear first in the section, and the remaining terms will be sorted alphabetically. If not specified, all terms are alphabetized. :return:
[ "Sort", "the", "terms", "in", "the", "section", ".", ":", "param", "order", ":", "If", "specified", "a", "list", "of", "qualified", "lowercased", "term", "names", ".", "These", "names", "will", "appear", "first", "in", "the", "section", "and", "the", "remaining", "terms", "will", "be", "sorted", "alphabetically", ".", "If", "not", "specified", "all", "terms", "are", "alphabetized", ".", ":", "return", ":" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L851-L876
Metatab/metatab
metatab/terms.py
SectionTerm._args
def _args(self, term, d): """Extract the chldren of a term that are arg-children from those that are row-children. """ # Get the term value name, the property name that should be assigned to the term value. tvm = self.doc.decl_terms.get(term, {}).get('termvaluename', '@value') # Convert the keys to lower case lower_d = {k.lower(): v for k, v in d.items()} args = [] for n in [tvm] + self.property_names: args.append(lower_d.get(n.lower(), '')) try: del lower_d[n.lower()] except KeyError: pass return term, args, lower_d
python
def _args(self, term, d): """Extract the chldren of a term that are arg-children from those that are row-children. """ # Get the term value name, the property name that should be assigned to the term value. tvm = self.doc.decl_terms.get(term, {}).get('termvaluename', '@value') # Convert the keys to lower case lower_d = {k.lower(): v for k, v in d.items()} args = [] for n in [tvm] + self.property_names: args.append(lower_d.get(n.lower(), '')) try: del lower_d[n.lower()] except KeyError: pass return term, args, lower_d
[ "def", "_args", "(", "self", ",", "term", ",", "d", ")", ":", "# Get the term value name, the property name that should be assigned to the term value.", "tvm", "=", "self", ".", "doc", ".", "decl_terms", ".", "get", "(", "term", ",", "{", "}", ")", ".", "get", "(", "'termvaluename'", ",", "'@value'", ")", "# Convert the keys to lower case", "lower_d", "=", "{", "k", ".", "lower", "(", ")", ":", "v", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", "}", "args", "=", "[", "]", "for", "n", "in", "[", "tvm", "]", "+", "self", ".", "property_names", ":", "args", ".", "append", "(", "lower_d", ".", "get", "(", "n", ".", "lower", "(", ")", ",", "''", ")", ")", "try", ":", "del", "lower_d", "[", "n", ".", "lower", "(", ")", "]", "except", "KeyError", ":", "pass", "return", "term", ",", "args", ",", "lower_d" ]
Extract the chldren of a term that are arg-children from those that are row-children.
[ "Extract", "the", "chldren", "of", "a", "term", "that", "are", "arg", "-", "children", "from", "those", "that", "are", "row", "-", "children", "." ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L899-L918
Metatab/metatab
metatab/terms.py
SectionTerm.rows
def rows(self): """Yield rows for the section""" for t in self.terms: for row in t.rows: term, value = row # Value can either be a string, or a dict if isinstance(value, dict): # Dict is for properties, which might be arg-children term, args, remain = self._args(term, value) yield term, args # 'remain' is all of the children that didn't have an arg-child column -- the # section didn't have a column heder for that ther. for k, v in remain.items(): yield term.split('.')[-1] + '.' + k, v else: yield row
python
def rows(self): """Yield rows for the section""" for t in self.terms: for row in t.rows: term, value = row # Value can either be a string, or a dict if isinstance(value, dict): # Dict is for properties, which might be arg-children term, args, remain = self._args(term, value) yield term, args # 'remain' is all of the children that didn't have an arg-child column -- the # section didn't have a column heder for that ther. for k, v in remain.items(): yield term.split('.')[-1] + '.' + k, v else: yield row
[ "def", "rows", "(", "self", ")", ":", "for", "t", "in", "self", ".", "terms", ":", "for", "row", "in", "t", ".", "rows", ":", "term", ",", "value", "=", "row", "# Value can either be a string, or a dict", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "# Dict is for properties, which might be arg-children", "term", ",", "args", ",", "remain", "=", "self", ".", "_args", "(", "term", ",", "value", ")", "yield", "term", ",", "args", "# 'remain' is all of the children that didn't have an arg-child column -- the", "# section didn't have a column heder for that ther.", "for", "k", ",", "v", "in", "remain", ".", "items", "(", ")", ":", "yield", "term", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "+", "'.'", "+", "k", ",", "v", "else", ":", "yield", "row" ]
Yield rows for the section
[ "Yield", "rows", "for", "the", "section" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L921-L937
Metatab/metatab
metatab/terms.py
SectionTerm.lines
def lines(self): """Iterate over all of the rows as text lines""" # Yield the section header if self.name != 'Root': yield ('Section', '|'.join([self.value] + self.property_names)) # Yield all of the rows for terms in the section for row in self.rows: term, value = row if not isinstance(value, (list, tuple)): value = [value] term = term.replace('root.', '').title() yield (term, value[0]) children = list(zip(self.property_names, value[1:])) for prop, value in children: if value and value.strip(): child_t = '.' + (prop.title()) yield (" "+child_t, value)
python
def lines(self): """Iterate over all of the rows as text lines""" # Yield the section header if self.name != 'Root': yield ('Section', '|'.join([self.value] + self.property_names)) # Yield all of the rows for terms in the section for row in self.rows: term, value = row if not isinstance(value, (list, tuple)): value = [value] term = term.replace('root.', '').title() yield (term, value[0]) children = list(zip(self.property_names, value[1:])) for prop, value in children: if value and value.strip(): child_t = '.' + (prop.title()) yield (" "+child_t, value)
[ "def", "lines", "(", "self", ")", ":", "# Yield the section header", "if", "self", ".", "name", "!=", "'Root'", ":", "yield", "(", "'Section'", ",", "'|'", ".", "join", "(", "[", "self", ".", "value", "]", "+", "self", ".", "property_names", ")", ")", "# Yield all of the rows for terms in the section", "for", "row", "in", "self", ".", "rows", ":", "term", ",", "value", "=", "row", "if", "not", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "value", "=", "[", "value", "]", "term", "=", "term", ".", "replace", "(", "'root.'", ",", "''", ")", ".", "title", "(", ")", "yield", "(", "term", ",", "value", "[", "0", "]", ")", "children", "=", "list", "(", "zip", "(", "self", ".", "property_names", ",", "value", "[", "1", ":", "]", ")", ")", "for", "prop", ",", "value", "in", "children", ":", "if", "value", "and", "value", ".", "strip", "(", ")", ":", "child_t", "=", "'.'", "+", "(", "prop", ".", "title", "(", ")", ")", "yield", "(", "\" \"", "+", "child_t", ",", "value", ")" ]
Iterate over all of the rows as text lines
[ "Iterate", "over", "all", "of", "the", "rows", "as", "text", "lines" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L940-L962
Metatab/metatab
metatab/terms.py
SectionTerm.as_dict
def as_dict(self, replace_value_names=True): """Return the whole section as a dict""" old_children = self.children self.children = self.terms d = super(SectionTerm, self).as_dict(replace_value_names) self.children = old_children return d
python
def as_dict(self, replace_value_names=True): """Return the whole section as a dict""" old_children = self.children self.children = self.terms d = super(SectionTerm, self).as_dict(replace_value_names) self.children = old_children return d
[ "def", "as_dict", "(", "self", ",", "replace_value_names", "=", "True", ")", ":", "old_children", "=", "self", ".", "children", "self", ".", "children", "=", "self", ".", "terms", "d", "=", "super", "(", "SectionTerm", ",", "self", ")", ".", "as_dict", "(", "replace_value_names", ")", "self", ".", "children", "=", "old_children", "return", "d" ]
Return the whole section as a dict
[ "Return", "the", "whole", "section", "as", "a", "dict" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L967-L976
bjodah/pycompilation
pycompilation/runners.py
CompilerRunner.find_compiler
def find_compiler(cls, preferred_vendor, metadir, cwd, use_meta=True): """ Identify a suitable C/fortran/other compiler When it is possible that the user (un)installs a compiler inbetween compilations of object files we want to catch that. This method allows compiler choice to be stored in a pickled metadata file. Provide metadir a dirpath to make the class save choice there in a file with cls.metadata_filename as name. """ cwd = cwd or '.' metadir = metadir or '.' metadir = os.path.join(cwd, metadir) used_metafile = False if not preferred_vendor and use_meta: try: preferred_vendor = cls.get_from_metadata_file( metadir, 'vendor') used_metafile = True except FileNotFoundError: pass candidates = list(cls.compiler_dict.keys()) if preferred_vendor: if preferred_vendor in candidates: candidates = [preferred_vendor]+candidates else: raise ValueError("Unknown vendor {}".format( preferred_vendor)) name, path = find_binary_of_command([ cls.compiler_dict[x] for x in candidates]) if use_meta and not used_metafile: if not os.path.isdir(metadir): raise FileNotFoundError("Not a dir: {}".format(metadir)) cls.save_to_metadata_file(metadir, 'compiler', (name, path)) cls.save_to_metadata_file( metadir, 'vendor', cls.compiler_name_vendor_mapping[name]) if cls.logger: cls.logger.info( 'Wrote choice of compiler to: metadir') return name, path, cls.compiler_name_vendor_mapping[name]
python
def find_compiler(cls, preferred_vendor, metadir, cwd, use_meta=True): """ Identify a suitable C/fortran/other compiler When it is possible that the user (un)installs a compiler inbetween compilations of object files we want to catch that. This method allows compiler choice to be stored in a pickled metadata file. Provide metadir a dirpath to make the class save choice there in a file with cls.metadata_filename as name. """ cwd = cwd or '.' metadir = metadir or '.' metadir = os.path.join(cwd, metadir) used_metafile = False if not preferred_vendor and use_meta: try: preferred_vendor = cls.get_from_metadata_file( metadir, 'vendor') used_metafile = True except FileNotFoundError: pass candidates = list(cls.compiler_dict.keys()) if preferred_vendor: if preferred_vendor in candidates: candidates = [preferred_vendor]+candidates else: raise ValueError("Unknown vendor {}".format( preferred_vendor)) name, path = find_binary_of_command([ cls.compiler_dict[x] for x in candidates]) if use_meta and not used_metafile: if not os.path.isdir(metadir): raise FileNotFoundError("Not a dir: {}".format(metadir)) cls.save_to_metadata_file(metadir, 'compiler', (name, path)) cls.save_to_metadata_file( metadir, 'vendor', cls.compiler_name_vendor_mapping[name]) if cls.logger: cls.logger.info( 'Wrote choice of compiler to: metadir') return name, path, cls.compiler_name_vendor_mapping[name]
[ "def", "find_compiler", "(", "cls", ",", "preferred_vendor", ",", "metadir", ",", "cwd", ",", "use_meta", "=", "True", ")", ":", "cwd", "=", "cwd", "or", "'.'", "metadir", "=", "metadir", "or", "'.'", "metadir", "=", "os", ".", "path", ".", "join", "(", "cwd", ",", "metadir", ")", "used_metafile", "=", "False", "if", "not", "preferred_vendor", "and", "use_meta", ":", "try", ":", "preferred_vendor", "=", "cls", ".", "get_from_metadata_file", "(", "metadir", ",", "'vendor'", ")", "used_metafile", "=", "True", "except", "FileNotFoundError", ":", "pass", "candidates", "=", "list", "(", "cls", ".", "compiler_dict", ".", "keys", "(", ")", ")", "if", "preferred_vendor", ":", "if", "preferred_vendor", "in", "candidates", ":", "candidates", "=", "[", "preferred_vendor", "]", "+", "candidates", "else", ":", "raise", "ValueError", "(", "\"Unknown vendor {}\"", ".", "format", "(", "preferred_vendor", ")", ")", "name", ",", "path", "=", "find_binary_of_command", "(", "[", "cls", ".", "compiler_dict", "[", "x", "]", "for", "x", "in", "candidates", "]", ")", "if", "use_meta", "and", "not", "used_metafile", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "metadir", ")", ":", "raise", "FileNotFoundError", "(", "\"Not a dir: {}\"", ".", "format", "(", "metadir", ")", ")", "cls", ".", "save_to_metadata_file", "(", "metadir", ",", "'compiler'", ",", "(", "name", ",", "path", ")", ")", "cls", ".", "save_to_metadata_file", "(", "metadir", ",", "'vendor'", ",", "cls", ".", "compiler_name_vendor_mapping", "[", "name", "]", ")", "if", "cls", ".", "logger", ":", "cls", ".", "logger", ".", "info", "(", "'Wrote choice of compiler to: metadir'", ")", "return", "name", ",", "path", ",", "cls", ".", "compiler_name_vendor_mapping", "[", "name", "]" ]
Identify a suitable C/fortran/other compiler When it is possible that the user (un)installs a compiler inbetween compilations of object files we want to catch that. This method allows compiler choice to be stored in a pickled metadata file. Provide metadir a dirpath to make the class save choice there in a file with cls.metadata_filename as name.
[ "Identify", "a", "suitable", "C", "/", "fortran", "/", "other", "compiler" ]
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/runners.py#L245-L288
bjodah/pycompilation
pycompilation/runners.py
CompilerRunner.cmd
def cmd(self): """ The command below covers most cases, if you need someting more complex subclass this. """ cmd = ( [self.compiler_binary] + self.flags + ['-U'+x for x in self.undef] + ['-D'+x for x in self.define] + ['-I'+x for x in self.include_dirs] + self.sources ) if self.run_linker: cmd += (['-L'+x for x in self.library_dirs] + [(x if os.path.exists(x) else '-l'+x) for x in self.libraries] + self.linkline) counted = [] for envvar in re.findall('\$\{(\w+)\}', ' '.join(cmd)): if os.getenv(envvar) is None: if envvar not in counted: counted.append(envvar) msg = "Environment variable '{}' undefined.".format( envvar) self.logger.error(msg) raise CompilationError(msg) return cmd
python
def cmd(self): """ The command below covers most cases, if you need someting more complex subclass this. """ cmd = ( [self.compiler_binary] + self.flags + ['-U'+x for x in self.undef] + ['-D'+x for x in self.define] + ['-I'+x for x in self.include_dirs] + self.sources ) if self.run_linker: cmd += (['-L'+x for x in self.library_dirs] + [(x if os.path.exists(x) else '-l'+x) for x in self.libraries] + self.linkline) counted = [] for envvar in re.findall('\$\{(\w+)\}', ' '.join(cmd)): if os.getenv(envvar) is None: if envvar not in counted: counted.append(envvar) msg = "Environment variable '{}' undefined.".format( envvar) self.logger.error(msg) raise CompilationError(msg) return cmd
[ "def", "cmd", "(", "self", ")", ":", "cmd", "=", "(", "[", "self", ".", "compiler_binary", "]", "+", "self", ".", "flags", "+", "[", "'-U'", "+", "x", "for", "x", "in", "self", ".", "undef", "]", "+", "[", "'-D'", "+", "x", "for", "x", "in", "self", ".", "define", "]", "+", "[", "'-I'", "+", "x", "for", "x", "in", "self", ".", "include_dirs", "]", "+", "self", ".", "sources", ")", "if", "self", ".", "run_linker", ":", "cmd", "+=", "(", "[", "'-L'", "+", "x", "for", "x", "in", "self", ".", "library_dirs", "]", "+", "[", "(", "x", "if", "os", ".", "path", ".", "exists", "(", "x", ")", "else", "'-l'", "+", "x", ")", "for", "x", "in", "self", ".", "libraries", "]", "+", "self", ".", "linkline", ")", "counted", "=", "[", "]", "for", "envvar", "in", "re", ".", "findall", "(", "'\\$\\{(\\w+)\\}'", ",", "' '", ".", "join", "(", "cmd", ")", ")", ":", "if", "os", ".", "getenv", "(", "envvar", ")", "is", "None", ":", "if", "envvar", "not", "in", "counted", ":", "counted", ".", "append", "(", "envvar", ")", "msg", "=", "\"Environment variable '{}' undefined.\"", ".", "format", "(", "envvar", ")", "self", ".", "logger", ".", "error", "(", "msg", ")", "raise", "CompilationError", "(", "msg", ")", "return", "cmd" ]
The command below covers most cases, if you need someting more complex subclass this.
[ "The", "command", "below", "covers", "most", "cases", "if", "you", "need", "someting", "more", "complex", "subclass", "this", "." ]
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/runners.py#L290-L316
elkiwy/paynter
paynter/paynter.py
Paynter.drawLine
def drawLine(self, x1, y1, x2, y2, silent=False): """ Draws a line on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: Starting X coordinate. :param y1: Starting Y coordinate. :param x2: End X coordinate. :param y2: End Y coordinate. :rtype: Nothing. """ start = time.time() #Downsample the coordinates x1 = int(x1/config.DOWNSAMPLING) x2 = int(x2/config.DOWNSAMPLING) y1 = int(y1/config.DOWNSAMPLING) y2 = int(y2/config.DOWNSAMPLING) if not silent : print('drawing line from: '+str((x1,y1))+' to: '+str((x2,y2))) #Calculate the direction and the length of the step direction = N.arctan2(y2 - y1, x2 - x1) length = self.brush.spacing #Prepare the loop x, y = x1, y1 totalSteps = int(N.sqrt((x2 - x)**2 + (y2 - y)**2)/length) lay = self.image.getActiveLayer() col = self.color secCol = self.secondColor mirr = self.mirrorMode #If I use source caching.. if self.brush.usesSourceCaching: #..than optimize it for faster drawing laydata = lay.data x -= self.brush.brushSize*0.5 y -= self.brush.brushSize*0.5 colbrsource = self.brush.coloredBrushSource canvSize = config.CANVAS_SIZE brmask = self.brush.brushMask for _ in range(totalSteps): #Make the dab on this point applyMirroredDab_jit(mirr, laydata, int(x), int(y), colbrsource.copy(), canvSize, brmask) #Mode the point for the next step and update the distances x += lendir_x(length, direction) y += lendir_y(length, direction) #..if I don't use source caching.. else: #..do the normal drawing for _ in range(totalSteps): #Make the dab on this point self.brush.makeDab(lay, int(x), int(y), col, secCol, mirror=mirr) #Mode the point for the next step and update the distances x += lendir_x(length, direction) y += lendir_y(length, direction)
python
def drawLine(self, x1, y1, x2, y2, silent=False): """ Draws a line on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: Starting X coordinate. :param y1: Starting Y coordinate. :param x2: End X coordinate. :param y2: End Y coordinate. :rtype: Nothing. """ start = time.time() #Downsample the coordinates x1 = int(x1/config.DOWNSAMPLING) x2 = int(x2/config.DOWNSAMPLING) y1 = int(y1/config.DOWNSAMPLING) y2 = int(y2/config.DOWNSAMPLING) if not silent : print('drawing line from: '+str((x1,y1))+' to: '+str((x2,y2))) #Calculate the direction and the length of the step direction = N.arctan2(y2 - y1, x2 - x1) length = self.brush.spacing #Prepare the loop x, y = x1, y1 totalSteps = int(N.sqrt((x2 - x)**2 + (y2 - y)**2)/length) lay = self.image.getActiveLayer() col = self.color secCol = self.secondColor mirr = self.mirrorMode #If I use source caching.. if self.brush.usesSourceCaching: #..than optimize it for faster drawing laydata = lay.data x -= self.brush.brushSize*0.5 y -= self.brush.brushSize*0.5 colbrsource = self.brush.coloredBrushSource canvSize = config.CANVAS_SIZE brmask = self.brush.brushMask for _ in range(totalSteps): #Make the dab on this point applyMirroredDab_jit(mirr, laydata, int(x), int(y), colbrsource.copy(), canvSize, brmask) #Mode the point for the next step and update the distances x += lendir_x(length, direction) y += lendir_y(length, direction) #..if I don't use source caching.. else: #..do the normal drawing for _ in range(totalSteps): #Make the dab on this point self.brush.makeDab(lay, int(x), int(y), col, secCol, mirror=mirr) #Mode the point for the next step and update the distances x += lendir_x(length, direction) y += lendir_y(length, direction)
[ "def", "drawLine", "(", "self", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "silent", "=", "False", ")", ":", "start", "=", "time", ".", "time", "(", ")", "#Downsample the coordinates", "x1", "=", "int", "(", "x1", "/", "config", ".", "DOWNSAMPLING", ")", "x2", "=", "int", "(", "x2", "/", "config", ".", "DOWNSAMPLING", ")", "y1", "=", "int", "(", "y1", "/", "config", ".", "DOWNSAMPLING", ")", "y2", "=", "int", "(", "y2", "/", "config", ".", "DOWNSAMPLING", ")", "if", "not", "silent", ":", "print", "(", "'drawing line from: '", "+", "str", "(", "(", "x1", ",", "y1", ")", ")", "+", "' to: '", "+", "str", "(", "(", "x2", ",", "y2", ")", ")", ")", "#Calculate the direction and the length of the step", "direction", "=", "N", ".", "arctan2", "(", "y2", "-", "y1", ",", "x2", "-", "x1", ")", "length", "=", "self", ".", "brush", ".", "spacing", "#Prepare the loop", "x", ",", "y", "=", "x1", ",", "y1", "totalSteps", "=", "int", "(", "N", ".", "sqrt", "(", "(", "x2", "-", "x", ")", "**", "2", "+", "(", "y2", "-", "y", ")", "**", "2", ")", "/", "length", ")", "lay", "=", "self", ".", "image", ".", "getActiveLayer", "(", ")", "col", "=", "self", ".", "color", "secCol", "=", "self", ".", "secondColor", "mirr", "=", "self", ".", "mirrorMode", "#If I use source caching..", "if", "self", ".", "brush", ".", "usesSourceCaching", ":", "#..than optimize it for faster drawing", "laydata", "=", "lay", ".", "data", "x", "-=", "self", ".", "brush", ".", "brushSize", "*", "0.5", "y", "-=", "self", ".", "brush", ".", "brushSize", "*", "0.5", "colbrsource", "=", "self", ".", "brush", ".", "coloredBrushSource", "canvSize", "=", "config", ".", "CANVAS_SIZE", "brmask", "=", "self", ".", "brush", ".", "brushMask", "for", "_", "in", "range", "(", "totalSteps", ")", ":", "#Make the dab on this point", "applyMirroredDab_jit", "(", "mirr", ",", "laydata", ",", "int", "(", "x", ")", ",", "int", "(", "y", ")", ",", "colbrsource", ".", "copy", "(", ")", ",", "canvSize", ",", "brmask", ")", "#Mode the point for the next step and update the distances", "x", "+=", "lendir_x", "(", "length", ",", "direction", ")", "y", "+=", "lendir_y", "(", "length", ",", "direction", ")", "#..if I don't use source caching..", "else", ":", "#..do the normal drawing", "for", "_", "in", "range", "(", "totalSteps", ")", ":", "#Make the dab on this point", "self", ".", "brush", ".", "makeDab", "(", "lay", ",", "int", "(", "x", ")", ",", "int", "(", "y", ")", ",", "col", ",", "secCol", ",", "mirror", "=", "mirr", ")", "#Mode the point for the next step and update the distances", "x", "+=", "lendir_x", "(", "length", ",", "direction", ")", "y", "+=", "lendir_y", "(", "length", ",", "direction", ")" ]
Draws a line on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: Starting X coordinate. :param y1: Starting Y coordinate. :param x2: End X coordinate. :param y2: End Y coordinate. :rtype: Nothing.
[ "Draws", "a", "line", "on", "the", "current", ":", "py", ":", "class", ":", "Layer", "with", "the", "current", ":", "py", ":", "class", ":", "Brush", ".", "Coordinates", "are", "relative", "to", "the", "original", "layer", "size", "WITHOUT", "downsampling", "applied", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L65-L123
elkiwy/paynter
paynter/paynter.py
Paynter.drawPoint
def drawPoint(self, x, y, silent=True): """ Draws a point on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: Point X coordinate. :param y1: Point Y coordinate. :rtype: Nothing. """ start = time.time() #Downsample the coordinates x = int(x/config.DOWNSAMPLING) y = int(y/config.DOWNSAMPLING) #Apply the dab with or without source caching if self.brush.usesSourceCaching: applyMirroredDab_jit(self.mirrorMode, self.image.getActiveLayer().data, int(x-self.brush.brushSize*0.5), int(y-self.brush.brushSize*0.5), self.brush.coloredBrushSource.copy(), config.CANVAS_SIZE, self.brush.brushMask) else: self.brush.makeDab(self.image.getActiveLayer(), int(x), int(y), self.color, self.secondColor, mirror=self.mirrorMode) config.AVGTIME.append(time.time()-start)
python
def drawPoint(self, x, y, silent=True): """ Draws a point on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: Point X coordinate. :param y1: Point Y coordinate. :rtype: Nothing. """ start = time.time() #Downsample the coordinates x = int(x/config.DOWNSAMPLING) y = int(y/config.DOWNSAMPLING) #Apply the dab with or without source caching if self.brush.usesSourceCaching: applyMirroredDab_jit(self.mirrorMode, self.image.getActiveLayer().data, int(x-self.brush.brushSize*0.5), int(y-self.brush.brushSize*0.5), self.brush.coloredBrushSource.copy(), config.CANVAS_SIZE, self.brush.brushMask) else: self.brush.makeDab(self.image.getActiveLayer(), int(x), int(y), self.color, self.secondColor, mirror=self.mirrorMode) config.AVGTIME.append(time.time()-start)
[ "def", "drawPoint", "(", "self", ",", "x", ",", "y", ",", "silent", "=", "True", ")", ":", "start", "=", "time", ".", "time", "(", ")", "#Downsample the coordinates", "x", "=", "int", "(", "x", "/", "config", ".", "DOWNSAMPLING", ")", "y", "=", "int", "(", "y", "/", "config", ".", "DOWNSAMPLING", ")", "#Apply the dab with or without source caching", "if", "self", ".", "brush", ".", "usesSourceCaching", ":", "applyMirroredDab_jit", "(", "self", ".", "mirrorMode", ",", "self", ".", "image", ".", "getActiveLayer", "(", ")", ".", "data", ",", "int", "(", "x", "-", "self", ".", "brush", ".", "brushSize", "*", "0.5", ")", ",", "int", "(", "y", "-", "self", ".", "brush", ".", "brushSize", "*", "0.5", ")", ",", "self", ".", "brush", ".", "coloredBrushSource", ".", "copy", "(", ")", ",", "config", ".", "CANVAS_SIZE", ",", "self", ".", "brush", ".", "brushMask", ")", "else", ":", "self", ".", "brush", ".", "makeDab", "(", "self", ".", "image", ".", "getActiveLayer", "(", ")", ",", "int", "(", "x", ")", ",", "int", "(", "y", ")", ",", "self", ".", "color", ",", "self", ".", "secondColor", ",", "mirror", "=", "self", ".", "mirrorMode", ")", "config", ".", "AVGTIME", ".", "append", "(", "time", ".", "time", "(", ")", "-", "start", ")" ]
Draws a point on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: Point X coordinate. :param y1: Point Y coordinate. :rtype: Nothing.
[ "Draws", "a", "point", "on", "the", "current", ":", "py", ":", "class", ":", "Layer", "with", "the", "current", ":", "py", ":", "class", ":", "Brush", ".", "Coordinates", "are", "relative", "to", "the", "original", "layer", "size", "WITHOUT", "downsampling", "applied", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L127-L147
elkiwy/paynter
paynter/paynter.py
Paynter.drawPath
def drawPath(self, pointList): """ Draws a series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`. No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param pointList: A list of point like :code:`[(0, 0), (100, 100), (100, 200)]`. :rtype: Nothing. """ self.drawLine(pointList[0][0], pointList[0][1], pointList[1][0], pointList[1][1]) i = 1 while i<len(pointList)-1: self.drawLine(pointList[i][0], pointList[i][1], pointList[i+1][0], pointList[i+1][1]) i+=1
python
def drawPath(self, pointList): """ Draws a series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`. No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param pointList: A list of point like :code:`[(0, 0), (100, 100), (100, 200)]`. :rtype: Nothing. """ self.drawLine(pointList[0][0], pointList[0][1], pointList[1][0], pointList[1][1]) i = 1 while i<len(pointList)-1: self.drawLine(pointList[i][0], pointList[i][1], pointList[i+1][0], pointList[i+1][1]) i+=1
[ "def", "drawPath", "(", "self", ",", "pointList", ")", ":", "self", ".", "drawLine", "(", "pointList", "[", "0", "]", "[", "0", "]", ",", "pointList", "[", "0", "]", "[", "1", "]", ",", "pointList", "[", "1", "]", "[", "0", "]", ",", "pointList", "[", "1", "]", "[", "1", "]", ")", "i", "=", "1", "while", "i", "<", "len", "(", "pointList", ")", "-", "1", ":", "self", ".", "drawLine", "(", "pointList", "[", "i", "]", "[", "0", "]", ",", "pointList", "[", "i", "]", "[", "1", "]", ",", "pointList", "[", "i", "+", "1", "]", "[", "0", "]", ",", "pointList", "[", "i", "+", "1", "]", "[", "1", "]", ")", "i", "+=", "1" ]
Draws a series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`. No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param pointList: A list of point like :code:`[(0, 0), (100, 100), (100, 200)]`. :rtype: Nothing.
[ "Draws", "a", "series", "of", "lines", "on", "the", "current", ":", "py", ":", "class", ":", "Layer", "with", "the", "current", ":", "py", ":", "class", ":", "Brush", ".", "No", "interpolation", "is", "applied", "to", "these", "point", "and", ":", "py", ":", "meth", ":", "drawLine", "will", "be", "used", "to", "connect", "all", "the", "points", "lineraly", ".", "Coordinates", "are", "relative", "to", "the", "original", "layer", "size", "WITHOUT", "downsampling", "applied", ".", ":", "param", "pointList", ":", "A", "list", "of", "point", "like", ":", "code", ":", "[", "(", "0", "0", ")", "(", "100", "100", ")", "(", "100", "200", ")", "]", ".", ":", "rtype", ":", "Nothing", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L153-L166
elkiwy/paynter
paynter/paynter.py
Paynter.drawClosedPath
def drawClosedPath(self, pointList): """ Draws a closed series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`. No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param pointList: A list of point like :code:`[(0, 0), (100, 100), (100, 200)]`. :rtype: Nothing. """ self.drawLine(pointList[0][0], pointList[0][1], pointList[1][0], pointList[1][1]) i = 1 while i<len(pointList)-1: self.drawLine(pointList[i][0], pointList[i][1], pointList[i+1][0], pointList[i+1][1]) i+=1 self.drawLine(pointList[-1][0], pointList[-1][1], pointList[0][0], pointList[0][1])
python
def drawClosedPath(self, pointList): """ Draws a closed series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`. No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param pointList: A list of point like :code:`[(0, 0), (100, 100), (100, 200)]`. :rtype: Nothing. """ self.drawLine(pointList[0][0], pointList[0][1], pointList[1][0], pointList[1][1]) i = 1 while i<len(pointList)-1: self.drawLine(pointList[i][0], pointList[i][1], pointList[i+1][0], pointList[i+1][1]) i+=1 self.drawLine(pointList[-1][0], pointList[-1][1], pointList[0][0], pointList[0][1])
[ "def", "drawClosedPath", "(", "self", ",", "pointList", ")", ":", "self", ".", "drawLine", "(", "pointList", "[", "0", "]", "[", "0", "]", ",", "pointList", "[", "0", "]", "[", "1", "]", ",", "pointList", "[", "1", "]", "[", "0", "]", ",", "pointList", "[", "1", "]", "[", "1", "]", ")", "i", "=", "1", "while", "i", "<", "len", "(", "pointList", ")", "-", "1", ":", "self", ".", "drawLine", "(", "pointList", "[", "i", "]", "[", "0", "]", ",", "pointList", "[", "i", "]", "[", "1", "]", ",", "pointList", "[", "i", "+", "1", "]", "[", "0", "]", ",", "pointList", "[", "i", "+", "1", "]", "[", "1", "]", ")", "i", "+=", "1", "self", ".", "drawLine", "(", "pointList", "[", "-", "1", "]", "[", "0", "]", ",", "pointList", "[", "-", "1", "]", "[", "1", "]", ",", "pointList", "[", "0", "]", "[", "0", "]", ",", "pointList", "[", "0", "]", "[", "1", "]", ")" ]
Draws a closed series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`. No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param pointList: A list of point like :code:`[(0, 0), (100, 100), (100, 200)]`. :rtype: Nothing.
[ "Draws", "a", "closed", "series", "of", "lines", "on", "the", "current", ":", "py", ":", "class", ":", "Layer", "with", "the", "current", ":", "py", ":", "class", ":", "Brush", ".", "No", "interpolation", "is", "applied", "to", "these", "point", "and", ":", "py", ":", "meth", ":", "drawLine", "will", "be", "used", "to", "connect", "all", "the", "points", "lineraly", ".", "Coordinates", "are", "relative", "to", "the", "original", "layer", "size", "WITHOUT", "downsampling", "applied", ".", ":", "param", "pointList", ":", "A", "list", "of", "point", "like", ":", "code", ":", "[", "(", "0", "0", ")", "(", "100", "100", ")", "(", "100", "200", ")", "]", ".", ":", "rtype", ":", "Nothing", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L169-L183
elkiwy/paynter
paynter/paynter.py
Paynter.drawRect
def drawRect(self, x1, y1, x2, y2, angle=0): """ Draws a rectangle on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: The X of the top-left corner of the rectangle. :param y1: The Y of the top-left corner of the rectangle. :param x2: The X of the bottom-right corner of the rectangle. :param y2: The Y of the bottom-right corner of the rectangle. :param angle: An angle (in degrees) of rotation around the center of the rectangle. :rtype: Nothing. """ vertices = [[x1,y1],[x2,y1],[x2,y2],[x1,y2],] rotatedVertices = rotateMatrix(vertices, (x1+x2)*0.5, (y1+y2)*0.5, angle) self.drawClosedPath(rotatedVertices)
python
def drawRect(self, x1, y1, x2, y2, angle=0): """ Draws a rectangle on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: The X of the top-left corner of the rectangle. :param y1: The Y of the top-left corner of the rectangle. :param x2: The X of the bottom-right corner of the rectangle. :param y2: The Y of the bottom-right corner of the rectangle. :param angle: An angle (in degrees) of rotation around the center of the rectangle. :rtype: Nothing. """ vertices = [[x1,y1],[x2,y1],[x2,y2],[x1,y2],] rotatedVertices = rotateMatrix(vertices, (x1+x2)*0.5, (y1+y2)*0.5, angle) self.drawClosedPath(rotatedVertices)
[ "def", "drawRect", "(", "self", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "angle", "=", "0", ")", ":", "vertices", "=", "[", "[", "x1", ",", "y1", "]", ",", "[", "x2", ",", "y1", "]", ",", "[", "x2", ",", "y2", "]", ",", "[", "x1", ",", "y2", "]", ",", "]", "rotatedVertices", "=", "rotateMatrix", "(", "vertices", ",", "(", "x1", "+", "x2", ")", "*", "0.5", ",", "(", "y1", "+", "y2", ")", "*", "0.5", ",", "angle", ")", "self", ".", "drawClosedPath", "(", "rotatedVertices", ")" ]
Draws a rectangle on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: The X of the top-left corner of the rectangle. :param y1: The Y of the top-left corner of the rectangle. :param x2: The X of the bottom-right corner of the rectangle. :param y2: The Y of the bottom-right corner of the rectangle. :param angle: An angle (in degrees) of rotation around the center of the rectangle. :rtype: Nothing.
[ "Draws", "a", "rectangle", "on", "the", "current", ":", "py", ":", "class", ":", "Layer", "with", "the", "current", ":", "py", ":", "class", ":", "Brush", ".", "Coordinates", "are", "relative", "to", "the", "original", "layer", "size", "WITHOUT", "downsampling", "applied", ".", ":", "param", "x1", ":", "The", "X", "of", "the", "top", "-", "left", "corner", "of", "the", "rectangle", ".", ":", "param", "y1", ":", "The", "Y", "of", "the", "top", "-", "left", "corner", "of", "the", "rectangle", ".", ":", "param", "x2", ":", "The", "X", "of", "the", "bottom", "-", "right", "corner", "of", "the", "rectangle", ".", ":", "param", "y2", ":", "The", "Y", "of", "the", "bottom", "-", "right", "corner", "of", "the", "rectangle", ".", ":", "param", "angle", ":", "An", "angle", "(", "in", "degrees", ")", "of", "rotation", "around", "the", "center", "of", "the", "rectangle", ".", ":", "rtype", ":", "Nothing", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L186-L200
elkiwy/paynter
paynter/paynter.py
Paynter.fillLayerWithColor
def fillLayerWithColor(self, color): """ Fills the current :py:class:`Layer` with the current :py:class:`Color`. :param color: The :py:class:`Color` to apply to the layer. :rtype: Nothing. """ layer = self.image.getActiveLayer().data colorRGBA = color.get_0_255() layer[:,:,0] = colorRGBA[0] layer[:,:,1] = colorRGBA[1] layer[:,:,2] = colorRGBA[2] layer[:,:,3] = colorRGBA[3]
python
def fillLayerWithColor(self, color): """ Fills the current :py:class:`Layer` with the current :py:class:`Color`. :param color: The :py:class:`Color` to apply to the layer. :rtype: Nothing. """ layer = self.image.getActiveLayer().data colorRGBA = color.get_0_255() layer[:,:,0] = colorRGBA[0] layer[:,:,1] = colorRGBA[1] layer[:,:,2] = colorRGBA[2] layer[:,:,3] = colorRGBA[3]
[ "def", "fillLayerWithColor", "(", "self", ",", "color", ")", ":", "layer", "=", "self", ".", "image", ".", "getActiveLayer", "(", ")", ".", "data", "colorRGBA", "=", "color", ".", "get_0_255", "(", ")", "layer", "[", ":", ",", ":", ",", "0", "]", "=", "colorRGBA", "[", "0", "]", "layer", "[", ":", ",", ":", ",", "1", "]", "=", "colorRGBA", "[", "1", "]", "layer", "[", ":", ",", ":", ",", "2", "]", "=", "colorRGBA", "[", "2", "]", "layer", "[", ":", ",", ":", ",", "3", "]", "=", "colorRGBA", "[", "3", "]" ]
Fills the current :py:class:`Layer` with the current :py:class:`Color`. :param color: The :py:class:`Color` to apply to the layer. :rtype: Nothing.
[ "Fills", "the", "current", ":", "py", ":", "class", ":", "Layer", "with", "the", "current", ":", "py", ":", "class", ":", "Color", ".", ":", "param", "color", ":", "The", ":", "py", ":", "class", ":", "Color", "to", "apply", "to", "the", "layer", ".", ":", "rtype", ":", "Nothing", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L203-L215
elkiwy/paynter
paynter/paynter.py
Paynter.addBorder
def addBorder(self, width, color=None): """ Add a border to the current :py:class:`Layer`. :param width: The width of the border. :param color: The :py:class:`Color` of the border, current :py:class:`Color` is the default value. :rtype: Nothing. """ width = int(width/config.DOWNSAMPLING) if color==None: color = self.color layer = self.image.getActiveLayer().data colorRGBA = color.get_0_255() print('adding border'+str(colorRGBA)+str(width)+str(layer.shape)) layer[0:width,:,0] = colorRGBA[0] layer[0:width,:,1] = colorRGBA[1] layer[0:width,:,2] = colorRGBA[2] layer[0:width,:,3] = colorRGBA[3] layer[:,0:width,0] = colorRGBA[0] layer[:,0:width,1] = colorRGBA[1] layer[:,0:width,2] = colorRGBA[2] layer[:,0:width,3] = colorRGBA[3] layer[layer.shape[0]-width:layer.shape[0],:,0] = colorRGBA[0] layer[layer.shape[0]-width:layer.shape[0],:,1] = colorRGBA[1] layer[layer.shape[0]-width:layer.shape[0],:,2] = colorRGBA[2] layer[layer.shape[0]-width:layer.shape[0],:,3] = colorRGBA[3] layer[:,layer.shape[1]-width:layer.shape[1],0] = colorRGBA[0] layer[:,layer.shape[1]-width:layer.shape[1],1] = colorRGBA[1] layer[:,layer.shape[1]-width:layer.shape[1],2] = colorRGBA[2] layer[:,layer.shape[1]-width:layer.shape[1],3] = colorRGBA[3]
python
def addBorder(self, width, color=None): """ Add a border to the current :py:class:`Layer`. :param width: The width of the border. :param color: The :py:class:`Color` of the border, current :py:class:`Color` is the default value. :rtype: Nothing. """ width = int(width/config.DOWNSAMPLING) if color==None: color = self.color layer = self.image.getActiveLayer().data colorRGBA = color.get_0_255() print('adding border'+str(colorRGBA)+str(width)+str(layer.shape)) layer[0:width,:,0] = colorRGBA[0] layer[0:width,:,1] = colorRGBA[1] layer[0:width,:,2] = colorRGBA[2] layer[0:width,:,3] = colorRGBA[3] layer[:,0:width,0] = colorRGBA[0] layer[:,0:width,1] = colorRGBA[1] layer[:,0:width,2] = colorRGBA[2] layer[:,0:width,3] = colorRGBA[3] layer[layer.shape[0]-width:layer.shape[0],:,0] = colorRGBA[0] layer[layer.shape[0]-width:layer.shape[0],:,1] = colorRGBA[1] layer[layer.shape[0]-width:layer.shape[0],:,2] = colorRGBA[2] layer[layer.shape[0]-width:layer.shape[0],:,3] = colorRGBA[3] layer[:,layer.shape[1]-width:layer.shape[1],0] = colorRGBA[0] layer[:,layer.shape[1]-width:layer.shape[1],1] = colorRGBA[1] layer[:,layer.shape[1]-width:layer.shape[1],2] = colorRGBA[2] layer[:,layer.shape[1]-width:layer.shape[1],3] = colorRGBA[3]
[ "def", "addBorder", "(", "self", ",", "width", ",", "color", "=", "None", ")", ":", "width", "=", "int", "(", "width", "/", "config", ".", "DOWNSAMPLING", ")", "if", "color", "==", "None", ":", "color", "=", "self", ".", "color", "layer", "=", "self", ".", "image", ".", "getActiveLayer", "(", ")", ".", "data", "colorRGBA", "=", "color", ".", "get_0_255", "(", ")", "print", "(", "'adding border'", "+", "str", "(", "colorRGBA", ")", "+", "str", "(", "width", ")", "+", "str", "(", "layer", ".", "shape", ")", ")", "layer", "[", "0", ":", "width", ",", ":", ",", "0", "]", "=", "colorRGBA", "[", "0", "]", "layer", "[", "0", ":", "width", ",", ":", ",", "1", "]", "=", "colorRGBA", "[", "1", "]", "layer", "[", "0", ":", "width", ",", ":", ",", "2", "]", "=", "colorRGBA", "[", "2", "]", "layer", "[", "0", ":", "width", ",", ":", ",", "3", "]", "=", "colorRGBA", "[", "3", "]", "layer", "[", ":", ",", "0", ":", "width", ",", "0", "]", "=", "colorRGBA", "[", "0", "]", "layer", "[", ":", ",", "0", ":", "width", ",", "1", "]", "=", "colorRGBA", "[", "1", "]", "layer", "[", ":", ",", "0", ":", "width", ",", "2", "]", "=", "colorRGBA", "[", "2", "]", "layer", "[", ":", ",", "0", ":", "width", ",", "3", "]", "=", "colorRGBA", "[", "3", "]", "layer", "[", "layer", ".", "shape", "[", "0", "]", "-", "width", ":", "layer", ".", "shape", "[", "0", "]", ",", ":", ",", "0", "]", "=", "colorRGBA", "[", "0", "]", "layer", "[", "layer", ".", "shape", "[", "0", "]", "-", "width", ":", "layer", ".", "shape", "[", "0", "]", ",", ":", ",", "1", "]", "=", "colorRGBA", "[", "1", "]", "layer", "[", "layer", ".", "shape", "[", "0", "]", "-", "width", ":", "layer", ".", "shape", "[", "0", "]", ",", ":", ",", "2", "]", "=", "colorRGBA", "[", "2", "]", "layer", "[", "layer", ".", "shape", "[", "0", "]", "-", "width", ":", "layer", ".", "shape", "[", "0", "]", ",", ":", ",", "3", "]", "=", "colorRGBA", "[", "3", "]", "layer", "[", ":", ",", "layer", ".", "shape", "[", "1", "]", "-", "width", ":", "layer", ".", "shape", "[", "1", "]", ",", "0", "]", "=", "colorRGBA", "[", "0", "]", "layer", "[", ":", ",", "layer", ".", "shape", "[", "1", "]", "-", "width", ":", "layer", ".", "shape", "[", "1", "]", ",", "1", "]", "=", "colorRGBA", "[", "1", "]", "layer", "[", ":", ",", "layer", ".", "shape", "[", "1", "]", "-", "width", ":", "layer", ".", "shape", "[", "1", "]", ",", "2", "]", "=", "colorRGBA", "[", "2", "]", "layer", "[", ":", ",", "layer", ".", "shape", "[", "1", "]", "-", "width", ":", "layer", ".", "shape", "[", "1", "]", ",", "3", "]", "=", "colorRGBA", "[", "3", "]" ]
Add a border to the current :py:class:`Layer`. :param width: The width of the border. :param color: The :py:class:`Color` of the border, current :py:class:`Color` is the default value. :rtype: Nothing.
[ "Add", "a", "border", "to", "the", "current", ":", "py", ":", "class", ":", "Layer", ".", ":", "param", "width", ":", "The", "width", "of", "the", "border", ".", ":", "param", "color", ":", "The", ":", "py", ":", "class", ":", "Color", "of", "the", "border", "current", ":", "py", ":", "class", ":", "Color", "is", "the", "default", "value", ".", ":", "rtype", ":", "Nothing", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L218-L250
elkiwy/paynter
paynter/paynter.py
Paynter.setColor
def setColor(self, color): """ Sets the current :py:class:`Color` to use. :param color: The :py:class:`Color` to use. :rtype: Nothing. """ self.color = color if self.brush and self.brush.doesUseSourceCaching(): self.brush.cacheBrush(color)
python
def setColor(self, color): """ Sets the current :py:class:`Color` to use. :param color: The :py:class:`Color` to use. :rtype: Nothing. """ self.color = color if self.brush and self.brush.doesUseSourceCaching(): self.brush.cacheBrush(color)
[ "def", "setColor", "(", "self", ",", "color", ")", ":", "self", ".", "color", "=", "color", "if", "self", ".", "brush", "and", "self", ".", "brush", ".", "doesUseSourceCaching", "(", ")", ":", "self", ".", "brush", ".", "cacheBrush", "(", "color", ")" ]
Sets the current :py:class:`Color` to use. :param color: The :py:class:`Color` to use. :rtype: Nothing.
[ "Sets", "the", "current", ":", "py", ":", "class", ":", "Color", "to", "use", ".", ":", "param", "color", ":", "The", ":", "py", ":", "class", ":", "Color", "to", "use", ".", ":", "rtype", ":", "Nothing", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L259-L268
elkiwy/paynter
paynter/paynter.py
Paynter.setColorAlpha
def setColorAlpha(self, fixed=None, proportional=None): """ Change the alpha of the current :py:class:`Color`. :param fixed: Set the absolute 0-1 value of the alpha. :param proportional: Set the relative value of the alpha (Es: If the current alpha is 0.8, a proportional value of 0.5 will set the final value to 0.4). :rtype: Nothing. """ if fixed!=None: self.color.set_alpha(fixed) elif proportional!=None: self.color.set_alpha(self.color.get_alpha()*proportional)
python
def setColorAlpha(self, fixed=None, proportional=None): """ Change the alpha of the current :py:class:`Color`. :param fixed: Set the absolute 0-1 value of the alpha. :param proportional: Set the relative value of the alpha (Es: If the current alpha is 0.8, a proportional value of 0.5 will set the final value to 0.4). :rtype: Nothing. """ if fixed!=None: self.color.set_alpha(fixed) elif proportional!=None: self.color.set_alpha(self.color.get_alpha()*proportional)
[ "def", "setColorAlpha", "(", "self", ",", "fixed", "=", "None", ",", "proportional", "=", "None", ")", ":", "if", "fixed", "!=", "None", ":", "self", ".", "color", ".", "set_alpha", "(", "fixed", ")", "elif", "proportional", "!=", "None", ":", "self", ".", "color", ".", "set_alpha", "(", "self", ".", "color", ".", "get_alpha", "(", ")", "*", "proportional", ")" ]
Change the alpha of the current :py:class:`Color`. :param fixed: Set the absolute 0-1 value of the alpha. :param proportional: Set the relative value of the alpha (Es: If the current alpha is 0.8, a proportional value of 0.5 will set the final value to 0.4). :rtype: Nothing.
[ "Change", "the", "alpha", "of", "the", "current", ":", "py", ":", "class", ":", "Color", ".", ":", "param", "fixed", ":", "Set", "the", "absolute", "0", "-", "1", "value", "of", "the", "alpha", ".", ":", "param", "proportional", ":", "Set", "the", "relative", "value", "of", "the", "alpha", "(", "Es", ":", "If", "the", "current", "alpha", "is", "0", ".", "8", "a", "proportional", "value", "of", "0", ".", "5", "will", "set", "the", "final", "value", "to", "0", ".", "4", ")", ".", ":", "rtype", ":", "Nothing", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L271-L282
elkiwy/paynter
paynter/paynter.py
Paynter.swapColors
def swapColors(self): """ Swaps the current :py:class:`Color` with the secondary :py:class:`Color`. :rtype: Nothing. """ rgba = self.color.get_0_255() self.color = self.secondColor self.secondColor = Color(rgba, '0-255')
python
def swapColors(self): """ Swaps the current :py:class:`Color` with the secondary :py:class:`Color`. :rtype: Nothing. """ rgba = self.color.get_0_255() self.color = self.secondColor self.secondColor = Color(rgba, '0-255')
[ "def", "swapColors", "(", "self", ")", ":", "rgba", "=", "self", ".", "color", ".", "get_0_255", "(", ")", "self", ".", "color", "=", "self", ".", "secondColor", "self", ".", "secondColor", "=", "Color", "(", "rgba", ",", "'0-255'", ")" ]
Swaps the current :py:class:`Color` with the secondary :py:class:`Color`. :rtype: Nothing.
[ "Swaps", "the", "current", ":", "py", ":", "class", ":", "Color", "with", "the", "secondary", ":", "py", ":", "class", ":", "Color", ".", ":", "rtype", ":", "Nothing", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L303-L311
elkiwy/paynter
paynter/paynter.py
Paynter.setBrush
def setBrush(self, b, resize=0, proportional=None): """ Sets the size of the current :py:class:`Brush`. :param brush: The :py:class:`Brush` object to use as a brush. :param resize: An optional absolute value to resize the brush before using it. :param proportional: An optional relative float 0-1 value to resize the brush before using it. :rtype: Nothing. """ if proportional!=None: resize = int(self.brush.brushSize*0.5) b.resizeBrush(resize) #If resize=0 it reset to its default size self.brush = b if self.brush and self.brush.doesUseSourceCaching(): self.brush.cacheBrush(self.color)
python
def setBrush(self, b, resize=0, proportional=None): """ Sets the size of the current :py:class:`Brush`. :param brush: The :py:class:`Brush` object to use as a brush. :param resize: An optional absolute value to resize the brush before using it. :param proportional: An optional relative float 0-1 value to resize the brush before using it. :rtype: Nothing. """ if proportional!=None: resize = int(self.brush.brushSize*0.5) b.resizeBrush(resize) #If resize=0 it reset to its default size self.brush = b if self.brush and self.brush.doesUseSourceCaching(): self.brush.cacheBrush(self.color)
[ "def", "setBrush", "(", "self", ",", "b", ",", "resize", "=", "0", ",", "proportional", "=", "None", ")", ":", "if", "proportional", "!=", "None", ":", "resize", "=", "int", "(", "self", ".", "brush", ".", "brushSize", "*", "0.5", ")", "b", ".", "resizeBrush", "(", "resize", ")", "#If resize=0 it reset to its default size", "self", ".", "brush", "=", "b", "if", "self", ".", "brush", "and", "self", ".", "brush", ".", "doesUseSourceCaching", "(", ")", ":", "self", ".", "brush", ".", "cacheBrush", "(", "self", ".", "color", ")" ]
Sets the size of the current :py:class:`Brush`. :param brush: The :py:class:`Brush` object to use as a brush. :param resize: An optional absolute value to resize the brush before using it. :param proportional: An optional relative float 0-1 value to resize the brush before using it. :rtype: Nothing.
[ "Sets", "the", "size", "of", "the", "current", ":", "py", ":", "class", ":", "Brush", ".", ":", "param", "brush", ":", "The", ":", "py", ":", "class", ":", "Brush", "object", "to", "use", "as", "a", "brush", ".", ":", "param", "resize", ":", "An", "optional", "absolute", "value", "to", "resize", "the", "brush", "before", "using", "it", ".", ":", "param", "proportional", ":", "An", "optional", "relative", "float", "0", "-", "1", "value", "to", "resize", "the", "brush", "before", "using", "it", ".", ":", "rtype", ":", "Nothing", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L314-L328
elkiwy/paynter
paynter/paynter.py
Paynter.setMirrorMode
def setMirrorMode(self, mirror): """ Sets the mirror mode to use in the next operation. :param mirror: A string object with one of these values : '', 'h', 'v', 'hv'. "h" stands for horizontal mirroring, while "v" stands for vertical mirroring. "hv" sets both at the same time. :rtype: Nothing. """ assert (mirror=='' or mirror=='h' or mirror=='v' or mirror=='hv'or mirror=='vh'), 'setMirrorMode: wrong mirror mode, got '+str(mirror)+' expected one of ["","h","v","hv"]' #Round up all the coordinates and convert them to int if mirror=='': mirror = 0 elif mirror=='h': mirror = 1 elif mirror=='v': mirror = 2 elif mirror=='hv': mirror = 3 elif mirror=='vh': mirror = 3 self.mirrorMode = mirror
python
def setMirrorMode(self, mirror): """ Sets the mirror mode to use in the next operation. :param mirror: A string object with one of these values : '', 'h', 'v', 'hv'. "h" stands for horizontal mirroring, while "v" stands for vertical mirroring. "hv" sets both at the same time. :rtype: Nothing. """ assert (mirror=='' or mirror=='h' or mirror=='v' or mirror=='hv'or mirror=='vh'), 'setMirrorMode: wrong mirror mode, got '+str(mirror)+' expected one of ["","h","v","hv"]' #Round up all the coordinates and convert them to int if mirror=='': mirror = 0 elif mirror=='h': mirror = 1 elif mirror=='v': mirror = 2 elif mirror=='hv': mirror = 3 elif mirror=='vh': mirror = 3 self.mirrorMode = mirror
[ "def", "setMirrorMode", "(", "self", ",", "mirror", ")", ":", "assert", "(", "mirror", "==", "''", "or", "mirror", "==", "'h'", "or", "mirror", "==", "'v'", "or", "mirror", "==", "'hv'", "or", "mirror", "==", "'vh'", ")", ",", "'setMirrorMode: wrong mirror mode, got '", "+", "str", "(", "mirror", ")", "+", "' expected one of [\"\",\"h\",\"v\",\"hv\"]'", "#Round up all the coordinates and convert them to int\t\t", "if", "mirror", "==", "''", ":", "mirror", "=", "0", "elif", "mirror", "==", "'h'", ":", "mirror", "=", "1", "elif", "mirror", "==", "'v'", ":", "mirror", "=", "2", "elif", "mirror", "==", "'hv'", ":", "mirror", "=", "3", "elif", "mirror", "==", "'vh'", ":", "mirror", "=", "3", "self", ".", "mirrorMode", "=", "mirror" ]
Sets the mirror mode to use in the next operation. :param mirror: A string object with one of these values : '', 'h', 'v', 'hv'. "h" stands for horizontal mirroring, while "v" stands for vertical mirroring. "hv" sets both at the same time. :rtype: Nothing.
[ "Sets", "the", "mirror", "mode", "to", "use", "in", "the", "next", "operation", ".", ":", "param", "mirror", ":", "A", "string", "object", "with", "one", "of", "these", "values", ":", "h", "v", "hv", ".", "h", "stands", "for", "horizontal", "mirroring", "while", "v", "stands", "for", "vertical", "mirroring", ".", "hv", "sets", "both", "at", "the", "same", "time", ".", ":", "rtype", ":", "Nothing", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L331-L346
elkiwy/paynter
paynter/paynter.py
Paynter.renderImage
def renderImage(self, output='', show=True): """ Renders the :py:class:`Image` and outputs the final PNG file. :param output: A string with the output file path, can be empty if you don't want to save the final image. :param show: A boolean telling the system to display the final image after the rendering is done. :rtype: Nothing. """ #Merge all the layers to apply blending modes resultLayer = self.image.mergeAllLayers() #Show and save the results img = PIL.Image.fromarray(resultLayer.data, 'RGBA') if show: img.show() if output!='': img.save(output, 'PNG')
python
def renderImage(self, output='', show=True): """ Renders the :py:class:`Image` and outputs the final PNG file. :param output: A string with the output file path, can be empty if you don't want to save the final image. :param show: A boolean telling the system to display the final image after the rendering is done. :rtype: Nothing. """ #Merge all the layers to apply blending modes resultLayer = self.image.mergeAllLayers() #Show and save the results img = PIL.Image.fromarray(resultLayer.data, 'RGBA') if show: img.show() if output!='': img.save(output, 'PNG')
[ "def", "renderImage", "(", "self", ",", "output", "=", "''", ",", "show", "=", "True", ")", ":", "#Merge all the layers to apply blending modes", "resultLayer", "=", "self", ".", "image", ".", "mergeAllLayers", "(", ")", "#Show and save the results", "img", "=", "PIL", ".", "Image", ".", "fromarray", "(", "resultLayer", ".", "data", ",", "'RGBA'", ")", "if", "show", ":", "img", ".", "show", "(", ")", "if", "output", "!=", "''", ":", "img", ".", "save", "(", "output", ",", "'PNG'", ")" ]
Renders the :py:class:`Image` and outputs the final PNG file. :param output: A string with the output file path, can be empty if you don't want to save the final image. :param show: A boolean telling the system to display the final image after the rendering is done. :rtype: Nothing.
[ "Renders", "the", ":", "py", ":", "class", ":", "Image", "and", "outputs", "the", "final", "PNG", "file", ".", ":", "param", "output", ":", "A", "string", "with", "the", "output", "file", "path", "can", "be", "empty", "if", "you", "don", "t", "want", "to", "save", "the", "final", "image", ".", ":", "param", "show", ":", "A", "boolean", "telling", "the", "system", "to", "display", "the", "final", "image", "after", "the", "rendering", "is", "done", ".", ":", "rtype", ":", "Nothing", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L349-L367
elkiwy/paynter
paynter/paynter.py
Paynter.setActiveLayerEffect
def setActiveLayerEffect(self, effect): """ Changes the effect of the current active :py:class:`Layer`. :param output: A string with the one of the blend modes listed in :py:meth:`newLayer`. :rtype: Nothing. """ self.image.layers[self.image.activeLayer].effect = effect
python
def setActiveLayerEffect(self, effect): """ Changes the effect of the current active :py:class:`Layer`. :param output: A string with the one of the blend modes listed in :py:meth:`newLayer`. :rtype: Nothing. """ self.image.layers[self.image.activeLayer].effect = effect
[ "def", "setActiveLayerEffect", "(", "self", ",", "effect", ")", ":", "self", ".", "image", ".", "layers", "[", "self", ".", "image", ".", "activeLayer", "]", ".", "effect", "=", "effect" ]
Changes the effect of the current active :py:class:`Layer`. :param output: A string with the one of the blend modes listed in :py:meth:`newLayer`. :rtype: Nothing.
[ "Changes", "the", "effect", "of", "the", "current", "active", ":", "py", ":", "class", ":", "Layer", ".", ":", "param", "output", ":", "A", "string", "with", "the", "one", "of", "the", "blend", "modes", "listed", "in", ":", "py", ":", "meth", ":", "newLayer", ".", ":", "rtype", ":", "Nothing", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L380-L387
PolyJIT/benchbuild
benchbuild/utils/download.py
get_hash_of_dirs
def get_hash_of_dirs(directory): """ Recursively hash the contents of the given directory. Args: directory (str): The root directory we want to hash. Returns: A hash of all the contents in the directory. """ import hashlib sha = hashlib.sha512() if not os.path.exists(directory): return -1 for root, _, files in os.walk(directory): for name in files: filepath = local.path(root) / name if filepath.exists(): with open(filepath, 'rb') as next_file: for line in next_file: sha.update(line) return sha.hexdigest()
python
def get_hash_of_dirs(directory): """ Recursively hash the contents of the given directory. Args: directory (str): The root directory we want to hash. Returns: A hash of all the contents in the directory. """ import hashlib sha = hashlib.sha512() if not os.path.exists(directory): return -1 for root, _, files in os.walk(directory): for name in files: filepath = local.path(root) / name if filepath.exists(): with open(filepath, 'rb') as next_file: for line in next_file: sha.update(line) return sha.hexdigest()
[ "def", "get_hash_of_dirs", "(", "directory", ")", ":", "import", "hashlib", "sha", "=", "hashlib", ".", "sha512", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "return", "-", "1", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "directory", ")", ":", "for", "name", "in", "files", ":", "filepath", "=", "local", ".", "path", "(", "root", ")", "/", "name", "if", "filepath", ".", "exists", "(", ")", ":", "with", "open", "(", "filepath", ",", "'rb'", ")", "as", "next_file", ":", "for", "line", "in", "next_file", ":", "sha", ".", "update", "(", "line", ")", "return", "sha", ".", "hexdigest", "(", ")" ]
Recursively hash the contents of the given directory. Args: directory (str): The root directory we want to hash. Returns: A hash of all the contents in the directory.
[ "Recursively", "hash", "the", "contents", "of", "the", "given", "directory", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L23-L45
PolyJIT/benchbuild
benchbuild/utils/download.py
source_required
def source_required(src_file): """ Check, if a download is required. Args: src_file: The filename to check for. src_root: The path we find the file in. Returns: True, if we need to download something, False otherwise. """ if not src_file.exists(): return True required = True hash_file = src_file.with_suffix(".hash", depth=0) LOG.debug("Hash file location: %s", hash_file) if hash_file.exists(): new_hash = get_hash_of_dirs(src_file) with open(hash_file, 'r') as h_file: old_hash = h_file.readline() required = not new_hash == old_hash if required: from benchbuild.utils.cmd import rm rm("-r", src_file) rm(hash_file) if required: LOG.info("Source required for: %s", src_file) LOG.debug("Reason: src-exists: %s hash-exists: %s", src_file.exists(), hash_file.exists()) return required
python
def source_required(src_file): """ Check, if a download is required. Args: src_file: The filename to check for. src_root: The path we find the file in. Returns: True, if we need to download something, False otherwise. """ if not src_file.exists(): return True required = True hash_file = src_file.with_suffix(".hash", depth=0) LOG.debug("Hash file location: %s", hash_file) if hash_file.exists(): new_hash = get_hash_of_dirs(src_file) with open(hash_file, 'r') as h_file: old_hash = h_file.readline() required = not new_hash == old_hash if required: from benchbuild.utils.cmd import rm rm("-r", src_file) rm(hash_file) if required: LOG.info("Source required for: %s", src_file) LOG.debug("Reason: src-exists: %s hash-exists: %s", src_file.exists(), hash_file.exists()) return required
[ "def", "source_required", "(", "src_file", ")", ":", "if", "not", "src_file", ".", "exists", "(", ")", ":", "return", "True", "required", "=", "True", "hash_file", "=", "src_file", ".", "with_suffix", "(", "\".hash\"", ",", "depth", "=", "0", ")", "LOG", ".", "debug", "(", "\"Hash file location: %s\"", ",", "hash_file", ")", "if", "hash_file", ".", "exists", "(", ")", ":", "new_hash", "=", "get_hash_of_dirs", "(", "src_file", ")", "with", "open", "(", "hash_file", ",", "'r'", ")", "as", "h_file", ":", "old_hash", "=", "h_file", ".", "readline", "(", ")", "required", "=", "not", "new_hash", "==", "old_hash", "if", "required", ":", "from", "benchbuild", ".", "utils", ".", "cmd", "import", "rm", "rm", "(", "\"-r\"", ",", "src_file", ")", "rm", "(", "hash_file", ")", "if", "required", ":", "LOG", ".", "info", "(", "\"Source required for: %s\"", ",", "src_file", ")", "LOG", ".", "debug", "(", "\"Reason: src-exists: %s hash-exists: %s\"", ",", "src_file", ".", "exists", "(", ")", ",", "hash_file", ".", "exists", "(", ")", ")", "return", "required" ]
Check, if a download is required. Args: src_file: The filename to check for. src_root: The path we find the file in. Returns: True, if we need to download something, False otherwise.
[ "Check", "if", "a", "download", "is", "required", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L48-L78
PolyJIT/benchbuild
benchbuild/utils/download.py
update_hash
def update_hash(src_file): """ Update the hash for the given file. Args: src: The file name. root: The path of the given file. """ hash_file = local.path(src_file) + ".hash" new_hash = 0 with open(hash_file, 'w') as h_file: new_hash = get_hash_of_dirs(src_file) h_file.write(str(new_hash)) return new_hash
python
def update_hash(src_file): """ Update the hash for the given file. Args: src: The file name. root: The path of the given file. """ hash_file = local.path(src_file) + ".hash" new_hash = 0 with open(hash_file, 'w') as h_file: new_hash = get_hash_of_dirs(src_file) h_file.write(str(new_hash)) return new_hash
[ "def", "update_hash", "(", "src_file", ")", ":", "hash_file", "=", "local", ".", "path", "(", "src_file", ")", "+", "\".hash\"", "new_hash", "=", "0", "with", "open", "(", "hash_file", ",", "'w'", ")", "as", "h_file", ":", "new_hash", "=", "get_hash_of_dirs", "(", "src_file", ")", "h_file", ".", "write", "(", "str", "(", "new_hash", ")", ")", "return", "new_hash" ]
Update the hash for the given file. Args: src: The file name. root: The path of the given file.
[ "Update", "the", "hash", "for", "the", "given", "file", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L81-L94
PolyJIT/benchbuild
benchbuild/utils/download.py
Copy
def Copy(From, To): """ Small copy wrapper. Args: From (str): Path to the SOURCE. To (str): Path to the TARGET. """ from benchbuild.utils.cmd import cp cp("-ar", "--reflink=auto", From, To)
python
def Copy(From, To): """ Small copy wrapper. Args: From (str): Path to the SOURCE. To (str): Path to the TARGET. """ from benchbuild.utils.cmd import cp cp("-ar", "--reflink=auto", From, To)
[ "def", "Copy", "(", "From", ",", "To", ")", ":", "from", "benchbuild", ".", "utils", ".", "cmd", "import", "cp", "cp", "(", "\"-ar\"", ",", "\"--reflink=auto\"", ",", "From", ",", "To", ")" ]
Small copy wrapper. Args: From (str): Path to the SOURCE. To (str): Path to the TARGET.
[ "Small", "copy", "wrapper", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L97-L106
PolyJIT/benchbuild
benchbuild/utils/download.py
CopyNoFail
def CopyNoFail(src, root=None): """ Just copy fName into the current working directory, if it exists. No action is executed, if fName does not exist. No Hash is checked. Args: src: The filename we want to copy to '.'. root: The optional source dir we should pull fName from. Defaults to benchbuild.settings.CFG["tmpdir"]. Returns: True, if we copied something. """ if root is None: root = str(CFG["tmp_dir"]) src_path = local.path(root) / src if src_path.exists(): Copy(src_path, '.') return True return False
python
def CopyNoFail(src, root=None): """ Just copy fName into the current working directory, if it exists. No action is executed, if fName does not exist. No Hash is checked. Args: src: The filename we want to copy to '.'. root: The optional source dir we should pull fName from. Defaults to benchbuild.settings.CFG["tmpdir"]. Returns: True, if we copied something. """ if root is None: root = str(CFG["tmp_dir"]) src_path = local.path(root) / src if src_path.exists(): Copy(src_path, '.') return True return False
[ "def", "CopyNoFail", "(", "src", ",", "root", "=", "None", ")", ":", "if", "root", "is", "None", ":", "root", "=", "str", "(", "CFG", "[", "\"tmp_dir\"", "]", ")", "src_path", "=", "local", ".", "path", "(", "root", ")", "/", "src", "if", "src_path", ".", "exists", "(", ")", ":", "Copy", "(", "src_path", ",", "'.'", ")", "return", "True", "return", "False" ]
Just copy fName into the current working directory, if it exists. No action is executed, if fName does not exist. No Hash is checked. Args: src: The filename we want to copy to '.'. root: The optional source dir we should pull fName from. Defaults to benchbuild.settings.CFG["tmpdir"]. Returns: True, if we copied something.
[ "Just", "copy", "fName", "into", "the", "current", "working", "directory", "if", "it", "exists", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L109-L130
PolyJIT/benchbuild
benchbuild/utils/download.py
Wget
def Wget(src_url, tgt_name, tgt_root=None): """ Download url, if required. Args: src_url (str): Our SOURCE url. tgt_name (str): The filename we want to have on disk. tgt_root (str): The TARGET directory for the download. Defaults to ``CFG["tmpdir"]``. """ if tgt_root is None: tgt_root = str(CFG["tmp_dir"]) from benchbuild.utils.cmd import wget tgt_file = local.path(tgt_root) / tgt_name if not source_required(tgt_file): Copy(tgt_file, ".") return wget(src_url, "-O", tgt_file) update_hash(tgt_file) Copy(tgt_file, ".")
python
def Wget(src_url, tgt_name, tgt_root=None): """ Download url, if required. Args: src_url (str): Our SOURCE url. tgt_name (str): The filename we want to have on disk. tgt_root (str): The TARGET directory for the download. Defaults to ``CFG["tmpdir"]``. """ if tgt_root is None: tgt_root = str(CFG["tmp_dir"]) from benchbuild.utils.cmd import wget tgt_file = local.path(tgt_root) / tgt_name if not source_required(tgt_file): Copy(tgt_file, ".") return wget(src_url, "-O", tgt_file) update_hash(tgt_file) Copy(tgt_file, ".")
[ "def", "Wget", "(", "src_url", ",", "tgt_name", ",", "tgt_root", "=", "None", ")", ":", "if", "tgt_root", "is", "None", ":", "tgt_root", "=", "str", "(", "CFG", "[", "\"tmp_dir\"", "]", ")", "from", "benchbuild", ".", "utils", ".", "cmd", "import", "wget", "tgt_file", "=", "local", ".", "path", "(", "tgt_root", ")", "/", "tgt_name", "if", "not", "source_required", "(", "tgt_file", ")", ":", "Copy", "(", "tgt_file", ",", "\".\"", ")", "return", "wget", "(", "src_url", ",", "\"-O\"", ",", "tgt_file", ")", "update_hash", "(", "tgt_file", ")", "Copy", "(", "tgt_file", ",", "\".\"", ")" ]
Download url, if required. Args: src_url (str): Our SOURCE url. tgt_name (str): The filename we want to have on disk. tgt_root (str): The TARGET directory for the download. Defaults to ``CFG["tmpdir"]``.
[ "Download", "url", "if", "required", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L133-L155
PolyJIT/benchbuild
benchbuild/utils/download.py
with_wget
def with_wget(url_dict=None, target_file=None): """ Decorate a project class with wget-based version information. This adds two attributes to a project class: - A `versions` method that returns a list of available versions for this project. - A `repository` attribute that provides a repository string to download from later. We use the `git rev-list` subcommand to list available versions. Args: url_dict (dict): A dictionary that assigns a version to a download URL. target_file (str): An optional path where we should put the clone. If unspecified, we will use the `SRC_FILE` attribute of the decorated class. """ def wget_decorator(cls): def download_impl(self): """Download the selected version from the url_dict value.""" t_file = target_file if target_file else self.SRC_FILE t_version = url_dict[self.version] Wget(t_version, t_file) @staticmethod def versions_impl(): """Return a list of versions from the url_dict keys.""" return list(url_dict.keys()) cls.versions = versions_impl cls.download = download_impl return cls return wget_decorator
python
def with_wget(url_dict=None, target_file=None): """ Decorate a project class with wget-based version information. This adds two attributes to a project class: - A `versions` method that returns a list of available versions for this project. - A `repository` attribute that provides a repository string to download from later. We use the `git rev-list` subcommand to list available versions. Args: url_dict (dict): A dictionary that assigns a version to a download URL. target_file (str): An optional path where we should put the clone. If unspecified, we will use the `SRC_FILE` attribute of the decorated class. """ def wget_decorator(cls): def download_impl(self): """Download the selected version from the url_dict value.""" t_file = target_file if target_file else self.SRC_FILE t_version = url_dict[self.version] Wget(t_version, t_file) @staticmethod def versions_impl(): """Return a list of versions from the url_dict keys.""" return list(url_dict.keys()) cls.versions = versions_impl cls.download = download_impl return cls return wget_decorator
[ "def", "with_wget", "(", "url_dict", "=", "None", ",", "target_file", "=", "None", ")", ":", "def", "wget_decorator", "(", "cls", ")", ":", "def", "download_impl", "(", "self", ")", ":", "\"\"\"Download the selected version from the url_dict value.\"\"\"", "t_file", "=", "target_file", "if", "target_file", "else", "self", ".", "SRC_FILE", "t_version", "=", "url_dict", "[", "self", ".", "version", "]", "Wget", "(", "t_version", ",", "t_file", ")", "@", "staticmethod", "def", "versions_impl", "(", ")", ":", "\"\"\"Return a list of versions from the url_dict keys.\"\"\"", "return", "list", "(", "url_dict", ".", "keys", "(", ")", ")", "cls", ".", "versions", "=", "versions_impl", "cls", ".", "download", "=", "download_impl", "return", "cls", "return", "wget_decorator" ]
Decorate a project class with wget-based version information. This adds two attributes to a project class: - A `versions` method that returns a list of available versions for this project. - A `repository` attribute that provides a repository string to download from later. We use the `git rev-list` subcommand to list available versions. Args: url_dict (dict): A dictionary that assigns a version to a download URL. target_file (str): An optional path where we should put the clone. If unspecified, we will use the `SRC_FILE` attribute of the decorated class.
[ "Decorate", "a", "project", "class", "with", "wget", "-", "based", "version", "information", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L158-L192
PolyJIT/benchbuild
benchbuild/utils/download.py
Git
def Git(repository, directory, rev=None, prefix=None, shallow_clone=True): """ Get a clone of the given repo Args: repository (str): Git URL of the SOURCE repo. directory (str): Name of the repo folder on disk. tgt_root (str): TARGET folder for the git repo. Defaults to ``CFG["tmpdir"]`` shallow_clone (bool): Only clone the repository shallow Defaults to true """ repository_loc = str(prefix) if prefix is None: repository_loc = str(CFG["tmp_dir"]) from benchbuild.utils.cmd import git src_dir = local.path(repository_loc) / directory if not source_required(src_dir): Copy(src_dir, ".") return extra_param = [] if shallow_clone: extra_param.append("--depth") extra_param.append("1") git("clone", extra_param, repository, src_dir) if rev: with local.cwd(src_dir): git("checkout", rev) update_hash(src_dir) Copy(src_dir, ".") return repository_loc
python
def Git(repository, directory, rev=None, prefix=None, shallow_clone=True): """ Get a clone of the given repo Args: repository (str): Git URL of the SOURCE repo. directory (str): Name of the repo folder on disk. tgt_root (str): TARGET folder for the git repo. Defaults to ``CFG["tmpdir"]`` shallow_clone (bool): Only clone the repository shallow Defaults to true """ repository_loc = str(prefix) if prefix is None: repository_loc = str(CFG["tmp_dir"]) from benchbuild.utils.cmd import git src_dir = local.path(repository_loc) / directory if not source_required(src_dir): Copy(src_dir, ".") return extra_param = [] if shallow_clone: extra_param.append("--depth") extra_param.append("1") git("clone", extra_param, repository, src_dir) if rev: with local.cwd(src_dir): git("checkout", rev) update_hash(src_dir) Copy(src_dir, ".") return repository_loc
[ "def", "Git", "(", "repository", ",", "directory", ",", "rev", "=", "None", ",", "prefix", "=", "None", ",", "shallow_clone", "=", "True", ")", ":", "repository_loc", "=", "str", "(", "prefix", ")", "if", "prefix", "is", "None", ":", "repository_loc", "=", "str", "(", "CFG", "[", "\"tmp_dir\"", "]", ")", "from", "benchbuild", ".", "utils", ".", "cmd", "import", "git", "src_dir", "=", "local", ".", "path", "(", "repository_loc", ")", "/", "directory", "if", "not", "source_required", "(", "src_dir", ")", ":", "Copy", "(", "src_dir", ",", "\".\"", ")", "return", "extra_param", "=", "[", "]", "if", "shallow_clone", ":", "extra_param", ".", "append", "(", "\"--depth\"", ")", "extra_param", ".", "append", "(", "\"1\"", ")", "git", "(", "\"clone\"", ",", "extra_param", ",", "repository", ",", "src_dir", ")", "if", "rev", ":", "with", "local", ".", "cwd", "(", "src_dir", ")", ":", "git", "(", "\"checkout\"", ",", "rev", ")", "update_hash", "(", "src_dir", ")", "Copy", "(", "src_dir", ",", "\".\"", ")", "return", "repository_loc" ]
Get a clone of the given repo Args: repository (str): Git URL of the SOURCE repo. directory (str): Name of the repo folder on disk. tgt_root (str): TARGET folder for the git repo. Defaults to ``CFG["tmpdir"]`` shallow_clone (bool): Only clone the repository shallow Defaults to true
[ "Get", "a", "clone", "of", "the", "given", "repo" ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L195-L230
PolyJIT/benchbuild
benchbuild/utils/download.py
with_git
def with_git(repo, target_dir=None, limit=None, refspec="HEAD", clone=True, rev_list_args=None, version_filter=lambda version: True): """ Decorate a project class with git-based version information. This adds two attributes to a project class: - A `versions` method that returns a list of available versions for this project. - A `repository` attribute that provides a repository string to download from later. We use the `git rev-list` subcommand to list available versions. Args: repo (str): Repository to download from, this will be stored in the `repository` attribute of the decorated class. target_dir (str): An optional path where we should put the clone. If unspecified, we will use the `SRC_FILE` attribute of the decorated class. limit (int): Limit the number of commits to consider for available versions. Versions are 'ordered' from latest to oldest. refspec (str): A git refspec string to start listing the versions from. clone (bool): Should we clone the repo if it isn't already available in our tmp dir? Defaults to `True`. You can set this to False to avoid time consuming clones, when the project has not been accessed at least once in your installation. ref_list_args (list of str): Additional arguments you want to pass to `git rev-list`. version_filter (class filter): Filter function to remove unwanted project versions. """ if not rev_list_args: rev_list_args = [] def git_decorator(cls): from benchbuild.utils.cmd import git @staticmethod def versions_impl(): """Return a list of versions from the git hashes up to :limit:.""" directory = cls.SRC_FILE if target_dir is None else target_dir repo_prefix = local.path(str(CFG["tmp_dir"])) repo_loc = local.path(repo_prefix) / directory if source_required(repo_loc): if not clone: return [] git("clone", repo, repo_loc) update_hash(repo_loc) with local.cwd(repo_loc): rev_list = git("rev-list", "--abbrev-commit", "--abbrev=10", refspec, *rev_list_args).strip().split('\n') latest = git("rev-parse", "--short=10", refspec).strip().split('\n') cls.VERSION = latest[0] if limit: return list(filter(version_filter, rev_list))[:limit] return list(filter(version_filter, rev_list)) def download_impl(self): """Download the selected version.""" nonlocal target_dir, git directory = cls.SRC_FILE if target_dir is None else target_dir Git(self.repository, directory) with local.cwd(directory): git("checkout", self.version) cls.versions = versions_impl cls.download = download_impl cls.repository = repo return cls return git_decorator
python
def with_git(repo, target_dir=None, limit=None, refspec="HEAD", clone=True, rev_list_args=None, version_filter=lambda version: True): """ Decorate a project class with git-based version information. This adds two attributes to a project class: - A `versions` method that returns a list of available versions for this project. - A `repository` attribute that provides a repository string to download from later. We use the `git rev-list` subcommand to list available versions. Args: repo (str): Repository to download from, this will be stored in the `repository` attribute of the decorated class. target_dir (str): An optional path where we should put the clone. If unspecified, we will use the `SRC_FILE` attribute of the decorated class. limit (int): Limit the number of commits to consider for available versions. Versions are 'ordered' from latest to oldest. refspec (str): A git refspec string to start listing the versions from. clone (bool): Should we clone the repo if it isn't already available in our tmp dir? Defaults to `True`. You can set this to False to avoid time consuming clones, when the project has not been accessed at least once in your installation. ref_list_args (list of str): Additional arguments you want to pass to `git rev-list`. version_filter (class filter): Filter function to remove unwanted project versions. """ if not rev_list_args: rev_list_args = [] def git_decorator(cls): from benchbuild.utils.cmd import git @staticmethod def versions_impl(): """Return a list of versions from the git hashes up to :limit:.""" directory = cls.SRC_FILE if target_dir is None else target_dir repo_prefix = local.path(str(CFG["tmp_dir"])) repo_loc = local.path(repo_prefix) / directory if source_required(repo_loc): if not clone: return [] git("clone", repo, repo_loc) update_hash(repo_loc) with local.cwd(repo_loc): rev_list = git("rev-list", "--abbrev-commit", "--abbrev=10", refspec, *rev_list_args).strip().split('\n') latest = git("rev-parse", "--short=10", refspec).strip().split('\n') cls.VERSION = latest[0] if limit: return list(filter(version_filter, rev_list))[:limit] return list(filter(version_filter, rev_list)) def download_impl(self): """Download the selected version.""" nonlocal target_dir, git directory = cls.SRC_FILE if target_dir is None else target_dir Git(self.repository, directory) with local.cwd(directory): git("checkout", self.version) cls.versions = versions_impl cls.download = download_impl cls.repository = repo return cls return git_decorator
[ "def", "with_git", "(", "repo", ",", "target_dir", "=", "None", ",", "limit", "=", "None", ",", "refspec", "=", "\"HEAD\"", ",", "clone", "=", "True", ",", "rev_list_args", "=", "None", ",", "version_filter", "=", "lambda", "version", ":", "True", ")", ":", "if", "not", "rev_list_args", ":", "rev_list_args", "=", "[", "]", "def", "git_decorator", "(", "cls", ")", ":", "from", "benchbuild", ".", "utils", ".", "cmd", "import", "git", "@", "staticmethod", "def", "versions_impl", "(", ")", ":", "\"\"\"Return a list of versions from the git hashes up to :limit:.\"\"\"", "directory", "=", "cls", ".", "SRC_FILE", "if", "target_dir", "is", "None", "else", "target_dir", "repo_prefix", "=", "local", ".", "path", "(", "str", "(", "CFG", "[", "\"tmp_dir\"", "]", ")", ")", "repo_loc", "=", "local", ".", "path", "(", "repo_prefix", ")", "/", "directory", "if", "source_required", "(", "repo_loc", ")", ":", "if", "not", "clone", ":", "return", "[", "]", "git", "(", "\"clone\"", ",", "repo", ",", "repo_loc", ")", "update_hash", "(", "repo_loc", ")", "with", "local", ".", "cwd", "(", "repo_loc", ")", ":", "rev_list", "=", "git", "(", "\"rev-list\"", ",", "\"--abbrev-commit\"", ",", "\"--abbrev=10\"", ",", "refspec", ",", "*", "rev_list_args", ")", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", "latest", "=", "git", "(", "\"rev-parse\"", ",", "\"--short=10\"", ",", "refspec", ")", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", "cls", ".", "VERSION", "=", "latest", "[", "0", "]", "if", "limit", ":", "return", "list", "(", "filter", "(", "version_filter", ",", "rev_list", ")", ")", "[", ":", "limit", "]", "return", "list", "(", "filter", "(", "version_filter", ",", "rev_list", ")", ")", "def", "download_impl", "(", "self", ")", ":", "\"\"\"Download the selected version.\"\"\"", "nonlocal", "target_dir", ",", "git", "directory", "=", "cls", ".", "SRC_FILE", "if", "target_dir", "is", "None", "else", "target_dir", "Git", "(", "self", ".", "repository", ",", "directory", ")", "with", "local", ".", "cwd", "(", "directory", ")", ":", "git", "(", "\"checkout\"", ",", "self", ".", "version", ")", "cls", ".", "versions", "=", "versions_impl", "cls", ".", "download", "=", "download_impl", "cls", ".", "repository", "=", "repo", "return", "cls", "return", "git_decorator" ]
Decorate a project class with git-based version information. This adds two attributes to a project class: - A `versions` method that returns a list of available versions for this project. - A `repository` attribute that provides a repository string to download from later. We use the `git rev-list` subcommand to list available versions. Args: repo (str): Repository to download from, this will be stored in the `repository` attribute of the decorated class. target_dir (str): An optional path where we should put the clone. If unspecified, we will use the `SRC_FILE` attribute of the decorated class. limit (int): Limit the number of commits to consider for available versions. Versions are 'ordered' from latest to oldest. refspec (str): A git refspec string to start listing the versions from. clone (bool): Should we clone the repo if it isn't already available in our tmp dir? Defaults to `True`. You can set this to False to avoid time consuming clones, when the project has not been accessed at least once in your installation. ref_list_args (list of str): Additional arguments you want to pass to `git rev-list`. version_filter (class filter): Filter function to remove unwanted project versions.
[ "Decorate", "a", "project", "class", "with", "git", "-", "based", "version", "information", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L233-L312
PolyJIT/benchbuild
benchbuild/utils/download.py
Svn
def Svn(url, fname, to=None): """ Checkout the SVN repo. Args: url (str): The SVN SOURCE repo. fname (str): The name of the repo on disk. to (str): The name of the TARGET folder on disk. Defaults to ``CFG["tmpdir"]`` """ if to is None: to = str(CFG["tmp_dir"]) src_dir = local.path(to) / fname if not source_required(src_dir): Copy(src_dir, ".") return from benchbuild.utils.cmd import svn svn("co", url, src_dir) update_hash(src_dir) Copy(src_dir, ".")
python
def Svn(url, fname, to=None): """ Checkout the SVN repo. Args: url (str): The SVN SOURCE repo. fname (str): The name of the repo on disk. to (str): The name of the TARGET folder on disk. Defaults to ``CFG["tmpdir"]`` """ if to is None: to = str(CFG["tmp_dir"]) src_dir = local.path(to) / fname if not source_required(src_dir): Copy(src_dir, ".") return from benchbuild.utils.cmd import svn svn("co", url, src_dir) update_hash(src_dir) Copy(src_dir, ".")
[ "def", "Svn", "(", "url", ",", "fname", ",", "to", "=", "None", ")", ":", "if", "to", "is", "None", ":", "to", "=", "str", "(", "CFG", "[", "\"tmp_dir\"", "]", ")", "src_dir", "=", "local", ".", "path", "(", "to", ")", "/", "fname", "if", "not", "source_required", "(", "src_dir", ")", ":", "Copy", "(", "src_dir", ",", "\".\"", ")", "return", "from", "benchbuild", ".", "utils", ".", "cmd", "import", "svn", "svn", "(", "\"co\"", ",", "url", ",", "src_dir", ")", "update_hash", "(", "src_dir", ")", "Copy", "(", "src_dir", ",", "\".\"", ")" ]
Checkout the SVN repo. Args: url (str): The SVN SOURCE repo. fname (str): The name of the repo on disk. to (str): The name of the TARGET folder on disk. Defaults to ``CFG["tmpdir"]``
[ "Checkout", "the", "SVN", "repo", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L315-L336
PolyJIT/benchbuild
benchbuild/utils/download.py
Rsync
def Rsync(url, tgt_name, tgt_root=None): """ RSync a folder. Args: url (str): The url of the SOURCE location. fname (str): The name of the TARGET. to (str): Path of the target location. Defaults to ``CFG["tmpdir"]``. """ if tgt_root is None: tgt_root = str(CFG["tmp_dir"]) from benchbuild.utils.cmd import rsync tgt_dir = local.path(tgt_root) / tgt_name if not source_required(tgt_dir): Copy(tgt_dir, ".") return rsync("-a", url, tgt_dir) update_hash(tgt_dir) Copy(tgt_dir, ".")
python
def Rsync(url, tgt_name, tgt_root=None): """ RSync a folder. Args: url (str): The url of the SOURCE location. fname (str): The name of the TARGET. to (str): Path of the target location. Defaults to ``CFG["tmpdir"]``. """ if tgt_root is None: tgt_root = str(CFG["tmp_dir"]) from benchbuild.utils.cmd import rsync tgt_dir = local.path(tgt_root) / tgt_name if not source_required(tgt_dir): Copy(tgt_dir, ".") return rsync("-a", url, tgt_dir) update_hash(tgt_dir) Copy(tgt_dir, ".")
[ "def", "Rsync", "(", "url", ",", "tgt_name", ",", "tgt_root", "=", "None", ")", ":", "if", "tgt_root", "is", "None", ":", "tgt_root", "=", "str", "(", "CFG", "[", "\"tmp_dir\"", "]", ")", "from", "benchbuild", ".", "utils", ".", "cmd", "import", "rsync", "tgt_dir", "=", "local", ".", "path", "(", "tgt_root", ")", "/", "tgt_name", "if", "not", "source_required", "(", "tgt_dir", ")", ":", "Copy", "(", "tgt_dir", ",", "\".\"", ")", "return", "rsync", "(", "\"-a\"", ",", "url", ",", "tgt_dir", ")", "update_hash", "(", "tgt_dir", ")", "Copy", "(", "tgt_dir", ",", "\".\"", ")" ]
RSync a folder. Args: url (str): The url of the SOURCE location. fname (str): The name of the TARGET. to (str): Path of the target location. Defaults to ``CFG["tmpdir"]``.
[ "RSync", "a", "folder", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L339-L361
portfoliome/foil
foil/strings.py
camel_to_snake
def camel_to_snake(s: str) -> str: """Convert string from camel case to snake case.""" return CAMEL_CASE_RE.sub(r'_\1', s).strip().lower()
python
def camel_to_snake(s: str) -> str: """Convert string from camel case to snake case.""" return CAMEL_CASE_RE.sub(r'_\1', s).strip().lower()
[ "def", "camel_to_snake", "(", "s", ":", "str", ")", "->", "str", ":", "return", "CAMEL_CASE_RE", ".", "sub", "(", "r'_\\1'", ",", "s", ")", ".", "strip", "(", ")", ".", "lower", "(", ")" ]
Convert string from camel case to snake case.
[ "Convert", "string", "from", "camel", "case", "to", "snake", "case", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/strings.py#L7-L10
portfoliome/foil
foil/strings.py
snake_to_camel
def snake_to_camel(s: str) -> str: """Convert string from snake case to camel case.""" fragments = s.split('_') return fragments[0] + ''.join(x.title() for x in fragments[1:])
python
def snake_to_camel(s: str) -> str: """Convert string from snake case to camel case.""" fragments = s.split('_') return fragments[0] + ''.join(x.title() for x in fragments[1:])
[ "def", "snake_to_camel", "(", "s", ":", "str", ")", "->", "str", ":", "fragments", "=", "s", ".", "split", "(", "'_'", ")", "return", "fragments", "[", "0", "]", "+", "''", ".", "join", "(", "x", ".", "title", "(", ")", "for", "x", "in", "fragments", "[", "1", ":", "]", ")" ]
Convert string from snake case to camel case.
[ "Convert", "string", "from", "snake", "case", "to", "camel", "case", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/strings.py#L13-L18
BlueBrain/hpcbench
hpcbench/benchmark/standard.py
Configuration._create_extractors
def _create_extractors(cls, metrics): """Build metrics extractors according to the `metrics` config :param metrics: Benchmark `metrics` configuration section """ metrics_dict = {} # group entries by `category` attribute (default is "standard") for metric, config in six.iteritems(metrics): category = config.get('category', StdBenchmark.DEFAULT_CATEGORY) metrics_dict.setdefault(category, {})[metric] = config # create one StdExtractor instance per category, # passing associated metrics return dict( (category, StdExtractor(metrics)) for category, metrics in six.iteritems(metrics_dict) )
python
def _create_extractors(cls, metrics): """Build metrics extractors according to the `metrics` config :param metrics: Benchmark `metrics` configuration section """ metrics_dict = {} # group entries by `category` attribute (default is "standard") for metric, config in six.iteritems(metrics): category = config.get('category', StdBenchmark.DEFAULT_CATEGORY) metrics_dict.setdefault(category, {})[metric] = config # create one StdExtractor instance per category, # passing associated metrics return dict( (category, StdExtractor(metrics)) for category, metrics in six.iteritems(metrics_dict) )
[ "def", "_create_extractors", "(", "cls", ",", "metrics", ")", ":", "metrics_dict", "=", "{", "}", "# group entries by `category` attribute (default is \"standard\")", "for", "metric", ",", "config", "in", "six", ".", "iteritems", "(", "metrics", ")", ":", "category", "=", "config", ".", "get", "(", "'category'", ",", "StdBenchmark", ".", "DEFAULT_CATEGORY", ")", "metrics_dict", ".", "setdefault", "(", "category", ",", "{", "}", ")", "[", "metric", "]", "=", "config", "# create one StdExtractor instance per category,", "# passing associated metrics", "return", "dict", "(", "(", "category", ",", "StdExtractor", "(", "metrics", ")", ")", "for", "category", ",", "metrics", "in", "six", ".", "iteritems", "(", "metrics_dict", ")", ")" ]
Build metrics extractors according to the `metrics` config :param metrics: Benchmark `metrics` configuration section
[ "Build", "metrics", "extractors", "according", "to", "the", "metrics", "config" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/standard.py#L160-L175
BlueBrain/hpcbench
hpcbench/benchmark/standard.py
StdExtractor.metrics
def metrics(self): """ :return: Description of metrics extracted by this class """ return dict( (name, getattr(Metrics, config['type'])) for name, config in six.iteritems(self._metrics) )
python
def metrics(self): """ :return: Description of metrics extracted by this class """ return dict( (name, getattr(Metrics, config['type'])) for name, config in six.iteritems(self._metrics) )
[ "def", "metrics", "(", "self", ")", ":", "return", "dict", "(", "(", "name", ",", "getattr", "(", "Metrics", ",", "config", "[", "'type'", "]", ")", ")", "for", "name", ",", "config", "in", "six", ".", "iteritems", "(", "self", ".", "_metrics", ")", ")" ]
:return: Description of metrics extracted by this class
[ ":", "return", ":", "Description", "of", "metrics", "extracted", "by", "this", "class" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/standard.py#L286-L293
BlueBrain/hpcbench
hpcbench/benchmark/standard.py
StdExtractor.froms
def froms(self): """Group metrics according to the `from` property. """ eax = {} for name, config in six.iteritems(self._metrics): from_ = self._get_property(config, 'from', default=self.stdout) eax.setdefault(from_, {})[name] = config return eax
python
def froms(self): """Group metrics according to the `from` property. """ eax = {} for name, config in six.iteritems(self._metrics): from_ = self._get_property(config, 'from', default=self.stdout) eax.setdefault(from_, {})[name] = config return eax
[ "def", "froms", "(", "self", ")", ":", "eax", "=", "{", "}", "for", "name", ",", "config", "in", "six", ".", "iteritems", "(", "self", ".", "_metrics", ")", ":", "from_", "=", "self", ".", "_get_property", "(", "config", ",", "'from'", ",", "default", "=", "self", ".", "stdout", ")", "eax", ".", "setdefault", "(", "from_", ",", "{", "}", ")", "[", "name", "]", "=", "config", "return", "eax" ]
Group metrics according to the `from` property.
[ "Group", "metrics", "according", "to", "the", "from", "property", "." ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/standard.py#L296-L303
sci-bots/svg-model
svg_model/tesselate.py
tesselate_shapes_frame
def tesselate_shapes_frame(df_shapes, shape_i_columns): ''' Tesselate each shape path into one or more triangles. Parameters ---------- df_shapes : pandas.DataFrame Table containing vertices of shapes, one row per vertex, with the *at least* the following columns: - ``x``: The x-coordinate of the vertex. - ``y``: The y-coordinate of the vertex. shape_i_columns : str or list Column(s) forming key to differentiate rows/vertices for each distinct shape. Returns ------- pandas.DataFrame Table where each row corresponds to a triangle vertex, with the following columns: - ``shape_i_columns[]``: The shape path index column(s). - ``triangle_i``: The integer triangle index within each electrode path. - ``vertex_i``: The integer vertex index within each triangle. ''' frames = [] if isinstance(shape_i_columns, bytes): shape_i_columns = [shape_i_columns] for shape_i, df_path in df_shapes.groupby(shape_i_columns): points_i = df_path[['x', 'y']].values if (points_i[0] == points_i[-1]).all(): # XXX End point is the same as the start point (do not include it). points_i = points_i[:-1] try: triangulator = Triangulator(points_i) except: import pdb; pdb.set_trace() continue if not isinstance(shape_i, (list, tuple)): shape_i = [shape_i] for i, triangle_i in enumerate(triangulator.triangles()): triangle_points_i = [shape_i + [i] + [j, x, y] for j, (x, y) in enumerate(triangle_i)] frames.extend(triangle_points_i) frames = None if not frames else frames return pd.DataFrame(frames, columns=shape_i_columns + ['triangle_i', 'vertex_i', 'x', 'y'])
python
def tesselate_shapes_frame(df_shapes, shape_i_columns): ''' Tesselate each shape path into one or more triangles. Parameters ---------- df_shapes : pandas.DataFrame Table containing vertices of shapes, one row per vertex, with the *at least* the following columns: - ``x``: The x-coordinate of the vertex. - ``y``: The y-coordinate of the vertex. shape_i_columns : str or list Column(s) forming key to differentiate rows/vertices for each distinct shape. Returns ------- pandas.DataFrame Table where each row corresponds to a triangle vertex, with the following columns: - ``shape_i_columns[]``: The shape path index column(s). - ``triangle_i``: The integer triangle index within each electrode path. - ``vertex_i``: The integer vertex index within each triangle. ''' frames = [] if isinstance(shape_i_columns, bytes): shape_i_columns = [shape_i_columns] for shape_i, df_path in df_shapes.groupby(shape_i_columns): points_i = df_path[['x', 'y']].values if (points_i[0] == points_i[-1]).all(): # XXX End point is the same as the start point (do not include it). points_i = points_i[:-1] try: triangulator = Triangulator(points_i) except: import pdb; pdb.set_trace() continue if not isinstance(shape_i, (list, tuple)): shape_i = [shape_i] for i, triangle_i in enumerate(triangulator.triangles()): triangle_points_i = [shape_i + [i] + [j, x, y] for j, (x, y) in enumerate(triangle_i)] frames.extend(triangle_points_i) frames = None if not frames else frames return pd.DataFrame(frames, columns=shape_i_columns + ['triangle_i', 'vertex_i', 'x', 'y'])
[ "def", "tesselate_shapes_frame", "(", "df_shapes", ",", "shape_i_columns", ")", ":", "frames", "=", "[", "]", "if", "isinstance", "(", "shape_i_columns", ",", "bytes", ")", ":", "shape_i_columns", "=", "[", "shape_i_columns", "]", "for", "shape_i", ",", "df_path", "in", "df_shapes", ".", "groupby", "(", "shape_i_columns", ")", ":", "points_i", "=", "df_path", "[", "[", "'x'", ",", "'y'", "]", "]", ".", "values", "if", "(", "points_i", "[", "0", "]", "==", "points_i", "[", "-", "1", "]", ")", ".", "all", "(", ")", ":", "# XXX End point is the same as the start point (do not include it).", "points_i", "=", "points_i", "[", ":", "-", "1", "]", "try", ":", "triangulator", "=", "Triangulator", "(", "points_i", ")", "except", ":", "import", "pdb", "pdb", ".", "set_trace", "(", ")", "continue", "if", "not", "isinstance", "(", "shape_i", ",", "(", "list", ",", "tuple", ")", ")", ":", "shape_i", "=", "[", "shape_i", "]", "for", "i", ",", "triangle_i", "in", "enumerate", "(", "triangulator", ".", "triangles", "(", ")", ")", ":", "triangle_points_i", "=", "[", "shape_i", "+", "[", "i", "]", "+", "[", "j", ",", "x", ",", "y", "]", "for", "j", ",", "(", "x", ",", "y", ")", "in", "enumerate", "(", "triangle_i", ")", "]", "frames", ".", "extend", "(", "triangle_points_i", ")", "frames", "=", "None", "if", "not", "frames", "else", "frames", "return", "pd", ".", "DataFrame", "(", "frames", ",", "columns", "=", "shape_i_columns", "+", "[", "'triangle_i'", ",", "'vertex_i'", ",", "'x'", ",", "'y'", "]", ")" ]
Tesselate each shape path into one or more triangles. Parameters ---------- df_shapes : pandas.DataFrame Table containing vertices of shapes, one row per vertex, with the *at least* the following columns: - ``x``: The x-coordinate of the vertex. - ``y``: The y-coordinate of the vertex. shape_i_columns : str or list Column(s) forming key to differentiate rows/vertices for each distinct shape. Returns ------- pandas.DataFrame Table where each row corresponds to a triangle vertex, with the following columns: - ``shape_i_columns[]``: The shape path index column(s). - ``triangle_i``: The integer triangle index within each electrode path. - ``vertex_i``: The integer vertex index within each triangle.
[ "Tesselate", "each", "shape", "path", "into", "one", "or", "more", "triangles", "." ]
train
https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/tesselate.py#L10-L59
BlueBrain/hpcbench
hpcbench/toolbox/contextlib_ext.py
capture_stdout
def capture_stdout(): """Intercept standard output in a with-context :return: cStringIO instance >>> with capture_stdout() as stdout: ... print stdout.getvalue() """ stdout = sys.stdout sys.stdout = six.moves.cStringIO() try: yield sys.stdout finally: sys.stdout = stdout
python
def capture_stdout(): """Intercept standard output in a with-context :return: cStringIO instance >>> with capture_stdout() as stdout: ... print stdout.getvalue() """ stdout = sys.stdout sys.stdout = six.moves.cStringIO() try: yield sys.stdout finally: sys.stdout = stdout
[ "def", "capture_stdout", "(", ")", ":", "stdout", "=", "sys", ".", "stdout", "sys", ".", "stdout", "=", "six", ".", "moves", ".", "cStringIO", "(", ")", "try", ":", "yield", "sys", ".", "stdout", "finally", ":", "sys", ".", "stdout", "=", "stdout" ]
Intercept standard output in a with-context :return: cStringIO instance >>> with capture_stdout() as stdout: ... print stdout.getvalue()
[ "Intercept", "standard", "output", "in", "a", "with", "-", "context", ":", "return", ":", "cStringIO", "instance" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/contextlib_ext.py#L15-L28
BlueBrain/hpcbench
hpcbench/toolbox/contextlib_ext.py
pushd
def pushd(path, mkdir=True, cleanup=False): """Change current working directory in a with-context :param mkdir: If True, then directory is created if it does not exist :param cleanup: If True and no pre-existing directory, the directory is cleaned up at the end """ cwd = os.getcwd() exists = osp.exists(path) if mkdir and not exists: os.makedirs(path) os.chdir(path) try: yield path finally: os.chdir(cwd) if not exists and cleanup: # NB: should we be checking for rmtree.avoids_symlink_attacks ? shutil.rmtree(path)
python
def pushd(path, mkdir=True, cleanup=False): """Change current working directory in a with-context :param mkdir: If True, then directory is created if it does not exist :param cleanup: If True and no pre-existing directory, the directory is cleaned up at the end """ cwd = os.getcwd() exists = osp.exists(path) if mkdir and not exists: os.makedirs(path) os.chdir(path) try: yield path finally: os.chdir(cwd) if not exists and cleanup: # NB: should we be checking for rmtree.avoids_symlink_attacks ? shutil.rmtree(path)
[ "def", "pushd", "(", "path", ",", "mkdir", "=", "True", ",", "cleanup", "=", "False", ")", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "exists", "=", "osp", ".", "exists", "(", "path", ")", "if", "mkdir", "and", "not", "exists", ":", "os", ".", "makedirs", "(", "path", ")", "os", ".", "chdir", "(", "path", ")", "try", ":", "yield", "path", "finally", ":", "os", ".", "chdir", "(", "cwd", ")", "if", "not", "exists", "and", "cleanup", ":", "# NB: should we be checking for rmtree.avoids_symlink_attacks ?", "shutil", ".", "rmtree", "(", "path", ")" ]
Change current working directory in a with-context :param mkdir: If True, then directory is created if it does not exist :param cleanup: If True and no pre-existing directory, the directory is cleaned up at the end
[ "Change", "current", "working", "directory", "in", "a", "with", "-", "context", ":", "param", "mkdir", ":", "If", "True", "then", "directory", "is", "created", "if", "it", "does", "not", "exist", ":", "param", "cleanup", ":", "If", "True", "and", "no", "pre", "-", "existing", "directory", "the", "directory", "is", "cleaned", "up", "at", "the", "end" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/contextlib_ext.py#L40-L57
BlueBrain/hpcbench
hpcbench/toolbox/contextlib_ext.py
mkdtemp
def mkdtemp(*args, **kwargs): """Create a temporary directory in a with-context keyword remove: Remove the directory when leaving the context if True. Default is True. other keywords arguments are given to the tempfile.mkdtemp function. """ remove = kwargs.pop('remove', True) path = tempfile.mkdtemp(*args, **kwargs) try: yield path finally: if remove: shutil.rmtree(path)
python
def mkdtemp(*args, **kwargs): """Create a temporary directory in a with-context keyword remove: Remove the directory when leaving the context if True. Default is True. other keywords arguments are given to the tempfile.mkdtemp function. """ remove = kwargs.pop('remove', True) path = tempfile.mkdtemp(*args, **kwargs) try: yield path finally: if remove: shutil.rmtree(path)
[ "def", "mkdtemp", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "remove", "=", "kwargs", ".", "pop", "(", "'remove'", ",", "True", ")", "path", "=", "tempfile", ".", "mkdtemp", "(", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "yield", "path", "finally", ":", "if", "remove", ":", "shutil", ".", "rmtree", "(", "path", ")" ]
Create a temporary directory in a with-context keyword remove: Remove the directory when leaving the context if True. Default is True. other keywords arguments are given to the tempfile.mkdtemp function.
[ "Create", "a", "temporary", "directory", "in", "a", "with", "-", "context" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/contextlib_ext.py#L91-L105
BlueBrain/hpcbench
hpcbench/toolbox/contextlib_ext.py
Timer.elapsed
def elapsed(self): """ :return: duration in seconds spent in the context. :rtype: float """ if self.end is None: return self() - self.end return self.end - self.start
python
def elapsed(self): """ :return: duration in seconds spent in the context. :rtype: float """ if self.end is None: return self() - self.end return self.end - self.start
[ "def", "elapsed", "(", "self", ")", ":", "if", "self", ".", "end", "is", "None", ":", "return", "self", "(", ")", "-", "self", ".", "end", "return", "self", ".", "end", "-", "self", ".", "start" ]
:return: duration in seconds spent in the context. :rtype: float
[ ":", "return", ":", "duration", "in", "seconds", "spent", "in", "the", "context", ".", ":", "rtype", ":", "float" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/contextlib_ext.py#L80-L87
Metatab/metatab
metatab/util.py
slugify
def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.type( """ import re import unicodedata value = str(value) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('utf8').strip().lower() value = re.sub(r'[^\w\s\-\.]', '', value) value = re.sub(r'[-\s]+', '-', value) return value
python
def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.type( """ import re import unicodedata value = str(value) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('utf8').strip().lower() value = re.sub(r'[^\w\s\-\.]', '', value) value = re.sub(r'[-\s]+', '-', value) return value
[ "def", "slugify", "(", "value", ")", ":", "import", "re", "import", "unicodedata", "value", "=", "str", "(", "value", ")", "value", "=", "unicodedata", ".", "normalize", "(", "'NFKD'", ",", "value", ")", ".", "encode", "(", "'ascii'", ",", "'ignore'", ")", ".", "decode", "(", "'utf8'", ")", ".", "strip", "(", ")", ".", "lower", "(", ")", "value", "=", "re", ".", "sub", "(", "r'[^\\w\\s\\-\\.]'", ",", "''", ",", "value", ")", "value", "=", "re", ".", "sub", "(", "r'[-\\s]+'", ",", "'-'", ",", "value", ")", "return", "value" ]
Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.type(
[ "Normalizes", "string", "converts", "to", "lowercase", "removes", "non", "-", "alpha", "characters", "and", "converts", "spaces", "to", "hyphens", ".", "type", "(" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/util.py#L40-L51
Metatab/metatab
metatab/util.py
import_name_or_class
def import_name_or_class(name): " Import an obect as either a fully qualified, dotted name, " if isinstance(name, str): # for "a.b.c.d" -> [ 'a.b.c', 'd' ] module_name, object_name = name.rsplit('.',1) # __import__ loads the multi-level of module, but returns # the top level, which we have to descend into mod = __import__(module_name) components = name.split('.') for comp in components[1:]: # Already got the top level, so start at 1 mod = getattr(mod, comp) return mod else: return name
python
def import_name_or_class(name): " Import an obect as either a fully qualified, dotted name, " if isinstance(name, str): # for "a.b.c.d" -> [ 'a.b.c', 'd' ] module_name, object_name = name.rsplit('.',1) # __import__ loads the multi-level of module, but returns # the top level, which we have to descend into mod = __import__(module_name) components = name.split('.') for comp in components[1:]: # Already got the top level, so start at 1 mod = getattr(mod, comp) return mod else: return name
[ "def", "import_name_or_class", "(", "name", ")", ":", "if", "isinstance", "(", "name", ",", "str", ")", ":", "# for \"a.b.c.d\" -> [ 'a.b.c', 'd' ]", "module_name", ",", "object_name", "=", "name", ".", "rsplit", "(", "'.'", ",", "1", ")", "# __import__ loads the multi-level of module, but returns", "# the top level, which we have to descend into", "mod", "=", "__import__", "(", "module_name", ")", "components", "=", "name", ".", "split", "(", "'.'", ")", "for", "comp", "in", "components", "[", "1", ":", "]", ":", "# Already got the top level, so start at 1", "mod", "=", "getattr", "(", "mod", ",", "comp", ")", "return", "mod", "else", ":", "return", "name" ]
Import an obect as either a fully qualified, dotted name,
[ "Import", "an", "obect", "as", "either", "a", "fully", "qualified", "dotted", "name" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/util.py#L208-L226
BlueBrain/hpcbench
hpcbench/campaign.py
pip_installer_url
def pip_installer_url(version=None): """Get argument to give to ``pip`` to install HPCBench. """ version = version or hpcbench.__version__ version = str(version) if '.dev' in version: git_rev = 'master' if 'TRAVIS_BRANCH' in os.environ: git_rev = version.split('+', 1)[-1] if '.' in git_rev: # get rid of date suffix git_rev = git_rev.split('.', 1)[0] git_rev = git_rev[1:] # get rid of scm letter return 'git+{project_url}@{git_rev}#egg=hpcbench'.format( project_url='http://github.com/BlueBrain/hpcbench', git_rev=git_rev or 'master', ) return 'hpcbench=={}'.format(version)
python
def pip_installer_url(version=None): """Get argument to give to ``pip`` to install HPCBench. """ version = version or hpcbench.__version__ version = str(version) if '.dev' in version: git_rev = 'master' if 'TRAVIS_BRANCH' in os.environ: git_rev = version.split('+', 1)[-1] if '.' in git_rev: # get rid of date suffix git_rev = git_rev.split('.', 1)[0] git_rev = git_rev[1:] # get rid of scm letter return 'git+{project_url}@{git_rev}#egg=hpcbench'.format( project_url='http://github.com/BlueBrain/hpcbench', git_rev=git_rev or 'master', ) return 'hpcbench=={}'.format(version)
[ "def", "pip_installer_url", "(", "version", "=", "None", ")", ":", "version", "=", "version", "or", "hpcbench", ".", "__version__", "version", "=", "str", "(", "version", ")", "if", "'.dev'", "in", "version", ":", "git_rev", "=", "'master'", "if", "'TRAVIS_BRANCH'", "in", "os", ".", "environ", ":", "git_rev", "=", "version", ".", "split", "(", "'+'", ",", "1", ")", "[", "-", "1", "]", "if", "'.'", "in", "git_rev", ":", "# get rid of date suffix", "git_rev", "=", "git_rev", ".", "split", "(", "'.'", ",", "1", ")", "[", "0", "]", "git_rev", "=", "git_rev", "[", "1", ":", "]", "# get rid of scm letter", "return", "'git+{project_url}@{git_rev}#egg=hpcbench'", ".", "format", "(", "project_url", "=", "'http://github.com/BlueBrain/hpcbench'", ",", "git_rev", "=", "git_rev", "or", "'master'", ",", ")", "return", "'hpcbench=={}'", ".", "format", "(", "version", ")" ]
Get argument to give to ``pip`` to install HPCBench.
[ "Get", "argument", "to", "give", "to", "pip", "to", "install", "HPCBench", "." ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L31-L47
BlueBrain/hpcbench
hpcbench/campaign.py
from_file
def from_file(campaign_file, **kwargs): """Load campaign from YAML file :return: memory representation of the YAML file :rtype: dictionary """ realpath = osp.realpath(campaign_file) if osp.isdir(realpath): campaign_file = osp.join(campaign_file, YAML_CAMPAIGN_FILE) campaign = Configuration.from_file(campaign_file) return default_campaign(campaign, **kwargs)
python
def from_file(campaign_file, **kwargs): """Load campaign from YAML file :return: memory representation of the YAML file :rtype: dictionary """ realpath = osp.realpath(campaign_file) if osp.isdir(realpath): campaign_file = osp.join(campaign_file, YAML_CAMPAIGN_FILE) campaign = Configuration.from_file(campaign_file) return default_campaign(campaign, **kwargs)
[ "def", "from_file", "(", "campaign_file", ",", "*", "*", "kwargs", ")", ":", "realpath", "=", "osp", ".", "realpath", "(", "campaign_file", ")", "if", "osp", ".", "isdir", "(", "realpath", ")", ":", "campaign_file", "=", "osp", ".", "join", "(", "campaign_file", ",", "YAML_CAMPAIGN_FILE", ")", "campaign", "=", "Configuration", ".", "from_file", "(", "campaign_file", ")", "return", "default_campaign", "(", "campaign", ",", "*", "*", "kwargs", ")" ]
Load campaign from YAML file :return: memory representation of the YAML file :rtype: dictionary
[ "Load", "campaign", "from", "YAML", "file" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L165-L175
BlueBrain/hpcbench
hpcbench/campaign.py
default_campaign
def default_campaign( campaign=None, expandcampvars=True, exclude_nodes=None, frozen=True ): """Fill an existing campaign with default values for optional keys :param campaign: dictionary :type campaign: str :param exclude_nodes: node set to exclude from allocations :type exclude_nodes: str :param expandcampvars: should env variables be expanded? True by default :type expandcampvars: bool :param frozen: whether the returned data-structure is immutable or not :type frozen: bool :return: object provided in parameter :rtype: dictionary """ campaign = campaign or nameddict() def _merger(_camp, _deft): for key in _deft.keys(): if ( key in _camp and isinstance(_camp[key], dict) and isinstance(_deft[key], collections.Mapping) ): _merger(_camp[key], _deft[key]) elif key not in _camp: _camp[key] = _deft[key] _merger(campaign, DEFAULT_CAMPAIGN) campaign.setdefault('campaign_id', str(uuid.uuid4())) for precondition in campaign.precondition.keys(): config = campaign.precondition[precondition] if not isinstance(config, list): campaign.precondition[precondition] = [config] def _expandvars(value): if isinstance(value, six.string_types): return expandvars(value) return value if expandcampvars: campaign = nameddict(dict_map_kv(campaign, _expandvars)) else: campaign = nameddict(campaign) if expandcampvars: if campaign.network.get('tags') is None: campaign.network['tags'] = {} NetworkConfig(campaign).expand() return freeze(campaign) if frozen else campaign
python
def default_campaign( campaign=None, expandcampvars=True, exclude_nodes=None, frozen=True ): """Fill an existing campaign with default values for optional keys :param campaign: dictionary :type campaign: str :param exclude_nodes: node set to exclude from allocations :type exclude_nodes: str :param expandcampvars: should env variables be expanded? True by default :type expandcampvars: bool :param frozen: whether the returned data-structure is immutable or not :type frozen: bool :return: object provided in parameter :rtype: dictionary """ campaign = campaign or nameddict() def _merger(_camp, _deft): for key in _deft.keys(): if ( key in _camp and isinstance(_camp[key], dict) and isinstance(_deft[key], collections.Mapping) ): _merger(_camp[key], _deft[key]) elif key not in _camp: _camp[key] = _deft[key] _merger(campaign, DEFAULT_CAMPAIGN) campaign.setdefault('campaign_id', str(uuid.uuid4())) for precondition in campaign.precondition.keys(): config = campaign.precondition[precondition] if not isinstance(config, list): campaign.precondition[precondition] = [config] def _expandvars(value): if isinstance(value, six.string_types): return expandvars(value) return value if expandcampvars: campaign = nameddict(dict_map_kv(campaign, _expandvars)) else: campaign = nameddict(campaign) if expandcampvars: if campaign.network.get('tags') is None: campaign.network['tags'] = {} NetworkConfig(campaign).expand() return freeze(campaign) if frozen else campaign
[ "def", "default_campaign", "(", "campaign", "=", "None", ",", "expandcampvars", "=", "True", ",", "exclude_nodes", "=", "None", ",", "frozen", "=", "True", ")", ":", "campaign", "=", "campaign", "or", "nameddict", "(", ")", "def", "_merger", "(", "_camp", ",", "_deft", ")", ":", "for", "key", "in", "_deft", ".", "keys", "(", ")", ":", "if", "(", "key", "in", "_camp", "and", "isinstance", "(", "_camp", "[", "key", "]", ",", "dict", ")", "and", "isinstance", "(", "_deft", "[", "key", "]", ",", "collections", ".", "Mapping", ")", ")", ":", "_merger", "(", "_camp", "[", "key", "]", ",", "_deft", "[", "key", "]", ")", "elif", "key", "not", "in", "_camp", ":", "_camp", "[", "key", "]", "=", "_deft", "[", "key", "]", "_merger", "(", "campaign", ",", "DEFAULT_CAMPAIGN", ")", "campaign", ".", "setdefault", "(", "'campaign_id'", ",", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ")", "for", "precondition", "in", "campaign", ".", "precondition", ".", "keys", "(", ")", ":", "config", "=", "campaign", ".", "precondition", "[", "precondition", "]", "if", "not", "isinstance", "(", "config", ",", "list", ")", ":", "campaign", ".", "precondition", "[", "precondition", "]", "=", "[", "config", "]", "def", "_expandvars", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "return", "expandvars", "(", "value", ")", "return", "value", "if", "expandcampvars", ":", "campaign", "=", "nameddict", "(", "dict_map_kv", "(", "campaign", ",", "_expandvars", ")", ")", "else", ":", "campaign", "=", "nameddict", "(", "campaign", ")", "if", "expandcampvars", ":", "if", "campaign", ".", "network", ".", "get", "(", "'tags'", ")", "is", "None", ":", "campaign", ".", "network", "[", "'tags'", "]", "=", "{", "}", "NetworkConfig", "(", "campaign", ")", ".", "expand", "(", ")", "return", "freeze", "(", "campaign", ")", "if", "frozen", "else", "campaign" ]
Fill an existing campaign with default values for optional keys :param campaign: dictionary :type campaign: str :param exclude_nodes: node set to exclude from allocations :type exclude_nodes: str :param expandcampvars: should env variables be expanded? True by default :type expandcampvars: bool :param frozen: whether the returned data-structure is immutable or not :type frozen: bool :return: object provided in parameter :rtype: dictionary
[ "Fill", "an", "existing", "campaign", "with", "default", "values", "for", "optional", "keys" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L178-L229
BlueBrain/hpcbench
hpcbench/campaign.py
get_benchmark_types
def get_benchmark_types(campaign): """Get of benchmarks referenced in the configuration :return: benchmarks :rtype: string generator """ for benchmarks in campaign.benchmarks.values(): for name, benchmark in benchmarks.items(): if name != 'sbatch': # exclude special sbatch name yield benchmark.type
python
def get_benchmark_types(campaign): """Get of benchmarks referenced in the configuration :return: benchmarks :rtype: string generator """ for benchmarks in campaign.benchmarks.values(): for name, benchmark in benchmarks.items(): if name != 'sbatch': # exclude special sbatch name yield benchmark.type
[ "def", "get_benchmark_types", "(", "campaign", ")", ":", "for", "benchmarks", "in", "campaign", ".", "benchmarks", ".", "values", "(", ")", ":", "for", "name", ",", "benchmark", "in", "benchmarks", ".", "items", "(", ")", ":", "if", "name", "!=", "'sbatch'", ":", "# exclude special sbatch name", "yield", "benchmark", ".", "type" ]
Get of benchmarks referenced in the configuration :return: benchmarks :rtype: string generator
[ "Get", "of", "benchmarks", "referenced", "in", "the", "configuration" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L409-L418
BlueBrain/hpcbench
hpcbench/campaign.py
get_metrics
def get_metrics(campaign, report, top=True): """Extract metrics from existing campaign :param campaign: campaign loaded with `hpcbench.campaign.from_file` :param report: instance of `hpcbench.campaign.ReportNode` :param top: this function is recursive. This parameter help distinguishing top-call. """ if top and campaign.process.type == 'slurm': for path, _ in report.collect('jobid', with_path=True): for child in ReportNode(path).children.values(): for metrics in get_metrics(campaign, child, top=False): yield metrics else: def metrics_node_extract(report): metrics_file = osp.join(report.path, JSON_METRICS_FILE) if osp.exists(metrics_file): with open(metrics_file) as istr: return json.load(istr) def metrics_iterator(report): return filter( lambda eax: eax[1] is not None, report.map(metrics_node_extract, with_path=True), ) for path, metrics in metrics_iterator(report): yield report.path_context(path), metrics
python
def get_metrics(campaign, report, top=True): """Extract metrics from existing campaign :param campaign: campaign loaded with `hpcbench.campaign.from_file` :param report: instance of `hpcbench.campaign.ReportNode` :param top: this function is recursive. This parameter help distinguishing top-call. """ if top and campaign.process.type == 'slurm': for path, _ in report.collect('jobid', with_path=True): for child in ReportNode(path).children.values(): for metrics in get_metrics(campaign, child, top=False): yield metrics else: def metrics_node_extract(report): metrics_file = osp.join(report.path, JSON_METRICS_FILE) if osp.exists(metrics_file): with open(metrics_file) as istr: return json.load(istr) def metrics_iterator(report): return filter( lambda eax: eax[1] is not None, report.map(metrics_node_extract, with_path=True), ) for path, metrics in metrics_iterator(report): yield report.path_context(path), metrics
[ "def", "get_metrics", "(", "campaign", ",", "report", ",", "top", "=", "True", ")", ":", "if", "top", "and", "campaign", ".", "process", ".", "type", "==", "'slurm'", ":", "for", "path", ",", "_", "in", "report", ".", "collect", "(", "'jobid'", ",", "with_path", "=", "True", ")", ":", "for", "child", "in", "ReportNode", "(", "path", ")", ".", "children", ".", "values", "(", ")", ":", "for", "metrics", "in", "get_metrics", "(", "campaign", ",", "child", ",", "top", "=", "False", ")", ":", "yield", "metrics", "else", ":", "def", "metrics_node_extract", "(", "report", ")", ":", "metrics_file", "=", "osp", ".", "join", "(", "report", ".", "path", ",", "JSON_METRICS_FILE", ")", "if", "osp", ".", "exists", "(", "metrics_file", ")", ":", "with", "open", "(", "metrics_file", ")", "as", "istr", ":", "return", "json", ".", "load", "(", "istr", ")", "def", "metrics_iterator", "(", "report", ")", ":", "return", "filter", "(", "lambda", "eax", ":", "eax", "[", "1", "]", "is", "not", "None", ",", "report", ".", "map", "(", "metrics_node_extract", ",", "with_path", "=", "True", ")", ",", ")", "for", "path", ",", "metrics", "in", "metrics_iterator", "(", "report", ")", ":", "yield", "report", ".", "path_context", "(", "path", ")", ",", "metrics" ]
Extract metrics from existing campaign :param campaign: campaign loaded with `hpcbench.campaign.from_file` :param report: instance of `hpcbench.campaign.ReportNode` :param top: this function is recursive. This parameter help distinguishing top-call.
[ "Extract", "metrics", "from", "existing", "campaign" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L421-L449
BlueBrain/hpcbench
hpcbench/campaign.py
Generator.write
def write(self, file): """Write YAML campaign template to the given open file """ render( self.template, file, benchmarks=self.benchmarks, hostname=socket.gethostname(), )
python
def write(self, file): """Write YAML campaign template to the given open file """ render( self.template, file, benchmarks=self.benchmarks, hostname=socket.gethostname(), )
[ "def", "write", "(", "self", ",", "file", ")", ":", "render", "(", "self", ".", "template", ",", "file", ",", "benchmarks", "=", "self", ".", "benchmarks", ",", "hostname", "=", "socket", ".", "gethostname", "(", ")", ",", ")" ]
Write YAML campaign template to the given open file
[ "Write", "YAML", "campaign", "template", "to", "the", "given", "open", "file" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L104-L112