repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
mromanello/hucitlib | knowledge_base/surfext/__init__.py | HucitAuthor.get_abbreviations | def get_abbreviations(self):
"""
Get abbreviations of the names of the author.
:return: a list of strings (empty list if no abbreviations available).
"""
abbreviations = []
try:
type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation"
, self.session.get_class(surf.ns.ECRM['E55_Type']))
abbreviations = [unicode(label)
for name in self.ecrm_P1_is_identified_by
for abbreviation in name.ecrm_P139_has_alternative_form
for label in abbreviation.rdfs_label
if name.uri == surf.ns.EFRBROO['F12_Name']
and abbreviation.ecrm_P2_has_type.first == type_abbreviation]
except Exception as e:
logger.debug("Exception raised when getting abbreviations for %a"%self)
finally:
return abbreviations | python | def get_abbreviations(self):
"""
Get abbreviations of the names of the author.
:return: a list of strings (empty list if no abbreviations available).
"""
abbreviations = []
try:
type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation"
, self.session.get_class(surf.ns.ECRM['E55_Type']))
abbreviations = [unicode(label)
for name in self.ecrm_P1_is_identified_by
for abbreviation in name.ecrm_P139_has_alternative_form
for label in abbreviation.rdfs_label
if name.uri == surf.ns.EFRBROO['F12_Name']
and abbreviation.ecrm_P2_has_type.first == type_abbreviation]
except Exception as e:
logger.debug("Exception raised when getting abbreviations for %a"%self)
finally:
return abbreviations | [
"def",
"get_abbreviations",
"(",
"self",
")",
":",
"abbreviations",
"=",
"[",
"]",
"try",
":",
"type_abbreviation",
"=",
"self",
".",
"session",
".",
"get_resource",
"(",
"BASE_URI_TYPES",
"%",
"\"abbreviation\"",
",",
"self",
".",
"session",
".",
"get_class",... | Get abbreviations of the names of the author.
:return: a list of strings (empty list if no abbreviations available). | [
"Get",
"abbreviations",
"of",
"the",
"names",
"of",
"the",
"author",
"."
] | 6587d1b04eb7e5b48ad7359be845e5d3b444d6fa | https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L164-L183 | train | 53,500 |
mromanello/hucitlib | knowledge_base/surfext/__init__.py | HucitAuthor.get_urn | def get_urn(self):
"""
Assumes that each HucitAuthor has only one CTS URN.
"""
# TODO: check type
try:
type_ctsurn = self.session.get_resource(BASE_URI_TYPES % "CTS_URN"
, self.session.get_class(surf.ns.ECRM['E55_Type']))
urn = [CTS_URN(urnstring.rdfs_label.one)
for urnstring in self.ecrm_P1_is_identified_by
if urnstring.uri == surf.ns.ECRM['E42_Identifier']
and urnstring.ecrm_P2_has_type.first == type_ctsurn][0]
return urn
except Exception as e:
return None | python | def get_urn(self):
"""
Assumes that each HucitAuthor has only one CTS URN.
"""
# TODO: check type
try:
type_ctsurn = self.session.get_resource(BASE_URI_TYPES % "CTS_URN"
, self.session.get_class(surf.ns.ECRM['E55_Type']))
urn = [CTS_URN(urnstring.rdfs_label.one)
for urnstring in self.ecrm_P1_is_identified_by
if urnstring.uri == surf.ns.ECRM['E42_Identifier']
and urnstring.ecrm_P2_has_type.first == type_ctsurn][0]
return urn
except Exception as e:
return None | [
"def",
"get_urn",
"(",
"self",
")",
":",
"# TODO: check type",
"try",
":",
"type_ctsurn",
"=",
"self",
".",
"session",
".",
"get_resource",
"(",
"BASE_URI_TYPES",
"%",
"\"CTS_URN\"",
",",
"self",
".",
"session",
".",
"get_class",
"(",
"surf",
".",
"ns",
".... | Assumes that each HucitAuthor has only one CTS URN. | [
"Assumes",
"that",
"each",
"HucitAuthor",
"has",
"only",
"one",
"CTS",
"URN",
"."
] | 6587d1b04eb7e5b48ad7359be845e5d3b444d6fa | https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L185-L199 | train | 53,501 |
mromanello/hucitlib | knowledge_base/surfext/__init__.py | HucitAuthor.to_json | def to_json(self):
"""
Serialises a HucitAuthor to a JSON formatted string.
Example:
>> homer = kb.get_resource_by_urn("urn:cts:greekLit:tlg0012")
>> homer.to_json()
{
"name_abbreviations": [
"Hom."
],
"urn": "urn:cts:greekLit:tlg0012",
"works": [
{
"urn": "urn:cts:greekLit:tlg0012.tlg001",
"titles": [
{
"language": "it",
"label": "Iliade"
},
{
"language": "la",
"label": "Ilias"
},
{
"language": "en",
"label": "Iliad"
},
{
"language": "de",
"label": "Ilias"
},
{
"language": "fr",
"label": "L'Iliade"
}
],
"uri": "http://purl.org/hucit/kb/works/2815",
"title_abbreviations": [
"Il."
]
},
{
"urn": "urn:cts:greekLit:tlg0012.tlg002",
"titles": [
{
"language": "en",
"label": "Odyssey"
},
{
"language": "fr",
"label": "L'Odyss\u00e9e"
},
{
"language": "it",
"label": "Odissea"
},
{
"language": "la",
"label": "Odyssea"
},
{
"language": "de",
"label": "Odyssee"
}
],
"uri": "http://purl.org/hucit/kb/works/2816",
"title_abbreviations": [
"Od."
]
},
{
"urn": "urn:cts:cwkb:927.2814",
"titles": [
{
"language": "la",
"label": "Epigrammata"
}
],
"uri": "http://purl.org/hucit/kb/works/2814",
"title_abbreviations": [
"Epigr."
]
}
],
"uri": "http://purl.org/hucit/kb/authors/927",
"names": [
{
"language": "fr",
"label": "Hom\u00e8re"
},
{
"language": "la",
"label": "Homerus"
},
{
"language": null,
"label": "Homeros"
},
{
"language": "en",
"label": "Homer"
},
{
"language": "it",
"label": "Omero"
}
]
}
"""
names = self.get_names()
return json.dumps({
"uri" : self.subject
, "urn" : str(self.get_urn())
, "names" : [{"language":lang, "label":label} for lang, label in names]
, "name_abbreviations" : self.get_abbreviations()
, "works" : [json.loads(work.to_json()) for work in self.get_works()]
}, indent=2) | python | def to_json(self):
"""
Serialises a HucitAuthor to a JSON formatted string.
Example:
>> homer = kb.get_resource_by_urn("urn:cts:greekLit:tlg0012")
>> homer.to_json()
{
"name_abbreviations": [
"Hom."
],
"urn": "urn:cts:greekLit:tlg0012",
"works": [
{
"urn": "urn:cts:greekLit:tlg0012.tlg001",
"titles": [
{
"language": "it",
"label": "Iliade"
},
{
"language": "la",
"label": "Ilias"
},
{
"language": "en",
"label": "Iliad"
},
{
"language": "de",
"label": "Ilias"
},
{
"language": "fr",
"label": "L'Iliade"
}
],
"uri": "http://purl.org/hucit/kb/works/2815",
"title_abbreviations": [
"Il."
]
},
{
"urn": "urn:cts:greekLit:tlg0012.tlg002",
"titles": [
{
"language": "en",
"label": "Odyssey"
},
{
"language": "fr",
"label": "L'Odyss\u00e9e"
},
{
"language": "it",
"label": "Odissea"
},
{
"language": "la",
"label": "Odyssea"
},
{
"language": "de",
"label": "Odyssee"
}
],
"uri": "http://purl.org/hucit/kb/works/2816",
"title_abbreviations": [
"Od."
]
},
{
"urn": "urn:cts:cwkb:927.2814",
"titles": [
{
"language": "la",
"label": "Epigrammata"
}
],
"uri": "http://purl.org/hucit/kb/works/2814",
"title_abbreviations": [
"Epigr."
]
}
],
"uri": "http://purl.org/hucit/kb/authors/927",
"names": [
{
"language": "fr",
"label": "Hom\u00e8re"
},
{
"language": "la",
"label": "Homerus"
},
{
"language": null,
"label": "Homeros"
},
{
"language": "en",
"label": "Homer"
},
{
"language": "it",
"label": "Omero"
}
]
}
"""
names = self.get_names()
return json.dumps({
"uri" : self.subject
, "urn" : str(self.get_urn())
, "names" : [{"language":lang, "label":label} for lang, label in names]
, "name_abbreviations" : self.get_abbreviations()
, "works" : [json.loads(work.to_json()) for work in self.get_works()]
}, indent=2) | [
"def",
"to_json",
"(",
"self",
")",
":",
"names",
"=",
"self",
".",
"get_names",
"(",
")",
"return",
"json",
".",
"dumps",
"(",
"{",
"\"uri\"",
":",
"self",
".",
"subject",
",",
"\"urn\"",
":",
"str",
"(",
"self",
".",
"get_urn",
"(",
")",
")",
"... | Serialises a HucitAuthor to a JSON formatted string.
Example:
>> homer = kb.get_resource_by_urn("urn:cts:greekLit:tlg0012")
>> homer.to_json()
{
"name_abbreviations": [
"Hom."
],
"urn": "urn:cts:greekLit:tlg0012",
"works": [
{
"urn": "urn:cts:greekLit:tlg0012.tlg001",
"titles": [
{
"language": "it",
"label": "Iliade"
},
{
"language": "la",
"label": "Ilias"
},
{
"language": "en",
"label": "Iliad"
},
{
"language": "de",
"label": "Ilias"
},
{
"language": "fr",
"label": "L'Iliade"
}
],
"uri": "http://purl.org/hucit/kb/works/2815",
"title_abbreviations": [
"Il."
]
},
{
"urn": "urn:cts:greekLit:tlg0012.tlg002",
"titles": [
{
"language": "en",
"label": "Odyssey"
},
{
"language": "fr",
"label": "L'Odyss\u00e9e"
},
{
"language": "it",
"label": "Odissea"
},
{
"language": "la",
"label": "Odyssea"
},
{
"language": "de",
"label": "Odyssee"
}
],
"uri": "http://purl.org/hucit/kb/works/2816",
"title_abbreviations": [
"Od."
]
},
{
"urn": "urn:cts:cwkb:927.2814",
"titles": [
{
"language": "la",
"label": "Epigrammata"
}
],
"uri": "http://purl.org/hucit/kb/works/2814",
"title_abbreviations": [
"Epigr."
]
}
],
"uri": "http://purl.org/hucit/kb/authors/927",
"names": [
{
"language": "fr",
"label": "Hom\u00e8re"
},
{
"language": "la",
"label": "Homerus"
},
{
"language": null,
"label": "Homeros"
},
{
"language": "en",
"label": "Homer"
},
{
"language": "it",
"label": "Omero"
}
]
} | [
"Serialises",
"a",
"HucitAuthor",
"to",
"a",
"JSON",
"formatted",
"string",
"."
] | 6587d1b04eb7e5b48ad7359be845e5d3b444d6fa | https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L225-L343 | train | 53,502 |
mromanello/hucitlib | knowledge_base/surfext/__init__.py | HucitWork.add_text_structure | def add_text_structure(self, label):
"""
Adds a citable text structure to the work.
"""
ts = self.session.get_resource("%s/text_structure" % self.subject
, self.session.get_class(surf.ns.HUCIT['TextStructure']))
ts.rdfs_label.append(Literal(label))
ts.save()
self.hucit_has_structure = ts
self.update()
return self.hucit_has_structure.one | python | def add_text_structure(self, label):
"""
Adds a citable text structure to the work.
"""
ts = self.session.get_resource("%s/text_structure" % self.subject
, self.session.get_class(surf.ns.HUCIT['TextStructure']))
ts.rdfs_label.append(Literal(label))
ts.save()
self.hucit_has_structure = ts
self.update()
return self.hucit_has_structure.one | [
"def",
"add_text_structure",
"(",
"self",
",",
"label",
")",
":",
"ts",
"=",
"self",
".",
"session",
".",
"get_resource",
"(",
"\"%s/text_structure\"",
"%",
"self",
".",
"subject",
",",
"self",
".",
"session",
".",
"get_class",
"(",
"surf",
".",
"ns",
".... | Adds a citable text structure to the work. | [
"Adds",
"a",
"citable",
"text",
"structure",
"to",
"the",
"work",
"."
] | 6587d1b04eb7e5b48ad7359be845e5d3b444d6fa | https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L487-L498 | train | 53,503 |
mromanello/hucitlib | knowledge_base/surfext/__init__.py | HucitWork.remove_text_structure | def remove_text_structure(self, text_structure): # TODO: delete also TextElements one by one
"""
Remove any citable text structure to the work.
"""
idx = self.hucit_has_structure.index(text_structure)
ts = self.hucit_has_structure.pop(idx)
ts.remove()
self.update()
return | python | def remove_text_structure(self, text_structure): # TODO: delete also TextElements one by one
"""
Remove any citable text structure to the work.
"""
idx = self.hucit_has_structure.index(text_structure)
ts = self.hucit_has_structure.pop(idx)
ts.remove()
self.update()
return | [
"def",
"remove_text_structure",
"(",
"self",
",",
"text_structure",
")",
":",
"# TODO: delete also TextElements one by one",
"idx",
"=",
"self",
".",
"hucit_has_structure",
".",
"index",
"(",
"text_structure",
")",
"ts",
"=",
"self",
".",
"hucit_has_structure",
".",
... | Remove any citable text structure to the work. | [
"Remove",
"any",
"citable",
"text",
"structure",
"to",
"the",
"work",
"."
] | 6587d1b04eb7e5b48ad7359be845e5d3b444d6fa | https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L500-L508 | train | 53,504 |
mromanello/hucitlib | knowledge_base/surfext/__init__.py | HucitWork._get_opus_maximum | def _get_opus_maximum(self):
"""Instantiate an opus maximum type."""
label = """The opux maximum of a given author
that is, the only preserved work by that
author or the most known one."""
opmax = self.session.get_resource(
BASE_URI_TYPES % "opmax",
self.session.get_class(surf.ns.ECRM['E55_Type'])
)
if opmax.is_present():
return opmax
else:
opmax.rdfs_label.append(Literal(label, "en"))
logger.debug("Created a new opus maximum type instance")
opmax.save()
return opmax | python | def _get_opus_maximum(self):
"""Instantiate an opus maximum type."""
label = """The opux maximum of a given author
that is, the only preserved work by that
author or the most known one."""
opmax = self.session.get_resource(
BASE_URI_TYPES % "opmax",
self.session.get_class(surf.ns.ECRM['E55_Type'])
)
if opmax.is_present():
return opmax
else:
opmax.rdfs_label.append(Literal(label, "en"))
logger.debug("Created a new opus maximum type instance")
opmax.save()
return opmax | [
"def",
"_get_opus_maximum",
"(",
"self",
")",
":",
"label",
"=",
"\"\"\"The opux maximum of a given author\n that is, the only preserved work by that\n author or the most known one.\"\"\"",
"opmax",
"=",
"self",
".",
"session",
".",
"get_resource",... | Instantiate an opus maximum type. | [
"Instantiate",
"an",
"opus",
"maximum",
"type",
"."
] | 6587d1b04eb7e5b48ad7359be845e5d3b444d6fa | https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L510-L526 | train | 53,505 |
mromanello/hucitlib | knowledge_base/surfext/__init__.py | HucitWork.set_as_opus_maximum | def set_as_opus_maximum(self): # TODO: test
"""Mark explicitly the work as the author's opus maximum."""
if self.is_opus_maximum():
return False
else:
opmax = self._get_opus_maximum()
self.ecrm_P2_has_type = opmax
self.update()
return True | python | def set_as_opus_maximum(self): # TODO: test
"""Mark explicitly the work as the author's opus maximum."""
if self.is_opus_maximum():
return False
else:
opmax = self._get_opus_maximum()
self.ecrm_P2_has_type = opmax
self.update()
return True | [
"def",
"set_as_opus_maximum",
"(",
"self",
")",
":",
"# TODO: test",
"if",
"self",
".",
"is_opus_maximum",
"(",
")",
":",
"return",
"False",
"else",
":",
"opmax",
"=",
"self",
".",
"_get_opus_maximum",
"(",
")",
"self",
".",
"ecrm_P2_has_type",
"=",
"opmax",... | Mark explicitly the work as the author's opus maximum. | [
"Mark",
"explicitly",
"the",
"work",
"as",
"the",
"author",
"s",
"opus",
"maximum",
"."
] | 6587d1b04eb7e5b48ad7359be845e5d3b444d6fa | https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L528-L536 | train | 53,506 |
mromanello/hucitlib | knowledge_base/surfext/__init__.py | HucitWork.is_opus_maximum | def is_opus_maximum(self):
"""Check whether the work is the author's opus maximum.
Two cases:
1. the work is flagged as opus max
2. there is only one work by this author
:return: boolean
"""
opmax = self._get_opus_maximum()
types = self.ecrm_P2_has_type
if opmax in types:
return True
else:
if len(self.author.get_works()) == 1:
return True
else:
return False | python | def is_opus_maximum(self):
"""Check whether the work is the author's opus maximum.
Two cases:
1. the work is flagged as opus max
2. there is only one work by this author
:return: boolean
"""
opmax = self._get_opus_maximum()
types = self.ecrm_P2_has_type
if opmax in types:
return True
else:
if len(self.author.get_works()) == 1:
return True
else:
return False | [
"def",
"is_opus_maximum",
"(",
"self",
")",
":",
"opmax",
"=",
"self",
".",
"_get_opus_maximum",
"(",
")",
"types",
"=",
"self",
".",
"ecrm_P2_has_type",
"if",
"opmax",
"in",
"types",
":",
"return",
"True",
"else",
":",
"if",
"len",
"(",
"self",
".",
"... | Check whether the work is the author's opus maximum.
Two cases:
1. the work is flagged as opus max
2. there is only one work by this author
:return: boolean | [
"Check",
"whether",
"the",
"work",
"is",
"the",
"author",
"s",
"opus",
"maximum",
"."
] | 6587d1b04eb7e5b48ad7359be845e5d3b444d6fa | https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L538-L556 | train | 53,507 |
mromanello/hucitlib | knowledge_base/surfext/__init__.py | HucitWork.author | def author(self):
"""
Returns the author to whom the work is attributed.
:return: an instance of `HucitWork` # TODO: check that's the case
"""
CreationEvent = self.session.get_class(surf.ns.EFRBROO['F27_Work_Conception'])
Person = self.session.get_class(surf.ns.EFRBROO['F10_Person'])
creation_event = CreationEvent.get_by(efrbroo_R16_initiated=self).first()
return Person.get_by(efrbroo_P14i_performed = creation_event).first() | python | def author(self):
"""
Returns the author to whom the work is attributed.
:return: an instance of `HucitWork` # TODO: check that's the case
"""
CreationEvent = self.session.get_class(surf.ns.EFRBROO['F27_Work_Conception'])
Person = self.session.get_class(surf.ns.EFRBROO['F10_Person'])
creation_event = CreationEvent.get_by(efrbroo_R16_initiated=self).first()
return Person.get_by(efrbroo_P14i_performed = creation_event).first() | [
"def",
"author",
"(",
"self",
")",
":",
"CreationEvent",
"=",
"self",
".",
"session",
".",
"get_class",
"(",
"surf",
".",
"ns",
".",
"EFRBROO",
"[",
"'F27_Work_Conception'",
"]",
")",
"Person",
"=",
"self",
".",
"session",
".",
"get_class",
"(",
"surf",
... | Returns the author to whom the work is attributed.
:return: an instance of `HucitWork` # TODO: check that's the case | [
"Returns",
"the",
"author",
"to",
"whom",
"the",
"work",
"is",
"attributed",
"."
] | 6587d1b04eb7e5b48ad7359be845e5d3b444d6fa | https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L566-L575 | train | 53,508 |
mromanello/hucitlib | knowledge_base/surfext/__init__.py | HucitWork.to_json | def to_json(self):
"""
Serialises a HucitWork to a JSON formatted string.
"""
titles = self.get_titles()
return json.dumps({
"uri" : self.subject
, "urn" : str(self.get_urn())
, "titles" : [{"language":lang, "label":label} for lang, label in titles]
, "title_abbreviations" : self.get_abbreviations()
}, indent=2) | python | def to_json(self):
"""
Serialises a HucitWork to a JSON formatted string.
"""
titles = self.get_titles()
return json.dumps({
"uri" : self.subject
, "urn" : str(self.get_urn())
, "titles" : [{"language":lang, "label":label} for lang, label in titles]
, "title_abbreviations" : self.get_abbreviations()
}, indent=2) | [
"def",
"to_json",
"(",
"self",
")",
":",
"titles",
"=",
"self",
".",
"get_titles",
"(",
")",
"return",
"json",
".",
"dumps",
"(",
"{",
"\"uri\"",
":",
"self",
".",
"subject",
",",
"\"urn\"",
":",
"str",
"(",
"self",
".",
"get_urn",
"(",
")",
")",
... | Serialises a HucitWork to a JSON formatted string. | [
"Serialises",
"a",
"HucitWork",
"to",
"a",
"JSON",
"formatted",
"string",
"."
] | 6587d1b04eb7e5b48ad7359be845e5d3b444d6fa | https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L583-L594 | train | 53,509 |
BlueBrain/hpcbench | hpcbench/driver/campaign.py | CampaignDriver.execution_cls | def execution_cls(self):
"""Get execution layer class
"""
name = self.campaign.process.type
for clazz in [ExecutionDriver, SrunExecutionDriver]:
if name == clazz.name:
return clazz
raise NameError("Unknown execution layer: '%s'" % name) | python | def execution_cls(self):
"""Get execution layer class
"""
name = self.campaign.process.type
for clazz in [ExecutionDriver, SrunExecutionDriver]:
if name == clazz.name:
return clazz
raise NameError("Unknown execution layer: '%s'" % name) | [
"def",
"execution_cls",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"campaign",
".",
"process",
".",
"type",
"for",
"clazz",
"in",
"[",
"ExecutionDriver",
",",
"SrunExecutionDriver",
"]",
":",
"if",
"name",
"==",
"clazz",
".",
"name",
":",
"return",... | Get execution layer class | [
"Get",
"execution",
"layer",
"class"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/campaign.py#L146-L153 | train | 53,510 |
BlueBrain/hpcbench | hpcbench/driver/campaign.py | HostDriver.children | def children(self):
"""Retrieve tags associated to the current node"""
tags = {'*'}
if self.tag:
network_tags = {self.tag: self.campaign.network.tags[self.tag]}
else:
network_tags = self.campaign.network.tags
for tag, configs in network_tags.items():
for config in configs:
for mode, kconfig in config.items():
if mode == 'match':
if kconfig.match(self.name) or kconfig.match(LOCALHOST):
tags.add(tag)
break
elif mode == 'nodes':
if self.name in kconfig or LOCALHOST in kconfig:
tags.add(tag)
break
elif mode == 'constraint':
tags.add(tag)
break
if tag in tags:
break
return tags | python | def children(self):
"""Retrieve tags associated to the current node"""
tags = {'*'}
if self.tag:
network_tags = {self.tag: self.campaign.network.tags[self.tag]}
else:
network_tags = self.campaign.network.tags
for tag, configs in network_tags.items():
for config in configs:
for mode, kconfig in config.items():
if mode == 'match':
if kconfig.match(self.name) or kconfig.match(LOCALHOST):
tags.add(tag)
break
elif mode == 'nodes':
if self.name in kconfig or LOCALHOST in kconfig:
tags.add(tag)
break
elif mode == 'constraint':
tags.add(tag)
break
if tag in tags:
break
return tags | [
"def",
"children",
"(",
"self",
")",
":",
"tags",
"=",
"{",
"'*'",
"}",
"if",
"self",
".",
"tag",
":",
"network_tags",
"=",
"{",
"self",
".",
"tag",
":",
"self",
".",
"campaign",
".",
"network",
".",
"tags",
"[",
"self",
".",
"tag",
"]",
"}",
"... | Retrieve tags associated to the current node | [
"Retrieve",
"tags",
"associated",
"to",
"the",
"current",
"node"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/campaign.py#L164-L187 | train | 53,511 |
KelSolaar/Manager | manager/component.py | Component.activate | def activate(self):
"""
Sets Component activation state.
:return: Method success.
:rtype: bool
"""
raise NotImplementedError("{0} | '{1}' must be implemented by '{2}' subclasses!".format(
self.__class__.__name__, self.activate.__name__, self.__class__.__name__)) | python | def activate(self):
"""
Sets Component activation state.
:return: Method success.
:rtype: bool
"""
raise NotImplementedError("{0} | '{1}' must be implemented by '{2}' subclasses!".format(
self.__class__.__name__, self.activate.__name__, self.__class__.__name__)) | [
"def",
"activate",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"{0} | '{1}' must be implemented by '{2}' subclasses!\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"activate",
".",
"__name__",
",",
"self",
".... | Sets Component activation state.
:return: Method success.
:rtype: bool | [
"Sets",
"Component",
"activation",
"state",
"."
] | 39c8153fc021fc8a76e345a6e336ec2644f089d1 | https://github.com/KelSolaar/Manager/blob/39c8153fc021fc8a76e345a6e336ec2644f089d1/manager/component.py#L198-L207 | train | 53,512 |
BlueBrain/hpcbench | hpcbench/toolbox/slurm/cluster.py | SlurmCluster.reservations | def reservations(self):
"""get nodes of every reservations"""
command = [SINFO, '--reservation']
output = subprocess.check_output(command, env=SINFO_ENV)
output = output.decode()
it = iter(output.splitlines())
next(it)
for line in it:
rsv = Reservation.from_sinfo(line)
yield rsv.name, rsv | python | def reservations(self):
"""get nodes of every reservations"""
command = [SINFO, '--reservation']
output = subprocess.check_output(command, env=SINFO_ENV)
output = output.decode()
it = iter(output.splitlines())
next(it)
for line in it:
rsv = Reservation.from_sinfo(line)
yield rsv.name, rsv | [
"def",
"reservations",
"(",
"self",
")",
":",
"command",
"=",
"[",
"SINFO",
",",
"'--reservation'",
"]",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"command",
",",
"env",
"=",
"SINFO_ENV",
")",
"output",
"=",
"output",
".",
"decode",
"(",
")"... | get nodes of every reservations | [
"get",
"nodes",
"of",
"every",
"reservations"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/slurm/cluster.py#L57-L66 | train | 53,513 |
eng-tools/sfsimodels | sfsimodels/models/abstract_models.py | PhysicalObject.set | def set(self, values):
"""
Set the object parameters using a dictionary
"""
if hasattr(self, "inputs"):
for item in self.inputs:
if hasattr(self, item):
setattr(self, item, values[item]) | python | def set(self, values):
"""
Set the object parameters using a dictionary
"""
if hasattr(self, "inputs"):
for item in self.inputs:
if hasattr(self, item):
setattr(self, item, values[item]) | [
"def",
"set",
"(",
"self",
",",
"values",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"inputs\"",
")",
":",
"for",
"item",
"in",
"self",
".",
"inputs",
":",
"if",
"hasattr",
"(",
"self",
",",
"item",
")",
":",
"setattr",
"(",
"self",
",",
"ite... | Set the object parameters using a dictionary | [
"Set",
"the",
"object",
"parameters",
"using",
"a",
"dictionary"
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/abstract_models.py#L44-L51 | train | 53,514 |
PolyJIT/benchbuild | benchbuild/utils/tasks.py | execute_plan | def execute_plan(plan):
""""Execute the plan.
Args:
plan (:obj:`list` of :obj:`actions.Step`): The plan we want to execute.
Returns:
(:obj:`list` of :obj:`actions.Step`): A list of failed actions.
"""
results = [action() for action in plan]
return [result for result in results if actns.step_has_failed(result)] | python | def execute_plan(plan):
""""Execute the plan.
Args:
plan (:obj:`list` of :obj:`actions.Step`): The plan we want to execute.
Returns:
(:obj:`list` of :obj:`actions.Step`): A list of failed actions.
"""
results = [action() for action in plan]
return [result for result in results if actns.step_has_failed(result)] | [
"def",
"execute_plan",
"(",
"plan",
")",
":",
"results",
"=",
"[",
"action",
"(",
")",
"for",
"action",
"in",
"plan",
"]",
"return",
"[",
"result",
"for",
"result",
"in",
"results",
"if",
"actns",
".",
"step_has_failed",
"(",
"result",
")",
"]"
] | Execute the plan.
Args:
plan (:obj:`list` of :obj:`actions.Step`): The plan we want to execute.
Returns:
(:obj:`list` of :obj:`actions.Step`): A list of failed actions. | [
"Execute",
"the",
"plan",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/tasks.py#L7-L17 | train | 53,515 |
portfoliome/foil | foil/formatters.py | format_repr | def format_repr(obj, attributes) -> str:
"""Format an object's repr method with specific attributes."""
attribute_repr = ', '.join(('{}={}'.format(attr, repr(getattr(obj, attr)))
for attr in attributes))
return "{0}({1})".format(obj.__class__.__qualname__, attribute_repr) | python | def format_repr(obj, attributes) -> str:
"""Format an object's repr method with specific attributes."""
attribute_repr = ', '.join(('{}={}'.format(attr, repr(getattr(obj, attr)))
for attr in attributes))
return "{0}({1})".format(obj.__class__.__qualname__, attribute_repr) | [
"def",
"format_repr",
"(",
"obj",
",",
"attributes",
")",
"->",
"str",
":",
"attribute_repr",
"=",
"', '",
".",
"join",
"(",
"(",
"'{}={}'",
".",
"format",
"(",
"attr",
",",
"repr",
"(",
"getattr",
"(",
"obj",
",",
"attr",
")",
")",
")",
"for",
"at... | Format an object's repr method with specific attributes. | [
"Format",
"an",
"object",
"s",
"repr",
"method",
"with",
"specific",
"attributes",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/formatters.py#L6-L11 | train | 53,516 |
eng-tools/sfsimodels | sfsimodels/build_model_descriptions.py | build_parameter_descriptions | def build_parameter_descriptions(obj, user_p=None, output="csv", show_none=True, ignore=None, plist=None):
"""
Creates a list of the decription of all the inputs of an object
:param obj: object, that has parameters
:param user_p: dict, user defined parameter descriptions
:param show_none: if false, only shows descriptions of parameters that are not None
:param ignore: list of parameters to not build
:return:
"""
if user_p is None:
user_p = {}
if ignore is None:
ignore = []
para = [[obj.__class__.__name__ + " inputs:", "", ""]]
if plist is None:
if not hasattr(obj, 'inputs'):
raise exceptions.ModelError("Object must contain parameter 'inputs' or set plist as an input")
plist = obj.inputs
p_dict = {}
if hasattr(obj, 'ancestor_types'):
bt = obj.ancestor_types
for otype in bt: # cycles from lowest class, so descriptions get overridden
if otype in vp:
for item in vp[otype]:
p_dict[item] = vp[otype][item]
for item in user_p: # user defined definitions override base ones
p_dict[item] = user_p[item]
else:
p_dict = user_p
for item in plist:
if show_none is False and getattr(obj, item) is None:
continue
if item in ignore:
continue
if item in p_dict:
para.append([item, p_dict[item][1], p_dict[item][0]])
else:
para.append([item, "", ""])
if output == "csv":
out_obj = []
for i in range(len(para)):
out_obj.append(",".join(para[i]))
elif output == "list":
out_obj = para
elif output == "dict":
out_obj = OrderedDict()
for i in range(len(para)):
out_obj[para[i][0]] = {"description": para[i][2], "units": para[i][1]}
else:
raise ValueError("output must be either: 'csv', 'dict' or 'list'.")
return out_obj | python | def build_parameter_descriptions(obj, user_p=None, output="csv", show_none=True, ignore=None, plist=None):
"""
Creates a list of the decription of all the inputs of an object
:param obj: object, that has parameters
:param user_p: dict, user defined parameter descriptions
:param show_none: if false, only shows descriptions of parameters that are not None
:param ignore: list of parameters to not build
:return:
"""
if user_p is None:
user_p = {}
if ignore is None:
ignore = []
para = [[obj.__class__.__name__ + " inputs:", "", ""]]
if plist is None:
if not hasattr(obj, 'inputs'):
raise exceptions.ModelError("Object must contain parameter 'inputs' or set plist as an input")
plist = obj.inputs
p_dict = {}
if hasattr(obj, 'ancestor_types'):
bt = obj.ancestor_types
for otype in bt: # cycles from lowest class, so descriptions get overridden
if otype in vp:
for item in vp[otype]:
p_dict[item] = vp[otype][item]
for item in user_p: # user defined definitions override base ones
p_dict[item] = user_p[item]
else:
p_dict = user_p
for item in plist:
if show_none is False and getattr(obj, item) is None:
continue
if item in ignore:
continue
if item in p_dict:
para.append([item, p_dict[item][1], p_dict[item][0]])
else:
para.append([item, "", ""])
if output == "csv":
out_obj = []
for i in range(len(para)):
out_obj.append(",".join(para[i]))
elif output == "list":
out_obj = para
elif output == "dict":
out_obj = OrderedDict()
for i in range(len(para)):
out_obj[para[i][0]] = {"description": para[i][2], "units": para[i][1]}
else:
raise ValueError("output must be either: 'csv', 'dict' or 'list'.")
return out_obj | [
"def",
"build_parameter_descriptions",
"(",
"obj",
",",
"user_p",
"=",
"None",
",",
"output",
"=",
"\"csv\"",
",",
"show_none",
"=",
"True",
",",
"ignore",
"=",
"None",
",",
"plist",
"=",
"None",
")",
":",
"if",
"user_p",
"is",
"None",
":",
"user_p",
"... | Creates a list of the decription of all the inputs of an object
:param obj: object, that has parameters
:param user_p: dict, user defined parameter descriptions
:param show_none: if false, only shows descriptions of parameters that are not None
:param ignore: list of parameters to not build
:return: | [
"Creates",
"a",
"list",
"of",
"the",
"decription",
"of",
"all",
"the",
"inputs",
"of",
"an",
"object"
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/build_model_descriptions.py#L8-L61 | train | 53,517 |
eng-tools/sfsimodels | sfsimodels/build_model_descriptions.py | all_descriptions | def all_descriptions():
"""
Generates a list of descriptions of all the models
:return:
"""
para = []
para += build_parameter_descriptions(models.Soil()) + [",,\n"]
para += build_parameter_descriptions(models.SoilProfile()) + [",,\n"]
para += build_parameter_descriptions(models.Foundation()) + [",,\n"]
para += build_parameter_descriptions(models.PadFoundation()) + [",,\n"]
para += build_parameter_descriptions(models.SDOFBuilding()) + [",,\n"]
para += build_parameter_descriptions(models.FrameBuilding2D(1, 1))
return para | python | def all_descriptions():
"""
Generates a list of descriptions of all the models
:return:
"""
para = []
para += build_parameter_descriptions(models.Soil()) + [",,\n"]
para += build_parameter_descriptions(models.SoilProfile()) + [",,\n"]
para += build_parameter_descriptions(models.Foundation()) + [",,\n"]
para += build_parameter_descriptions(models.PadFoundation()) + [",,\n"]
para += build_parameter_descriptions(models.SDOFBuilding()) + [",,\n"]
para += build_parameter_descriptions(models.FrameBuilding2D(1, 1))
return para | [
"def",
"all_descriptions",
"(",
")",
":",
"para",
"=",
"[",
"]",
"para",
"+=",
"build_parameter_descriptions",
"(",
"models",
".",
"Soil",
"(",
")",
")",
"+",
"[",
"\",,\\n\"",
"]",
"para",
"+=",
"build_parameter_descriptions",
"(",
"models",
".",
"SoilProfi... | Generates a list of descriptions of all the models
:return: | [
"Generates",
"a",
"list",
"of",
"descriptions",
"of",
"all",
"the",
"models"
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/build_model_descriptions.py#L64-L78 | train | 53,518 |
sci-bots/svg-model | svg_model/plot.py | plot_shapes_heat_map | def plot_shapes_heat_map(df_shapes, shape_i_columns, values, axis=None,
vmin=None, vmax=None, value_formatter=None,
color_map=None):
'''
Plot polygon shapes, colored based on values mapped onto
a colormap.
Args
----
df_shapes (pandas.DataFrame) : Polygon table containing
the columns `'id', 'x', 'y'`. Coordinates must be
ordered to be grouped by `'id'`.
values (pandas.Series) : Numeric values indexed by `'id'`.
These values are used to look up color in the color map.
axis : A matplotlib axis. If `None`, an axis is created.
vmin : Minimum value to clip values at.
vmax : Maximum value to clip values at.
color_map : A matplotlib color map (see `matplotlib.cm`).
Returns
-------
(tuple) : First element is heat map axis, second element
is colorbar axis.
'''
df_shapes = df_shapes.copy()
# Matplotlib draws from bottom to top, so invert `y` coordinates.
df_shapes.loc[:, 'y'] = df_shapes.y.max() - df_shapes.y.copy().values
aspect_ratio = ((df_shapes.x.max() - df_shapes.x.min()) /
(df_shapes.y.max() - df_shapes.y.min()))
if vmin is not None or vmax is not None:
norm = mpl.colors.Normalize(vmin=vmin or min(values),
vmax=vmax or max(values))
else:
norm = None
if axis is None:
fig, axis = plt.subplots(figsize=(10, 10 * aspect_ratio))
else:
fig = axis.get_figure()
patches = OrderedDict([(id, Polygon(df_shape_i[['x', 'y']].values))
for id, df_shape_i in
df_shapes.groupby(shape_i_columns)])
patches = pd.Series(patches)
collection = PatchCollection(patches.values, cmap=color_map,
norm=norm)
collection.set_array(values.ix[patches.index])
axis.add_collection(collection)
axis_divider = make_axes_locatable(axis)
# Append color axis to the right of `axis`, with 10% width of `axis`.
color_axis = axis_divider.append_axes("right", size="10%", pad=0.05)
colorbar = fig.colorbar(collection, format=value_formatter,
cax=color_axis)
tick_labels = colorbar.ax.get_yticklabels()
if vmin is not None:
tick_labels[0] = '$\leq$%s' % tick_labels[0].get_text()
if vmax is not None:
tick_labels[-1] = '$\geq$%s' % tick_labels[-1].get_text()
colorbar.ax.set_yticklabels(tick_labels)
axis.set_xlim(df_shapes.x.min(), df_shapes.x.max())
axis.set_ylim(df_shapes.y.min(), df_shapes.y.max())
return axis, colorbar | python | def plot_shapes_heat_map(df_shapes, shape_i_columns, values, axis=None,
vmin=None, vmax=None, value_formatter=None,
color_map=None):
'''
Plot polygon shapes, colored based on values mapped onto
a colormap.
Args
----
df_shapes (pandas.DataFrame) : Polygon table containing
the columns `'id', 'x', 'y'`. Coordinates must be
ordered to be grouped by `'id'`.
values (pandas.Series) : Numeric values indexed by `'id'`.
These values are used to look up color in the color map.
axis : A matplotlib axis. If `None`, an axis is created.
vmin : Minimum value to clip values at.
vmax : Maximum value to clip values at.
color_map : A matplotlib color map (see `matplotlib.cm`).
Returns
-------
(tuple) : First element is heat map axis, second element
is colorbar axis.
'''
df_shapes = df_shapes.copy()
# Matplotlib draws from bottom to top, so invert `y` coordinates.
df_shapes.loc[:, 'y'] = df_shapes.y.max() - df_shapes.y.copy().values
aspect_ratio = ((df_shapes.x.max() - df_shapes.x.min()) /
(df_shapes.y.max() - df_shapes.y.min()))
if vmin is not None or vmax is not None:
norm = mpl.colors.Normalize(vmin=vmin or min(values),
vmax=vmax or max(values))
else:
norm = None
if axis is None:
fig, axis = plt.subplots(figsize=(10, 10 * aspect_ratio))
else:
fig = axis.get_figure()
patches = OrderedDict([(id, Polygon(df_shape_i[['x', 'y']].values))
for id, df_shape_i in
df_shapes.groupby(shape_i_columns)])
patches = pd.Series(patches)
collection = PatchCollection(patches.values, cmap=color_map,
norm=norm)
collection.set_array(values.ix[patches.index])
axis.add_collection(collection)
axis_divider = make_axes_locatable(axis)
# Append color axis to the right of `axis`, with 10% width of `axis`.
color_axis = axis_divider.append_axes("right", size="10%", pad=0.05)
colorbar = fig.colorbar(collection, format=value_formatter,
cax=color_axis)
tick_labels = colorbar.ax.get_yticklabels()
if vmin is not None:
tick_labels[0] = '$\leq$%s' % tick_labels[0].get_text()
if vmax is not None:
tick_labels[-1] = '$\geq$%s' % tick_labels[-1].get_text()
colorbar.ax.set_yticklabels(tick_labels)
axis.set_xlim(df_shapes.x.min(), df_shapes.x.max())
axis.set_ylim(df_shapes.y.min(), df_shapes.y.max())
return axis, colorbar | [
"def",
"plot_shapes_heat_map",
"(",
"df_shapes",
",",
"shape_i_columns",
",",
"values",
",",
"axis",
"=",
"None",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
",",
"value_formatter",
"=",
"None",
",",
"color_map",
"=",
"None",
")",
":",
"df_shapes",... | Plot polygon shapes, colored based on values mapped onto
a colormap.
Args
----
df_shapes (pandas.DataFrame) : Polygon table containing
the columns `'id', 'x', 'y'`. Coordinates must be
ordered to be grouped by `'id'`.
values (pandas.Series) : Numeric values indexed by `'id'`.
These values are used to look up color in the color map.
axis : A matplotlib axis. If `None`, an axis is created.
vmin : Minimum value to clip values at.
vmax : Maximum value to clip values at.
color_map : A matplotlib color map (see `matplotlib.cm`).
Returns
-------
(tuple) : First element is heat map axis, second element
is colorbar axis. | [
"Plot",
"polygon",
"shapes",
"colored",
"based",
"on",
"values",
"mapped",
"onto",
"a",
"colormap",
"."
] | 2d119650f995e62b29ce0b3151a23f3b957cb072 | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/plot.py#L62-L135 | train | 53,519 |
sci-bots/svg-model | svg_model/plot.py | plot_color_map_bars | def plot_color_map_bars(values, vmin=None, vmax=None, color_map=None,
axis=None, **kwargs):
'''
Plot bar for each value in `values`, colored based on values mapped onto
the specified color map.
Args
----
values (pandas.Series) : Numeric values to plot one bar per value.
axis : A matplotlib axis. If `None`, an axis is created.
vmin : Minimum value to clip values at.
vmax : Maximum value to clip values at.
color_map : A matplotlib color map (see `matplotlib.cm`).
**kwargs : Extra keyword arguments to pass to `values.plot`.
Returns
-------
(axis) : Bar plot axis.
'''
if axis is None:
fig, axis = plt.subplots()
norm = mpl.colors.Normalize(vmin=vmin or min(values),
vmax=vmax or max(values), clip=True)
if color_map is None:
color_map = mpl.rcParams['image.cmap']
colors = color_map(norm(values.values).filled())
values.plot(kind='bar', ax=axis, color=colors, **kwargs)
return axis | python | def plot_color_map_bars(values, vmin=None, vmax=None, color_map=None,
axis=None, **kwargs):
'''
Plot bar for each value in `values`, colored based on values mapped onto
the specified color map.
Args
----
values (pandas.Series) : Numeric values to plot one bar per value.
axis : A matplotlib axis. If `None`, an axis is created.
vmin : Minimum value to clip values at.
vmax : Maximum value to clip values at.
color_map : A matplotlib color map (see `matplotlib.cm`).
**kwargs : Extra keyword arguments to pass to `values.plot`.
Returns
-------
(axis) : Bar plot axis.
'''
if axis is None:
fig, axis = plt.subplots()
norm = mpl.colors.Normalize(vmin=vmin or min(values),
vmax=vmax or max(values), clip=True)
if color_map is None:
color_map = mpl.rcParams['image.cmap']
colors = color_map(norm(values.values).filled())
values.plot(kind='bar', ax=axis, color=colors, **kwargs)
return axis | [
"def",
"plot_color_map_bars",
"(",
"values",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
",",
"color_map",
"=",
"None",
",",
"axis",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"axis",
"is",
"None",
":",
"fig",
",",
"axis",
"=",
... | Plot bar for each value in `values`, colored based on values mapped onto
the specified color map.
Args
----
values (pandas.Series) : Numeric values to plot one bar per value.
axis : A matplotlib axis. If `None`, an axis is created.
vmin : Minimum value to clip values at.
vmax : Maximum value to clip values at.
color_map : A matplotlib color map (see `matplotlib.cm`).
**kwargs : Extra keyword arguments to pass to `values.plot`.
Returns
-------
(axis) : Bar plot axis. | [
"Plot",
"bar",
"for",
"each",
"value",
"in",
"values",
"colored",
"based",
"on",
"values",
"mapped",
"onto",
"the",
"specified",
"color",
"map",
"."
] | 2d119650f995e62b29ce0b3151a23f3b957cb072 | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/plot.py#L138-L169 | train | 53,520 |
portfoliome/foil | foil/parsers.py | parse_broken_json | def parse_broken_json(json_text: str) -> dict:
"""
Parses broken JSON that the standard Python JSON module cannot parse.
Ex: {success:true}
Keys do not contain quotes and the JSON cannot be parsed using the regular json encoder.
YAML happens to be a superset of JSON and can parse json without quotes.
"""
# Add spacing between Key and Value to prevent parsing error
json_text = json_text.replace(":", ": ")
json_dict = yaml.load(json_text)
return json_dict | python | def parse_broken_json(json_text: str) -> dict:
"""
Parses broken JSON that the standard Python JSON module cannot parse.
Ex: {success:true}
Keys do not contain quotes and the JSON cannot be parsed using the regular json encoder.
YAML happens to be a superset of JSON and can parse json without quotes.
"""
# Add spacing between Key and Value to prevent parsing error
json_text = json_text.replace(":", ": ")
json_dict = yaml.load(json_text)
return json_dict | [
"def",
"parse_broken_json",
"(",
"json_text",
":",
"str",
")",
"->",
"dict",
":",
"# Add spacing between Key and Value to prevent parsing error",
"json_text",
"=",
"json_text",
".",
"replace",
"(",
"\":\"",
",",
"\": \"",
")",
"json_dict",
"=",
"yaml",
".",
"load",
... | Parses broken JSON that the standard Python JSON module cannot parse.
Ex: {success:true}
Keys do not contain quotes and the JSON cannot be parsed using the regular json encoder.
YAML happens to be a superset of JSON and can parse json without quotes. | [
"Parses",
"broken",
"JSON",
"that",
"the",
"standard",
"Python",
"JSON",
"module",
"cannot",
"parse",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/parsers.py#L121-L135 | train | 53,521 |
BlueBrain/hpcbench | hpcbench/driver/executor.py | ExecutionDriver._executor_script | def _executor_script(self):
"""Create shell-script in charge of executing the benchmark
and return its path.
"""
fd, path = tempfile.mkstemp(suffix='.sh', dir=os.getcwd())
os.close(fd)
with open(path, 'w') as ostr:
self._write_executor_script(ostr)
mode = os.stat(path).st_mode
os.chmod(path, mode | stat.S_IEXEC | stat.S_IRGRP | stat.S_IRUSR)
return path | python | def _executor_script(self):
"""Create shell-script in charge of executing the benchmark
and return its path.
"""
fd, path = tempfile.mkstemp(suffix='.sh', dir=os.getcwd())
os.close(fd)
with open(path, 'w') as ostr:
self._write_executor_script(ostr)
mode = os.stat(path).st_mode
os.chmod(path, mode | stat.S_IEXEC | stat.S_IRGRP | stat.S_IRUSR)
return path | [
"def",
"_executor_script",
"(",
"self",
")",
":",
"fd",
",",
"path",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
"=",
"'.sh'",
",",
"dir",
"=",
"os",
".",
"getcwd",
"(",
")",
")",
"os",
".",
"close",
"(",
"fd",
")",
"with",
"open",
"(",
"path... | Create shell-script in charge of executing the benchmark
and return its path. | [
"Create",
"shell",
"-",
"script",
"in",
"charge",
"of",
"executing",
"the",
"benchmark",
"and",
"return",
"its",
"path",
"."
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L56-L66 | train | 53,522 |
BlueBrain/hpcbench | hpcbench/driver/executor.py | ExecutionDriver._write_executor_script | def _write_executor_script(self, ostr):
"""Write shell script in charge of executing the command"""
environment = self.execution.get('environment') or {}
if not isinstance(environment, Mapping):
msg = 'Expected mapping for environment but got '
msg += str(type(environment))
raise Exception(msg)
escaped_environment = dict(
(var, six.moves.shlex_quote(str(value)))
for var, value in environment.items()
)
modules = self.execution.get('modules') or []
properties = dict(
command=self.command,
cwd=os.getcwd(),
modules=modules,
environment=escaped_environment,
)
self._jinja_executor_template.stream(**properties).dump(ostr) | python | def _write_executor_script(self, ostr):
"""Write shell script in charge of executing the command"""
environment = self.execution.get('environment') or {}
if not isinstance(environment, Mapping):
msg = 'Expected mapping for environment but got '
msg += str(type(environment))
raise Exception(msg)
escaped_environment = dict(
(var, six.moves.shlex_quote(str(value)))
for var, value in environment.items()
)
modules = self.execution.get('modules') or []
properties = dict(
command=self.command,
cwd=os.getcwd(),
modules=modules,
environment=escaped_environment,
)
self._jinja_executor_template.stream(**properties).dump(ostr) | [
"def",
"_write_executor_script",
"(",
"self",
",",
"ostr",
")",
":",
"environment",
"=",
"self",
".",
"execution",
".",
"get",
"(",
"'environment'",
")",
"or",
"{",
"}",
"if",
"not",
"isinstance",
"(",
"environment",
",",
"Mapping",
")",
":",
"msg",
"=",... | Write shell script in charge of executing the command | [
"Write",
"shell",
"script",
"in",
"charge",
"of",
"executing",
"the",
"command"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L77-L95 | train | 53,523 |
BlueBrain/hpcbench | hpcbench/driver/executor.py | ExecutionDriver.command_str | def command_str(self):
"""get command to execute as string properly escaped
:return: string
"""
if isinstance(self.command, six.string_types):
return self.command
return ' '.join(map(six.moves.shlex_quote, self.command)) | python | def command_str(self):
"""get command to execute as string properly escaped
:return: string
"""
if isinstance(self.command, six.string_types):
return self.command
return ' '.join(map(six.moves.shlex_quote, self.command)) | [
"def",
"command_str",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"command",
",",
"six",
".",
"string_types",
")",
":",
"return",
"self",
".",
"command",
"return",
"' '",
".",
"join",
"(",
"map",
"(",
"six",
".",
"moves",
".",
"shlex... | get command to execute as string properly escaped
:return: string | [
"get",
"command",
"to",
"execute",
"as",
"string",
"properly",
"escaped"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L125-L132 | train | 53,524 |
BlueBrain/hpcbench | hpcbench/driver/executor.py | ExecutionDriver.popen | def popen(self, stdout, stderr):
"""Build popen object to run
:rtype: subprocess.Popen
"""
self.logger.info('Executing command: %s', self.command_str)
return subprocess.Popen([self._executor_script], stdout=stdout, stderr=stderr) | python | def popen(self, stdout, stderr):
"""Build popen object to run
:rtype: subprocess.Popen
"""
self.logger.info('Executing command: %s', self.command_str)
return subprocess.Popen([self._executor_script], stdout=stdout, stderr=stderr) | [
"def",
"popen",
"(",
"self",
",",
"stdout",
",",
"stderr",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Executing command: %s'",
",",
"self",
".",
"command_str",
")",
"return",
"subprocess",
".",
"Popen",
"(",
"[",
"self",
".",
"_executor_script",
... | Build popen object to run
:rtype: subprocess.Popen | [
"Build",
"popen",
"object",
"to",
"run"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L134-L140 | train | 53,525 |
BlueBrain/hpcbench | hpcbench/driver/executor.py | SrunExecutionDriver.srun | def srun(self):
"""Get path to srun executable
:rtype: string
"""
commands = self.campaign.process.get('commands', {})
srun = find_executable(commands.get('srun', 'srun'))
if six.PY2:
srun = srun.encode('utf-8')
return srun | python | def srun(self):
"""Get path to srun executable
:rtype: string
"""
commands = self.campaign.process.get('commands', {})
srun = find_executable(commands.get('srun', 'srun'))
if six.PY2:
srun = srun.encode('utf-8')
return srun | [
"def",
"srun",
"(",
"self",
")",
":",
"commands",
"=",
"self",
".",
"campaign",
".",
"process",
".",
"get",
"(",
"'commands'",
",",
"{",
"}",
")",
"srun",
"=",
"find_executable",
"(",
"commands",
".",
"get",
"(",
"'srun'",
",",
"'srun'",
")",
")",
... | Get path to srun executable
:rtype: string | [
"Get",
"path",
"to",
"srun",
"executable"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L217-L226 | train | 53,526 |
BlueBrain/hpcbench | hpcbench/driver/executor.py | SrunExecutionDriver.common_srun_options | def common_srun_options(cls, campaign):
"""Get options to be given to all srun commands
:rtype: list of string
"""
default = dict(campaign.process.get('srun') or {})
default.update(output='slurm-%N-%t.stdout', error='slurm-%N-%t.error')
return default | python | def common_srun_options(cls, campaign):
"""Get options to be given to all srun commands
:rtype: list of string
"""
default = dict(campaign.process.get('srun') or {})
default.update(output='slurm-%N-%t.stdout', error='slurm-%N-%t.error')
return default | [
"def",
"common_srun_options",
"(",
"cls",
",",
"campaign",
")",
":",
"default",
"=",
"dict",
"(",
"campaign",
".",
"process",
".",
"get",
"(",
"'srun'",
")",
"or",
"{",
"}",
")",
"default",
".",
"update",
"(",
"output",
"=",
"'slurm-%N-%t.stdout'",
",",
... | Get options to be given to all srun commands
:rtype: list of string | [
"Get",
"options",
"to",
"be",
"given",
"to",
"all",
"srun",
"commands"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L229-L236 | train | 53,527 |
BlueBrain/hpcbench | hpcbench/driver/executor.py | SrunExecutionDriver.command | def command(self):
"""get command to execute
:return: list of string
"""
srun_optlist = build_slurm_arguments(self.parent.command.srun or {})
if not isinstance(self.root.network.nodes(self.tag), ConstraintTag):
pargs = parse_constraint_in_args(srun_optlist)
self.command_expansion_vars['process_count'] = pargs.ntasks
if not pargs.constraint:
# Expand nodelist if --constraint option is not specified
# in srun options
srun_optlist += [
'--nodelist=' + ','.join(self.srun_nodes),
'--nodes=' + str(len(self.srun_nodes)),
]
command = super(SrunExecutionDriver, self).command
return [self.srun] + srun_optlist + command | python | def command(self):
"""get command to execute
:return: list of string
"""
srun_optlist = build_slurm_arguments(self.parent.command.srun or {})
if not isinstance(self.root.network.nodes(self.tag), ConstraintTag):
pargs = parse_constraint_in_args(srun_optlist)
self.command_expansion_vars['process_count'] = pargs.ntasks
if not pargs.constraint:
# Expand nodelist if --constraint option is not specified
# in srun options
srun_optlist += [
'--nodelist=' + ','.join(self.srun_nodes),
'--nodes=' + str(len(self.srun_nodes)),
]
command = super(SrunExecutionDriver, self).command
return [self.srun] + srun_optlist + command | [
"def",
"command",
"(",
"self",
")",
":",
"srun_optlist",
"=",
"build_slurm_arguments",
"(",
"self",
".",
"parent",
".",
"command",
".",
"srun",
"or",
"{",
"}",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"root",
".",
"network",
".",
"nodes",
"(",... | get command to execute
:return: list of string | [
"get",
"command",
"to",
"execute"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L243-L260 | train | 53,528 |
BlueBrain/hpcbench | hpcbench/driver/executor.py | SrunExecutionDriver.srun_nodes | def srun_nodes(self):
"""Get list of nodes where to execute the command
"""
count = self.execution.get('srun_nodes', 0)
if isinstance(count, six.string_types):
tag = count
count = 0
elif isinstance(count, SEQUENCES):
return count
else:
assert isinstance(count, int)
tag = self.tag
nodes = self._srun_nodes(tag, count)
if 'srun_nodes' in self.execution:
self.execution['srun_nodes'] = nodes
self.execution['srun_nodes_count'] = len(nodes)
return nodes | python | def srun_nodes(self):
"""Get list of nodes where to execute the command
"""
count = self.execution.get('srun_nodes', 0)
if isinstance(count, six.string_types):
tag = count
count = 0
elif isinstance(count, SEQUENCES):
return count
else:
assert isinstance(count, int)
tag = self.tag
nodes = self._srun_nodes(tag, count)
if 'srun_nodes' in self.execution:
self.execution['srun_nodes'] = nodes
self.execution['srun_nodes_count'] = len(nodes)
return nodes | [
"def",
"srun_nodes",
"(",
"self",
")",
":",
"count",
"=",
"self",
".",
"execution",
".",
"get",
"(",
"'srun_nodes'",
",",
"0",
")",
"if",
"isinstance",
"(",
"count",
",",
"six",
".",
"string_types",
")",
":",
"tag",
"=",
"count",
"count",
"=",
"0",
... | Get list of nodes where to execute the command | [
"Get",
"list",
"of",
"nodes",
"where",
"to",
"execute",
"the",
"command"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L263-L279 | train | 53,529 |
Capitains/Nautilus | capitains_nautilus/collections/sparql.py | clear_graph | def clear_graph(identifier=None):
""" Clean up a graph by removing it
:param identifier: Root identifier of the graph
:return:
"""
graph = get_graph()
if identifier:
graph.destroy(identifier)
try:
graph.close()
except:
warn("Unable to close the Graph") | python | def clear_graph(identifier=None):
""" Clean up a graph by removing it
:param identifier: Root identifier of the graph
:return:
"""
graph = get_graph()
if identifier:
graph.destroy(identifier)
try:
graph.close()
except:
warn("Unable to close the Graph") | [
"def",
"clear_graph",
"(",
"identifier",
"=",
"None",
")",
":",
"graph",
"=",
"get_graph",
"(",
")",
"if",
"identifier",
":",
"graph",
".",
"destroy",
"(",
"identifier",
")",
"try",
":",
"graph",
".",
"close",
"(",
")",
"except",
":",
"warn",
"(",
"\... | Clean up a graph by removing it
:param identifier: Root identifier of the graph
:return: | [
"Clean",
"up",
"a",
"graph",
"by",
"removing",
"it"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/collections/sparql.py#L13-L25 | train | 53,530 |
Capitains/Nautilus | capitains_nautilus/collections/sparql.py | SparqlNavigatedCollection.set_label | def set_label(self, label, lang):
""" Add the label of the collection in given lang
:param label: Label Value
:param lang: Language code
"""
try:
self.metadata.add(SKOS.prefLabel, Literal(label, lang=lang))
self.graph.addN([
(self.asNode(), RDFS.label, Literal(label, lang=lang), self.graph),
])
except Exception as E:
pass | python | def set_label(self, label, lang):
""" Add the label of the collection in given lang
:param label: Label Value
:param lang: Language code
"""
try:
self.metadata.add(SKOS.prefLabel, Literal(label, lang=lang))
self.graph.addN([
(self.asNode(), RDFS.label, Literal(label, lang=lang), self.graph),
])
except Exception as E:
pass | [
"def",
"set_label",
"(",
"self",
",",
"label",
",",
"lang",
")",
":",
"try",
":",
"self",
".",
"metadata",
".",
"add",
"(",
"SKOS",
".",
"prefLabel",
",",
"Literal",
"(",
"label",
",",
"lang",
"=",
"lang",
")",
")",
"self",
".",
"graph",
".",
"ad... | Add the label of the collection in given lang
:param label: Label Value
:param lang: Language code | [
"Add",
"the",
"label",
"of",
"the",
"collection",
"in",
"given",
"lang"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/collections/sparql.py#L92-L104 | train | 53,531 |
Capitains/Nautilus | capitains_nautilus/collections/sparql.py | SparqlNavigatedCollection.members | def members(self):
""" Children of the collection's item
:rtype: [Collection]
"""
return list(
[
self.children_class(child)
for child in self.graph.subjects(RDF_NAMESPACES.DTS.parent, self.asNode())
]
) | python | def members(self):
""" Children of the collection's item
:rtype: [Collection]
"""
return list(
[
self.children_class(child)
for child in self.graph.subjects(RDF_NAMESPACES.DTS.parent, self.asNode())
]
) | [
"def",
"members",
"(",
"self",
")",
":",
"return",
"list",
"(",
"[",
"self",
".",
"children_class",
"(",
"child",
")",
"for",
"child",
"in",
"self",
".",
"graph",
".",
"subjects",
"(",
"RDF_NAMESPACES",
".",
"DTS",
".",
"parent",
",",
"self",
".",
"a... | Children of the collection's item
:rtype: [Collection] | [
"Children",
"of",
"the",
"collection",
"s",
"item"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/collections/sparql.py#L130-L140 | train | 53,532 |
Capitains/Nautilus | capitains_nautilus/collections/sparql.py | SparqlNavigatedCollection.parent | def parent(self):
""" Parent of current object
:rtype: Collection
"""
parent = list(self.graph.objects(self.asNode(), RDF_NAMESPACES.DTS.parent))
if parent:
return self.parent_class(parent[0])
return None | python | def parent(self):
""" Parent of current object
:rtype: Collection
"""
parent = list(self.graph.objects(self.asNode(), RDF_NAMESPACES.DTS.parent))
if parent:
return self.parent_class(parent[0])
return None | [
"def",
"parent",
"(",
"self",
")",
":",
"parent",
"=",
"list",
"(",
"self",
".",
"graph",
".",
"objects",
"(",
"self",
".",
"asNode",
"(",
")",
",",
"RDF_NAMESPACES",
".",
"DTS",
".",
"parent",
")",
")",
"if",
"parent",
":",
"return",
"self",
".",
... | Parent of current object
:rtype: Collection | [
"Parent",
"of",
"current",
"object"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/collections/sparql.py#L186-L194 | train | 53,533 |
PolyJIT/benchbuild | benchbuild/experiments/raw.py | RawRuntime.actions_for_project | def actions_for_project(self, project):
"""Compile & Run the experiment with -O3 enabled."""
project.cflags = ["-O3", "-fno-omit-frame-pointer"]
project.runtime_extension = time.RunWithTime(
run.RuntimeExtension(project, self))
return self.default_runtime_actions(project) | python | def actions_for_project(self, project):
"""Compile & Run the experiment with -O3 enabled."""
project.cflags = ["-O3", "-fno-omit-frame-pointer"]
project.runtime_extension = time.RunWithTime(
run.RuntimeExtension(project, self))
return self.default_runtime_actions(project) | [
"def",
"actions_for_project",
"(",
"self",
",",
"project",
")",
":",
"project",
".",
"cflags",
"=",
"[",
"\"-O3\"",
",",
"\"-fno-omit-frame-pointer\"",
"]",
"project",
".",
"runtime_extension",
"=",
"time",
".",
"RunWithTime",
"(",
"run",
".",
"RuntimeExtension"... | Compile & Run the experiment with -O3 enabled. | [
"Compile",
"&",
"Run",
"the",
"experiment",
"with",
"-",
"O3",
"enabled",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/experiments/raw.py#L27-L32 | train | 53,534 |
PolyJIT/benchbuild | benchbuild/utils/actions.py | to_step_result | def to_step_result(func):
"""Convert a function return to a list of StepResults.
All Step subclasses automatically wrap the result of their
__call__ method's result with this wrapper.
If the result is not a list of StepResult values, one will
be generated.
result of `[StepResult.OK]`, or convert the given result into
a list.
Args:
func: The function to wrap.
"""
@ft.wraps(func)
def wrapper(*args, **kwargs):
"""Wrapper stub."""
res = func(*args, **kwargs)
if not res:
res = [StepResult.OK]
if not hasattr(res, "__iter__"):
res = [res]
return res
return wrapper | python | def to_step_result(func):
"""Convert a function return to a list of StepResults.
All Step subclasses automatically wrap the result of their
__call__ method's result with this wrapper.
If the result is not a list of StepResult values, one will
be generated.
result of `[StepResult.OK]`, or convert the given result into
a list.
Args:
func: The function to wrap.
"""
@ft.wraps(func)
def wrapper(*args, **kwargs):
"""Wrapper stub."""
res = func(*args, **kwargs)
if not res:
res = [StepResult.OK]
if not hasattr(res, "__iter__"):
res = [res]
return res
return wrapper | [
"def",
"to_step_result",
"(",
"func",
")",
":",
"@",
"ft",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrapper stub.\"\"\"",
"res",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwa... | Convert a function return to a list of StepResults.
All Step subclasses automatically wrap the result of their
__call__ method's result with this wrapper.
If the result is not a list of StepResult values, one will
be generated.
result of `[StepResult.OK]`, or convert the given result into
a list.
Args:
func: The function to wrap. | [
"Convert",
"a",
"function",
"return",
"to",
"a",
"list",
"of",
"StepResults",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/actions.py#L64-L90 | train | 53,535 |
PolyJIT/benchbuild | benchbuild/utils/actions.py | prepend_status | def prepend_status(func):
"""Prepends the output of `func` with the status."""
@ft.wraps(func)
def wrapper(self, *args, **kwargs):
"""Wrapper stub."""
res = func(self, *args, **kwargs)
if self.status is not StepResult.UNSET:
res = "[{status}]".format(status=self.status.name) + res
return res
return wrapper | python | def prepend_status(func):
"""Prepends the output of `func` with the status."""
@ft.wraps(func)
def wrapper(self, *args, **kwargs):
"""Wrapper stub."""
res = func(self, *args, **kwargs)
if self.status is not StepResult.UNSET:
res = "[{status}]".format(status=self.status.name) + res
return res
return wrapper | [
"def",
"prepend_status",
"(",
"func",
")",
":",
"@",
"ft",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrapper stub.\"\"\"",
"res",
"=",
"func",
"(",
"self",
",",
"*",
"... | Prepends the output of `func` with the status. | [
"Prepends",
"the",
"output",
"of",
"func",
"with",
"the",
"status",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/actions.py#L93-L104 | train | 53,536 |
PolyJIT/benchbuild | benchbuild/utils/actions.py | notify_step_begin_end | def notify_step_begin_end(func):
"""Print the beginning and the end of a `func`."""
@ft.wraps(func)
def wrapper(self, *args, **kwargs):
"""Wrapper stub."""
cls = self.__class__
on_step_begin = cls.ON_STEP_BEGIN
on_step_end = cls.ON_STEP_END
for begin_listener in on_step_begin:
begin_listener(self)
res = func(self, *args, **kwargs)
for end_listener in on_step_end:
end_listener(self, func)
return res
return wrapper | python | def notify_step_begin_end(func):
"""Print the beginning and the end of a `func`."""
@ft.wraps(func)
def wrapper(self, *args, **kwargs):
"""Wrapper stub."""
cls = self.__class__
on_step_begin = cls.ON_STEP_BEGIN
on_step_end = cls.ON_STEP_END
for begin_listener in on_step_begin:
begin_listener(self)
res = func(self, *args, **kwargs)
for end_listener in on_step_end:
end_listener(self, func)
return res
return wrapper | [
"def",
"notify_step_begin_end",
"(",
"func",
")",
":",
"@",
"ft",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrapper stub.\"\"\"",
"cls",
"=",
"self",
".",
"__class__",
"on... | Print the beginning and the end of a `func`. | [
"Print",
"the",
"beginning",
"and",
"the",
"end",
"of",
"a",
"func",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/actions.py#L107-L126 | train | 53,537 |
PolyJIT/benchbuild | benchbuild/utils/actions.py | log_before_after | def log_before_after(name: str, desc: str):
"""Log customized stirng before & after running func."""
def func_decorator(f):
"""Wrapper stub."""
@ft.wraps(f)
def wrapper(*args, **kwargs):
"""Wrapper stub."""
LOG.info("\n%s - %s", name, desc)
res = f(*args, **kwargs)
if StepResult.ERROR not in res:
LOG.info("%s - OK\n", name)
else:
LOG.error("%s - ERROR\n", name)
return res
return wrapper
return func_decorator | python | def log_before_after(name: str, desc: str):
"""Log customized stirng before & after running func."""
def func_decorator(f):
"""Wrapper stub."""
@ft.wraps(f)
def wrapper(*args, **kwargs):
"""Wrapper stub."""
LOG.info("\n%s - %s", name, desc)
res = f(*args, **kwargs)
if StepResult.ERROR not in res:
LOG.info("%s - OK\n", name)
else:
LOG.error("%s - ERROR\n", name)
return res
return wrapper
return func_decorator | [
"def",
"log_before_after",
"(",
"name",
":",
"str",
",",
"desc",
":",
"str",
")",
":",
"def",
"func_decorator",
"(",
"f",
")",
":",
"\"\"\"Wrapper stub.\"\"\"",
"@",
"ft",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*"... | Log customized stirng before & after running func. | [
"Log",
"customized",
"stirng",
"before",
"&",
"after",
"running",
"func",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/actions.py#L129-L148 | train | 53,538 |
lazygunner/xunleipy | xunleipy/rsa_lib.py | euclid | def euclid(a, b):
"""returns the Greatest Common Divisor of a and b"""
a = abs(a)
b = abs(b)
if a < b:
a, b = b, a
while b != 0:
a, b = b, a % b
return a | python | def euclid(a, b):
"""returns the Greatest Common Divisor of a and b"""
a = abs(a)
b = abs(b)
if a < b:
a, b = b, a
while b != 0:
a, b = b, a % b
return a | [
"def",
"euclid",
"(",
"a",
",",
"b",
")",
":",
"a",
"=",
"abs",
"(",
"a",
")",
"b",
"=",
"abs",
"(",
"b",
")",
"if",
"a",
"<",
"b",
":",
"a",
",",
"b",
"=",
"b",
",",
"a",
"while",
"b",
"!=",
"0",
":",
"a",
",",
"b",
"=",
"b",
",",
... | returns the Greatest Common Divisor of a and b | [
"returns",
"the",
"Greatest",
"Common",
"Divisor",
"of",
"a",
"and",
"b"
] | cded7598a7bf04495156bae2d747883d1eacb3f4 | https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L13-L21 | train | 53,539 |
lazygunner/xunleipy | xunleipy/rsa_lib.py | coPrime | def coPrime(l):
"""returns 'True' if the values in the list L are all co-prime
otherwise, it returns 'False'. """
for i, j in combinations(l, 2):
if euclid(i, j) != 1:
return False
return True | python | def coPrime(l):
"""returns 'True' if the values in the list L are all co-prime
otherwise, it returns 'False'. """
for i, j in combinations(l, 2):
if euclid(i, j) != 1:
return False
return True | [
"def",
"coPrime",
"(",
"l",
")",
":",
"for",
"i",
",",
"j",
"in",
"combinations",
"(",
"l",
",",
"2",
")",
":",
"if",
"euclid",
"(",
"i",
",",
"j",
")",
"!=",
"1",
":",
"return",
"False",
"return",
"True"
] | returns 'True' if the values in the list L are all co-prime
otherwise, it returns 'False'. | [
"returns",
"True",
"if",
"the",
"values",
"in",
"the",
"list",
"L",
"are",
"all",
"co",
"-",
"prime",
"otherwise",
"it",
"returns",
"False",
"."
] | cded7598a7bf04495156bae2d747883d1eacb3f4 | https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L24-L30 | train | 53,540 |
lazygunner/xunleipy | xunleipy/rsa_lib.py | modInv | def modInv(a, m):
"""returns the multiplicative inverse of a in modulo m as a
positive value between zero and m-1"""
# notice that a and m need to co-prime to each other.
if coPrime([a, m]):
linearCombination = extendedEuclid(a, m)
return linearCombination[1] % m
else:
return 0 | python | def modInv(a, m):
"""returns the multiplicative inverse of a in modulo m as a
positive value between zero and m-1"""
# notice that a and m need to co-prime to each other.
if coPrime([a, m]):
linearCombination = extendedEuclid(a, m)
return linearCombination[1] % m
else:
return 0 | [
"def",
"modInv",
"(",
"a",
",",
"m",
")",
":",
"# notice that a and m need to co-prime to each other.",
"if",
"coPrime",
"(",
"[",
"a",
",",
"m",
"]",
")",
":",
"linearCombination",
"=",
"extendedEuclid",
"(",
"a",
",",
"m",
")",
"return",
"linearCombination",... | returns the multiplicative inverse of a in modulo m as a
positive value between zero and m-1 | [
"returns",
"the",
"multiplicative",
"inverse",
"of",
"a",
"in",
"modulo",
"m",
"as",
"a",
"positive",
"value",
"between",
"zero",
"and",
"m",
"-",
"1"
] | cded7598a7bf04495156bae2d747883d1eacb3f4 | https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L43-L51 | train | 53,541 |
lazygunner/xunleipy | xunleipy/rsa_lib.py | int2baseTwo | def int2baseTwo(x):
"""x is a positive integer. Convert it to base two as a list of integers
in reverse order as a list."""
# repeating x >>= 1 and x & 1 will do the trick
assert x >= 0
bitInverse = []
while x != 0:
bitInverse.append(x & 1)
x >>= 1
return bitInverse | python | def int2baseTwo(x):
"""x is a positive integer. Convert it to base two as a list of integers
in reverse order as a list."""
# repeating x >>= 1 and x & 1 will do the trick
assert x >= 0
bitInverse = []
while x != 0:
bitInverse.append(x & 1)
x >>= 1
return bitInverse | [
"def",
"int2baseTwo",
"(",
"x",
")",
":",
"# repeating x >>= 1 and x & 1 will do the trick",
"assert",
"x",
">=",
"0",
"bitInverse",
"=",
"[",
"]",
"while",
"x",
"!=",
"0",
":",
"bitInverse",
".",
"append",
"(",
"x",
"&",
"1",
")",
"x",
">>=",
"1",
"retu... | x is a positive integer. Convert it to base two as a list of integers
in reverse order as a list. | [
"x",
"is",
"a",
"positive",
"integer",
".",
"Convert",
"it",
"to",
"base",
"two",
"as",
"a",
"list",
"of",
"integers",
"in",
"reverse",
"order",
"as",
"a",
"list",
"."
] | cded7598a7bf04495156bae2d747883d1eacb3f4 | https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L67-L76 | train | 53,542 |
lazygunner/xunleipy | xunleipy/rsa_lib.py | newKey | def newKey(a, b, k):
""" Try to find two large pseudo primes roughly between a and b.
Generate public and private keys for RSA encryption.
Raises ValueError if it fails to find one"""
try:
p = findAPrime(a, b, k)
while True:
q = findAPrime(a, b, k)
if q != p:
break
except:
raise ValueError
n = p * q
m = (p - 1) * (q - 1)
while True:
e = random.randint(1, m)
if coPrime([e, m]):
break
d = modInv(e, m)
return (n, e, d) | python | def newKey(a, b, k):
""" Try to find two large pseudo primes roughly between a and b.
Generate public and private keys for RSA encryption.
Raises ValueError if it fails to find one"""
try:
p = findAPrime(a, b, k)
while True:
q = findAPrime(a, b, k)
if q != p:
break
except:
raise ValueError
n = p * q
m = (p - 1) * (q - 1)
while True:
e = random.randint(1, m)
if coPrime([e, m]):
break
d = modInv(e, m)
return (n, e, d) | [
"def",
"newKey",
"(",
"a",
",",
"b",
",",
"k",
")",
":",
"try",
":",
"p",
"=",
"findAPrime",
"(",
"a",
",",
"b",
",",
"k",
")",
"while",
"True",
":",
"q",
"=",
"findAPrime",
"(",
"a",
",",
"b",
",",
"k",
")",
"if",
"q",
"!=",
"p",
":",
... | Try to find two large pseudo primes roughly between a and b.
Generate public and private keys for RSA encryption.
Raises ValueError if it fails to find one | [
"Try",
"to",
"find",
"two",
"large",
"pseudo",
"primes",
"roughly",
"between",
"a",
"and",
"b",
".",
"Generate",
"public",
"and",
"private",
"keys",
"for",
"RSA",
"encryption",
".",
"Raises",
"ValueError",
"if",
"it",
"fails",
"to",
"find",
"one"
] | cded7598a7bf04495156bae2d747883d1eacb3f4 | https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L180-L202 | train | 53,543 |
lazygunner/xunleipy | xunleipy/rsa_lib.py | blocks2numList | def blocks2numList(blocks, n):
"""inverse function of numList2blocks."""
toProcess = copy.copy(blocks)
returnList = []
for numBlock in toProcess:
inner = []
for i in range(0, n):
inner.append(numBlock % 256)
numBlock >>= 8
inner.reverse()
returnList.extend(inner)
return returnList | python | def blocks2numList(blocks, n):
"""inverse function of numList2blocks."""
toProcess = copy.copy(blocks)
returnList = []
for numBlock in toProcess:
inner = []
for i in range(0, n):
inner.append(numBlock % 256)
numBlock >>= 8
inner.reverse()
returnList.extend(inner)
return returnList | [
"def",
"blocks2numList",
"(",
"blocks",
",",
"n",
")",
":",
"toProcess",
"=",
"copy",
".",
"copy",
"(",
"blocks",
")",
"returnList",
"=",
"[",
"]",
"for",
"numBlock",
"in",
"toProcess",
":",
"inner",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"... | inverse function of numList2blocks. | [
"inverse",
"function",
"of",
"numList2blocks",
"."
] | cded7598a7bf04495156bae2d747883d1eacb3f4 | https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L239-L250 | train | 53,544 |
lazygunner/xunleipy | xunleipy/rsa_lib.py | encrypt | def encrypt(message, modN, e, blockSize):
"""given a string message, public keys and blockSize, encrypt using
RSA algorithms."""
numList = string2numList(message)
numBlocks = numList2blocks(numList, blockSize) # only one block
message = numBlocks[0]
# return [modExp(blocks, e, modN) for blocks in numBlocks]
return modExp(message, e, modN) | python | def encrypt(message, modN, e, blockSize):
"""given a string message, public keys and blockSize, encrypt using
RSA algorithms."""
numList = string2numList(message)
numBlocks = numList2blocks(numList, blockSize) # only one block
message = numBlocks[0]
# return [modExp(blocks, e, modN) for blocks in numBlocks]
return modExp(message, e, modN) | [
"def",
"encrypt",
"(",
"message",
",",
"modN",
",",
"e",
",",
"blockSize",
")",
":",
"numList",
"=",
"string2numList",
"(",
"message",
")",
"numBlocks",
"=",
"numList2blocks",
"(",
"numList",
",",
"blockSize",
")",
"# only one block",
"message",
"=",
"numBlo... | given a string message, public keys and blockSize, encrypt using
RSA algorithms. | [
"given",
"a",
"string",
"message",
"public",
"keys",
"and",
"blockSize",
"encrypt",
"using",
"RSA",
"algorithms",
"."
] | cded7598a7bf04495156bae2d747883d1eacb3f4 | https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L253-L260 | train | 53,545 |
lazygunner/xunleipy | xunleipy/rsa_lib.py | decrypt | def decrypt(secret, modN, d, blockSize):
"""reverse function of encrypt"""
numBlocks = [modExp(blocks, d, modN) for blocks in secret]
numList = blocks2numList(numBlocks, blockSize)
return numList2string(numList) | python | def decrypt(secret, modN, d, blockSize):
"""reverse function of encrypt"""
numBlocks = [modExp(blocks, d, modN) for blocks in secret]
numList = blocks2numList(numBlocks, blockSize)
return numList2string(numList) | [
"def",
"decrypt",
"(",
"secret",
",",
"modN",
",",
"d",
",",
"blockSize",
")",
":",
"numBlocks",
"=",
"[",
"modExp",
"(",
"blocks",
",",
"d",
",",
"modN",
")",
"for",
"blocks",
"in",
"secret",
"]",
"numList",
"=",
"blocks2numList",
"(",
"numBlocks",
... | reverse function of encrypt | [
"reverse",
"function",
"of",
"encrypt"
] | cded7598a7bf04495156bae2d747883d1eacb3f4 | https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L263-L267 | train | 53,546 |
portfoliome/foil | foil/paths.py | match_files | def match_files(files, pattern: Pattern):
"""Yields file name if matches a regular expression pattern."""
for name in files:
if re.match(pattern, name):
yield name | python | def match_files(files, pattern: Pattern):
"""Yields file name if matches a regular expression pattern."""
for name in files:
if re.match(pattern, name):
yield name | [
"def",
"match_files",
"(",
"files",
",",
"pattern",
":",
"Pattern",
")",
":",
"for",
"name",
"in",
"files",
":",
"if",
"re",
".",
"match",
"(",
"pattern",
",",
"name",
")",
":",
"yield",
"name"
] | Yields file name if matches a regular expression pattern. | [
"Yields",
"file",
"name",
"if",
"matches",
"a",
"regular",
"expression",
"pattern",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/paths.py#L45-L50 | train | 53,547 |
portfoliome/foil | foil/paths.py | match_zipfile_members | def match_zipfile_members(zipfile_path: str, pattern: Pattern):
"""Match files to a pattern within a zip file's content."""
with ZipFile(zipfile_path, mode='r') as zfile:
members = zfile.namelist()
yield from match_files(members, pattern) | python | def match_zipfile_members(zipfile_path: str, pattern: Pattern):
"""Match files to a pattern within a zip file's content."""
with ZipFile(zipfile_path, mode='r') as zfile:
members = zfile.namelist()
yield from match_files(members, pattern) | [
"def",
"match_zipfile_members",
"(",
"zipfile_path",
":",
"str",
",",
"pattern",
":",
"Pattern",
")",
":",
"with",
"ZipFile",
"(",
"zipfile_path",
",",
"mode",
"=",
"'r'",
")",
"as",
"zfile",
":",
"members",
"=",
"zfile",
".",
"namelist",
"(",
")",
"yiel... | Match files to a pattern within a zip file's content. | [
"Match",
"files",
"to",
"a",
"pattern",
"within",
"a",
"zip",
"file",
"s",
"content",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/paths.py#L53-L59 | train | 53,548 |
portfoliome/foil | foil/paths.py | directory_files | def directory_files(path):
"""Yield directory file names."""
for entry in os.scandir(path):
if not entry.name.startswith('.') and entry.is_file():
yield entry.name | python | def directory_files(path):
"""Yield directory file names."""
for entry in os.scandir(path):
if not entry.name.startswith('.') and entry.is_file():
yield entry.name | [
"def",
"directory_files",
"(",
"path",
")",
":",
"for",
"entry",
"in",
"os",
".",
"scandir",
"(",
"path",
")",
":",
"if",
"not",
"entry",
".",
"name",
".",
"startswith",
"(",
"'.'",
")",
"and",
"entry",
".",
"is_file",
"(",
")",
":",
"yield",
"entr... | Yield directory file names. | [
"Yield",
"directory",
"file",
"names",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/paths.py#L68-L73 | train | 53,549 |
portfoliome/foil | foil/paths.py | get_file_listing_sha | def get_file_listing_sha(listing_paths: Iterable) -> str:
"""Return sha256 string for group of FTP listings."""
return sha256(''.join(sorted(listing_paths)).encode('utf-8')).hexdigest() | python | def get_file_listing_sha(listing_paths: Iterable) -> str:
"""Return sha256 string for group of FTP listings."""
return sha256(''.join(sorted(listing_paths)).encode('utf-8')).hexdigest() | [
"def",
"get_file_listing_sha",
"(",
"listing_paths",
":",
"Iterable",
")",
"->",
"str",
":",
"return",
"sha256",
"(",
"''",
".",
"join",
"(",
"sorted",
"(",
"listing_paths",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"(",
")"
] | Return sha256 string for group of FTP listings. | [
"Return",
"sha256",
"string",
"for",
"group",
"of",
"FTP",
"listings",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/paths.py#L76-L79 | train | 53,550 |
OzymandiasTheGreat/python-libinput | libinput/device.py | DeviceConfigTap.set_button_map | def set_button_map(self, button_map):
"""Set the finger number to button number mapping for tap-to-click.
The default mapping on most devices is to have a 1, 2 and 3 finger tap
to map to the left, right and middle button, respectively. A device may
permit changing the button mapping but disallow specific maps. In this
case :attr:`~libinput.constant.ConfigStatus.UNSUPPORTED` is returned,
the caller is expected to handle this case correctly.
Changing the button mapping may not take effect immediately, the device
may wait until it is in a neutral state before applying any changes.
The mapping may be changed when tap-to-click is disabled. The new
mapping takes effect when tap-to-click is enabled in the future.
If :attr:`finger_count` is 0, this method raises :exc:`AssertionError`.
Args:
button_map (~libinput.constant.TapButtonMap): The new
finger-to-button number mapping.
Returns:
~libinput.constant.ConfigStatus: A config status code.
Raises:
AssertionError
"""
assert self.finger_count > 0, 'This device does not support tapping'
return self._libinput.libinput_device_config_tap_set_button_map(
self._handle, button_map) | python | def set_button_map(self, button_map):
"""Set the finger number to button number mapping for tap-to-click.
The default mapping on most devices is to have a 1, 2 and 3 finger tap
to map to the left, right and middle button, respectively. A device may
permit changing the button mapping but disallow specific maps. In this
case :attr:`~libinput.constant.ConfigStatus.UNSUPPORTED` is returned,
the caller is expected to handle this case correctly.
Changing the button mapping may not take effect immediately, the device
may wait until it is in a neutral state before applying any changes.
The mapping may be changed when tap-to-click is disabled. The new
mapping takes effect when tap-to-click is enabled in the future.
If :attr:`finger_count` is 0, this method raises :exc:`AssertionError`.
Args:
button_map (~libinput.constant.TapButtonMap): The new
finger-to-button number mapping.
Returns:
~libinput.constant.ConfigStatus: A config status code.
Raises:
AssertionError
"""
assert self.finger_count > 0, 'This device does not support tapping'
return self._libinput.libinput_device_config_tap_set_button_map(
self._handle, button_map) | [
"def",
"set_button_map",
"(",
"self",
",",
"button_map",
")",
":",
"assert",
"self",
".",
"finger_count",
">",
"0",
",",
"'This device does not support tapping'",
"return",
"self",
".",
"_libinput",
".",
"libinput_device_config_tap_set_button_map",
"(",
"self",
".",
... | Set the finger number to button number mapping for tap-to-click.
The default mapping on most devices is to have a 1, 2 and 3 finger tap
to map to the left, right and middle button, respectively. A device may
permit changing the button mapping but disallow specific maps. In this
case :attr:`~libinput.constant.ConfigStatus.UNSUPPORTED` is returned,
the caller is expected to handle this case correctly.
Changing the button mapping may not take effect immediately, the device
may wait until it is in a neutral state before applying any changes.
The mapping may be changed when tap-to-click is disabled. The new
mapping takes effect when tap-to-click is enabled in the future.
If :attr:`finger_count` is 0, this method raises :exc:`AssertionError`.
Args:
button_map (~libinput.constant.TapButtonMap): The new
finger-to-button number mapping.
Returns:
~libinput.constant.ConfigStatus: A config status code.
Raises:
AssertionError | [
"Set",
"the",
"finger",
"number",
"to",
"button",
"number",
"mapping",
"for",
"tap",
"-",
"to",
"-",
"click",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L279-L307 | train | 53,551 |
OzymandiasTheGreat/python-libinput | libinput/device.py | DeviceConfigCalibration.set_matrix | def set_matrix(self, matrix):
"""Apply the 3x3 transformation matrix to absolute device coordinates.
This matrix has no effect on relative events.
Given a 6-element array [a, b, c, d, e, f], the matrix is applied as
::
[ a b c ] [ x ]
[ d e f ] * [ y ]
[ 0 0 1 ] [ 1 ]
The translation component (c, f) is expected to be normalized to
the device coordinate range. For example, the matrix
::
[ 1 0 1 ]
[ 0 1 -1 ]
[ 0 0 1 ]
moves all coordinates by 1 device-width to the right and
1 device-height up.
The rotation matrix for rotation around the origin is defined as
::
[ cos(a) -sin(a) 0 ]
[ sin(a) cos(a) 0 ]
[ 0 0 1 ]
Note that any rotation requires an additional translation component
to translate the rotated coordinates back into the original device
space. The rotation matrixes for 90, 180 and 270 degrees clockwise are::
90 deg cw: 180 deg cw: 270 deg cw:
[ 0 -1 1] [ -1 0 1] [ 0 1 0 ]
[ 1 0 0] [ 0 -1 1] [ -1 0 1 ]
[ 0 0 1] [ 0 0 1] [ 0 0 1 ]
Args:
matrix (iterable): An array representing the first two rows of
a 3x3 matrix as described above.
Returns:
~libinput.constant.ConfigStatus: A config status code.
"""
matrix = (c_float * 6)(*matrix)
return self._libinput.libinput_device_config_calibration_set_matrix(
self._handle, matrix) | python | def set_matrix(self, matrix):
"""Apply the 3x3 transformation matrix to absolute device coordinates.
This matrix has no effect on relative events.
Given a 6-element array [a, b, c, d, e, f], the matrix is applied as
::
[ a b c ] [ x ]
[ d e f ] * [ y ]
[ 0 0 1 ] [ 1 ]
The translation component (c, f) is expected to be normalized to
the device coordinate range. For example, the matrix
::
[ 1 0 1 ]
[ 0 1 -1 ]
[ 0 0 1 ]
moves all coordinates by 1 device-width to the right and
1 device-height up.
The rotation matrix for rotation around the origin is defined as
::
[ cos(a) -sin(a) 0 ]
[ sin(a) cos(a) 0 ]
[ 0 0 1 ]
Note that any rotation requires an additional translation component
to translate the rotated coordinates back into the original device
space. The rotation matrixes for 90, 180 and 270 degrees clockwise are::
90 deg cw: 180 deg cw: 270 deg cw:
[ 0 -1 1] [ -1 0 1] [ 0 1 0 ]
[ 1 0 0] [ 0 -1 1] [ -1 0 1 ]
[ 0 0 1] [ 0 0 1] [ 0 0 1 ]
Args:
matrix (iterable): An array representing the first two rows of
a 3x3 matrix as described above.
Returns:
~libinput.constant.ConfigStatus: A config status code.
"""
matrix = (c_float * 6)(*matrix)
return self._libinput.libinput_device_config_calibration_set_matrix(
self._handle, matrix) | [
"def",
"set_matrix",
"(",
"self",
",",
"matrix",
")",
":",
"matrix",
"=",
"(",
"c_float",
"*",
"6",
")",
"(",
"*",
"matrix",
")",
"return",
"self",
".",
"_libinput",
".",
"libinput_device_config_calibration_set_matrix",
"(",
"self",
".",
"_handle",
",",
"m... | Apply the 3x3 transformation matrix to absolute device coordinates.
This matrix has no effect on relative events.
Given a 6-element array [a, b, c, d, e, f], the matrix is applied as
::
[ a b c ] [ x ]
[ d e f ] * [ y ]
[ 0 0 1 ] [ 1 ]
The translation component (c, f) is expected to be normalized to
the device coordinate range. For example, the matrix
::
[ 1 0 1 ]
[ 0 1 -1 ]
[ 0 0 1 ]
moves all coordinates by 1 device-width to the right and
1 device-height up.
The rotation matrix for rotation around the origin is defined as
::
[ cos(a) -sin(a) 0 ]
[ sin(a) cos(a) 0 ]
[ 0 0 1 ]
Note that any rotation requires an additional translation component
to translate the rotated coordinates back into the original device
space. The rotation matrixes for 90, 180 and 270 degrees clockwise are::
90 deg cw: 180 deg cw: 270 deg cw:
[ 0 -1 1] [ -1 0 1] [ 0 1 0 ]
[ 1 0 0] [ 0 -1 1] [ -1 0 1 ]
[ 0 0 1] [ 0 0 1] [ 0 0 1 ]
Args:
matrix (iterable): An array representing the first two rows of
a 3x3 matrix as described above.
Returns:
~libinput.constant.ConfigStatus: A config status code. | [
"Apply",
"the",
"3x3",
"transformation",
"matrix",
"to",
"absolute",
"device",
"coordinates",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L489-L537 | train | 53,552 |
OzymandiasTheGreat/python-libinput | libinput/device.py | DeviceConfigCalibration.matrix | def matrix(self):
"""The current calibration matrix for this device.
Returns:
(bool, (float, float, float, float, float, float)): :obj:`False` if
no calibration is set and
the returned matrix is the identity matrix, :obj:`True`
otherwise. :obj:`tuple` representing the first two rows of
a 3x3 matrix as described in :meth:`set_matrix`.
"""
matrix = (c_float * 6)()
rc = self._libinput.libinput_device_config_calibration_get_matrix(
self._handle, matrix)
return rc, tuple(matrix) | python | def matrix(self):
"""The current calibration matrix for this device.
Returns:
(bool, (float, float, float, float, float, float)): :obj:`False` if
no calibration is set and
the returned matrix is the identity matrix, :obj:`True`
otherwise. :obj:`tuple` representing the first two rows of
a 3x3 matrix as described in :meth:`set_matrix`.
"""
matrix = (c_float * 6)()
rc = self._libinput.libinput_device_config_calibration_get_matrix(
self._handle, matrix)
return rc, tuple(matrix) | [
"def",
"matrix",
"(",
"self",
")",
":",
"matrix",
"=",
"(",
"c_float",
"*",
"6",
")",
"(",
")",
"rc",
"=",
"self",
".",
"_libinput",
".",
"libinput_device_config_calibration_get_matrix",
"(",
"self",
".",
"_handle",
",",
"matrix",
")",
"return",
"rc",
",... | The current calibration matrix for this device.
Returns:
(bool, (float, float, float, float, float, float)): :obj:`False` if
no calibration is set and
the returned matrix is the identity matrix, :obj:`True`
otherwise. :obj:`tuple` representing the first two rows of
a 3x3 matrix as described in :meth:`set_matrix`. | [
"The",
"current",
"calibration",
"matrix",
"for",
"this",
"device",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L540-L554 | train | 53,553 |
OzymandiasTheGreat/python-libinput | libinput/device.py | DeviceConfigCalibration.default_matrix | def default_matrix(self):
"""The default calibration matrix for this device.
On most devices, this is the identity matrix. If the udev property
``LIBINPUT_CALIBRATION_MATRIX`` is set on the respective udev device,
that property's value becomes the default matrix, see
`Static device configuration via udev`_.
Returns:
(bool, (float, float, float, float, float, float)): :obj:`False` if
no calibration is set and
the returned matrix is the identity matrix, :obj:`True`
otherwise. :obj:`tuple` representing the first two rows of
a 3x3 matrix as described
in :meth:`config_calibration_set_matrix`.
"""
matrix = (c_float * 6)()
rc = self._libinput \
.libinput_device_config_calibration_get_default_matrix(
self._handle, matrix)
return rc, tuple(matrix) | python | def default_matrix(self):
"""The default calibration matrix for this device.
On most devices, this is the identity matrix. If the udev property
``LIBINPUT_CALIBRATION_MATRIX`` is set on the respective udev device,
that property's value becomes the default matrix, see
`Static device configuration via udev`_.
Returns:
(bool, (float, float, float, float, float, float)): :obj:`False` if
no calibration is set and
the returned matrix is the identity matrix, :obj:`True`
otherwise. :obj:`tuple` representing the first two rows of
a 3x3 matrix as described
in :meth:`config_calibration_set_matrix`.
"""
matrix = (c_float * 6)()
rc = self._libinput \
.libinput_device_config_calibration_get_default_matrix(
self._handle, matrix)
return rc, tuple(matrix) | [
"def",
"default_matrix",
"(",
"self",
")",
":",
"matrix",
"=",
"(",
"c_float",
"*",
"6",
")",
"(",
")",
"rc",
"=",
"self",
".",
"_libinput",
".",
"libinput_device_config_calibration_get_default_matrix",
"(",
"self",
".",
"_handle",
",",
"matrix",
")",
"retur... | The default calibration matrix for this device.
On most devices, this is the identity matrix. If the udev property
``LIBINPUT_CALIBRATION_MATRIX`` is set on the respective udev device,
that property's value becomes the default matrix, see
`Static device configuration via udev`_.
Returns:
(bool, (float, float, float, float, float, float)): :obj:`False` if
no calibration is set and
the returned matrix is the identity matrix, :obj:`True`
otherwise. :obj:`tuple` representing the first two rows of
a 3x3 matrix as described
in :meth:`config_calibration_set_matrix`. | [
"The",
"default",
"calibration",
"matrix",
"for",
"this",
"device",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L557-L578 | train | 53,554 |
OzymandiasTheGreat/python-libinput | libinput/device.py | Device.sysname | def sysname(self):
"""The system name of the device.
To get the descriptive device name, use :attr:`name`.
Returns:
str: System name of the device.
"""
pchar = self._libinput.libinput_device_get_sysname(self._handle)
return string_at(pchar).decode() | python | def sysname(self):
"""The system name of the device.
To get the descriptive device name, use :attr:`name`.
Returns:
str: System name of the device.
"""
pchar = self._libinput.libinput_device_get_sysname(self._handle)
return string_at(pchar).decode() | [
"def",
"sysname",
"(",
"self",
")",
":",
"pchar",
"=",
"self",
".",
"_libinput",
".",
"libinput_device_get_sysname",
"(",
"self",
".",
"_handle",
")",
"return",
"string_at",
"(",
"pchar",
")",
".",
"decode",
"(",
")"
] | The system name of the device.
To get the descriptive device name, use :attr:`name`.
Returns:
str: System name of the device. | [
"The",
"system",
"name",
"of",
"the",
"device",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L1674-L1684 | train | 53,555 |
OzymandiasTheGreat/python-libinput | libinput/device.py | Device.set_seat_logical_name | def set_seat_logical_name(self, seat):
"""Change the logical seat associated with this device by removing
the device and adding it to the new seat.
This command is identical to physically unplugging the device, then
re-plugging it as a member of the new seat. libinput will generate
a :attr:`~libinput.constant.EventType.DEVICE_REMOVED` event and this
:class:`Device` is considered removed from the context; it will not
generate further events.
A :attr:`~libinput.constant.EventType.DEVICE_ADDED` event is
generated with a new :class:`Device`. It is the caller's
responsibility to update references to the new device accordingly.
If the logical seat name already exists in the device's physical seat,
the device is added to this seat. Otherwise, a new seat is created.
Note:
This change applies to this device until removal or
:meth:`~libinput.LibInput.suspend`, whichever happens earlier.
Args:
seat (str): The new logical seat name.
Raises:
AssertionError
"""
rc = self._libinput.libinput_device_set_seat_logical_name(
self._handle, seat.encode())
assert rc == 0, 'Cannot assign device to {}'.format(seat) | python | def set_seat_logical_name(self, seat):
"""Change the logical seat associated with this device by removing
the device and adding it to the new seat.
This command is identical to physically unplugging the device, then
re-plugging it as a member of the new seat. libinput will generate
a :attr:`~libinput.constant.EventType.DEVICE_REMOVED` event and this
:class:`Device` is considered removed from the context; it will not
generate further events.
A :attr:`~libinput.constant.EventType.DEVICE_ADDED` event is
generated with a new :class:`Device`. It is the caller's
responsibility to update references to the new device accordingly.
If the logical seat name already exists in the device's physical seat,
the device is added to this seat. Otherwise, a new seat is created.
Note:
This change applies to this device until removal or
:meth:`~libinput.LibInput.suspend`, whichever happens earlier.
Args:
seat (str): The new logical seat name.
Raises:
AssertionError
"""
rc = self._libinput.libinput_device_set_seat_logical_name(
self._handle, seat.encode())
assert rc == 0, 'Cannot assign device to {}'.format(seat) | [
"def",
"set_seat_logical_name",
"(",
"self",
",",
"seat",
")",
":",
"rc",
"=",
"self",
".",
"_libinput",
".",
"libinput_device_set_seat_logical_name",
"(",
"self",
".",
"_handle",
",",
"seat",
".",
"encode",
"(",
")",
")",
"assert",
"rc",
"==",
"0",
",",
... | Change the logical seat associated with this device by removing
the device and adding it to the new seat.
This command is identical to physically unplugging the device, then
re-plugging it as a member of the new seat. libinput will generate
a :attr:`~libinput.constant.EventType.DEVICE_REMOVED` event and this
:class:`Device` is considered removed from the context; it will not
generate further events.
A :attr:`~libinput.constant.EventType.DEVICE_ADDED` event is
generated with a new :class:`Device`. It is the caller's
responsibility to update references to the new device accordingly.
If the logical seat name already exists in the device's physical seat,
the device is added to this seat. Otherwise, a new seat is created.
Note:
This change applies to this device until removal or
:meth:`~libinput.LibInput.suspend`, whichever happens earlier.
Args:
seat (str): The new logical seat name.
Raises:
AssertionError | [
"Change",
"the",
"logical",
"seat",
"associated",
"with",
"this",
"device",
"by",
"removing",
"the",
"device",
"and",
"adding",
"it",
"to",
"the",
"new",
"seat",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L1735-L1762 | train | 53,556 |
OzymandiasTheGreat/python-libinput | libinput/device.py | Device.capabilities | def capabilities(self):
"""A tuple of capabilities this device supports.
Returns:
(~libinput.constant.DeviceCapability): Device capabilities.
"""
caps = []
for cap in DeviceCapability:
if self._libinput.libinput_device_has_capability(self._handle, cap):
caps.append(cap)
return tuple(caps) | python | def capabilities(self):
"""A tuple of capabilities this device supports.
Returns:
(~libinput.constant.DeviceCapability): Device capabilities.
"""
caps = []
for cap in DeviceCapability:
if self._libinput.libinput_device_has_capability(self._handle, cap):
caps.append(cap)
return tuple(caps) | [
"def",
"capabilities",
"(",
"self",
")",
":",
"caps",
"=",
"[",
"]",
"for",
"cap",
"in",
"DeviceCapability",
":",
"if",
"self",
".",
"_libinput",
".",
"libinput_device_has_capability",
"(",
"self",
".",
"_handle",
",",
"cap",
")",
":",
"caps",
".",
"appe... | A tuple of capabilities this device supports.
Returns:
(~libinput.constant.DeviceCapability): Device capabilities. | [
"A",
"tuple",
"of",
"capabilities",
"this",
"device",
"supports",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L1800-L1811 | train | 53,557 |
OzymandiasTheGreat/python-libinput | libinput/device.py | Device.size | def size(self):
"""The physical size of a device in mm, where meaningful.
This property is only valid on devices with the required data, i.e.
tablets, touchpads and touchscreens. For other devices this property
raises :exc:`AssertionError`.
Returns:
(float, float): (Width, Height) in mm.
Raises:
AssertionError
"""
width = c_double(0)
height = c_double(0)
rc = self._libinput.libinput_device_get_size(
self._handle, byref(width), byref(height))
assert rc == 0, 'This device does not provide size information'
return width.value, height.value | python | def size(self):
"""The physical size of a device in mm, where meaningful.
This property is only valid on devices with the required data, i.e.
tablets, touchpads and touchscreens. For other devices this property
raises :exc:`AssertionError`.
Returns:
(float, float): (Width, Height) in mm.
Raises:
AssertionError
"""
width = c_double(0)
height = c_double(0)
rc = self._libinput.libinput_device_get_size(
self._handle, byref(width), byref(height))
assert rc == 0, 'This device does not provide size information'
return width.value, height.value | [
"def",
"size",
"(",
"self",
")",
":",
"width",
"=",
"c_double",
"(",
"0",
")",
"height",
"=",
"c_double",
"(",
"0",
")",
"rc",
"=",
"self",
".",
"_libinput",
".",
"libinput_device_get_size",
"(",
"self",
".",
"_handle",
",",
"byref",
"(",
"width",
")... | The physical size of a device in mm, where meaningful.
This property is only valid on devices with the required data, i.e.
tablets, touchpads and touchscreens. For other devices this property
raises :exc:`AssertionError`.
Returns:
(float, float): (Width, Height) in mm.
Raises:
AssertionError | [
"The",
"physical",
"size",
"of",
"a",
"device",
"in",
"mm",
"where",
"meaningful",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L1814-L1832 | train | 53,558 |
OzymandiasTheGreat/python-libinput | libinput/device.py | DevicePointer.has_button | def has_button(self, button):
"""Check if this device has a given button.
Args:
button (int): Button to check for, see ``input.h`` for button
definitions.
Returns:
bool: :obj:`True` if the device has this button, :obj:`False` if
it does not.
Raises:
AssertionError
"""
rc = self._libinput.libinput_device_pointer_has_button(
self._handle, button)
assert rc >= 0, 'This device is not a pointer device'
return bool(rc) | python | def has_button(self, button):
"""Check if this device has a given button.
Args:
button (int): Button to check for, see ``input.h`` for button
definitions.
Returns:
bool: :obj:`True` if the device has this button, :obj:`False` if
it does not.
Raises:
AssertionError
"""
rc = self._libinput.libinput_device_pointer_has_button(
self._handle, button)
assert rc >= 0, 'This device is not a pointer device'
return bool(rc) | [
"def",
"has_button",
"(",
"self",
",",
"button",
")",
":",
"rc",
"=",
"self",
".",
"_libinput",
".",
"libinput_device_pointer_has_button",
"(",
"self",
".",
"_handle",
",",
"button",
")",
"assert",
"rc",
">=",
"0",
",",
"'This device is not a pointer device'",
... | Check if this device has a given button.
Args:
button (int): Button to check for, see ``input.h`` for button
definitions.
Returns:
bool: :obj:`True` if the device has this button, :obj:`False` if
it does not.
Raises:
AssertionError | [
"Check",
"if",
"this",
"device",
"has",
"a",
"given",
"button",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L1892-L1908 | train | 53,559 |
OzymandiasTheGreat/python-libinput | libinput/device.py | DeviceTabletPad.num_mode_groups | def num_mode_groups(self):
"""Most devices only provide a single mode group, however devices
such as the Wacom Cintiq 22HD provide two mode groups.
If multiple mode groups are available, a caller should use
:meth:`~libinput.define.TabletPadModeGroup.has_button`,
:meth:`~libinput.define.TabletPadModeGroup.has_ring`
and :meth:`~libinput.define.TabletPadModeGroup.has_strip` to associate
each button, ring and strip with the correct mode group.
Returns:
int: The number of mode groups available on this device.
Raises:
AttributeError
"""
num = self._libinput.libinput_device_tablet_pad_get_num_mode_groups(
self._handle)
if num < 0:
raise AttributeError('This device is not a tablet pad device')
return num | python | def num_mode_groups(self):
"""Most devices only provide a single mode group, however devices
such as the Wacom Cintiq 22HD provide two mode groups.
If multiple mode groups are available, a caller should use
:meth:`~libinput.define.TabletPadModeGroup.has_button`,
:meth:`~libinput.define.TabletPadModeGroup.has_ring`
and :meth:`~libinput.define.TabletPadModeGroup.has_strip` to associate
each button, ring and strip with the correct mode group.
Returns:
int: The number of mode groups available on this device.
Raises:
AttributeError
"""
num = self._libinput.libinput_device_tablet_pad_get_num_mode_groups(
self._handle)
if num < 0:
raise AttributeError('This device is not a tablet pad device')
return num | [
"def",
"num_mode_groups",
"(",
"self",
")",
":",
"num",
"=",
"self",
".",
"_libinput",
".",
"libinput_device_tablet_pad_get_num_mode_groups",
"(",
"self",
".",
"_handle",
")",
"if",
"num",
"<",
"0",
":",
"raise",
"AttributeError",
"(",
"'This device is not a table... | Most devices only provide a single mode group, however devices
such as the Wacom Cintiq 22HD provide two mode groups.
If multiple mode groups are available, a caller should use
:meth:`~libinput.define.TabletPadModeGroup.has_button`,
:meth:`~libinput.define.TabletPadModeGroup.has_ring`
and :meth:`~libinput.define.TabletPadModeGroup.has_strip` to associate
each button, ring and strip with the correct mode group.
Returns:
int: The number of mode groups available on this device.
Raises:
AttributeError | [
"Most",
"devices",
"only",
"provide",
"a",
"single",
"mode",
"group",
"however",
"devices",
"such",
"as",
"the",
"Wacom",
"Cintiq",
"22HD",
"provide",
"two",
"mode",
"groups",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L2029-L2049 | train | 53,560 |
OzymandiasTheGreat/python-libinput | libinput/device.py | Seat.physical_name | def physical_name(self):
"""The physical name of the seat.
For libinput contexts created from udev, this is always the same value
as passed into :meth:`~libinput.LibInputUdev.assign_seat` and all
seats from that context will have the same physical name.
The physical name of the seat is one that is usually set by the system
or lower levels of the stack. In most cases, this is the base filter
for devices - devices assigned to seats outside the current seat will
not be available to the caller.
Returns:
str: The physical name of this seat.
"""
pchar = self._libinput.libinput_seat_get_physical_name(self._handle)
return string_at(pchar).decode() | python | def physical_name(self):
"""The physical name of the seat.
For libinput contexts created from udev, this is always the same value
as passed into :meth:`~libinput.LibInputUdev.assign_seat` and all
seats from that context will have the same physical name.
The physical name of the seat is one that is usually set by the system
or lower levels of the stack. In most cases, this is the base filter
for devices - devices assigned to seats outside the current seat will
not be available to the caller.
Returns:
str: The physical name of this seat.
"""
pchar = self._libinput.libinput_seat_get_physical_name(self._handle)
return string_at(pchar).decode() | [
"def",
"physical_name",
"(",
"self",
")",
":",
"pchar",
"=",
"self",
".",
"_libinput",
".",
"libinput_seat_get_physical_name",
"(",
"self",
".",
"_handle",
")",
"return",
"string_at",
"(",
"pchar",
")",
".",
"decode",
"(",
")"
] | The physical name of the seat.
For libinput contexts created from udev, this is always the same value
as passed into :meth:`~libinput.LibInputUdev.assign_seat` and all
seats from that context will have the same physical name.
The physical name of the seat is one that is usually set by the system
or lower levels of the stack. In most cases, this is the base filter
for devices - devices assigned to seats outside the current seat will
not be available to the caller.
Returns:
str: The physical name of this seat. | [
"The",
"physical",
"name",
"of",
"the",
"seat",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L2111-L2128 | train | 53,561 |
OzymandiasTheGreat/python-libinput | libinput/device.py | Seat.logical_name | def logical_name(self):
"""The logical name of the seat.
This is an identifier to group sets of devices within the compositor.
Returns:
str: The logical name of this seat.
"""
pchar = self._libinput.libinput_seat_get_logical_name(self._handle)
return string_at(pchar).decode() | python | def logical_name(self):
"""The logical name of the seat.
This is an identifier to group sets of devices within the compositor.
Returns:
str: The logical name of this seat.
"""
pchar = self._libinput.libinput_seat_get_logical_name(self._handle)
return string_at(pchar).decode() | [
"def",
"logical_name",
"(",
"self",
")",
":",
"pchar",
"=",
"self",
".",
"_libinput",
".",
"libinput_seat_get_logical_name",
"(",
"self",
".",
"_handle",
")",
"return",
"string_at",
"(",
"pchar",
")",
".",
"decode",
"(",
")"
] | The logical name of the seat.
This is an identifier to group sets of devices within the compositor.
Returns:
str: The logical name of this seat. | [
"The",
"logical",
"name",
"of",
"the",
"seat",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L2131-L2141 | train | 53,562 |
PolyJIT/benchbuild | benchbuild/utils/log.py | configure | def configure():
"""Load logging configuration from our own defaults."""
log_levels = {
5: logging.NOTSET,
4: logging.DEBUG,
3: logging.INFO,
2: logging.WARNING,
1: logging.ERROR,
0: logging.CRITICAL
}
logging.captureWarnings(True)
root_logger = logging.getLogger()
if settings.CFG["debug"]:
details_format = logging.Formatter(
'%(name)s (%(filename)s:%(lineno)s) [%(levelname)s] %(message)s')
details_hdl = logging.StreamHandler()
details_hdl.setFormatter(details_format)
root_logger.addHandler(details_hdl)
else:
brief_format = logging.Formatter('%(message)s')
console_hdl = logging.StreamHandler()
console_hdl.setFormatter(brief_format)
root_logger.addHandler(console_hdl)
root_logger.setLevel(log_levels[int(settings.CFG["verbosity"])])
configure_plumbum_log()
configure_migrate_log()
configure_parse_log() | python | def configure():
"""Load logging configuration from our own defaults."""
log_levels = {
5: logging.NOTSET,
4: logging.DEBUG,
3: logging.INFO,
2: logging.WARNING,
1: logging.ERROR,
0: logging.CRITICAL
}
logging.captureWarnings(True)
root_logger = logging.getLogger()
if settings.CFG["debug"]:
details_format = logging.Formatter(
'%(name)s (%(filename)s:%(lineno)s) [%(levelname)s] %(message)s')
details_hdl = logging.StreamHandler()
details_hdl.setFormatter(details_format)
root_logger.addHandler(details_hdl)
else:
brief_format = logging.Formatter('%(message)s')
console_hdl = logging.StreamHandler()
console_hdl.setFormatter(brief_format)
root_logger.addHandler(console_hdl)
root_logger.setLevel(log_levels[int(settings.CFG["verbosity"])])
configure_plumbum_log()
configure_migrate_log()
configure_parse_log() | [
"def",
"configure",
"(",
")",
":",
"log_levels",
"=",
"{",
"5",
":",
"logging",
".",
"NOTSET",
",",
"4",
":",
"logging",
".",
"DEBUG",
",",
"3",
":",
"logging",
".",
"INFO",
",",
"2",
":",
"logging",
".",
"WARNING",
",",
"1",
":",
"logging",
".",... | Load logging configuration from our own defaults. | [
"Load",
"logging",
"configuration",
"from",
"our",
"own",
"defaults",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/log.py#L28-L56 | train | 53,563 |
sci-bots/svg-model | svg_model/shapes_canvas.py | ShapesCanvas.find_shape | def find_shape(self, canvas_x, canvas_y):
'''
Look up shape based on canvas coordinates.
'''
shape_x, shape_y, w = self.canvas_to_shapes_transform.dot([canvas_x,
canvas_y,
1])
if hasattr(self.space, 'point_query_first'):
# Assume `pymunk<5.0`.
shape = self.space.point_query_first((shape_x, shape_y))
else:
# Assume `pymunk>=5.0`, where `point_query_first` method has been
# deprecated.
info = self.space.point_query_nearest((shape_x, shape_y), 0,
[pymunk.ShapeFilter
.ALL_CATEGORIES])
shape = info.shape if info else None
if shape:
return self.bodies[shape.body]
return None | python | def find_shape(self, canvas_x, canvas_y):
'''
Look up shape based on canvas coordinates.
'''
shape_x, shape_y, w = self.canvas_to_shapes_transform.dot([canvas_x,
canvas_y,
1])
if hasattr(self.space, 'point_query_first'):
# Assume `pymunk<5.0`.
shape = self.space.point_query_first((shape_x, shape_y))
else:
# Assume `pymunk>=5.0`, where `point_query_first` method has been
# deprecated.
info = self.space.point_query_nearest((shape_x, shape_y), 0,
[pymunk.ShapeFilter
.ALL_CATEGORIES])
shape = info.shape if info else None
if shape:
return self.bodies[shape.body]
return None | [
"def",
"find_shape",
"(",
"self",
",",
"canvas_x",
",",
"canvas_y",
")",
":",
"shape_x",
",",
"shape_y",
",",
"w",
"=",
"self",
".",
"canvas_to_shapes_transform",
".",
"dot",
"(",
"[",
"canvas_x",
",",
"canvas_y",
",",
"1",
"]",
")",
"if",
"hasattr",
"... | Look up shape based on canvas coordinates. | [
"Look",
"up",
"shape",
"based",
"on",
"canvas",
"coordinates",
"."
] | 2d119650f995e62b29ce0b3151a23f3b957cb072 | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/shapes_canvas.py#L128-L148 | train | 53,564 |
sci-bots/svg-model | svg_model/data_frame.py | get_bounding_box | def get_bounding_box(df_points):
'''
Calculate the bounding box of all points in a data frame.
'''
xy_min = df_points[['x', 'y']].min()
xy_max = df_points[['x', 'y']].max()
wh = xy_max - xy_min
wh.index = 'width', 'height'
bbox = pd.concat([xy_min, wh])
bbox.name = 'bounding_box'
return bbox | python | def get_bounding_box(df_points):
'''
Calculate the bounding box of all points in a data frame.
'''
xy_min = df_points[['x', 'y']].min()
xy_max = df_points[['x', 'y']].max()
wh = xy_max - xy_min
wh.index = 'width', 'height'
bbox = pd.concat([xy_min, wh])
bbox.name = 'bounding_box'
return bbox | [
"def",
"get_bounding_box",
"(",
"df_points",
")",
":",
"xy_min",
"=",
"df_points",
"[",
"[",
"'x'",
",",
"'y'",
"]",
"]",
".",
"min",
"(",
")",
"xy_max",
"=",
"df_points",
"[",
"[",
"'x'",
",",
"'y'",
"]",
"]",
".",
"max",
"(",
")",
"wh",
"=",
... | Calculate the bounding box of all points in a data frame. | [
"Calculate",
"the",
"bounding",
"box",
"of",
"all",
"points",
"in",
"a",
"data",
"frame",
"."
] | 2d119650f995e62b29ce0b3151a23f3b957cb072 | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/data_frame.py#L77-L88 | train | 53,565 |
portfoliome/foil | foil/deserializers.py | json_decoder_hook | def json_decoder_hook(dct, str_decoders=STRING_DECODERS,
converters=MappingProxyType(dict())) -> dict:
"""Decoder for parsing typical objects like uuid's and dates."""
for k, v in dct.items():
if k in converters:
parse_func = converters[k]
dct[k] = parse_func(v)
elif isinstance(v, str):
for decode_func in str_decoders:
v = decode_func(v)
if not isinstance(v, str):
break
dct[k] = v
elif isinstance(v, collections.Mapping):
dct[k] = json_decoder_hook(v, str_decoders, converters)
return dct | python | def json_decoder_hook(dct, str_decoders=STRING_DECODERS,
converters=MappingProxyType(dict())) -> dict:
"""Decoder for parsing typical objects like uuid's and dates."""
for k, v in dct.items():
if k in converters:
parse_func = converters[k]
dct[k] = parse_func(v)
elif isinstance(v, str):
for decode_func in str_decoders:
v = decode_func(v)
if not isinstance(v, str):
break
dct[k] = v
elif isinstance(v, collections.Mapping):
dct[k] = json_decoder_hook(v, str_decoders, converters)
return dct | [
"def",
"json_decoder_hook",
"(",
"dct",
",",
"str_decoders",
"=",
"STRING_DECODERS",
",",
"converters",
"=",
"MappingProxyType",
"(",
"dict",
"(",
")",
")",
")",
"->",
"dict",
":",
"for",
"k",
",",
"v",
"in",
"dct",
".",
"items",
"(",
")",
":",
"if",
... | Decoder for parsing typical objects like uuid's and dates. | [
"Decoder",
"for",
"parsing",
"typical",
"objects",
"like",
"uuid",
"s",
"and",
"dates",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/deserializers.py#L45-L65 | train | 53,566 |
portfoliome/foil | foil/deserializers.py | make_json_decoder_hook | def make_json_decoder_hook(str_decoders=STRING_DECODERS,
extra_str_decoders=tuple(),
converters=MappingProxyType(dict())) -> Callable:
"""Customize JSON string decoder hooks.
Object hook for typical deserialization scenarios.
Notes
-----
Specifying a field in converters will ensure custom decoding/passthrough.
Parameters
----------
str_decoders: functions for decoding strings to objects.
extra_str_decoders: appends additional string decoders to str_decoders.
converters: field / parser function mapping.
"""
str_decoders = tuple(chain(str_decoders, extra_str_decoders))
object_hook = partial(json_decoder_hook, str_decoders=str_decoders,
converters=converters)
return object_hook | python | def make_json_decoder_hook(str_decoders=STRING_DECODERS,
extra_str_decoders=tuple(),
converters=MappingProxyType(dict())) -> Callable:
"""Customize JSON string decoder hooks.
Object hook for typical deserialization scenarios.
Notes
-----
Specifying a field in converters will ensure custom decoding/passthrough.
Parameters
----------
str_decoders: functions for decoding strings to objects.
extra_str_decoders: appends additional string decoders to str_decoders.
converters: field / parser function mapping.
"""
str_decoders = tuple(chain(str_decoders, extra_str_decoders))
object_hook = partial(json_decoder_hook, str_decoders=str_decoders,
converters=converters)
return object_hook | [
"def",
"make_json_decoder_hook",
"(",
"str_decoders",
"=",
"STRING_DECODERS",
",",
"extra_str_decoders",
"=",
"tuple",
"(",
")",
",",
"converters",
"=",
"MappingProxyType",
"(",
"dict",
"(",
")",
")",
")",
"->",
"Callable",
":",
"str_decoders",
"=",
"tuple",
"... | Customize JSON string decoder hooks.
Object hook for typical deserialization scenarios.
Notes
-----
Specifying a field in converters will ensure custom decoding/passthrough.
Parameters
----------
str_decoders: functions for decoding strings to objects.
extra_str_decoders: appends additional string decoders to str_decoders.
converters: field / parser function mapping. | [
"Customize",
"JSON",
"string",
"decoder",
"hooks",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/deserializers.py#L68-L90 | train | 53,567 |
BlueBrain/hpcbench | hpcbench/cli/benwait.py | wait_for_completion | def wait_for_completion(report, interval=10):
"""Wait for asynchronous jobs stil running in the given campaign.
:param report: memory representation of a campaign report
:type campaign: ReportNode
:param interval: wait interval
:type interval: int or float
:return: list of asynchronous job identifiers
"""
for jobid in report.collect('jobid'):
try:
if not Job.finished(jobid):
logging.info('waiting for SLURM job %s', jobid)
time.sleep(interval)
while not Job.finished(jobid):
time.sleep(interval)
yield Job.fromid(jobid)._asdict()
except OSError as e:
if e.errno == errno.ENOENT:
yield dict(id=str(jobid))
else:
raise e | python | def wait_for_completion(report, interval=10):
"""Wait for asynchronous jobs stil running in the given campaign.
:param report: memory representation of a campaign report
:type campaign: ReportNode
:param interval: wait interval
:type interval: int or float
:return: list of asynchronous job identifiers
"""
for jobid in report.collect('jobid'):
try:
if not Job.finished(jobid):
logging.info('waiting for SLURM job %s', jobid)
time.sleep(interval)
while not Job.finished(jobid):
time.sleep(interval)
yield Job.fromid(jobid)._asdict()
except OSError as e:
if e.errno == errno.ENOENT:
yield dict(id=str(jobid))
else:
raise e | [
"def",
"wait_for_completion",
"(",
"report",
",",
"interval",
"=",
"10",
")",
":",
"for",
"jobid",
"in",
"report",
".",
"collect",
"(",
"'jobid'",
")",
":",
"try",
":",
"if",
"not",
"Job",
".",
"finished",
"(",
"jobid",
")",
":",
"logging",
".",
"inf... | Wait for asynchronous jobs stil running in the given campaign.
:param report: memory representation of a campaign report
:type campaign: ReportNode
:param interval: wait interval
:type interval: int or float
:return: list of asynchronous job identifiers | [
"Wait",
"for",
"asynchronous",
"jobs",
"stil",
"running",
"in",
"the",
"given",
"campaign",
"."
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/cli/benwait.py#L110-L131 | train | 53,568 |
BlueBrain/hpcbench | hpcbench/cli/benwait.py | main | def main(argv=None):
"""ben-wait entry point"""
arguments = cli_common(__doc__, argv=argv)
report = ReportNode(arguments['CAMPAIGN-DIR'])
jobs = wait_for_completion(report, float(arguments['--interval']))
status = ReportStatus(report, jobs)
if not arguments['--silent']:
fmt = arguments['--format'] or 'log'
status.log(fmt)
if argv is None:
sys.exit(0 if status.succeeded else 1)
return status.status | python | def main(argv=None):
"""ben-wait entry point"""
arguments = cli_common(__doc__, argv=argv)
report = ReportNode(arguments['CAMPAIGN-DIR'])
jobs = wait_for_completion(report, float(arguments['--interval']))
status = ReportStatus(report, jobs)
if not arguments['--silent']:
fmt = arguments['--format'] or 'log'
status.log(fmt)
if argv is None:
sys.exit(0 if status.succeeded else 1)
return status.status | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"arguments",
"=",
"cli_common",
"(",
"__doc__",
",",
"argv",
"=",
"argv",
")",
"report",
"=",
"ReportNode",
"(",
"arguments",
"[",
"'CAMPAIGN-DIR'",
"]",
")",
"jobs",
"=",
"wait_for_completion",
"(",
"re... | ben-wait entry point | [
"ben",
"-",
"wait",
"entry",
"point"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/cli/benwait.py#L134-L145 | train | 53,569 |
elkiwy/paynter | paynter/color.py | getColors_Triad | def getColors_Triad(hue=None, sat = 1, val = 1, spread = 60):
"""
Create a palette with one main color and two opposite color evenly spread apart from the main one.
:param hue: A 0-1 float with the starting hue value.
:param sat: A 0-1 float with the palette saturation.
:param val: A 0-1 float with the palette value.
:param val: An int with the spread in degrees from the opposite color.
:rtype: A list of :py:class:`Color` objects.
"""
palette = list()
if hue==None:
leadHue = randFloat(0, 1)
else:
leadHue = hue
palette.append(Color(0,0,0,1).set_HSV(leadHue, sat, val))
palette.append(Color(0,0,0,1).set_HSV((leadHue + 0.5 + spread/360) % 1, sat, val))
palette.append(Color(0,0,0,1).set_HSV((leadHue + 0.5 - spread/360) % 1, sat, val))
return palette | python | def getColors_Triad(hue=None, sat = 1, val = 1, spread = 60):
"""
Create a palette with one main color and two opposite color evenly spread apart from the main one.
:param hue: A 0-1 float with the starting hue value.
:param sat: A 0-1 float with the palette saturation.
:param val: A 0-1 float with the palette value.
:param val: An int with the spread in degrees from the opposite color.
:rtype: A list of :py:class:`Color` objects.
"""
palette = list()
if hue==None:
leadHue = randFloat(0, 1)
else:
leadHue = hue
palette.append(Color(0,0,0,1).set_HSV(leadHue, sat, val))
palette.append(Color(0,0,0,1).set_HSV((leadHue + 0.5 + spread/360) % 1, sat, val))
palette.append(Color(0,0,0,1).set_HSV((leadHue + 0.5 - spread/360) % 1, sat, val))
return palette | [
"def",
"getColors_Triad",
"(",
"hue",
"=",
"None",
",",
"sat",
"=",
"1",
",",
"val",
"=",
"1",
",",
"spread",
"=",
"60",
")",
":",
"palette",
"=",
"list",
"(",
")",
"if",
"hue",
"==",
"None",
":",
"leadHue",
"=",
"randFloat",
"(",
"0",
",",
"1"... | Create a palette with one main color and two opposite color evenly spread apart from the main one.
:param hue: A 0-1 float with the starting hue value.
:param sat: A 0-1 float with the palette saturation.
:param val: A 0-1 float with the palette value.
:param val: An int with the spread in degrees from the opposite color.
:rtype: A list of :py:class:`Color` objects. | [
"Create",
"a",
"palette",
"with",
"one",
"main",
"color",
"and",
"two",
"opposite",
"color",
"evenly",
"spread",
"apart",
"from",
"the",
"main",
"one",
"."
] | f73cb5bb010a6b32ee41640a50396ed0bae8d496 | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/color.py#L71-L89 | train | 53,570 |
BlueBrain/hpcbench | hpcbench/driver/slurm.py | SbatchDriver.default_job_name | def default_job_name(self):
"""Slurm job name if not already specified
in the `sbatch` section"""
name = ''
if not self.root.existing_campaign:
campaign_file = osp.basename(self.root.campaign_file)
campaign = osp.splitext(campaign_file)[0]
name += campaign + '/'
name += self.tag
return name | python | def default_job_name(self):
"""Slurm job name if not already specified
in the `sbatch` section"""
name = ''
if not self.root.existing_campaign:
campaign_file = osp.basename(self.root.campaign_file)
campaign = osp.splitext(campaign_file)[0]
name += campaign + '/'
name += self.tag
return name | [
"def",
"default_job_name",
"(",
"self",
")",
":",
"name",
"=",
"''",
"if",
"not",
"self",
".",
"root",
".",
"existing_campaign",
":",
"campaign_file",
"=",
"osp",
".",
"basename",
"(",
"self",
".",
"root",
".",
"campaign_file",
")",
"campaign",
"=",
"osp... | Slurm job name if not already specified
in the `sbatch` section | [
"Slurm",
"job",
"name",
"if",
"not",
"already",
"specified",
"in",
"the",
"sbatch",
"section"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/slurm.py#L102-L111 | train | 53,571 |
BlueBrain/hpcbench | hpcbench/cli/bentpl.py | main | def main(argv=None):
"""ben-tpl entry point"""
arguments = cli_common(__doc__, argv=argv)
plugin = 'benchmark' if arguments['benchmark'] else None
if arguments['-g']:
template.generate_config(plugin, arguments['<FILE>'])
else:
with open(arguments['<FILE>']) as istr:
context = json.load(istr)
kwargs = dict(no_input=True, extra_context=context)
if arguments['--output-dir']:
kwargs.update(output_dir=arguments['--output-dir'])
if arguments['--interactive']:
kwargs.update(no_input=False)
logging.info(
'generating template in directory ' + kwargs.get('output_dir', os.getcwd())
)
template.generate_template(plugin, **kwargs) | python | def main(argv=None):
"""ben-tpl entry point"""
arguments = cli_common(__doc__, argv=argv)
plugin = 'benchmark' if arguments['benchmark'] else None
if arguments['-g']:
template.generate_config(plugin, arguments['<FILE>'])
else:
with open(arguments['<FILE>']) as istr:
context = json.load(istr)
kwargs = dict(no_input=True, extra_context=context)
if arguments['--output-dir']:
kwargs.update(output_dir=arguments['--output-dir'])
if arguments['--interactive']:
kwargs.update(no_input=False)
logging.info(
'generating template in directory ' + kwargs.get('output_dir', os.getcwd())
)
template.generate_template(plugin, **kwargs) | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"arguments",
"=",
"cli_common",
"(",
"__doc__",
",",
"argv",
"=",
"argv",
")",
"plugin",
"=",
"'benchmark'",
"if",
"arguments",
"[",
"'benchmark'",
"]",
"else",
"None",
"if",
"arguments",
"[",
"'-g'",
... | ben-tpl entry point | [
"ben",
"-",
"tpl",
"entry",
"point"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/cli/bentpl.py#L27-L45 | train | 53,572 |
portfoliome/foil | foil/order.py | partition_ordered | def partition_ordered(sequence, key=None):
"""Partition ordered sequence by key.
Sequence is expected to already be ordered.
Parameters
----------
sequence: iterable data.
key: partition key function
Yields
-------
iterable tuple(s) of partition key, data list pairs.
Examples
--------
1. By object attributes.
Partition sequence of objects by a height and weight attributes
into an ordered dict.
>> attributes = ('height', 'weight')
>> OrderedDict(partition_ordered(sequence, attrgetter(*attributes)))
2. By index items.
Partition sequence by the first character index of each element.
>> index = 0
>> sequence = ['112', '124', '289', '220', 'Z23']
>> list(partition_ordered(sequence, itemgetter(index)))
"""
yield from ((k, list(g)) for k, g in groupby(sequence, key=key)) | python | def partition_ordered(sequence, key=None):
"""Partition ordered sequence by key.
Sequence is expected to already be ordered.
Parameters
----------
sequence: iterable data.
key: partition key function
Yields
-------
iterable tuple(s) of partition key, data list pairs.
Examples
--------
1. By object attributes.
Partition sequence of objects by a height and weight attributes
into an ordered dict.
>> attributes = ('height', 'weight')
>> OrderedDict(partition_ordered(sequence, attrgetter(*attributes)))
2. By index items.
Partition sequence by the first character index of each element.
>> index = 0
>> sequence = ['112', '124', '289', '220', 'Z23']
>> list(partition_ordered(sequence, itemgetter(index)))
"""
yield from ((k, list(g)) for k, g in groupby(sequence, key=key)) | [
"def",
"partition_ordered",
"(",
"sequence",
",",
"key",
"=",
"None",
")",
":",
"yield",
"from",
"(",
"(",
"k",
",",
"list",
"(",
"g",
")",
")",
"for",
"k",
",",
"g",
"in",
"groupby",
"(",
"sequence",
",",
"key",
"=",
"key",
")",
")"
] | Partition ordered sequence by key.
Sequence is expected to already be ordered.
Parameters
----------
sequence: iterable data.
key: partition key function
Yields
-------
iterable tuple(s) of partition key, data list pairs.
Examples
--------
1. By object attributes.
Partition sequence of objects by a height and weight attributes
into an ordered dict.
>> attributes = ('height', 'weight')
>> OrderedDict(partition_ordered(sequence, attrgetter(*attributes)))
2. By index items.
Partition sequence by the first character index of each element.
>> index = 0
>> sequence = ['112', '124', '289', '220', 'Z23']
>> list(partition_ordered(sequence, itemgetter(index))) | [
"Partition",
"ordered",
"sequence",
"by",
"key",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/order.py#L4-L37 | train | 53,573 |
portfoliome/foil | foil/order.py | partition | def partition(predicate, iterable):
"""Use a predicate to partition true and false entries.
Reference
---------
Python itertools documentation.
"""
t1, t2 = tee(iterable)
return filterfalse(predicate, t1), filter(predicate, t2) | python | def partition(predicate, iterable):
"""Use a predicate to partition true and false entries.
Reference
---------
Python itertools documentation.
"""
t1, t2 = tee(iterable)
return filterfalse(predicate, t1), filter(predicate, t2) | [
"def",
"partition",
"(",
"predicate",
",",
"iterable",
")",
":",
"t1",
",",
"t2",
"=",
"tee",
"(",
"iterable",
")",
"return",
"filterfalse",
"(",
"predicate",
",",
"t1",
")",
",",
"filter",
"(",
"predicate",
",",
"t2",
")"
] | Use a predicate to partition true and false entries.
Reference
---------
Python itertools documentation. | [
"Use",
"a",
"predicate",
"to",
"partition",
"true",
"and",
"false",
"entries",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/order.py#L40-L50 | train | 53,574 |
PolyJIT/benchbuild | benchbuild/projects/gentoo/portage_gen.py | PortageFactory | def PortageFactory(name, NAME, DOMAIN, BaseClass=autoportage.AutoPortage):
"""
Create a new dynamic portage project.
Auto-Generated projects can only be used for compilie-time experiments,
because there simply is no run-time test defined for it. Therefore,
we implement the run symbol as a noop (with minor logging).
This way we avoid the default implementation for run() that all projects
inherit.
Args:
name: Name of the dynamic class.
NAME: NAME property of the dynamic class.
DOMAIN: DOMAIN property of the dynamic class.
BaseClass: Base class to use for the dynamic class.
Returns:
A new class with NAME,DOMAIN properties set, unable to perform
run-time tests.
Examples:
>>> from benchbuild.projects.gentoo.portage_gen import PortageFactory
>>> from benchbuild.experiments.empty import Empty
>>> c = PortageFactory("test", "NAME", "DOMAIN")
>>> c
<class '__main__.test'>
>>> i = c(Empty())
>>> i.NAME
'NAME'
>>> i.DOMAIN
'DOMAIN'
"""
def run_not_supported(self, *args, **kwargs):
"""Dynamic projects don't support a run() test."""
del args, kwargs # Unused
LOG.warning(
"Runtime testing not supported on auto-generated projects.")
return
newclass = type(
name, (BaseClass, ), {
"NAME": NAME,
"DOMAIN": DOMAIN,
"SRC_FILE": "none",
"VERSION": BaseClass.VERSION,
"GROUP": "auto-gentoo",
"run": run_not_supported,
"__module__": "__main__"
})
return newclass | python | def PortageFactory(name, NAME, DOMAIN, BaseClass=autoportage.AutoPortage):
"""
Create a new dynamic portage project.
Auto-Generated projects can only be used for compilie-time experiments,
because there simply is no run-time test defined for it. Therefore,
we implement the run symbol as a noop (with minor logging).
This way we avoid the default implementation for run() that all projects
inherit.
Args:
name: Name of the dynamic class.
NAME: NAME property of the dynamic class.
DOMAIN: DOMAIN property of the dynamic class.
BaseClass: Base class to use for the dynamic class.
Returns:
A new class with NAME,DOMAIN properties set, unable to perform
run-time tests.
Examples:
>>> from benchbuild.projects.gentoo.portage_gen import PortageFactory
>>> from benchbuild.experiments.empty import Empty
>>> c = PortageFactory("test", "NAME", "DOMAIN")
>>> c
<class '__main__.test'>
>>> i = c(Empty())
>>> i.NAME
'NAME'
>>> i.DOMAIN
'DOMAIN'
"""
def run_not_supported(self, *args, **kwargs):
"""Dynamic projects don't support a run() test."""
del args, kwargs # Unused
LOG.warning(
"Runtime testing not supported on auto-generated projects.")
return
newclass = type(
name, (BaseClass, ), {
"NAME": NAME,
"DOMAIN": DOMAIN,
"SRC_FILE": "none",
"VERSION": BaseClass.VERSION,
"GROUP": "auto-gentoo",
"run": run_not_supported,
"__module__": "__main__"
})
return newclass | [
"def",
"PortageFactory",
"(",
"name",
",",
"NAME",
",",
"DOMAIN",
",",
"BaseClass",
"=",
"autoportage",
".",
"AutoPortage",
")",
":",
"def",
"run_not_supported",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Dynamic projects don't ... | Create a new dynamic portage project.
Auto-Generated projects can only be used for compilie-time experiments,
because there simply is no run-time test defined for it. Therefore,
we implement the run symbol as a noop (with minor logging).
This way we avoid the default implementation for run() that all projects
inherit.
Args:
name: Name of the dynamic class.
NAME: NAME property of the dynamic class.
DOMAIN: DOMAIN property of the dynamic class.
BaseClass: Base class to use for the dynamic class.
Returns:
A new class with NAME,DOMAIN properties set, unable to perform
run-time tests.
Examples:
>>> from benchbuild.projects.gentoo.portage_gen import PortageFactory
>>> from benchbuild.experiments.empty import Empty
>>> c = PortageFactory("test", "NAME", "DOMAIN")
>>> c
<class '__main__.test'>
>>> i = c(Empty())
>>> i.NAME
'NAME'
>>> i.DOMAIN
'DOMAIN' | [
"Create",
"a",
"new",
"dynamic",
"portage",
"project",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/projects/gentoo/portage_gen.py#L66-L118 | train | 53,575 |
chrisjsewell/jsonextended | jsonextended/units/core.py | apply_unitschema | def apply_unitschema(data, uschema, as_quantity=True,
raise_outerr=False, convert_base=False,
use_wildcards=False, list_of_dicts=False):
""" apply the unit schema to the data
Parameters
----------
data : dict
uschema : dict
units schema to apply
as_quantity : bool
if true, return values as pint.Quantity objects
raise_outerr : bool
raise error if a unit cannot be found in the outschema
convert_to_base : bool
rescale units to base units
use_wildcards : bool
if true, can use * (matches everything) and ? (matches any single character)
list_of_dicts: bool
treat list of dicts as additional branches
Examples
--------
>>> from pprint import pprint
>>> data = {'energy':1,'x':[1,2],'other':{'y':[4,5]},'y':[4,5],'meta':None}
>>> uschema = {'energy':'eV','x':'nm','other':{'y':'m'},'y':'cm'}
>>> data_units = apply_unitschema(data,uschema)
>>> pprint(data_units)
{'energy': <Quantity(1, 'electron_volt')>,
'meta': None,
'other': {'y': <Quantity([4 5], 'meter')>},
'x': <Quantity([1 2], 'nanometer')>,
'y': <Quantity([4 5], 'centimeter')>}
>>> newschema = {'energy':'kJ','other':{'y':'nm'},'y':'m'}
>>> new_data = apply_unitschema(data_units,newschema)
>>> str(new_data["energy"])
'1.60217653e-22 kilojoule'
>>> new_data["other"]["y"].magnitude.round(3).tolist(), str(new_data["other"]["y"].units)
([4000000000.0, 5000000000.0], 'nanometer')
>>> old_data = apply_unitschema(new_data,uschema,as_quantity=False)
>>> old_data["energy"]
1.0
>>> old_data["other"]["y"].round(3).tolist()
[4.0, 5.0]
""" # noqa: E501
try:
from pint import UnitRegistry
ureg = UnitRegistry()
from pint.quantity import _Quantity
except ImportError:
raise ImportError('please install pint to use this module')
list_of_dicts = '__list__' if list_of_dicts else None
# flatten edict
uschema_flat = flatten(uschema, key_as_tuple=True)
# sorted by longest key size, to get best match first
uschema_keys = sorted(uschema_flat, key=len, reverse=True)
data_flat = flatten(data, key_as_tuple=True, list_of_dicts=list_of_dicts)
for dkey, dvalue in data_flat.items():
converted = False
for ukey in uschema_keys:
if not len(ukey) == len(dkey[-len(ukey):]):
continue
if use_wildcards:
match = all(
[fnmatch(d, u) for u, d in zip(ukey, dkey[-len(ukey):])])
else:
match = ukey == dkey[-len(ukey):]
if match:
# handle that it return an numpy object type if list of floats
if isinstance(dvalue, (list, tuple)):
dvalue = np.array(dvalue)
if dvalue.dtype == np.object:
dvalue = dvalue.astype(float)
if isinstance(dvalue, _Quantity):
quantity = dvalue.to(uschema_flat[ukey])
else:
quantity = ureg.Quantity(dvalue, uschema_flat[ukey])
if convert_base:
quantity = quantity.to_base_units()
if as_quantity:
data_flat[dkey] = quantity
else:
data_flat[dkey] = quantity.magnitude
break
if not converted and raise_outerr:
raise KeyError('could not find units for {}'.format(dkey))
return unflatten(data_flat, list_of_dicts=list_of_dicts) | python | def apply_unitschema(data, uschema, as_quantity=True,
raise_outerr=False, convert_base=False,
use_wildcards=False, list_of_dicts=False):
""" apply the unit schema to the data
Parameters
----------
data : dict
uschema : dict
units schema to apply
as_quantity : bool
if true, return values as pint.Quantity objects
raise_outerr : bool
raise error if a unit cannot be found in the outschema
convert_to_base : bool
rescale units to base units
use_wildcards : bool
if true, can use * (matches everything) and ? (matches any single character)
list_of_dicts: bool
treat list of dicts as additional branches
Examples
--------
>>> from pprint import pprint
>>> data = {'energy':1,'x':[1,2],'other':{'y':[4,5]},'y':[4,5],'meta':None}
>>> uschema = {'energy':'eV','x':'nm','other':{'y':'m'},'y':'cm'}
>>> data_units = apply_unitschema(data,uschema)
>>> pprint(data_units)
{'energy': <Quantity(1, 'electron_volt')>,
'meta': None,
'other': {'y': <Quantity([4 5], 'meter')>},
'x': <Quantity([1 2], 'nanometer')>,
'y': <Quantity([4 5], 'centimeter')>}
>>> newschema = {'energy':'kJ','other':{'y':'nm'},'y':'m'}
>>> new_data = apply_unitschema(data_units,newschema)
>>> str(new_data["energy"])
'1.60217653e-22 kilojoule'
>>> new_data["other"]["y"].magnitude.round(3).tolist(), str(new_data["other"]["y"].units)
([4000000000.0, 5000000000.0], 'nanometer')
>>> old_data = apply_unitschema(new_data,uschema,as_quantity=False)
>>> old_data["energy"]
1.0
>>> old_data["other"]["y"].round(3).tolist()
[4.0, 5.0]
""" # noqa: E501
try:
from pint import UnitRegistry
ureg = UnitRegistry()
from pint.quantity import _Quantity
except ImportError:
raise ImportError('please install pint to use this module')
list_of_dicts = '__list__' if list_of_dicts else None
# flatten edict
uschema_flat = flatten(uschema, key_as_tuple=True)
# sorted by longest key size, to get best match first
uschema_keys = sorted(uschema_flat, key=len, reverse=True)
data_flat = flatten(data, key_as_tuple=True, list_of_dicts=list_of_dicts)
for dkey, dvalue in data_flat.items():
converted = False
for ukey in uschema_keys:
if not len(ukey) == len(dkey[-len(ukey):]):
continue
if use_wildcards:
match = all(
[fnmatch(d, u) for u, d in zip(ukey, dkey[-len(ukey):])])
else:
match = ukey == dkey[-len(ukey):]
if match:
# handle that it return an numpy object type if list of floats
if isinstance(dvalue, (list, tuple)):
dvalue = np.array(dvalue)
if dvalue.dtype == np.object:
dvalue = dvalue.astype(float)
if isinstance(dvalue, _Quantity):
quantity = dvalue.to(uschema_flat[ukey])
else:
quantity = ureg.Quantity(dvalue, uschema_flat[ukey])
if convert_base:
quantity = quantity.to_base_units()
if as_quantity:
data_flat[dkey] = quantity
else:
data_flat[dkey] = quantity.magnitude
break
if not converted and raise_outerr:
raise KeyError('could not find units for {}'.format(dkey))
return unflatten(data_flat, list_of_dicts=list_of_dicts) | [
"def",
"apply_unitschema",
"(",
"data",
",",
"uschema",
",",
"as_quantity",
"=",
"True",
",",
"raise_outerr",
"=",
"False",
",",
"convert_base",
"=",
"False",
",",
"use_wildcards",
"=",
"False",
",",
"list_of_dicts",
"=",
"False",
")",
":",
"# noqa: E501",
"... | apply the unit schema to the data
Parameters
----------
data : dict
uschema : dict
units schema to apply
as_quantity : bool
if true, return values as pint.Quantity objects
raise_outerr : bool
raise error if a unit cannot be found in the outschema
convert_to_base : bool
rescale units to base units
use_wildcards : bool
if true, can use * (matches everything) and ? (matches any single character)
list_of_dicts: bool
treat list of dicts as additional branches
Examples
--------
>>> from pprint import pprint
>>> data = {'energy':1,'x':[1,2],'other':{'y':[4,5]},'y':[4,5],'meta':None}
>>> uschema = {'energy':'eV','x':'nm','other':{'y':'m'},'y':'cm'}
>>> data_units = apply_unitschema(data,uschema)
>>> pprint(data_units)
{'energy': <Quantity(1, 'electron_volt')>,
'meta': None,
'other': {'y': <Quantity([4 5], 'meter')>},
'x': <Quantity([1 2], 'nanometer')>,
'y': <Quantity([4 5], 'centimeter')>}
>>> newschema = {'energy':'kJ','other':{'y':'nm'},'y':'m'}
>>> new_data = apply_unitschema(data_units,newschema)
>>> str(new_data["energy"])
'1.60217653e-22 kilojoule'
>>> new_data["other"]["y"].magnitude.round(3).tolist(), str(new_data["other"]["y"].units)
([4000000000.0, 5000000000.0], 'nanometer')
>>> old_data = apply_unitschema(new_data,uschema,as_quantity=False)
>>> old_data["energy"]
1.0
>>> old_data["other"]["y"].round(3).tolist()
[4.0, 5.0] | [
"apply",
"the",
"unit",
"schema",
"to",
"the",
"data"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/units/core.py#L23-L123 | train | 53,576 |
PolyJIT/benchbuild | benchbuild/utils/versions.py | get_version_from_cache_dir | def get_version_from_cache_dir(src_file):
"""
Creates a version for a project out of the hash.
The hash is taken from the directory of the source file.
Args:
src_file: The source file of the project using this function.
Returns:
Either returns the first 8 digits of the hash as string,
the entire hash as a string if the hash consists out of less
than 7 digits or None if the path is incorrect.
"""
if src_file is None:
return None
tmp_dir = local.path(str(CFG["tmp_dir"]))
if tmp_dir.exists():
cache_file = tmp_dir / src_file
dir_hash = get_hash_of_dirs(cache_file)
if dir_hash is None:
return None
if len(str(dir_hash)) <= 7:
return str(dir_hash)
return str(dir_hash)[:7]
return None | python | def get_version_from_cache_dir(src_file):
"""
Creates a version for a project out of the hash.
The hash is taken from the directory of the source file.
Args:
src_file: The source file of the project using this function.
Returns:
Either returns the first 8 digits of the hash as string,
the entire hash as a string if the hash consists out of less
than 7 digits or None if the path is incorrect.
"""
if src_file is None:
return None
tmp_dir = local.path(str(CFG["tmp_dir"]))
if tmp_dir.exists():
cache_file = tmp_dir / src_file
dir_hash = get_hash_of_dirs(cache_file)
if dir_hash is None:
return None
if len(str(dir_hash)) <= 7:
return str(dir_hash)
return str(dir_hash)[:7]
return None | [
"def",
"get_version_from_cache_dir",
"(",
"src_file",
")",
":",
"if",
"src_file",
"is",
"None",
":",
"return",
"None",
"tmp_dir",
"=",
"local",
".",
"path",
"(",
"str",
"(",
"CFG",
"[",
"\"tmp_dir\"",
"]",
")",
")",
"if",
"tmp_dir",
".",
"exists",
"(",
... | Creates a version for a project out of the hash.
The hash is taken from the directory of the source file.
Args:
src_file: The source file of the project using this function.
Returns:
Either returns the first 8 digits of the hash as string,
the entire hash as a string if the hash consists out of less
than 7 digits or None if the path is incorrect. | [
"Creates",
"a",
"version",
"for",
"a",
"project",
"out",
"of",
"the",
"hash",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/versions.py#L11-L37 | train | 53,577 |
PolyJIT/benchbuild | benchbuild/utils/path.py | path_to_list | def path_to_list(pathstr):
"""Conver a path string to a list of path elements."""
return [elem for elem in pathstr.split(os.path.pathsep) if elem] | python | def path_to_list(pathstr):
"""Conver a path string to a list of path elements."""
return [elem for elem in pathstr.split(os.path.pathsep) if elem] | [
"def",
"path_to_list",
"(",
"pathstr",
")",
":",
"return",
"[",
"elem",
"for",
"elem",
"in",
"pathstr",
".",
"split",
"(",
"os",
".",
"path",
".",
"pathsep",
")",
"if",
"elem",
"]"
] | Conver a path string to a list of path elements. | [
"Conver",
"a",
"path",
"string",
"to",
"a",
"list",
"of",
"path",
"elements",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/path.py#L12-L14 | train | 53,578 |
PolyJIT/benchbuild | benchbuild/utils/path.py | determine_path | def determine_path():
"""Borrowed from wxglade.py"""
root = __file__
if os.path.islink(root):
root = os.path.realpath(root)
return os.path.dirname(os.path.abspath(root)) | python | def determine_path():
"""Borrowed from wxglade.py"""
root = __file__
if os.path.islink(root):
root = os.path.realpath(root)
return os.path.dirname(os.path.abspath(root)) | [
"def",
"determine_path",
"(",
")",
":",
"root",
"=",
"__file__",
"if",
"os",
".",
"path",
".",
"islink",
"(",
"root",
")",
":",
"root",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"root",
")",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"... | Borrowed from wxglade.py | [
"Borrowed",
"from",
"wxglade",
".",
"py"
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/path.py#L17-L22 | train | 53,579 |
PolyJIT/benchbuild | benchbuild/utils/path.py | template_str | def template_str(template):
"""Read a template file from the resources and return it as str."""
tmpl_file = os.path.join(determine_path(), template)
with open(tmpl_file, mode='r') as tmpl_strm:
return "".join(tmpl_strm.readlines()) | python | def template_str(template):
"""Read a template file from the resources and return it as str."""
tmpl_file = os.path.join(determine_path(), template)
with open(tmpl_file, mode='r') as tmpl_strm:
return "".join(tmpl_strm.readlines()) | [
"def",
"template_str",
"(",
"template",
")",
":",
"tmpl_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"determine_path",
"(",
")",
",",
"template",
")",
"with",
"open",
"(",
"tmpl_file",
",",
"mode",
"=",
"'r'",
")",
"as",
"tmpl_strm",
":",
"return",... | Read a template file from the resources and return it as str. | [
"Read",
"a",
"template",
"file",
"from",
"the",
"resources",
"and",
"return",
"it",
"as",
"str",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/path.py#L55-L59 | train | 53,580 |
PolyJIT/benchbuild | benchbuild/utils/path.py | mkdir_interactive | def mkdir_interactive(dirpath):
"""
Create a directory if required.
This will query the user for a confirmation.
Args:
dirname: The path to create.
"""
from benchbuild.utils.cmd import mkdir
if os.path.exists(dirpath):
return
response = ui.ask(
"The directory {dirname} does not exist yet. "
"Should I create it?".format(dirname=dirpath),
default_answer=True,
default_answer_str="yes")
if response:
mkdir("-p", dirpath)
print("Created directory {0}.".format(dirpath)) | python | def mkdir_interactive(dirpath):
"""
Create a directory if required.
This will query the user for a confirmation.
Args:
dirname: The path to create.
"""
from benchbuild.utils.cmd import mkdir
if os.path.exists(dirpath):
return
response = ui.ask(
"The directory {dirname} does not exist yet. "
"Should I create it?".format(dirname=dirpath),
default_answer=True,
default_answer_str="yes")
if response:
mkdir("-p", dirpath)
print("Created directory {0}.".format(dirpath)) | [
"def",
"mkdir_interactive",
"(",
"dirpath",
")",
":",
"from",
"benchbuild",
".",
"utils",
".",
"cmd",
"import",
"mkdir",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dirpath",
")",
":",
"return",
"response",
"=",
"ui",
".",
"ask",
"(",
"\"The directory ... | Create a directory if required.
This will query the user for a confirmation.
Args:
dirname: The path to create. | [
"Create",
"a",
"directory",
"if",
"required",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/path.py#L108-L129 | train | 53,581 |
mckib2/rawdatarinator | rawdatarinator/readMeasDataVB15.py | get_val_by_text | def get_val_by_text(root,search):
"""From MeasYaps XML root find next sibling of node matching 'search'.
MeasYaps looks like:
<value>Key</value>
<value>Value</value>
Thus 'search' is the Key and we want to find the node that has the Value.
We return the node containing the desired Value.
Arguments:
root (Element) root XML node (xml.etree.ElementTree Element)
search (String) String to match Element.text
"""
found_flag = False
for el in root.iter():
if found_flag:
return(el)
if el.text == search:
# We want the next el
found_flag = True | python | def get_val_by_text(root,search):
"""From MeasYaps XML root find next sibling of node matching 'search'.
MeasYaps looks like:
<value>Key</value>
<value>Value</value>
Thus 'search' is the Key and we want to find the node that has the Value.
We return the node containing the desired Value.
Arguments:
root (Element) root XML node (xml.etree.ElementTree Element)
search (String) String to match Element.text
"""
found_flag = False
for el in root.iter():
if found_flag:
return(el)
if el.text == search:
# We want the next el
found_flag = True | [
"def",
"get_val_by_text",
"(",
"root",
",",
"search",
")",
":",
"found_flag",
"=",
"False",
"for",
"el",
"in",
"root",
".",
"iter",
"(",
")",
":",
"if",
"found_flag",
":",
"return",
"(",
"el",
")",
"if",
"el",
".",
"text",
"==",
"search",
":",
"# W... | From MeasYaps XML root find next sibling of node matching 'search'.
MeasYaps looks like:
<value>Key</value>
<value>Value</value>
Thus 'search' is the Key and we want to find the node that has the Value.
We return the node containing the desired Value.
Arguments:
root (Element) root XML node (xml.etree.ElementTree Element)
search (String) String to match Element.text | [
"From",
"MeasYaps",
"XML",
"root",
"find",
"next",
"sibling",
"of",
"node",
"matching",
"search",
"."
] | 03a85fd8f5e380b424027d28e97972bd7a6a3f1b | https://github.com/mckib2/rawdatarinator/blob/03a85fd8f5e380b424027d28e97972bd7a6a3f1b/rawdatarinator/readMeasDataVB15.py#L9-L30 | train | 53,582 |
mckib2/rawdatarinator | rawdatarinator/readMeasDataVB15.py | get_yaps_by_name | def get_yaps_by_name(root,name,afun=lambda x:x,default=None):
"""From XML root, return value of node matching attribute 'name'.
Arguments:
root (Element) Root XML node (xml.etree.ElementTree Element).
This is the root of the entire XML document, not the YAPS
subtree.
name (String) name='name' attribute of ParamLong tag to be
matched.
afun Anonymous function in the form of a lambda expression to
process the string value. Defaults to the identity function.
default Default value if node is not found. Defaults to 'None'.
"""
node = root.find("ParamMap[@name='YAPS']/ParamLong[@name='%s']/value" % name)
if node is not None:
return(afun(node.text))
else:
return(default) | python | def get_yaps_by_name(root,name,afun=lambda x:x,default=None):
"""From XML root, return value of node matching attribute 'name'.
Arguments:
root (Element) Root XML node (xml.etree.ElementTree Element).
This is the root of the entire XML document, not the YAPS
subtree.
name (String) name='name' attribute of ParamLong tag to be
matched.
afun Anonymous function in the form of a lambda expression to
process the string value. Defaults to the identity function.
default Default value if node is not found. Defaults to 'None'.
"""
node = root.find("ParamMap[@name='YAPS']/ParamLong[@name='%s']/value" % name)
if node is not None:
return(afun(node.text))
else:
return(default) | [
"def",
"get_yaps_by_name",
"(",
"root",
",",
"name",
",",
"afun",
"=",
"lambda",
"x",
":",
"x",
",",
"default",
"=",
"None",
")",
":",
"node",
"=",
"root",
".",
"find",
"(",
"\"ParamMap[@name='YAPS']/ParamLong[@name='%s']/value\"",
"%",
"name",
")",
"if",
... | From XML root, return value of node matching attribute 'name'.
Arguments:
root (Element) Root XML node (xml.etree.ElementTree Element).
This is the root of the entire XML document, not the YAPS
subtree.
name (String) name='name' attribute of ParamLong tag to be
matched.
afun Anonymous function in the form of a lambda expression to
process the string value. Defaults to the identity function.
default Default value if node is not found. Defaults to 'None'. | [
"From",
"XML",
"root",
"return",
"value",
"of",
"node",
"matching",
"attribute",
"name",
"."
] | 03a85fd8f5e380b424027d28e97972bd7a6a3f1b | https://github.com/mckib2/rawdatarinator/blob/03a85fd8f5e380b424027d28e97972bd7a6a3f1b/rawdatarinator/readMeasDataVB15.py#L32-L53 | train | 53,583 |
mckib2/rawdatarinator | rawdatarinator/readMeasDataVB15.py | main | def main(args):
'''Function run when called from command line.'''
options = { '-rfft': ['resetFFTscale',False],
'-r1': ['readOneCoil',False],
'-rp': ['readPhaseCorInfo',False],
'-rn': ['readNavigator',False],
'-skipts': ['readTimeStamp',True],
'-nnavek': ['nNavEK',False],
'-ros': ['removeOS',False],
'-rosa': ['removeOSafter',False],
'-I': ['transformToImageSpace',False],
'-w': ['writeToFile',False],
'-npz': ['npz',False] }
decode_simple_opts(options,args,readMeasDataVB15) | python | def main(args):
'''Function run when called from command line.'''
options = { '-rfft': ['resetFFTscale',False],
'-r1': ['readOneCoil',False],
'-rp': ['readPhaseCorInfo',False],
'-rn': ['readNavigator',False],
'-skipts': ['readTimeStamp',True],
'-nnavek': ['nNavEK',False],
'-ros': ['removeOS',False],
'-rosa': ['removeOSafter',False],
'-I': ['transformToImageSpace',False],
'-w': ['writeToFile',False],
'-npz': ['npz',False] }
decode_simple_opts(options,args,readMeasDataVB15) | [
"def",
"main",
"(",
"args",
")",
":",
"options",
"=",
"{",
"'-rfft'",
":",
"[",
"'resetFFTscale'",
",",
"False",
"]",
",",
"'-r1'",
":",
"[",
"'readOneCoil'",
",",
"False",
"]",
",",
"'-rp'",
":",
"[",
"'readPhaseCorInfo'",
",",
"False",
"]",
",",
"'... | Function run when called from command line. | [
"Function",
"run",
"when",
"called",
"from",
"command",
"line",
"."
] | 03a85fd8f5e380b424027d28e97972bd7a6a3f1b | https://github.com/mckib2/rawdatarinator/blob/03a85fd8f5e380b424027d28e97972bd7a6a3f1b/rawdatarinator/readMeasDataVB15.py#L651-L666 | train | 53,584 |
chrisjsewell/jsonextended | jsonextended/ejson.py | _get_keys_folder | def _get_keys_folder(jdir, key_path=None, in_memory=True,
ignore_prefix=('.', '_')):
""" get json keys from directory structure
e.g.
jdir
sub_dir1
data1.json
data2.json
sub_dir2
data.json
_get_keys_folder(jdir)
=> ['sub_dir1', 'sub_dir2']
_get_keys_folder(jdir,['sub_dir1'])
=> ['data1', 'data2']
NB: json files are identified with .json extension
files/directories beginning with '.' are ignored
"""
if not hasattr(jdir, 'iterdir'):
raise ValueError('jdir is not a path object; {}'.format(jdir))
key_path = [] if key_path is None else key_path
keys = []
key_found = False if key_path else True
search_key = key_path[0] if len(key_path) > 0 else None
for jsub in jdir.iterdir():
if jsub.is_file() and jsub.name[-5:] == '.json':
name, ext = os.path.splitext(jsub.name)
if name == search_key or not key_path:
key_found = True
if key_path:
return jkeys(jsub, key_path[1:], in_memory, ignore_prefix)
else:
keys.append(name)
elif (jsub.is_dir()
and not jsub.name.startswith(ignore_prefix)
and (jsub.name == search_key or not key_path)):
key_found = True
if jsub.name in keys:
raise IOError(
'directory has a sub-dir and file with same name: '
'{1} and {1}.json in {0}'.format(jdir, jsub.name))
if key_path:
return jkeys(jsub, key_path[1:], in_memory, ignore_prefix)
else:
keys.append(jsub.name)
if not key_found:
raise KeyError('key not found: {0}'.format(search_key))
return sorted(keys) | python | def _get_keys_folder(jdir, key_path=None, in_memory=True,
ignore_prefix=('.', '_')):
""" get json keys from directory structure
e.g.
jdir
sub_dir1
data1.json
data2.json
sub_dir2
data.json
_get_keys_folder(jdir)
=> ['sub_dir1', 'sub_dir2']
_get_keys_folder(jdir,['sub_dir1'])
=> ['data1', 'data2']
NB: json files are identified with .json extension
files/directories beginning with '.' are ignored
"""
if not hasattr(jdir, 'iterdir'):
raise ValueError('jdir is not a path object; {}'.format(jdir))
key_path = [] if key_path is None else key_path
keys = []
key_found = False if key_path else True
search_key = key_path[0] if len(key_path) > 0 else None
for jsub in jdir.iterdir():
if jsub.is_file() and jsub.name[-5:] == '.json':
name, ext = os.path.splitext(jsub.name)
if name == search_key or not key_path:
key_found = True
if key_path:
return jkeys(jsub, key_path[1:], in_memory, ignore_prefix)
else:
keys.append(name)
elif (jsub.is_dir()
and not jsub.name.startswith(ignore_prefix)
and (jsub.name == search_key or not key_path)):
key_found = True
if jsub.name in keys:
raise IOError(
'directory has a sub-dir and file with same name: '
'{1} and {1}.json in {0}'.format(jdir, jsub.name))
if key_path:
return jkeys(jsub, key_path[1:], in_memory, ignore_prefix)
else:
keys.append(jsub.name)
if not key_found:
raise KeyError('key not found: {0}'.format(search_key))
return sorted(keys) | [
"def",
"_get_keys_folder",
"(",
"jdir",
",",
"key_path",
"=",
"None",
",",
"in_memory",
"=",
"True",
",",
"ignore_prefix",
"=",
"(",
"'.'",
",",
"'_'",
")",
")",
":",
"if",
"not",
"hasattr",
"(",
"jdir",
",",
"'iterdir'",
")",
":",
"raise",
"ValueError... | get json keys from directory structure
e.g.
jdir
sub_dir1
data1.json
data2.json
sub_dir2
data.json
_get_keys_folder(jdir)
=> ['sub_dir1', 'sub_dir2']
_get_keys_folder(jdir,['sub_dir1'])
=> ['data1', 'data2']
NB: json files are identified with .json extension
files/directories beginning with '.' are ignored | [
"get",
"json",
"keys",
"from",
"directory",
"structure"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/ejson.py#L74-L134 | train | 53,585 |
chrisjsewell/jsonextended | jsonextended/ejson.py | jkeys | def jkeys(jfile, key_path=None, in_memory=True, ignore_prefix=('.', '_')):
""" get keys for initial json level, or at level after following key_path
Parameters
----------
jfile : str, file_like or path_like
if str, must be existing file or folder,
if file_like, must have 'read' method
if path_like, must have 'iterdir' method (see pathlib.Path)
key_path : list[str]
a list of keys to index into the json before returning keys
in_memory : bool
if true reads json into memory before finding keys
(this is faster but uses more memory)
ignore_prefix : list[str]
ignore folders beginning with these prefixes
Examples
--------
>>> from jsonextended.utils import MockPath
>>> file_obj = MockPath('test.json',is_file=True,
... content='''
... {
... "a": 1,
... "b": [1.1,2.1],
... "c": {"d":"e","f":"g"}
... }
... ''')
...
>>> jkeys(file_obj)
['a', 'b', 'c']
>>> jkeys(file_obj,["c"])
['d', 'f']
>>> from jsonextended.utils import get_test_path
>>> path = get_test_path()
>>> jkeys(path)
['dir1', 'dir2', 'dir3']
>>> path = get_test_path()
>>> jkeys(path, ['dir1','file1'], in_memory=True)
['initial', 'meta', 'optimised', 'units']
"""
key_path = [] if key_path is None else key_path
def eval_file(file_obj):
if not in_memory:
return _get_keys_ijson(file_obj, key_path)
else:
return _get_keys(file_obj, key_path)
if isinstance(jfile, basestring):
if not os.path.exists(jfile):
raise IOError('jfile does not exist: {}'.format(jfile))
if os.path.isdir(jfile):
jpath = pathlib.Path(jfile)
return _get_keys_folder(jpath, key_path, in_memory, ignore_prefix)
else:
with open(jfile, 'r') as file_obj:
return eval_file(file_obj)
elif hasattr(jfile, 'read'):
return eval_file(jfile)
elif hasattr(jfile, 'iterdir'):
if jfile.is_file():
with jfile.open('r') as file_obj:
return eval_file(file_obj)
else:
return _get_keys_folder(jfile, key_path, in_memory, ignore_prefix)
else:
raise ValueError(
'jfile should be a str, '
'file_like or path_like object: {}'.format(jfile)) | python | def jkeys(jfile, key_path=None, in_memory=True, ignore_prefix=('.', '_')):
""" get keys for initial json level, or at level after following key_path
Parameters
----------
jfile : str, file_like or path_like
if str, must be existing file or folder,
if file_like, must have 'read' method
if path_like, must have 'iterdir' method (see pathlib.Path)
key_path : list[str]
a list of keys to index into the json before returning keys
in_memory : bool
if true reads json into memory before finding keys
(this is faster but uses more memory)
ignore_prefix : list[str]
ignore folders beginning with these prefixes
Examples
--------
>>> from jsonextended.utils import MockPath
>>> file_obj = MockPath('test.json',is_file=True,
... content='''
... {
... "a": 1,
... "b": [1.1,2.1],
... "c": {"d":"e","f":"g"}
... }
... ''')
...
>>> jkeys(file_obj)
['a', 'b', 'c']
>>> jkeys(file_obj,["c"])
['d', 'f']
>>> from jsonextended.utils import get_test_path
>>> path = get_test_path()
>>> jkeys(path)
['dir1', 'dir2', 'dir3']
>>> path = get_test_path()
>>> jkeys(path, ['dir1','file1'], in_memory=True)
['initial', 'meta', 'optimised', 'units']
"""
key_path = [] if key_path is None else key_path
def eval_file(file_obj):
if not in_memory:
return _get_keys_ijson(file_obj, key_path)
else:
return _get_keys(file_obj, key_path)
if isinstance(jfile, basestring):
if not os.path.exists(jfile):
raise IOError('jfile does not exist: {}'.format(jfile))
if os.path.isdir(jfile):
jpath = pathlib.Path(jfile)
return _get_keys_folder(jpath, key_path, in_memory, ignore_prefix)
else:
with open(jfile, 'r') as file_obj:
return eval_file(file_obj)
elif hasattr(jfile, 'read'):
return eval_file(jfile)
elif hasattr(jfile, 'iterdir'):
if jfile.is_file():
with jfile.open('r') as file_obj:
return eval_file(file_obj)
else:
return _get_keys_folder(jfile, key_path, in_memory, ignore_prefix)
else:
raise ValueError(
'jfile should be a str, '
'file_like or path_like object: {}'.format(jfile)) | [
"def",
"jkeys",
"(",
"jfile",
",",
"key_path",
"=",
"None",
",",
"in_memory",
"=",
"True",
",",
"ignore_prefix",
"=",
"(",
"'.'",
",",
"'_'",
")",
")",
":",
"key_path",
"=",
"[",
"]",
"if",
"key_path",
"is",
"None",
"else",
"key_path",
"def",
"eval_f... | get keys for initial json level, or at level after following key_path
Parameters
----------
jfile : str, file_like or path_like
if str, must be existing file or folder,
if file_like, must have 'read' method
if path_like, must have 'iterdir' method (see pathlib.Path)
key_path : list[str]
a list of keys to index into the json before returning keys
in_memory : bool
if true reads json into memory before finding keys
(this is faster but uses more memory)
ignore_prefix : list[str]
ignore folders beginning with these prefixes
Examples
--------
>>> from jsonextended.utils import MockPath
>>> file_obj = MockPath('test.json',is_file=True,
... content='''
... {
... "a": 1,
... "b": [1.1,2.1],
... "c": {"d":"e","f":"g"}
... }
... ''')
...
>>> jkeys(file_obj)
['a', 'b', 'c']
>>> jkeys(file_obj,["c"])
['d', 'f']
>>> from jsonextended.utils import get_test_path
>>> path = get_test_path()
>>> jkeys(path)
['dir1', 'dir2', 'dir3']
>>> path = get_test_path()
>>> jkeys(path, ['dir1','file1'], in_memory=True)
['initial', 'meta', 'optimised', 'units'] | [
"get",
"keys",
"for",
"initial",
"json",
"level",
"or",
"at",
"level",
"after",
"following",
"key_path"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/ejson.py#L137-L211 | train | 53,586 |
chrisjsewell/jsonextended | jsonextended/ejson.py | _file_with_keys | def _file_with_keys(file_obj, key_path=None, parse_decimal=False):
"""read json with keys
Parameters
----------
file_obj : object
object with read method
key_path : list[str]
key to index befor parsing
parse_decimal : bool
whether to parse numbers as Decimal instances (retains exact precision)
Notes
-----
ijson outputs decimals as Decimal class (for arbitrary precision)
"""
key_path = [] if key_path is None else key_path
try:
objs = ijson.items(file_obj, '.'.join(key_path))
except NameError:
warnings.warn('ijson package not found in environment, \
please install for on-disk key indexing', ImportWarning)
data = json.load(
file_obj, parse_float=Decimal if parse_decimal else float,
object_hook=decode)
return indexes(data, key_path)
try:
data = next(objs) # .next()
except StopIteration:
raise KeyError('key path not available in json: {}'.format(key_path))
# by default ijson parses Decimal values
if not parse_decimal:
convert_type(data, Decimal, float, in_place=True)
datastr = json.dumps(data)
data = json.loads(datastr, object_hook=decode)
return data | python | def _file_with_keys(file_obj, key_path=None, parse_decimal=False):
"""read json with keys
Parameters
----------
file_obj : object
object with read method
key_path : list[str]
key to index befor parsing
parse_decimal : bool
whether to parse numbers as Decimal instances (retains exact precision)
Notes
-----
ijson outputs decimals as Decimal class (for arbitrary precision)
"""
key_path = [] if key_path is None else key_path
try:
objs = ijson.items(file_obj, '.'.join(key_path))
except NameError:
warnings.warn('ijson package not found in environment, \
please install for on-disk key indexing', ImportWarning)
data = json.load(
file_obj, parse_float=Decimal if parse_decimal else float,
object_hook=decode)
return indexes(data, key_path)
try:
data = next(objs) # .next()
except StopIteration:
raise KeyError('key path not available in json: {}'.format(key_path))
# by default ijson parses Decimal values
if not parse_decimal:
convert_type(data, Decimal, float, in_place=True)
datastr = json.dumps(data)
data = json.loads(datastr, object_hook=decode)
return data | [
"def",
"_file_with_keys",
"(",
"file_obj",
",",
"key_path",
"=",
"None",
",",
"parse_decimal",
"=",
"False",
")",
":",
"key_path",
"=",
"[",
"]",
"if",
"key_path",
"is",
"None",
"else",
"key_path",
"try",
":",
"objs",
"=",
"ijson",
".",
"items",
"(",
"... | read json with keys
Parameters
----------
file_obj : object
object with read method
key_path : list[str]
key to index befor parsing
parse_decimal : bool
whether to parse numbers as Decimal instances (retains exact precision)
Notes
-----
ijson outputs decimals as Decimal class (for arbitrary precision) | [
"read",
"json",
"with",
"keys"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/ejson.py#L214-L254 | train | 53,587 |
chrisjsewell/jsonextended | jsonextended/ejson.py | _folder_to_json | def _folder_to_json(jdir, key_path=None, in_memory=True,
ignore_prefix=('.', '_'), dic={}, parse_decimal=False):
""" read in folder structure as json
e.g.
jdir
sub_dir1
data.json
sub_dir2
data.json
_folder_to_json(jdir)
=> {'sub_dir1':{'data':{...}},
'sub_dir2':{'data':{...}}}
NB: json files are identified with .json extension
"""
key_path = [] if key_path is None else key_path
if not hasattr(jdir, 'iterdir'):
raise ValueError('jdir is not a path object; {}'.format(jdir))
key_found = False if key_path else True
search_key = key_path[0] if len(key_path) > 0 else None
for jsub in jdir.iterdir():
if jsub.is_file() and jsub.name.endswith('.json'):
name, ext = os.path.splitext(jsub.name)
if name == search_key or not key_path:
key_found = True
if key_path:
data = to_dict(jsub, key_path[1:], in_memory,
ignore_prefix, parse_decimal)
if isinstance(data, dict):
dic.update(data)
else:
dic.update({_Terminus(): data})
else:
dic[name] = to_dict(jsub, key_path[1:], in_memory,
ignore_prefix, parse_decimal)
elif (jsub.is_dir()
and not jsub.name.startswith(ignore_prefix)
and (jsub.name == search_key or not key_path)):
key_found = True
if jsub.name in dic.keys():
raise IOError(
'directory has a sub-dir and file with same name: '
'{1} and {1}.json in {0}'.format(jdir, jsub.name))
if key_path:
sub_d = dic
else:
dic[jsub.name] = {}
sub_d = dic[jsub.name]
_folder_to_json(jsub, key_path[1:], in_memory, ignore_prefix,
sub_d, parse_decimal)
if not key_found:
raise KeyError('key not found: {0}'.format(search_key)) | python | def _folder_to_json(jdir, key_path=None, in_memory=True,
ignore_prefix=('.', '_'), dic={}, parse_decimal=False):
""" read in folder structure as json
e.g.
jdir
sub_dir1
data.json
sub_dir2
data.json
_folder_to_json(jdir)
=> {'sub_dir1':{'data':{...}},
'sub_dir2':{'data':{...}}}
NB: json files are identified with .json extension
"""
key_path = [] if key_path is None else key_path
if not hasattr(jdir, 'iterdir'):
raise ValueError('jdir is not a path object; {}'.format(jdir))
key_found = False if key_path else True
search_key = key_path[0] if len(key_path) > 0 else None
for jsub in jdir.iterdir():
if jsub.is_file() and jsub.name.endswith('.json'):
name, ext = os.path.splitext(jsub.name)
if name == search_key or not key_path:
key_found = True
if key_path:
data = to_dict(jsub, key_path[1:], in_memory,
ignore_prefix, parse_decimal)
if isinstance(data, dict):
dic.update(data)
else:
dic.update({_Terminus(): data})
else:
dic[name] = to_dict(jsub, key_path[1:], in_memory,
ignore_prefix, parse_decimal)
elif (jsub.is_dir()
and not jsub.name.startswith(ignore_prefix)
and (jsub.name == search_key or not key_path)):
key_found = True
if jsub.name in dic.keys():
raise IOError(
'directory has a sub-dir and file with same name: '
'{1} and {1}.json in {0}'.format(jdir, jsub.name))
if key_path:
sub_d = dic
else:
dic[jsub.name] = {}
sub_d = dic[jsub.name]
_folder_to_json(jsub, key_path[1:], in_memory, ignore_prefix,
sub_d, parse_decimal)
if not key_found:
raise KeyError('key not found: {0}'.format(search_key)) | [
"def",
"_folder_to_json",
"(",
"jdir",
",",
"key_path",
"=",
"None",
",",
"in_memory",
"=",
"True",
",",
"ignore_prefix",
"=",
"(",
"'.'",
",",
"'_'",
")",
",",
"dic",
"=",
"{",
"}",
",",
"parse_decimal",
"=",
"False",
")",
":",
"key_path",
"=",
"[",... | read in folder structure as json
e.g.
jdir
sub_dir1
data.json
sub_dir2
data.json
_folder_to_json(jdir)
=> {'sub_dir1':{'data':{...}},
'sub_dir2':{'data':{...}}}
NB: json files are identified with .json extension | [
"read",
"in",
"folder",
"structure",
"as",
"json"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/ejson.py#L267-L329 | train | 53,588 |
chrisjsewell/jsonextended | jsonextended/ejson.py | to_dict | def to_dict(jfile, key_path=None, in_memory=True,
ignore_prefix=('.', '_'), parse_decimal=False):
""" input json to dict
Parameters
----------
jfile : str, file_like or path_like
if str, must be existing file or folder,
if file_like, must have 'read' method
if path_like, must have 'iterdir' method (see pathlib.Path)
key_path : list[str]
a list of keys to index into the json before parsing it
in_memory : bool
if true reads full json into memory before filtering keys
(this is faster but uses more memory)
ignore_prefix : list[str]
ignore folders beginning with these prefixes
parse_decimal : bool
whether to parse numbers as Decimal instances (retains exact precision)
Examples
--------
>>> from pprint import pformat
>>> from jsonextended.utils import MockPath
>>> file_obj = MockPath('test.json',is_file=True,
... content='''
... {
... "a": 1,
... "b": [1.1,2.1],
... "c": {"d":"e"}
... }
... ''')
...
>>> dstr = pformat(to_dict(file_obj))
>>> print(dstr.replace("u'","'"))
{'a': 1, 'b': [1.1, 2.1], 'c': {'d': 'e'}}
>>> dstr = pformat(to_dict(file_obj,parse_decimal=True))
>>> print(dstr.replace("u'","'"))
{'a': 1, 'b': [Decimal('1.1'), Decimal('2.1')], 'c': {'d': 'e'}}
>>> str(to_dict(file_obj,["c","d"]))
'e'
>>> from jsonextended.utils import get_test_path
>>> path = get_test_path()
>>> jdict1 = to_dict(path)
>>> pprint(jdict1,depth=2)
dir1:
dir1_1: {...}
file1: {...}
file2: {...}
dir2:
file1: {...}
dir3:
>>> jdict2 = to_dict(path,['dir1','file1','initial'],in_memory=False)
>>> pprint(jdict2,depth=1)
crystallographic: {...}
primitive: {...}
"""
key_path = [] if key_path is None else key_path
if isinstance(jfile, basestring):
if not os.path.exists(jfile):
raise IOError('jfile does not exist: {}'.format(jfile))
if os.path.isdir(jfile):
data = {}
jpath = pathlib.Path(jfile)
_folder_to_json(jpath, key_path[:], in_memory, ignore_prefix,
data, parse_decimal)
if isinstance(list(data.keys())[0], _Terminus):
data = data.values()[0]
else:
with open(jfile, 'r') as file_obj:
if key_path and not in_memory:
data = _file_with_keys(file_obj, key_path, parse_decimal)
elif key_path:
data = json.load(
file_obj, object_hook=decode,
parse_float=Decimal if parse_decimal else float)
data = indexes(data, key_path)
else:
data = json.load(
file_obj, object_hook=decode,
parse_float=Decimal if parse_decimal else float)
elif hasattr(jfile, 'read'):
if key_path and not in_memory:
data = _file_with_keys(jfile, key_path, parse_decimal)
elif key_path:
data = json.load(
jfile, object_hook=decode,
parse_float=Decimal if parse_decimal else float)
data = indexes(data, key_path)
else:
data = json.load(
jfile, object_hook=decode,
parse_float=Decimal if parse_decimal else float)
elif hasattr(jfile, 'iterdir'):
if jfile.is_file():
with jfile.open() as file_obj:
if key_path and not in_memory:
data = _file_with_keys(file_obj, key_path, parse_decimal)
elif key_path:
data = json.load(
file_obj, object_hook=decode,
parse_float=Decimal if parse_decimal else float)
data = indexes(data, key_path)
else:
data = json.load(
file_obj, object_hook=decode,
parse_float=Decimal if parse_decimal else float)
else:
data = {}
_folder_to_json(jfile, key_path[:], in_memory, ignore_prefix,
data, parse_decimal)
if isinstance(list(data.keys())[0], _Terminus):
data = data.values()[0]
else:
raise ValueError(
'jfile should be a str, '
'file_like or path_like object: {}'.format(jfile))
return data | python | def to_dict(jfile, key_path=None, in_memory=True,
ignore_prefix=('.', '_'), parse_decimal=False):
""" input json to dict
Parameters
----------
jfile : str, file_like or path_like
if str, must be existing file or folder,
if file_like, must have 'read' method
if path_like, must have 'iterdir' method (see pathlib.Path)
key_path : list[str]
a list of keys to index into the json before parsing it
in_memory : bool
if true reads full json into memory before filtering keys
(this is faster but uses more memory)
ignore_prefix : list[str]
ignore folders beginning with these prefixes
parse_decimal : bool
whether to parse numbers as Decimal instances (retains exact precision)
Examples
--------
>>> from pprint import pformat
>>> from jsonextended.utils import MockPath
>>> file_obj = MockPath('test.json',is_file=True,
... content='''
... {
... "a": 1,
... "b": [1.1,2.1],
... "c": {"d":"e"}
... }
... ''')
...
>>> dstr = pformat(to_dict(file_obj))
>>> print(dstr.replace("u'","'"))
{'a': 1, 'b': [1.1, 2.1], 'c': {'d': 'e'}}
>>> dstr = pformat(to_dict(file_obj,parse_decimal=True))
>>> print(dstr.replace("u'","'"))
{'a': 1, 'b': [Decimal('1.1'), Decimal('2.1')], 'c': {'d': 'e'}}
>>> str(to_dict(file_obj,["c","d"]))
'e'
>>> from jsonextended.utils import get_test_path
>>> path = get_test_path()
>>> jdict1 = to_dict(path)
>>> pprint(jdict1,depth=2)
dir1:
dir1_1: {...}
file1: {...}
file2: {...}
dir2:
file1: {...}
dir3:
>>> jdict2 = to_dict(path,['dir1','file1','initial'],in_memory=False)
>>> pprint(jdict2,depth=1)
crystallographic: {...}
primitive: {...}
"""
key_path = [] if key_path is None else key_path
if isinstance(jfile, basestring):
if not os.path.exists(jfile):
raise IOError('jfile does not exist: {}'.format(jfile))
if os.path.isdir(jfile):
data = {}
jpath = pathlib.Path(jfile)
_folder_to_json(jpath, key_path[:], in_memory, ignore_prefix,
data, parse_decimal)
if isinstance(list(data.keys())[0], _Terminus):
data = data.values()[0]
else:
with open(jfile, 'r') as file_obj:
if key_path and not in_memory:
data = _file_with_keys(file_obj, key_path, parse_decimal)
elif key_path:
data = json.load(
file_obj, object_hook=decode,
parse_float=Decimal if parse_decimal else float)
data = indexes(data, key_path)
else:
data = json.load(
file_obj, object_hook=decode,
parse_float=Decimal if parse_decimal else float)
elif hasattr(jfile, 'read'):
if key_path and not in_memory:
data = _file_with_keys(jfile, key_path, parse_decimal)
elif key_path:
data = json.load(
jfile, object_hook=decode,
parse_float=Decimal if parse_decimal else float)
data = indexes(data, key_path)
else:
data = json.load(
jfile, object_hook=decode,
parse_float=Decimal if parse_decimal else float)
elif hasattr(jfile, 'iterdir'):
if jfile.is_file():
with jfile.open() as file_obj:
if key_path and not in_memory:
data = _file_with_keys(file_obj, key_path, parse_decimal)
elif key_path:
data = json.load(
file_obj, object_hook=decode,
parse_float=Decimal if parse_decimal else float)
data = indexes(data, key_path)
else:
data = json.load(
file_obj, object_hook=decode,
parse_float=Decimal if parse_decimal else float)
else:
data = {}
_folder_to_json(jfile, key_path[:], in_memory, ignore_prefix,
data, parse_decimal)
if isinstance(list(data.keys())[0], _Terminus):
data = data.values()[0]
else:
raise ValueError(
'jfile should be a str, '
'file_like or path_like object: {}'.format(jfile))
return data | [
"def",
"to_dict",
"(",
"jfile",
",",
"key_path",
"=",
"None",
",",
"in_memory",
"=",
"True",
",",
"ignore_prefix",
"=",
"(",
"'.'",
",",
"'_'",
")",
",",
"parse_decimal",
"=",
"False",
")",
":",
"key_path",
"=",
"[",
"]",
"if",
"key_path",
"is",
"Non... | input json to dict
Parameters
----------
jfile : str, file_like or path_like
if str, must be existing file or folder,
if file_like, must have 'read' method
if path_like, must have 'iterdir' method (see pathlib.Path)
key_path : list[str]
a list of keys to index into the json before parsing it
in_memory : bool
if true reads full json into memory before filtering keys
(this is faster but uses more memory)
ignore_prefix : list[str]
ignore folders beginning with these prefixes
parse_decimal : bool
whether to parse numbers as Decimal instances (retains exact precision)
Examples
--------
>>> from pprint import pformat
>>> from jsonextended.utils import MockPath
>>> file_obj = MockPath('test.json',is_file=True,
... content='''
... {
... "a": 1,
... "b": [1.1,2.1],
... "c": {"d":"e"}
... }
... ''')
...
>>> dstr = pformat(to_dict(file_obj))
>>> print(dstr.replace("u'","'"))
{'a': 1, 'b': [1.1, 2.1], 'c': {'d': 'e'}}
>>> dstr = pformat(to_dict(file_obj,parse_decimal=True))
>>> print(dstr.replace("u'","'"))
{'a': 1, 'b': [Decimal('1.1'), Decimal('2.1')], 'c': {'d': 'e'}}
>>> str(to_dict(file_obj,["c","d"]))
'e'
>>> from jsonextended.utils import get_test_path
>>> path = get_test_path()
>>> jdict1 = to_dict(path)
>>> pprint(jdict1,depth=2)
dir1:
dir1_1: {...}
file1: {...}
file2: {...}
dir2:
file1: {...}
dir3:
>>> jdict2 = to_dict(path,['dir1','file1','initial'],in_memory=False)
>>> pprint(jdict2,depth=1)
crystallographic: {...}
primitive: {...} | [
"input",
"json",
"to",
"dict"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/ejson.py#L332-L459 | train | 53,589 |
portfoliome/foil | foil/iteration.py | chunks | def chunks(items, chunksize):
"""Turn generator sequence into sequence of chunks."""
items = iter(items)
for first in items:
chunk = chain((first,), islice(items, chunksize - 1))
yield chunk
deque(chunk, 0) | python | def chunks(items, chunksize):
"""Turn generator sequence into sequence of chunks."""
items = iter(items)
for first in items:
chunk = chain((first,), islice(items, chunksize - 1))
yield chunk
deque(chunk, 0) | [
"def",
"chunks",
"(",
"items",
",",
"chunksize",
")",
":",
"items",
"=",
"iter",
"(",
"items",
")",
"for",
"first",
"in",
"items",
":",
"chunk",
"=",
"chain",
"(",
"(",
"first",
",",
")",
",",
"islice",
"(",
"items",
",",
"chunksize",
"-",
"1",
"... | Turn generator sequence into sequence of chunks. | [
"Turn",
"generator",
"sequence",
"into",
"sequence",
"of",
"chunks",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/iteration.py#L5-L12 | train | 53,590 |
PolyJIT/benchbuild | benchbuild/utils/unionfs.py | unionfs | def unionfs(rw='rw', ro=None, union='union'):
"""
Decorator for the UnionFS feature.
This configures a unionfs for projects. The given base_dir and/or image_dir
are layered as follows:
image_dir=RW:base_dir=RO
All writes go to the image_dir, while base_dir delivers the (read-only)
versions of the rest of the filesystem.
The unified version will be provided in the project's builddir. Unmouting
is done as soon as the function completes.
Args:
rw: writeable storage area for the unified fuse filesystem.
ro: read-only storage area for the unified fuse filesystem.
union: mountpoint of the unified fuse filesystem.
"""
from functools import wraps
def wrap_in_union_fs(func):
"""
Function that wraps a given function inside the file system.
Args:
func: The function that needs to be wrapped inside the unions fs.
Return:
The file system with the function wrapped inside.
"""
@wraps(func)
def wrap_in_union_fs_func(project, *args, **kwargs):
"""
Wrap the func in the UnionFS mount stack.
We make sure that the mount points all exist and stack up the
directories for the unionfs. All directories outside of the default
build environment are tracked for deletion.
"""
container = project.container
if container is None or in_container():
return func(project, *args, **kwargs)
build_dir = local.path(project.builddir)
LOG.debug("UnionFS - Project builddir: %s", project.builddir)
if __unionfs_is_active(root=build_dir):
LOG.debug(
"UnionFS already active in %s, nesting not supported.",
build_dir)
return func(project, *args, **kwargs)
ro_dir = local.path(container.local)
rw_dir = build_dir / rw
un_dir = build_dir / union
LOG.debug("UnionFS - RW: %s", rw_dir)
unionfs_cmd = __unionfs_set_up(ro_dir, rw_dir, un_dir)
project_builddir_bak = project.builddir
project.builddir = un_dir
proc = unionfs_cmd.popen()
while (not __unionfs_is_active(root=un_dir)) and \
(proc.poll() is None):
pass
ret = None
if proc.poll() is None:
try:
with local.cwd(un_dir):
ret = func(project, *args, **kwargs)
finally:
project.builddir = project_builddir_bak
from signal import SIGINT
is_running = proc.poll() is None
while __unionfs_is_active(root=un_dir) and is_running:
try:
proc.send_signal(SIGINT)
proc.wait(timeout=3)
except subprocess.TimeoutExpired:
proc.kill()
is_running = False
LOG.debug("Unionfs shut down.")
if __unionfs_is_active(root=un_dir):
raise UnmountError()
return ret
return wrap_in_union_fs_func
return wrap_in_union_fs | python | def unionfs(rw='rw', ro=None, union='union'):
"""
Decorator for the UnionFS feature.
This configures a unionfs for projects. The given base_dir and/or image_dir
are layered as follows:
image_dir=RW:base_dir=RO
All writes go to the image_dir, while base_dir delivers the (read-only)
versions of the rest of the filesystem.
The unified version will be provided in the project's builddir. Unmouting
is done as soon as the function completes.
Args:
rw: writeable storage area for the unified fuse filesystem.
ro: read-only storage area for the unified fuse filesystem.
union: mountpoint of the unified fuse filesystem.
"""
from functools import wraps
def wrap_in_union_fs(func):
"""
Function that wraps a given function inside the file system.
Args:
func: The function that needs to be wrapped inside the unions fs.
Return:
The file system with the function wrapped inside.
"""
@wraps(func)
def wrap_in_union_fs_func(project, *args, **kwargs):
"""
Wrap the func in the UnionFS mount stack.
We make sure that the mount points all exist and stack up the
directories for the unionfs. All directories outside of the default
build environment are tracked for deletion.
"""
container = project.container
if container is None or in_container():
return func(project, *args, **kwargs)
build_dir = local.path(project.builddir)
LOG.debug("UnionFS - Project builddir: %s", project.builddir)
if __unionfs_is_active(root=build_dir):
LOG.debug(
"UnionFS already active in %s, nesting not supported.",
build_dir)
return func(project, *args, **kwargs)
ro_dir = local.path(container.local)
rw_dir = build_dir / rw
un_dir = build_dir / union
LOG.debug("UnionFS - RW: %s", rw_dir)
unionfs_cmd = __unionfs_set_up(ro_dir, rw_dir, un_dir)
project_builddir_bak = project.builddir
project.builddir = un_dir
proc = unionfs_cmd.popen()
while (not __unionfs_is_active(root=un_dir)) and \
(proc.poll() is None):
pass
ret = None
if proc.poll() is None:
try:
with local.cwd(un_dir):
ret = func(project, *args, **kwargs)
finally:
project.builddir = project_builddir_bak
from signal import SIGINT
is_running = proc.poll() is None
while __unionfs_is_active(root=un_dir) and is_running:
try:
proc.send_signal(SIGINT)
proc.wait(timeout=3)
except subprocess.TimeoutExpired:
proc.kill()
is_running = False
LOG.debug("Unionfs shut down.")
if __unionfs_is_active(root=un_dir):
raise UnmountError()
return ret
return wrap_in_union_fs_func
return wrap_in_union_fs | [
"def",
"unionfs",
"(",
"rw",
"=",
"'rw'",
",",
"ro",
"=",
"None",
",",
"union",
"=",
"'union'",
")",
":",
"from",
"functools",
"import",
"wraps",
"def",
"wrap_in_union_fs",
"(",
"func",
")",
":",
"\"\"\"\n Function that wraps a given function inside the fil... | Decorator for the UnionFS feature.
This configures a unionfs for projects. The given base_dir and/or image_dir
are layered as follows:
image_dir=RW:base_dir=RO
All writes go to the image_dir, while base_dir delivers the (read-only)
versions of the rest of the filesystem.
The unified version will be provided in the project's builddir. Unmouting
is done as soon as the function completes.
Args:
rw: writeable storage area for the unified fuse filesystem.
ro: read-only storage area for the unified fuse filesystem.
union: mountpoint of the unified fuse filesystem. | [
"Decorator",
"for",
"the",
"UnionFS",
"feature",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/unionfs.py#L14-L105 | train | 53,591 |
PolyJIT/benchbuild | benchbuild/utils/unionfs.py | __update_cleanup_paths | def __update_cleanup_paths(new_path):
"""
Add the new path to the list of paths to clean up afterwards.
Args:
new_path: Path to the directory that need to be cleaned up.
"""
cleanup_dirs = settings.CFG["cleanup_paths"].value
cleanup_dirs = set(cleanup_dirs)
cleanup_dirs.add(new_path)
cleanup_dirs = list(cleanup_dirs)
settings.CFG["cleanup_paths"] = cleanup_dirs | python | def __update_cleanup_paths(new_path):
"""
Add the new path to the list of paths to clean up afterwards.
Args:
new_path: Path to the directory that need to be cleaned up.
"""
cleanup_dirs = settings.CFG["cleanup_paths"].value
cleanup_dirs = set(cleanup_dirs)
cleanup_dirs.add(new_path)
cleanup_dirs = list(cleanup_dirs)
settings.CFG["cleanup_paths"] = cleanup_dirs | [
"def",
"__update_cleanup_paths",
"(",
"new_path",
")",
":",
"cleanup_dirs",
"=",
"settings",
".",
"CFG",
"[",
"\"cleanup_paths\"",
"]",
".",
"value",
"cleanup_dirs",
"=",
"set",
"(",
"cleanup_dirs",
")",
"cleanup_dirs",
".",
"add",
"(",
"new_path",
")",
"clean... | Add the new path to the list of paths to clean up afterwards.
Args:
new_path: Path to the directory that need to be cleaned up. | [
"Add",
"the",
"new",
"path",
"to",
"the",
"list",
"of",
"paths",
"to",
"clean",
"up",
"afterwards",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/unionfs.py#L108-L119 | train | 53,592 |
PolyJIT/benchbuild | benchbuild/utils/unionfs.py | __is_outside_of_builddir | def __is_outside_of_builddir(project, path_to_check):
"""Check if a project lies outside of its expected directory."""
bdir = project.builddir
cprefix = os.path.commonprefix([path_to_check, bdir])
return cprefix != bdir | python | def __is_outside_of_builddir(project, path_to_check):
"""Check if a project lies outside of its expected directory."""
bdir = project.builddir
cprefix = os.path.commonprefix([path_to_check, bdir])
return cprefix != bdir | [
"def",
"__is_outside_of_builddir",
"(",
"project",
",",
"path_to_check",
")",
":",
"bdir",
"=",
"project",
".",
"builddir",
"cprefix",
"=",
"os",
".",
"path",
".",
"commonprefix",
"(",
"[",
"path_to_check",
",",
"bdir",
"]",
")",
"return",
"cprefix",
"!=",
... | Check if a project lies outside of its expected directory. | [
"Check",
"if",
"a",
"project",
"lies",
"outside",
"of",
"its",
"expected",
"directory",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/unionfs.py#L122-L126 | train | 53,593 |
PolyJIT/benchbuild | benchbuild/utils/unionfs.py | __unionfs_set_up | def __unionfs_set_up(ro_dir, rw_dir, mount_dir):
"""
Setup a unionfs via unionfs-fuse.
Args:
ro_base: base_directory of the project
rw_image: virtual image of actual file system
mountpoint: location where ro_base and rw_image merge
"""
mount_dir.mkdir()
rw_dir.mkdir()
if not ro_dir.exists():
LOG.error("Base dir does not exist: '%s'", ro_dir)
raise ValueError("Base directory does not exist")
from benchbuild.utils.cmd import unionfs as unionfs_cmd
LOG.debug("Mounting UnionFS on %s with RO:%s RW:%s", mount_dir, ro_dir,
rw_dir)
return unionfs_cmd["-f", "-o", "auto_unmount,allow_other,cow", rw_dir +
"=RW:" + ro_dir + "=RO", mount_dir] | python | def __unionfs_set_up(ro_dir, rw_dir, mount_dir):
"""
Setup a unionfs via unionfs-fuse.
Args:
ro_base: base_directory of the project
rw_image: virtual image of actual file system
mountpoint: location where ro_base and rw_image merge
"""
mount_dir.mkdir()
rw_dir.mkdir()
if not ro_dir.exists():
LOG.error("Base dir does not exist: '%s'", ro_dir)
raise ValueError("Base directory does not exist")
from benchbuild.utils.cmd import unionfs as unionfs_cmd
LOG.debug("Mounting UnionFS on %s with RO:%s RW:%s", mount_dir, ro_dir,
rw_dir)
return unionfs_cmd["-f", "-o", "auto_unmount,allow_other,cow", rw_dir +
"=RW:" + ro_dir + "=RO", mount_dir] | [
"def",
"__unionfs_set_up",
"(",
"ro_dir",
",",
"rw_dir",
",",
"mount_dir",
")",
":",
"mount_dir",
".",
"mkdir",
"(",
")",
"rw_dir",
".",
"mkdir",
"(",
")",
"if",
"not",
"ro_dir",
".",
"exists",
"(",
")",
":",
"LOG",
".",
"error",
"(",
"\"Base dir does ... | Setup a unionfs via unionfs-fuse.
Args:
ro_base: base_directory of the project
rw_image: virtual image of actual file system
mountpoint: location where ro_base and rw_image merge | [
"Setup",
"a",
"unionfs",
"via",
"unionfs",
"-",
"fuse",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/unionfs.py#L138-L157 | train | 53,594 |
BlueBrain/hpcbench | hpcbench/benchmark/hpl.py | get_precision_regex | def get_precision_regex():
"""Build regular expression used to extract precision
metric from command output"""
expr = re.escape(PRECISION_FORMULA)
expr += r'=\s*(\S*)\s.*\s([A-Z]*)'
return re.compile(expr) | python | def get_precision_regex():
"""Build regular expression used to extract precision
metric from command output"""
expr = re.escape(PRECISION_FORMULA)
expr += r'=\s*(\S*)\s.*\s([A-Z]*)'
return re.compile(expr) | [
"def",
"get_precision_regex",
"(",
")",
":",
"expr",
"=",
"re",
".",
"escape",
"(",
"PRECISION_FORMULA",
")",
"expr",
"+=",
"r'=\\s*(\\S*)\\s.*\\s([A-Z]*)'",
"return",
"re",
".",
"compile",
"(",
"expr",
")"
] | Build regular expression used to extract precision
metric from command output | [
"Build",
"regular",
"expression",
"used",
"to",
"extract",
"precision",
"metric",
"from",
"command",
"output"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/hpl.py#L19-L24 | train | 53,595 |
BlueBrain/hpcbench | hpcbench/benchmark/hpl.py | HPL._build_data | def _build_data(self):
"""Build HPL data from basic parameters"""
def baseN(nodes, mpn):
return int(math.sqrt(mpn * 0.80 * nodes * 1024 * 1024 / 8))
def nFromNb(baseN, nb):
factor = int(baseN / nb)
if factor % 2 != 0:
factor -= 1
return nb * factor
def get_grid(nodes, ppn):
cores = nodes * ppn
sqrt = math.sqrt(cores)
factors = [
num for num in range(2, int(math.floor(sqrt) + 1)) if cores % num == 0
]
if len(factors) == 0:
factors = [1]
diff = 0
keep = 0
for factor in factors:
if diff == 0:
diff = cores - factor
if keep == 0:
keep = factor
tmp_diff = cores - factor
if tmp_diff < diff:
diff = tmp_diff
keep = factor
return [keep, int(cores / keep)]
properties = dict(
realN=nFromNb(baseN(self.nodes, self.memory_per_node), self.block_size),
nb=self.block_size,
pQ=get_grid(self.nodes, self.cores_per_node),
)
return self._data_from_jinja(**properties) | python | def _build_data(self):
"""Build HPL data from basic parameters"""
def baseN(nodes, mpn):
return int(math.sqrt(mpn * 0.80 * nodes * 1024 * 1024 / 8))
def nFromNb(baseN, nb):
factor = int(baseN / nb)
if factor % 2 != 0:
factor -= 1
return nb * factor
def get_grid(nodes, ppn):
cores = nodes * ppn
sqrt = math.sqrt(cores)
factors = [
num for num in range(2, int(math.floor(sqrt) + 1)) if cores % num == 0
]
if len(factors) == 0:
factors = [1]
diff = 0
keep = 0
for factor in factors:
if diff == 0:
diff = cores - factor
if keep == 0:
keep = factor
tmp_diff = cores - factor
if tmp_diff < diff:
diff = tmp_diff
keep = factor
return [keep, int(cores / keep)]
properties = dict(
realN=nFromNb(baseN(self.nodes, self.memory_per_node), self.block_size),
nb=self.block_size,
pQ=get_grid(self.nodes, self.cores_per_node),
)
return self._data_from_jinja(**properties) | [
"def",
"_build_data",
"(",
"self",
")",
":",
"def",
"baseN",
"(",
"nodes",
",",
"mpn",
")",
":",
"return",
"int",
"(",
"math",
".",
"sqrt",
"(",
"mpn",
"*",
"0.80",
"*",
"nodes",
"*",
"1024",
"*",
"1024",
"/",
"8",
")",
")",
"def",
"nFromNb",
"... | Build HPL data from basic parameters | [
"Build",
"HPL",
"data",
"from",
"basic",
"parameters"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/hpl.py#L212-L251 | train | 53,596 |
BlueBrain/hpcbench | hpcbench/benchmark/hpl.py | HPL.mpirun | def mpirun(self):
"""Additional options passed as a list to the ``mpirun`` command"""
cmd = self.attributes['mpirun']
if cmd and cmd[0] != 'mpirun':
cmd = ['mpirun']
return [str(e) for e in cmd] | python | def mpirun(self):
"""Additional options passed as a list to the ``mpirun`` command"""
cmd = self.attributes['mpirun']
if cmd and cmd[0] != 'mpirun':
cmd = ['mpirun']
return [str(e) for e in cmd] | [
"def",
"mpirun",
"(",
"self",
")",
":",
"cmd",
"=",
"self",
".",
"attributes",
"[",
"'mpirun'",
"]",
"if",
"cmd",
"and",
"cmd",
"[",
"0",
"]",
"!=",
"'mpirun'",
":",
"cmd",
"=",
"[",
"'mpirun'",
"]",
"return",
"[",
"str",
"(",
"e",
")",
"for",
... | Additional options passed as a list to the ``mpirun`` command | [
"Additional",
"options",
"passed",
"as",
"a",
"list",
"to",
"the",
"mpirun",
"command"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/hpl.py#L263-L268 | train | 53,597 |
BlueBrain/hpcbench | hpcbench/toolbox/env.py | expandvars | def expandvars(s, vars=None):
"""Perform variable substitution on the given string
Supported syntax:
* $VARIABLE
* ${VARIABLE}
* ${#VARIABLE}
* ${VARIABLE:-default}
:param s: message to expand
:type s: str
:param vars: dictionary of variables. Default is ``os.environ``
:type vars: dict
:return: expanded string
:rtype: str
"""
tpl = TemplateWithDefaults(s)
return tpl.substitute(vars or os.environ) | python | def expandvars(s, vars=None):
"""Perform variable substitution on the given string
Supported syntax:
* $VARIABLE
* ${VARIABLE}
* ${#VARIABLE}
* ${VARIABLE:-default}
:param s: message to expand
:type s: str
:param vars: dictionary of variables. Default is ``os.environ``
:type vars: dict
:return: expanded string
:rtype: str
"""
tpl = TemplateWithDefaults(s)
return tpl.substitute(vars or os.environ) | [
"def",
"expandvars",
"(",
"s",
",",
"vars",
"=",
"None",
")",
":",
"tpl",
"=",
"TemplateWithDefaults",
"(",
"s",
")",
"return",
"tpl",
".",
"substitute",
"(",
"vars",
"or",
"os",
".",
"environ",
")"
] | Perform variable substitution on the given string
Supported syntax:
* $VARIABLE
* ${VARIABLE}
* ${#VARIABLE}
* ${VARIABLE:-default}
:param s: message to expand
:type s: str
:param vars: dictionary of variables. Default is ``os.environ``
:type vars: dict
:return: expanded string
:rtype: str | [
"Perform",
"variable",
"substitution",
"on",
"the",
"given",
"string"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/env.py#L35-L54 | train | 53,598 |
BlueBrain/hpcbench | hpcbench/toolbox/edsl.py | kwargsql.xor | def xor(cls, obj, **kwargs):
"""Query an object.
:param obj:
object to test
:param kwargs: query specified in kwargssql
:return:
`True` if exactly one `kwargs` expression is `True`,
`False` otherwise.
:rtype: bool
"""
return cls.__eval_seqexp(obj, operator.xor, **kwargs) | python | def xor(cls, obj, **kwargs):
"""Query an object.
:param obj:
object to test
:param kwargs: query specified in kwargssql
:return:
`True` if exactly one `kwargs` expression is `True`,
`False` otherwise.
:rtype: bool
"""
return cls.__eval_seqexp(obj, operator.xor, **kwargs) | [
"def",
"xor",
"(",
"cls",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"__eval_seqexp",
"(",
"obj",
",",
"operator",
".",
"xor",
",",
"*",
"*",
"kwargs",
")"
] | Query an object.
:param obj:
object to test
:param kwargs: query specified in kwargssql
:return:
`True` if exactly one `kwargs` expression is `True`,
`False` otherwise.
:rtype: bool | [
"Query",
"an",
"object",
"."
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/edsl.py#L158-L171 | train | 53,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.