repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
elifesciences/elife-tools | elifetools/parseJATS.py | https://github.com/elifesciences/elife-tools/blob/4b9e38cbe485c61a4ed7cbd8970c6b318334fd86/elifetools/parseJATS.py#L37-L45 | def title_prefix(soup):
"titlePrefix for article JSON is only articles with certain display_channel values"
prefix = None
display_channel_match_list = ['feature article', 'insight', 'editorial']
for d_channel in display_channel(soup):
if d_channel.lower() in display_channel_match_list:
... | [
"def",
"title_prefix",
"(",
"soup",
")",
":",
"prefix",
"=",
"None",
"display_channel_match_list",
"=",
"[",
"'feature article'",
",",
"'insight'",
",",
"'editorial'",
"]",
"for",
"d_channel",
"in",
"display_channel",
"(",
"soup",
")",
":",
"if",
"d_channel",
... | titlePrefix for article JSON is only articles with certain display_channel values | [
"titlePrefix",
"for",
"article",
"JSON",
"is",
"only",
"articles",
"with",
"certain",
"display_channel",
"values"
] | python | train |
tsroten/pynlpir | pynlpir/pos_map.py | https://github.com/tsroten/pynlpir/blob/8d5e994796a2b5d513f7db8d76d7d24a85d531b1/pynlpir/pos_map.py#L173-L191 | def get_pos_name(code, name='parent', english=True, pos_tags=POS_MAP):
"""Gets the part of speech name for *code*.
:param str code: The part of speech code to lookup, e.g. ``'nsf'``.
:param str name: Which part of speech name to include in the output. Must
be one of ``'parent'``, ``'child'``, or ``... | [
"def",
"get_pos_name",
"(",
"code",
",",
"name",
"=",
"'parent'",
",",
"english",
"=",
"True",
",",
"pos_tags",
"=",
"POS_MAP",
")",
":",
"return",
"_get_pos_name",
"(",
"code",
",",
"name",
",",
"english",
",",
"pos_tags",
")"
] | Gets the part of speech name for *code*.
:param str code: The part of speech code to lookup, e.g. ``'nsf'``.
:param str name: Which part of speech name to include in the output. Must
be one of ``'parent'``, ``'child'``, or ``'all'``. Defaults to
``'parent'``. ``'parent'`` indicates that only th... | [
"Gets",
"the",
"part",
"of",
"speech",
"name",
"for",
"*",
"code",
"*",
"."
] | python | train |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/symbol/symbol_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/symbol/symbol_client.py#L72-L93 | def create_requests_request_id_debug_entries(self, batch, request_id, collection):
"""CreateRequestsRequestIdDebugEntries.
[Preview API] Create debug entries for a symbol request as specified by its identifier.
:param :class:`<DebugEntryCreateBatch> <azure.devops.v5_0.symbol.models.DebugEntryCre... | [
"def",
"create_requests_request_id_debug_entries",
"(",
"self",
",",
"batch",
",",
"request_id",
",",
"collection",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"request_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'requestId'",
"]",
"=",
"self",
"."... | CreateRequestsRequestIdDebugEntries.
[Preview API] Create debug entries for a symbol request as specified by its identifier.
:param :class:`<DebugEntryCreateBatch> <azure.devops.v5_0.symbol.models.DebugEntryCreateBatch>` batch: A batch that contains debug entries to create.
:param str request_id... | [
"CreateRequestsRequestIdDebugEntries",
".",
"[",
"Preview",
"API",
"]",
"Create",
"debug",
"entries",
"for",
"a",
"symbol",
"request",
"as",
"specified",
"by",
"its",
"identifier",
".",
":",
"param",
":",
"class",
":",
"<DebugEntryCreateBatch",
">",
"<azure",
".... | python | train |
nikcub/floyd | floyd/util/dateformat.py | https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/floyd/util/dateformat.py#L377-L388 | def Z(self):
"""
Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
timezones west of UTC is always negative, and for those east of UTC is
always positive.
"""
if not self.timezone:
return 0
offset = self.timezone.utcoffset(self.data)
# Only days can be negative... | [
"def",
"Z",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"timezone",
":",
"return",
"0",
"offset",
"=",
"self",
".",
"timezone",
".",
"utcoffset",
"(",
"self",
".",
"data",
")",
"# Only days can be negative, so negative offsets have days=-1 and",
"# seconds ... | Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
timezones west of UTC is always negative, and for those east of UTC is
always positive. | [
"Time",
"zone",
"offset",
"in",
"seconds",
"(",
"i",
".",
"e",
".",
"-",
"43200",
"to",
"43200",
")",
".",
"The",
"offset",
"for",
"timezones",
"west",
"of",
"UTC",
"is",
"always",
"negative",
"and",
"for",
"those",
"east",
"of",
"UTC",
"is",
"always... | python | train |
kislyuk/aegea | aegea/packages/github3/github.py | https://github.com/kislyuk/aegea/blob/94957e9dba036eae3052e2662c208b259c08399a/aegea/packages/github3/github.py#L1052-L1064 | def repository(self, owner, repository):
"""Returns a Repository object for the specified combination of
owner and repository
:param str owner: (required)
:param str repository: (required)
:returns: :class:`Repository <github3.repos.Repository>`
"""
json = None
... | [
"def",
"repository",
"(",
"self",
",",
"owner",
",",
"repository",
")",
":",
"json",
"=",
"None",
"if",
"owner",
"and",
"repository",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'repos'",
",",
"owner",
",",
"repository",
")",
"json",
"=",
"self",... | Returns a Repository object for the specified combination of
owner and repository
:param str owner: (required)
:param str repository: (required)
:returns: :class:`Repository <github3.repos.Repository>` | [
"Returns",
"a",
"Repository",
"object",
"for",
"the",
"specified",
"combination",
"of",
"owner",
"and",
"repository"
] | python | train |
hyperledger/sawtooth-core | rest_api/sawtooth_rest_api/route_handlers.py | https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/rest_api/sawtooth_rest_api/route_handlers.py#L124-L185 | async def submit_batches(self, request):
"""Accepts a binary encoded BatchList and submits it to the validator.
Request:
body: octet-stream BatchList of one or more Batches
Response:
status:
- 202: Batches submitted and pending
link: /batches... | [
"async",
"def",
"submit_batches",
"(",
"self",
",",
"request",
")",
":",
"timer_ctx",
"=",
"self",
".",
"_post_batches_total_time",
".",
"time",
"(",
")",
"self",
".",
"_post_batches_count",
".",
"inc",
"(",
")",
"# Parse request",
"if",
"request",
".",
"hea... | Accepts a binary encoded BatchList and submits it to the validator.
Request:
body: octet-stream BatchList of one or more Batches
Response:
status:
- 202: Batches submitted and pending
link: /batches or /batch_statuses link for submitted batches | [
"Accepts",
"a",
"binary",
"encoded",
"BatchList",
"and",
"submits",
"it",
"to",
"the",
"validator",
"."
] | python | train |
hectane/python-hectane | pyhectane/django.py | https://github.com/hectane/python-hectane/blob/e0fe1df576f776566e813f71782f8adf60146383/pyhectane/django.py#L55-L78 | def send_messages(self, emails):
"""
Attempt to send the specified emails.
"""
num_sent = 0
for e in emails:
html = None
if isinstance(e, EmailMultiAlternatives):
for a in e.alternatives:
if a[1] == 'text/html':
... | [
"def",
"send_messages",
"(",
"self",
",",
"emails",
")",
":",
"num_sent",
"=",
"0",
"for",
"e",
"in",
"emails",
":",
"html",
"=",
"None",
"if",
"isinstance",
"(",
"e",
",",
"EmailMultiAlternatives",
")",
":",
"for",
"a",
"in",
"e",
".",
"alternatives",... | Attempt to send the specified emails. | [
"Attempt",
"to",
"send",
"the",
"specified",
"emails",
"."
] | python | train |
gusutabopb/aioinflux | aioinflux/serialization/usertype.py | https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/usertype.py#L67-L122 | def _make_serializer(meas, schema, rm_none, extra_tags, placeholder): # noqa: C901
"""Factory of line protocol parsers"""
_validate_schema(schema, placeholder)
tags = []
fields = []
ts = None
meas = meas
for k, t in schema.items():
if t is MEASUREMENT:
meas = f"{{i.{k}}}... | [
"def",
"_make_serializer",
"(",
"meas",
",",
"schema",
",",
"rm_none",
",",
"extra_tags",
",",
"placeholder",
")",
":",
"# noqa: C901",
"_validate_schema",
"(",
"schema",
",",
"placeholder",
")",
"tags",
"=",
"[",
"]",
"fields",
"=",
"[",
"]",
"ts",
"=",
... | Factory of line protocol parsers | [
"Factory",
"of",
"line",
"protocol",
"parsers"
] | python | train |
jfear/sramongo | sramongo/services/entrez.py | https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/services/entrez.py#L86-L115 | def epost(database, ids: List[str], webenv=False, api_key=False, email=False, **kwargs) -> Optional[EpostResult]:
"""Post IDs using the Entrez ESearch API.
Parameters
----------
database : str
Entez database to search.
ids : list
List of IDs to submit to the server.
webenv : str... | [
"def",
"epost",
"(",
"database",
",",
"ids",
":",
"List",
"[",
"str",
"]",
",",
"webenv",
"=",
"False",
",",
"api_key",
"=",
"False",
",",
"email",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
"->",
"Optional",
"[",
"EpostResult",
"]",
":",
"url",
... | Post IDs using the Entrez ESearch API.
Parameters
----------
database : str
Entez database to search.
ids : list
List of IDs to submit to the server.
webenv : str
An Entrez WebEnv to post ids to.
api_key : str
A users API key which allows more requests per second... | [
"Post",
"IDs",
"using",
"the",
"Entrez",
"ESearch",
"API",
"."
] | python | train |
libtcod/python-tcod | tcod/random.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/random.py#L58-L62 | def _new_from_cdata(cls, cdata: Any) -> "Random":
"""Return a new instance encapsulating this cdata."""
self = object.__new__(cls) # type: "Random"
self.random_c = cdata
return self | [
"def",
"_new_from_cdata",
"(",
"cls",
",",
"cdata",
":",
"Any",
")",
"->",
"\"Random\"",
":",
"self",
"=",
"object",
".",
"__new__",
"(",
"cls",
")",
"# type: \"Random\"",
"self",
".",
"random_c",
"=",
"cdata",
"return",
"self"
] | Return a new instance encapsulating this cdata. | [
"Return",
"a",
"new",
"instance",
"encapsulating",
"this",
"cdata",
"."
] | python | train |
biolink/ontobio | ontobio/sparql/rdflib_bridge.py | https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/sparql/rdflib_bridge.py#L15-L44 | def rdfgraph_to_ontol(rg):
"""
Return an Ontology object from an rdflib graph object
Status: Incomplete
"""
digraph = networkx.MultiDiGraph()
from rdflib.namespace import RDF
label_map = {}
for c in rg.subjects(RDF.type, OWL.Class):
cid = contract_uri_wrap(c)
logging.inf... | [
"def",
"rdfgraph_to_ontol",
"(",
"rg",
")",
":",
"digraph",
"=",
"networkx",
".",
"MultiDiGraph",
"(",
")",
"from",
"rdflib",
".",
"namespace",
"import",
"RDF",
"label_map",
"=",
"{",
"}",
"for",
"c",
"in",
"rg",
".",
"subjects",
"(",
"RDF",
".",
"type... | Return an Ontology object from an rdflib graph object
Status: Incomplete | [
"Return",
"an",
"Ontology",
"object",
"from",
"an",
"rdflib",
"graph",
"object"
] | python | train |
aiortc/aiortc | aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/60ed036abf4575bd63985724b4493d569e6da29b/aiortc/rtcpeerconnection.py#L319-L343 | def addTrack(self, track):
"""
Add a :class:`MediaStreamTrack` to the set of media tracks which
will be transmitted to the remote peer.
"""
# check state is valid
self.__assertNotClosed()
if track.kind not in ['audio', 'video']:
raise InternalError('In... | [
"def",
"addTrack",
"(",
"self",
",",
"track",
")",
":",
"# check state is valid",
"self",
".",
"__assertNotClosed",
"(",
")",
"if",
"track",
".",
"kind",
"not",
"in",
"[",
"'audio'",
",",
"'video'",
"]",
":",
"raise",
"InternalError",
"(",
"'Invalid track ki... | Add a :class:`MediaStreamTrack` to the set of media tracks which
will be transmitted to the remote peer. | [
"Add",
"a",
":",
"class",
":",
"MediaStreamTrack",
"to",
"the",
"set",
"of",
"media",
"tracks",
"which",
"will",
"be",
"transmitted",
"to",
"the",
"remote",
"peer",
"."
] | python | train |
molmod/molmod | molmod/io/cube.py | https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/io/cube.py#L260-L267 | def copy(self, newdata=None):
'''Return a copy of the cube with optionally new data.'''
if newdata is None:
newdata = self.data.copy()
return self.__class__(
self.molecule, self.origin.copy(), self.axes.copy(),
self.nrep.copy(), newdata, self.subtitle, self.nu... | [
"def",
"copy",
"(",
"self",
",",
"newdata",
"=",
"None",
")",
":",
"if",
"newdata",
"is",
"None",
":",
"newdata",
"=",
"self",
".",
"data",
".",
"copy",
"(",
")",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"molecule",
",",
"self",
".",
... | Return a copy of the cube with optionally new data. | [
"Return",
"a",
"copy",
"of",
"the",
"cube",
"with",
"optionally",
"new",
"data",
"."
] | python | train |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/publisher/plos.py | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/publisher/plos.py#L1192-L1216 | def convert_ref_list_elements(self):
"""
List of references (citations) for an article, which is often called
“References”, “Bibliography”, or “Additional Reading”.
No distinction is made between lists of cited references and lists of
suggested references.
This method s... | [
"def",
"convert_ref_list_elements",
"(",
"self",
")",
":",
"#TODO: Handle nested ref-lists",
"for",
"ref_list",
"in",
"self",
".",
"main",
".",
"getroot",
"(",
")",
".",
"findall",
"(",
"'.//ref-list'",
")",
":",
"remove_all_attributes",
"(",
"ref_list",
")",
"r... | List of references (citations) for an article, which is often called
“References”, “Bibliography”, or “Additional Reading”.
No distinction is made between lists of cited references and lists of
suggested references.
This method should not be confused with the method(s) employed for the... | [
"List",
"of",
"references",
"(",
"citations",
")",
"for",
"an",
"article",
"which",
"is",
"often",
"called",
"“References”",
"“Bibliography”",
"or",
"“Additional",
"Reading”",
"."
] | python | train |
night-crawler/django-docker-helpers | django_docker_helpers/utils.py | https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L143-L156 | def dotkey(obj: dict, path: str, default=None, separator='.'):
"""
Provides an interface to traverse nested dict values by dot-separated paths. Wrapper for ``dpath.util.get``.
:param obj: dict like ``{'some': {'value': 3}}``
:param path: ``'some.value'``
:param separator: ``'.'`` or ``'/'`` or what... | [
"def",
"dotkey",
"(",
"obj",
":",
"dict",
",",
"path",
":",
"str",
",",
"default",
"=",
"None",
",",
"separator",
"=",
"'.'",
")",
":",
"try",
":",
"return",
"get",
"(",
"obj",
",",
"path",
",",
"separator",
"=",
"separator",
")",
"except",
"KeyErr... | Provides an interface to traverse nested dict values by dot-separated paths. Wrapper for ``dpath.util.get``.
:param obj: dict like ``{'some': {'value': 3}}``
:param path: ``'some.value'``
:param separator: ``'.'`` or ``'/'`` or whatever
:param default: default for KeyError
:return: dict value or de... | [
"Provides",
"an",
"interface",
"to",
"traverse",
"nested",
"dict",
"values",
"by",
"dot",
"-",
"separated",
"paths",
".",
"Wrapper",
"for",
"dpath",
".",
"util",
".",
"get",
"."
] | python | train |
saltstack/salt | salt/loader.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L913-L926 | def call(fun, **kwargs):
'''
Directly call a function inside a loader directory
'''
args = kwargs.get('args', [])
dirs = kwargs.get('dirs', [])
funcs = LazyLoader(
[os.path.join(SALT_BASE_PATH, 'modules')] + dirs,
None,
tag='modules',
virtual_enable=False,
)
... | [
"def",
"call",
"(",
"fun",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"kwargs",
".",
"get",
"(",
"'args'",
",",
"[",
"]",
")",
"dirs",
"=",
"kwargs",
".",
"get",
"(",
"'dirs'",
",",
"[",
"]",
")",
"funcs",
"=",
"LazyLoader",
"(",
"[",
"o... | Directly call a function inside a loader directory | [
"Directly",
"call",
"a",
"function",
"inside",
"a",
"loader",
"directory"
] | python | train |
materialsproject/pymatgen | pymatgen/electronic_structure/bandstructure.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/electronic_structure/bandstructure.py#L922-L959 | def from_old_dict(cls, d):
"""
Args:
d (dict): A dict with all data for a band structure symm line
object.
Returns:
A BandStructureSymmLine object
"""
# Strip the label to recover initial string (see trick used in as_dict to handle $ chars)... | [
"def",
"from_old_dict",
"(",
"cls",
",",
"d",
")",
":",
"# Strip the label to recover initial string (see trick used in as_dict to handle $ chars)",
"labels_dict",
"=",
"{",
"k",
".",
"strip",
"(",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"d",
"[",
"'labels_dict... | Args:
d (dict): A dict with all data for a band structure symm line
object.
Returns:
A BandStructureSymmLine object | [
"Args",
":",
"d",
"(",
"dict",
")",
":",
"A",
"dict",
"with",
"all",
"data",
"for",
"a",
"band",
"structure",
"symm",
"line",
"object",
".",
"Returns",
":",
"A",
"BandStructureSymmLine",
"object"
] | python | train |
pudo/jsongraph | jsongraph/context.py | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/context.py#L51-L59 | def delete(self):
""" Delete all statements matching the current context identifier
from the main store. """
if self.parent.buffered:
query = 'CLEAR SILENT GRAPH %s ;' % self.identifier.n3()
self.parent.graph.update(query)
self.flush()
else:
... | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
".",
"buffered",
":",
"query",
"=",
"'CLEAR SILENT GRAPH %s ;'",
"%",
"self",
".",
"identifier",
".",
"n3",
"(",
")",
"self",
".",
"parent",
".",
"graph",
".",
"update",
"(",
"query",... | Delete all statements matching the current context identifier
from the main store. | [
"Delete",
"all",
"statements",
"matching",
"the",
"current",
"context",
"identifier",
"from",
"the",
"main",
"store",
"."
] | python | train |
CitrineInformatics/pif-dft | dfttopif/parsers/base.py | https://github.com/CitrineInformatics/pif-dft/blob/d5411dc1f6c6e8d454b132977ca7ab3bb8131a80/dfttopif/parsers/base.py#L196-L205 | def is_converged(self):
'''Whether the calculation has converged
Returns: Property where "scalar" is a boolean indicating
'''
# Check for cached result
if self._converged is None:
self._converged = self._is_converged()
return Property(scalars=[Scalar... | [
"def",
"is_converged",
"(",
"self",
")",
":",
"# Check for cached result",
"if",
"self",
".",
"_converged",
"is",
"None",
":",
"self",
".",
"_converged",
"=",
"self",
".",
"_is_converged",
"(",
")",
"return",
"Property",
"(",
"scalars",
"=",
"[",
"Scalar",
... | Whether the calculation has converged
Returns: Property where "scalar" is a boolean indicating | [
"Whether",
"the",
"calculation",
"has",
"converged",
"Returns",
":",
"Property",
"where",
"scalar",
"is",
"a",
"boolean",
"indicating"
] | python | train |
tango-controls/pytango | tango/utils.py | https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/utils.py#L1170-L1180 | def findentry(self, item):
"""A caseless way of checking if an item is in the list or not.
It returns None or the entry."""
if not isinstance(item, str):
raise TypeError(
'Members of this object must be strings. '
'You supplied \"%s\"' % type(item))
... | [
"def",
"findentry",
"(",
"self",
",",
"item",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'Members of this object must be strings. '",
"'You supplied \\\"%s\\\"'",
"%",
"type",
"(",
"item",
")",
")",
"for... | A caseless way of checking if an item is in the list or not.
It returns None or the entry. | [
"A",
"caseless",
"way",
"of",
"checking",
"if",
"an",
"item",
"is",
"in",
"the",
"list",
"or",
"not",
".",
"It",
"returns",
"None",
"or",
"the",
"entry",
"."
] | python | train |
Ceasar/easywatch | easywatch/easywatch.py | https://github.com/Ceasar/easywatch/blob/1dd464d2acca5932473759b187dec4eb63dab2d9/easywatch/easywatch.py#L13-L36 | def watch(path, handler):
"""Watch a directory for events.
- path should be the directory to watch
- handler should a function which takes an event_type and src_path
and does something interesting. event_type will be one of 'created',
'deleted', 'modified', or 'moved'. src_path will be t... | [
"def",
"watch",
"(",
"path",
",",
"handler",
")",
":",
"# let the user just deal with events",
"@",
"functools",
".",
"wraps",
"(",
"handler",
")",
"def",
"wrapper",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"event",
".",
"is_directory",
":",
"retu... | Watch a directory for events.
- path should be the directory to watch
- handler should a function which takes an event_type and src_path
and does something interesting. event_type will be one of 'created',
'deleted', 'modified', or 'moved'. src_path will be the absolute
path to the f... | [
"Watch",
"a",
"directory",
"for",
"events",
".",
"-",
"path",
"should",
"be",
"the",
"directory",
"to",
"watch",
"-",
"handler",
"should",
"a",
"function",
"which",
"takes",
"an",
"event_type",
"and",
"src_path",
"and",
"does",
"something",
"interesting",
".... | python | train |
PyGithub/PyGithub | github/AuthenticatedUser.py | https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/AuthenticatedUser.py#L657-L667 | def get_authorizations(self):
"""
:calls: `GET /authorizations <http://developer.github.com/v3/oauth>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Authorization.Authorization`
"""
return github.PaginatedList.PaginatedList(
github.Authorizati... | [
"def",
"get_authorizations",
"(",
"self",
")",
":",
"return",
"github",
".",
"PaginatedList",
".",
"PaginatedList",
"(",
"github",
".",
"Authorization",
".",
"Authorization",
",",
"self",
".",
"_requester",
",",
"\"/authorizations\"",
",",
"None",
")"
] | :calls: `GET /authorizations <http://developer.github.com/v3/oauth>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Authorization.Authorization` | [
":",
"calls",
":",
"GET",
"/",
"authorizations",
"<http",
":",
"//",
"developer",
".",
"github",
".",
"com",
"/",
"v3",
"/",
"oauth",
">",
"_",
":",
"rtype",
":",
":",
"class",
":",
"github",
".",
"PaginatedList",
".",
"PaginatedList",
"of",
":",
"cl... | python | train |
soravux/scoop | scoop/backports/dictconfig.py | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/backports/dictconfig.py#L153-L174 | def resolve(self, s):
"""
Resolve strings to objects using standard import and attribute
syntax.
"""
name = s.split('.')
used = name.pop(0)
try:
found = self.importer(used)
for frag in name:
used += '.' + frag
... | [
"def",
"resolve",
"(",
"self",
",",
"s",
")",
":",
"name",
"=",
"s",
".",
"split",
"(",
"'.'",
")",
"used",
"=",
"name",
".",
"pop",
"(",
"0",
")",
"try",
":",
"found",
"=",
"self",
".",
"importer",
"(",
"used",
")",
"for",
"frag",
"in",
"nam... | Resolve strings to objects using standard import and attribute
syntax. | [
"Resolve",
"strings",
"to",
"objects",
"using",
"standard",
"import",
"and",
"attribute",
"syntax",
"."
] | python | train |
googledatalab/pydatalab | google/datalab/_context.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/_context.py#L102-L124 | def default():
"""Retrieves a default Context object, creating it if necessary.
The default Context is a global shared instance used every time the default context is
retrieved.
Attempting to use a Context with no project_id will raise an exception, so on first use
set_project_id must be c... | [
"def",
"default",
"(",
")",
":",
"credentials",
"=",
"du",
".",
"get_credentials",
"(",
")",
"project",
"=",
"du",
".",
"get_default_project_id",
"(",
")",
"if",
"Context",
".",
"_global_context",
"is",
"None",
":",
"config",
"=",
"Context",
".",
"_get_def... | Retrieves a default Context object, creating it if necessary.
The default Context is a global shared instance used every time the default context is
retrieved.
Attempting to use a Context with no project_id will raise an exception, so on first use
set_project_id must be called.
Returns:
... | [
"Retrieves",
"a",
"default",
"Context",
"object",
"creating",
"it",
"if",
"necessary",
"."
] | python | train |
josuebrunel/myql | myql/contrib/finance/stockscraper/stockretriever.py | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/finance/stockscraper/stockretriever.py#L49-L54 | def get_historical_info(self, symbol,items=None, startDate=None, endDate=None, limit=None):
"""get_historical_info() uses the csv datatable to retrieve all available historical data on a typical historical prices page
"""
startDate, endDate = self.__get_time_range(startDate, endDate)
res... | [
"def",
"get_historical_info",
"(",
"self",
",",
"symbol",
",",
"items",
"=",
"None",
",",
"startDate",
"=",
"None",
",",
"endDate",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"startDate",
",",
"endDate",
"=",
"self",
".",
"__get_time_range",
"(",
... | get_historical_info() uses the csv datatable to retrieve all available historical data on a typical historical prices page | [
"get_historical_info",
"()",
"uses",
"the",
"csv",
"datatable",
"to",
"retrieve",
"all",
"available",
"historical",
"data",
"on",
"a",
"typical",
"historical",
"prices",
"page"
] | python | train |
hovren/crisp | crisp/imu.py | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/imu.py#L66-L77 | def rate(self):
"""Get the sample rate in Hz.
Returns
---------
rate : float
The sample rate, in Hz, calculated from the timestamps
"""
N = len(self.timestamps)
t = self.timestamps[-1] - self.timestamps[0]
rate = 1.0 * N / ... | [
"def",
"rate",
"(",
"self",
")",
":",
"N",
"=",
"len",
"(",
"self",
".",
"timestamps",
")",
"t",
"=",
"self",
".",
"timestamps",
"[",
"-",
"1",
"]",
"-",
"self",
".",
"timestamps",
"[",
"0",
"]",
"rate",
"=",
"1.0",
"*",
"N",
"/",
"t",
"retur... | Get the sample rate in Hz.
Returns
---------
rate : float
The sample rate, in Hz, calculated from the timestamps | [
"Get",
"the",
"sample",
"rate",
"in",
"Hz",
".",
"Returns",
"---------",
"rate",
":",
"float",
"The",
"sample",
"rate",
"in",
"Hz",
"calculated",
"from",
"the",
"timestamps"
] | python | train |
rochacbruno/python-pagseguro | pagseguro/__init__.py | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L209-L211 | def get(self, url):
""" do a get transaction """
return requests.get(url, params=self.data, headers=self.config.HEADERS) | [
"def",
"get",
"(",
"self",
",",
"url",
")",
":",
"return",
"requests",
".",
"get",
"(",
"url",
",",
"params",
"=",
"self",
".",
"data",
",",
"headers",
"=",
"self",
".",
"config",
".",
"HEADERS",
")"
] | do a get transaction | [
"do",
"a",
"get",
"transaction"
] | python | train |
shmir/PyIxNetwork | ixnetwork/ixn_interface.py | https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/ixn_interface.py#L55-L68 | def _create(self, **attributes):
""" Create new interface on IxNetwork.
Set enabled and description (==name).
:return: interface object reference.
"""
attributes['enabled'] = True
if 'name' in self._data:
attributes['description'] = self._data['name']
... | [
"def",
"_create",
"(",
"self",
",",
"*",
"*",
"attributes",
")",
":",
"attributes",
"[",
"'enabled'",
"]",
"=",
"True",
"if",
"'name'",
"in",
"self",
".",
"_data",
":",
"attributes",
"[",
"'description'",
"]",
"=",
"self",
".",
"_data",
"[",
"'name'",
... | Create new interface on IxNetwork.
Set enabled and description (==name).
:return: interface object reference. | [
"Create",
"new",
"interface",
"on",
"IxNetwork",
"."
] | python | train |
hazelcast/hazelcast-python-client | hazelcast/proxy/transactional_map.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/transactional_map.py#L25-L33 | def get(self, key):
"""
Transactional implementation of :func:`Map.get(key) <hazelcast.proxy.map.Map.get>`
:param key: (object), the specified key.
:return: (object), the value for the specified key.
"""
check_not_none(key, "key can't be none")
return self._encod... | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"check_not_none",
"(",
"key",
",",
"\"key can't be none\"",
")",
"return",
"self",
".",
"_encode_invoke",
"(",
"transactional_map_get_codec",
",",
"key",
"=",
"self",
".",
"_to_data",
"(",
"key",
")",
")"
] | Transactional implementation of :func:`Map.get(key) <hazelcast.proxy.map.Map.get>`
:param key: (object), the specified key.
:return: (object), the value for the specified key. | [
"Transactional",
"implementation",
"of",
":",
"func",
":",
"Map",
".",
"get",
"(",
"key",
")",
"<hazelcast",
".",
"proxy",
".",
"map",
".",
"Map",
".",
"get",
">"
] | python | train |
summa-tx/riemann | riemann/tx/tx_builder.py | https://github.com/summa-tx/riemann/blob/04ae336dfd4007ceaed748daadc91cc32fa278ec/riemann/tx/tx_builder.py#L263-L319 | def make_tx(version, tx_ins, tx_outs, lock_time,
expiry=None, value_balance=0, tx_shielded_spends=None,
tx_shielded_outputs=None, tx_witnesses=None, tx_joinsplits=None,
joinsplit_pubkey=None, joinsplit_sig=None, binding_sig=None):
'''
int, list(TxIn), list(TxOut), int, list(I... | [
"def",
"make_tx",
"(",
"version",
",",
"tx_ins",
",",
"tx_outs",
",",
"lock_time",
",",
"expiry",
"=",
"None",
",",
"value_balance",
"=",
"0",
",",
"tx_shielded_spends",
"=",
"None",
",",
"tx_shielded_outputs",
"=",
"None",
",",
"tx_witnesses",
"=",
"None",
... | int, list(TxIn), list(TxOut), int, list(InputWitness) -> Tx | [
"int",
"list",
"(",
"TxIn",
")",
"list",
"(",
"TxOut",
")",
"int",
"list",
"(",
"InputWitness",
")",
"-",
">",
"Tx"
] | python | train |
Opentrons/opentrons | api/src/opentrons/protocol_api/labware.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L124-L157 | def _from_center_cartesian(
self, x: float, y: float, z: float) -> Point:
"""
Specifies an arbitrary point relative to the center of the well based
on percentages of the radius in each axis. For example, to specify the
back-right corner of a well at 1/4 of the well depth from... | [
"def",
"_from_center_cartesian",
"(",
"self",
",",
"x",
":",
"float",
",",
"y",
":",
"float",
",",
"z",
":",
"float",
")",
"->",
"Point",
":",
"center",
"=",
"self",
".",
"center",
"(",
")",
"if",
"self",
".",
"_shape",
"is",
"WellShape",
".",
"REC... | Specifies an arbitrary point relative to the center of the well based
on percentages of the radius in each axis. For example, to specify the
back-right corner of a well at 1/4 of the well depth from the bottom,
the call would be `_from_center_cartesian(1, 1, -0.5)`.
No checks are perfor... | [
"Specifies",
"an",
"arbitrary",
"point",
"relative",
"to",
"the",
"center",
"of",
"the",
"well",
"based",
"on",
"percentages",
"of",
"the",
"radius",
"in",
"each",
"axis",
".",
"For",
"example",
"to",
"specify",
"the",
"back",
"-",
"right",
"corner",
"of",... | python | train |
pennlabs/penn-sdk-python | penn/dining.py | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/dining.py#L157-L173 | def venues(self):
"""Get a list of all venue objects.
>>> venues = din.venues()
"""
response = self._request(V2_ENDPOINTS['VENUES'])
# Normalize `dateHours` to array
for venue in response["result_data"]["document"]["venue"]:
if venue.get("id") in VENUE_NAME... | [
"def",
"venues",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_request",
"(",
"V2_ENDPOINTS",
"[",
"'VENUES'",
"]",
")",
"# Normalize `dateHours` to array",
"for",
"venue",
"in",
"response",
"[",
"\"result_data\"",
"]",
"[",
"\"document\"",
"]",
"[",
... | Get a list of all venue objects.
>>> venues = din.venues() | [
"Get",
"a",
"list",
"of",
"all",
"venue",
"objects",
"."
] | python | train |
houtianze/bypy | bypy/bypy.py | https://github.com/houtianze/bypy/blob/c59b6183e2fca45f11138bbcdec6247449b2eaad/bypy/bypy.py#L2912-L2920 | def dumpcache(self):
''' Usage: dumpcache - display file hash cache'''
if cached.cacheloaded:
#pprint.pprint(cached.cache)
MyPrettyPrinter().pprint(cached.cache)
return const.ENoError
else:
perr("Cache not loaded.")
return const.ECacheNotLoaded | [
"def",
"dumpcache",
"(",
"self",
")",
":",
"if",
"cached",
".",
"cacheloaded",
":",
"#pprint.pprint(cached.cache)",
"MyPrettyPrinter",
"(",
")",
".",
"pprint",
"(",
"cached",
".",
"cache",
")",
"return",
"const",
".",
"ENoError",
"else",
":",
"perr",
"(",
... | Usage: dumpcache - display file hash cache | [
"Usage",
":",
"dumpcache",
"-",
"display",
"file",
"hash",
"cache"
] | python | train |
kristianfoerster/melodist | melodist/humidity.py | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/humidity.py#L33-L109 | def disaggregate_humidity(data_daily, method='equal', temp=None,
a0=None, a1=None, kr=None,
month_hour_precip_mean=None, preserve_daily_mean=False):
"""general function for humidity disaggregation
Args:
daily_data: daily values
method: keyword... | [
"def",
"disaggregate_humidity",
"(",
"data_daily",
",",
"method",
"=",
"'equal'",
",",
"temp",
"=",
"None",
",",
"a0",
"=",
"None",
",",
"a1",
"=",
"None",
",",
"kr",
"=",
"None",
",",
"month_hour_precip_mean",
"=",
"None",
",",
"preserve_daily_mean",
"=",... | general function for humidity disaggregation
Args:
daily_data: daily values
method: keyword specifying the disaggregation method to be used
temp: hourly temperature time series (necessary for some methods)
kr: parameter for linear_dewpoint_variation method (6 or 12)
month_ho... | [
"general",
"function",
"for",
"humidity",
"disaggregation"
] | python | train |
googleapis/google-cloud-python | bigquery/google/cloud/bigquery/external_config.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/external_config.py#L697-L718 | def from_api_repr(cls, resource):
"""Factory: construct an :class:`~.external_config.ExternalConfig`
instance given its API representation.
Args:
resource (Dict[str, Any]):
Definition of an :class:`~.external_config.ExternalConfig`
instance in the sam... | [
"def",
"from_api_repr",
"(",
"cls",
",",
"resource",
")",
":",
"config",
"=",
"cls",
"(",
"resource",
"[",
"\"sourceFormat\"",
"]",
")",
"for",
"optcls",
"in",
"_OPTION_CLASSES",
":",
"opts",
"=",
"resource",
".",
"get",
"(",
"optcls",
".",
"_RESOURCE_NAME... | Factory: construct an :class:`~.external_config.ExternalConfig`
instance given its API representation.
Args:
resource (Dict[str, Any]):
Definition of an :class:`~.external_config.ExternalConfig`
instance in the same representation as is returned from the
... | [
"Factory",
":",
"construct",
"an",
":",
"class",
":",
"~",
".",
"external_config",
".",
"ExternalConfig",
"instance",
"given",
"its",
"API",
"representation",
"."
] | python | train |
GetmeUK/MongoFrames | mongoframes/frames.py | https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L771-L775 | def get_db(cls):
"""Return the database for the collection"""
if cls._db:
return getattr(cls._client, cls._db)
return cls._client.get_default_database() | [
"def",
"get_db",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_db",
":",
"return",
"getattr",
"(",
"cls",
".",
"_client",
",",
"cls",
".",
"_db",
")",
"return",
"cls",
".",
"_client",
".",
"get_default_database",
"(",
")"
] | Return the database for the collection | [
"Return",
"the",
"database",
"for",
"the",
"collection"
] | python | train |
mdeous/fatbotslim | fatbotslim/handlers.py | https://github.com/mdeous/fatbotslim/blob/341595d24454a79caee23750eac271f9d0626c88/fatbotslim/handlers.py#L284-L306 | def handle_rights(self, msg):
"""
Catch-all command that is called whenever a restricted command is triggered.
:param msg: message that triggered the command.
:type msg: :class:`fatbotslim.irc.Message`
"""
command = msg.args[0][1:]
if command in self.commands_rig... | [
"def",
"handle_rights",
"(",
"self",
",",
"msg",
")",
":",
"command",
"=",
"msg",
".",
"args",
"[",
"0",
"]",
"[",
"1",
":",
"]",
"if",
"command",
"in",
"self",
".",
"commands_rights",
":",
"if",
"msg",
".",
"src",
".",
"name",
".",
"lower",
"(",... | Catch-all command that is called whenever a restricted command is triggered.
:param msg: message that triggered the command.
:type msg: :class:`fatbotslim.irc.Message` | [
"Catch",
"-",
"all",
"command",
"that",
"is",
"called",
"whenever",
"a",
"restricted",
"command",
"is",
"triggered",
"."
] | python | train |
edx/edx-enterprise | enterprise/messages.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/messages.py#L77-L97 | def add_unenrollable_item_message(request, item):
"""
Add a message to the Django message store indicating that the item (i.e. course run, program) is unenrollable.
:param request: The current request.
:param item: The item that is unenrollable (i.e. a course run).
"""
messages.info(
re... | [
"def",
"add_unenrollable_item_message",
"(",
"request",
",",
"item",
")",
":",
"messages",
".",
"info",
"(",
"request",
",",
"_",
"(",
"'{strong_start}Something happened.{strong_end} '",
"'{span_start}This {item} is not currently open to new learners. Please start over and select a... | Add a message to the Django message store indicating that the item (i.e. course run, program) is unenrollable.
:param request: The current request.
:param item: The item that is unenrollable (i.e. a course run). | [
"Add",
"a",
"message",
"to",
"the",
"Django",
"message",
"store",
"indicating",
"that",
"the",
"item",
"(",
"i",
".",
"e",
".",
"course",
"run",
"program",
")",
"is",
"unenrollable",
"."
] | python | valid |
OpenGov/python_data_wrap | datawrap/listwrap.py | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/listwrap.py#L393-L431 | def _get_single_index_request(self, index, set_to_value=False, value=None):
'''
Helper function which implements single index requests for __getitem__.
'''
adjusted_index = index
# Multiply by step length
if self.range.step:
step = self.range.step
... | [
"def",
"_get_single_index_request",
"(",
"self",
",",
"index",
",",
"set_to_value",
"=",
"False",
",",
"value",
"=",
"None",
")",
":",
"adjusted_index",
"=",
"index",
"# Multiply by step length",
"if",
"self",
".",
"range",
".",
"step",
":",
"step",
"=",
"se... | Helper function which implements single index requests for __getitem__. | [
"Helper",
"function",
"which",
"implements",
"single",
"index",
"requests",
"for",
"__getitem__",
"."
] | python | train |
googleapis/google-cloud-python | irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py#L82-L88 | def incident_path(cls, project, incident):
"""Return a fully-qualified incident string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}",
project=project,
incident=incident,
) | [
"def",
"incident_path",
"(",
"cls",
",",
"project",
",",
"incident",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/incidents/{incident}\"",
",",
"project",
"=",
"project",
",",
"incident",
"=",
"in... | Return a fully-qualified incident string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"incident",
"string",
"."
] | python | train |
ARMmbed/icetea | icetea_lib/tools/GenericProcess.py | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GenericProcess.py#L247-L260 | def readline(self):
"""
Readline implementation.
:return: popped line from descriptor queue. None if nothing found
:raises: RuntimeError if errors happened while reading PIPE
"""
try:
return self._descriptor.read_queue.pop()
except IndexError:
... | [
"def",
"readline",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_descriptor",
".",
"read_queue",
".",
"pop",
"(",
")",
"except",
"IndexError",
":",
"# No lines in queue",
"if",
"self",
".",
"has_error",
"(",
")",
":",
"raise",
"RuntimeError",... | Readline implementation.
:return: popped line from descriptor queue. None if nothing found
:raises: RuntimeError if errors happened while reading PIPE | [
"Readline",
"implementation",
"."
] | python | train |
carlosp420/dataset-creator | dataset_creator/utils.py | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/utils.py#L89-L126 | def make_dataset_header(data, file_format, aminoacids):
"""Creates the dataset header for NEXUS files from ``#NEXUS`` to ``MATRIX``.
Parameters:
data (namedtuple): with necessary info for dataset creation.
file_format (str): TNT, PHYLIP, NEXUS, FASTA
aminoacids (boolean): If ``ami... | [
"def",
"make_dataset_header",
"(",
"data",
",",
"file_format",
",",
"aminoacids",
")",
":",
"if",
"aminoacids",
":",
"datatype",
"=",
"'PROTEIN'",
"else",
":",
"datatype",
"=",
"'DNA'",
"if",
"file_format",
"in",
"[",
"'NEXUS'",
",",
"'PHYLIP'",
",",
"'FASTA... | Creates the dataset header for NEXUS files from ``#NEXUS`` to ``MATRIX``.
Parameters:
data (namedtuple): with necessary info for dataset creation.
file_format (str): TNT, PHYLIP, NEXUS, FASTA
aminoacids (boolean): If ``aminoacids is True`` the header will show
... | [
"Creates",
"the",
"dataset",
"header",
"for",
"NEXUS",
"files",
"from",
"#NEXUS",
"to",
"MATRIX",
"."
] | python | train |
bitshares/python-bitshares | bitshares/bitshares.py | https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L895-L922 | def set_proxy(self, proxy_account, account=None, **kwargs):
""" Set a specific proxy for account
:param bitshares.account.Account proxy_account: Account to be
proxied
:param str account: (optional) the account to allow access
to (defaults to ``default... | [
"def",
"set_proxy",
"(",
"self",
",",
"proxy_account",
",",
"account",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"account",
":",
"if",
"\"default_account\"",
"in",
"self",
".",
"config",
":",
"account",
"=",
"self",
".",
"config",
"[... | Set a specific proxy for account
:param bitshares.account.Account proxy_account: Account to be
proxied
:param str account: (optional) the account to allow access
to (defaults to ``default_account``) | [
"Set",
"a",
"specific",
"proxy",
"for",
"account"
] | python | train |
openstax/rhaptos.cnxmlutils | rhaptos/cnxmlutils/utils.py | https://github.com/openstax/rhaptos.cnxmlutils/blob/c32b1a7428dc652e8cd745f3fdf4019a20543649/rhaptos/cnxmlutils/utils.py#L233-L238 | def aloha_to_etree(html_source):
""" Converts HTML5 from Aloha editor output to a lxml etree. """
xml = _tidy2xhtml5(html_source)
for i, transform in enumerate(ALOHA2HTML_TRANSFORM_PIPELINE):
xml = transform(xml)
return xml | [
"def",
"aloha_to_etree",
"(",
"html_source",
")",
":",
"xml",
"=",
"_tidy2xhtml5",
"(",
"html_source",
")",
"for",
"i",
",",
"transform",
"in",
"enumerate",
"(",
"ALOHA2HTML_TRANSFORM_PIPELINE",
")",
":",
"xml",
"=",
"transform",
"(",
"xml",
")",
"return",
"... | Converts HTML5 from Aloha editor output to a lxml etree. | [
"Converts",
"HTML5",
"from",
"Aloha",
"editor",
"output",
"to",
"a",
"lxml",
"etree",
"."
] | python | train |
nschloe/colorio | experiments/new-cs.py | https://github.com/nschloe/colorio/blob/357d6001b3cf30f752e23726bf429dc1d1c60b3a/experiments/new-cs.py#L309-L346 | def build_grad_matrices(V, points):
"""Build the sparse m-by-n matrices that map a coefficient set for a function in V
to the values of dx and dy at a number m of points.
"""
# See <https://www.allanswered.com/post/lkbkm/#zxqgk>
mesh = V.mesh()
bbt = BoundingBoxTree()
bbt.build(mesh)
do... | [
"def",
"build_grad_matrices",
"(",
"V",
",",
"points",
")",
":",
"# See <https://www.allanswered.com/post/lkbkm/#zxqgk>",
"mesh",
"=",
"V",
".",
"mesh",
"(",
")",
"bbt",
"=",
"BoundingBoxTree",
"(",
")",
"bbt",
".",
"build",
"(",
"mesh",
")",
"dofmap",
"=",
... | Build the sparse m-by-n matrices that map a coefficient set for a function in V
to the values of dx and dy at a number m of points. | [
"Build",
"the",
"sparse",
"m",
"-",
"by",
"-",
"n",
"matrices",
"that",
"map",
"a",
"coefficient",
"set",
"for",
"a",
"function",
"in",
"V",
"to",
"the",
"values",
"of",
"dx",
"and",
"dy",
"at",
"a",
"number",
"m",
"of",
"points",
"."
] | python | train |
konstantint/PassportEye | passporteye/mrz/image.py | https://github.com/konstantint/PassportEye/blob/b32afba0f5dc4eb600c4edc4f49e5d49959c5415/passporteye/mrz/image.py#L254-L267 | def _try_larger_image(self, roi, cur_text, cur_mrz, filter_order=3):
"""Attempts to improve the OCR result by scaling the image. If the new mrz is better, returns it, otherwise returns
the old mrz."""
if roi.shape[1] <= 700:
scale_by = int(1050.0 / roi.shape[1] + 0.5)
roi... | [
"def",
"_try_larger_image",
"(",
"self",
",",
"roi",
",",
"cur_text",
",",
"cur_mrz",
",",
"filter_order",
"=",
"3",
")",
":",
"if",
"roi",
".",
"shape",
"[",
"1",
"]",
"<=",
"700",
":",
"scale_by",
"=",
"int",
"(",
"1050.0",
"/",
"roi",
".",
"shap... | Attempts to improve the OCR result by scaling the image. If the new mrz is better, returns it, otherwise returns
the old mrz. | [
"Attempts",
"to",
"improve",
"the",
"OCR",
"result",
"by",
"scaling",
"the",
"image",
".",
"If",
"the",
"new",
"mrz",
"is",
"better",
"returns",
"it",
"otherwise",
"returns",
"the",
"old",
"mrz",
"."
] | python | train |
hamperbot/hamper | hamper/commander.py | https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/commander.py#L348-L368 | def runPlugins(self, category, func, protocol, *args):
"""
Run the specified set of plugins against a given protocol.
"""
# Plugins are already sorted by priority
for plugin in self.plugins:
# If a plugin throws an exception, we should catch it gracefully.
... | [
"def",
"runPlugins",
"(",
"self",
",",
"category",
",",
"func",
",",
"protocol",
",",
"*",
"args",
")",
":",
"# Plugins are already sorted by priority",
"for",
"plugin",
"in",
"self",
".",
"plugins",
":",
"# If a plugin throws an exception, we should catch it gracefully... | Run the specified set of plugins against a given protocol. | [
"Run",
"the",
"specified",
"set",
"of",
"plugins",
"against",
"a",
"given",
"protocol",
"."
] | python | train |
twilio/twilio-python | twilio/rest/sync/v1/service/sync_map/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/sync/v1/service/sync_map/__init__.py#L372-L386 | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncMapContext for this SyncMapInstance
:rtype: twilio.rest.sync.v1.service.sync_map.SyncMapConte... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"SyncMapContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncMapContext for this SyncMapInstance
:rtype: twilio.rest.sync.v1.service.sync_map.SyncMapContext | [
"Generate",
"an",
"instance",
"context",
"for",
"the",
"instance",
"the",
"context",
"is",
"capable",
"of",
"performing",
"various",
"actions",
".",
"All",
"instance",
"actions",
"are",
"proxied",
"to",
"the",
"context"
] | python | train |
ranaroussi/ezibpy | ezibpy/ezibpy.py | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1892-L1929 | def requestHistoricalData(self, contracts=None, resolution="1 min",
lookback="1 D", data="TRADES", end_datetime=None, rth=False,
csv_path=None, format_date=2, utc=False):
"""
Download to historical data
https://www.interactivebrokers.com/en/software/api/apiguide/java/req... | [
"def",
"requestHistoricalData",
"(",
"self",
",",
"contracts",
"=",
"None",
",",
"resolution",
"=",
"\"1 min\"",
",",
"lookback",
"=",
"\"1 D\"",
",",
"data",
"=",
"\"TRADES\"",
",",
"end_datetime",
"=",
"None",
",",
"rth",
"=",
"False",
",",
"csv_path",
"... | Download to historical data
https://www.interactivebrokers.com/en/software/api/apiguide/java/reqhistoricaldata.htm | [
"Download",
"to",
"historical",
"data",
"https",
":",
"//",
"www",
".",
"interactivebrokers",
".",
"com",
"/",
"en",
"/",
"software",
"/",
"api",
"/",
"apiguide",
"/",
"java",
"/",
"reqhistoricaldata",
".",
"htm"
] | python | train |
nccgroup/Scout2 | AWSScout2/services/cloudwatch.py | https://github.com/nccgroup/Scout2/blob/5d86d46d7ed91a92000496189e9cfa6b98243937/AWSScout2/services/cloudwatch.py#L21-L35 | def parse_alarm(self, global_params, region, alarm):
"""
Parse a single CloudWatch trail
:param global_params: Parameters shared for all regions
:param region: Name of the AWS region
:param alarm: Alarm
"""
alarm['arn'... | [
"def",
"parse_alarm",
"(",
"self",
",",
"global_params",
",",
"region",
",",
"alarm",
")",
":",
"alarm",
"[",
"'arn'",
"]",
"=",
"alarm",
".",
"pop",
"(",
"'AlarmArn'",
")",
"alarm",
"[",
"'name'",
"]",
"=",
"alarm",
".",
"pop",
"(",
"'AlarmName'",
"... | Parse a single CloudWatch trail
:param global_params: Parameters shared for all regions
:param region: Name of the AWS region
:param alarm: Alarm | [
"Parse",
"a",
"single",
"CloudWatch",
"trail"
] | python | train |
cloud-custodian/cloud-custodian | tools/c7n_azure/c7n_azure/utils.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L259-L270 | def _get_port_range(range_str):
""" Given a string with a port or port range: '80', '80-120'
Returns tuple with range start and end ports: (80, 80), (80, 120)
"""
if range_str == '*':
return PortsRangeHelper.PortsRange(start=0, end=65535)
s = range_str.split('-')... | [
"def",
"_get_port_range",
"(",
"range_str",
")",
":",
"if",
"range_str",
"==",
"'*'",
":",
"return",
"PortsRangeHelper",
".",
"PortsRange",
"(",
"start",
"=",
"0",
",",
"end",
"=",
"65535",
")",
"s",
"=",
"range_str",
".",
"split",
"(",
"'-'",
")",
"if... | Given a string with a port or port range: '80', '80-120'
Returns tuple with range start and end ports: (80, 80), (80, 120) | [
"Given",
"a",
"string",
"with",
"a",
"port",
"or",
"port",
"range",
":",
"80",
"80",
"-",
"120",
"Returns",
"tuple",
"with",
"range",
"start",
"and",
"end",
"ports",
":",
"(",
"80",
"80",
")",
"(",
"80",
"120",
")"
] | python | train |
GaryLee/cmdlet | cmdlet/cmds.py | https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L691-L695 | def substitute(prev, *args, **kw):
'''alias of string.Template.substitute'''
template_obj = string.Template(*args, **kw)
for data in prev:
yield template_obj.substitute(data) | [
"def",
"substitute",
"(",
"prev",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"template_obj",
"=",
"string",
".",
"Template",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"for",
"data",
"in",
"prev",
":",
"yield",
"template_obj",
".",
"substitu... | alias of string.Template.substitute | [
"alias",
"of",
"string",
".",
"Template",
".",
"substitute"
] | python | valid |
nccgroup/Scout2 | AWSScout2/services/redshift.py | https://github.com/nccgroup/Scout2/blob/5d86d46d7ed91a92000496189e9cfa6b98243937/AWSScout2/services/redshift.py#L60-L70 | def parse_security_group(self, global_params, region, security_group):
"""
Parse a single Redsfhit security group
:param global_params: Parameters shared for all regions
:param region: Name of the AWS region
:param security)_group: Security gro... | [
"def",
"parse_security_group",
"(",
"self",
",",
"global_params",
",",
"region",
",",
"security_group",
")",
":",
"name",
"=",
"security_group",
".",
"pop",
"(",
"'ClusterSecurityGroupName'",
")",
"security_group",
"[",
"'name'",
"]",
"=",
"name",
"self",
".",
... | Parse a single Redsfhit security group
:param global_params: Parameters shared for all regions
:param region: Name of the AWS region
:param security)_group: Security group | [
"Parse",
"a",
"single",
"Redsfhit",
"security",
"group"
] | python | train |
Projectplace/basepage | basepage/base_page.py | https://github.com/Projectplace/basepage/blob/735476877eb100db0981590a6d12140e68652167/basepage/base_page.py#L722-L738 | def wait_for_non_empty_text(self, locator, params=None, timeout=5):
"""
Wait and get elements when they're populated with any text.
:param locator: locator tuple
:param params: (optional) locator params
:param timeout: (optional) maximum waiting time (in seconds) (default: 5)
... | [
"def",
"wait_for_non_empty_text",
"(",
"self",
",",
"locator",
",",
"params",
"=",
"None",
",",
"timeout",
"=",
"5",
")",
":",
"def",
"_do_wait",
"(",
")",
":",
"elements",
"=",
"self",
".",
"get_present_elements",
"(",
"locator",
",",
"params",
",",
"ti... | Wait and get elements when they're populated with any text.
:param locator: locator tuple
:param params: (optional) locator params
:param timeout: (optional) maximum waiting time (in seconds) (default: 5)
:return: list of WebElements | [
"Wait",
"and",
"get",
"elements",
"when",
"they",
"re",
"populated",
"with",
"any",
"text",
"."
] | python | train |
fitnr/twitter_bot_utils | twitter_bot_utils/helpers.py | https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/helpers.py#L98-L113 | def remove_entities(status, entitylist):
'''Remove entities for a list of items.'''
try:
entities = status.entities
text = status.text
except AttributeError:
entities = status.get('entities', dict())
text = status['text']
indices = [ent['indices'] for etype, entval in li... | [
"def",
"remove_entities",
"(",
"status",
",",
"entitylist",
")",
":",
"try",
":",
"entities",
"=",
"status",
".",
"entities",
"text",
"=",
"status",
".",
"text",
"except",
"AttributeError",
":",
"entities",
"=",
"status",
".",
"get",
"(",
"'entities'",
","... | Remove entities for a list of items. | [
"Remove",
"entities",
"for",
"a",
"list",
"of",
"items",
"."
] | python | train |
fermiPy/fermipy | fermipy/jobs/chain.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/chain.py#L345-L365 | def update_args(self, override_args):
"""Update the argument used to invoke the application
Note that this will also update the dictionary of input
and output files.
Parameters
-----------
override_args : dict
dictionary passed to the links
"""
... | [
"def",
"update_args",
"(",
"self",
",",
"override_args",
")",
":",
"self",
".",
"args",
"=",
"extract_arguments",
"(",
"override_args",
",",
"self",
".",
"args",
")",
"self",
".",
"_map_arguments",
"(",
"self",
".",
"args",
")",
"scratch_dir",
"=",
"self",... | Update the argument used to invoke the application
Note that this will also update the dictionary of input
and output files.
Parameters
-----------
override_args : dict
dictionary passed to the links | [
"Update",
"the",
"argument",
"used",
"to",
"invoke",
"the",
"application"
] | python | train |
Ouranosinc/xclim | xclim/checks.py | https://github.com/Ouranosinc/xclim/blob/2080d139188bd8de2aeca097a025c2d89d6e0e09/xclim/checks.py#L108-L118 | def valid_daily_max_min_temperature(comp, units='K'):
r"""Decorator to check that a computation runs on valid min and max temperature datasets."""
@wraps(comp)
def func(tasmax, tasmin, **kwds):
valid_daily_max_temperature(tasmax, units)
valid_daily_min_temperature(tasmin, units)
re... | [
"def",
"valid_daily_max_min_temperature",
"(",
"comp",
",",
"units",
"=",
"'K'",
")",
":",
"@",
"wraps",
"(",
"comp",
")",
"def",
"func",
"(",
"tasmax",
",",
"tasmin",
",",
"*",
"*",
"kwds",
")",
":",
"valid_daily_max_temperature",
"(",
"tasmax",
",",
"u... | r"""Decorator to check that a computation runs on valid min and max temperature datasets. | [
"r",
"Decorator",
"to",
"check",
"that",
"a",
"computation",
"runs",
"on",
"valid",
"min",
"and",
"max",
"temperature",
"datasets",
"."
] | python | train |
shoebot/shoebot | lib/web/BeautifulSoup.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L1398-L1416 | def parse_declaration(self, i):
"""Treat a bogus SGML declaration as raw data. Treat a CDATA
declaration as a CData object."""
j = None
if self.rawdata[i:i+9] == '<![CDATA[':
k = self.rawdata.find(']]>', i)
if k == -1:
k = len(self.rawdata)
... | [
"def",
"parse_declaration",
"(",
"self",
",",
"i",
")",
":",
"j",
"=",
"None",
"if",
"self",
".",
"rawdata",
"[",
"i",
":",
"i",
"+",
"9",
"]",
"==",
"'<![CDATA['",
":",
"k",
"=",
"self",
".",
"rawdata",
".",
"find",
"(",
"']]>'",
",",
"i",
")"... | Treat a bogus SGML declaration as raw data. Treat a CDATA
declaration as a CData object. | [
"Treat",
"a",
"bogus",
"SGML",
"declaration",
"as",
"raw",
"data",
".",
"Treat",
"a",
"CDATA",
"declaration",
"as",
"a",
"CData",
"object",
"."
] | python | valid |
KelSolaar/Foundations | foundations/parsers.py | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/parsers.py#L238-L253 | def namespace_splitter(self, value):
"""
Setter for **self.__namespace_splitter** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
... | [
"def",
"namespace_splitter",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"unicode",
",",
"\"'{0}' attribute: '{1}' type is not 'unicode'!\"",
".",
"format",
"(",
"\"namespace_splitter\"",... | Setter for **self.__namespace_splitter** attribute.
:param value: Attribute value.
:type value: unicode | [
"Setter",
"for",
"**",
"self",
".",
"__namespace_splitter",
"**",
"attribute",
"."
] | python | train |
devassistant/devassistant | devassistant/dapi/dapicli.py | https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L302-L319 | def format_installed_dap_list(simple=False):
'''Formats all installed DAPs in a human readable form to list of lines'''
lines = []
if simple:
for pkg in sorted(get_installed_daps()):
lines.append(pkg)
else:
for pkg, instances in sorted(get_installed_daps_detailed().items()):
... | [
"def",
"format_installed_dap_list",
"(",
"simple",
"=",
"False",
")",
":",
"lines",
"=",
"[",
"]",
"if",
"simple",
":",
"for",
"pkg",
"in",
"sorted",
"(",
"get_installed_daps",
"(",
")",
")",
":",
"lines",
".",
"append",
"(",
"pkg",
")",
"else",
":",
... | Formats all installed DAPs in a human readable form to list of lines | [
"Formats",
"all",
"installed",
"DAPs",
"in",
"a",
"human",
"readable",
"form",
"to",
"list",
"of",
"lines"
] | python | train |
mozilla/treeherder | treeherder/seta/models.py | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/seta/models.py#L21-L37 | def adjust_jobs_priority(self, high_value_jobs, priority=1):
"""For every job priority determine if we need to increase or decrease the job priority
Currently, high value jobs have a priority of 1 and a timeout of 0.
"""
# Only job priorities that don't have an expiration date (2 weeks ... | [
"def",
"adjust_jobs_priority",
"(",
"self",
",",
"high_value_jobs",
",",
"priority",
"=",
"1",
")",
":",
"# Only job priorities that don't have an expiration date (2 weeks for new jobs or year 2100",
"# for jobs update via load_preseed) are updated",
"for",
"jp",
"in",
"JobPriority... | For every job priority determine if we need to increase or decrease the job priority
Currently, high value jobs have a priority of 1 and a timeout of 0. | [
"For",
"every",
"job",
"priority",
"determine",
"if",
"we",
"need",
"to",
"increase",
"or",
"decrease",
"the",
"job",
"priority"
] | python | train |
funilrys/PyFunceble | PyFunceble/database.py | https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/database.py#L270-L279 | def _backup(self):
"""
Save the current database into the inactive-db.json file.
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
# We save the current database state into the database file.
Dict(PyFunceble... | [
"def",
"_backup",
"(",
"self",
")",
":",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"inactive_database\"",
"]",
":",
"# The database subsystem is activated.",
"# We save the current database state into the database file.",
"Dict",
"(",
"PyFunceble",
".",
"INTERN",
"["... | Save the current database into the inactive-db.json file. | [
"Save",
"the",
"current",
"database",
"into",
"the",
"inactive",
"-",
"db",
".",
"json",
"file",
"."
] | python | test |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_system_monitor.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_system_monitor.py#L90-L101 | def system_monitor_power_alert_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
power = ET.SubElement(system_monitor, "power")
aler... | [
"def",
"system_monitor_power_alert_state",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"system_monitor",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"system-monitor\"",
",",
"xmlns",
"=... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
hozn/stravalib | stravalib/attributes.py | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/attributes.py#L81-L95 | def unmarshal(self, v):
"""
Convert the value from parsed JSON structure to native python representation.
By default this will leave the value as-is since the JSON parsing routines
typically convert to native types. The exception may be date strings or other
more complex types, ... | [
"def",
"unmarshal",
"(",
"self",
",",
"v",
")",
":",
"if",
"self",
".",
"units",
":",
"# Note that we don't want to cast to type in this case!",
"if",
"not",
"isinstance",
"(",
"v",
",",
"Quantity",
")",
":",
"v",
"=",
"self",
".",
"units",
"(",
"v",
")",
... | Convert the value from parsed JSON structure to native python representation.
By default this will leave the value as-is since the JSON parsing routines
typically convert to native types. The exception may be date strings or other
more complex types, where subclasses will override this behavior... | [
"Convert",
"the",
"value",
"from",
"parsed",
"JSON",
"structure",
"to",
"native",
"python",
"representation",
"."
] | python | train |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L553-L558 | def get_config(self, key, default=None):
''' Lookup a config field and return its value, first checking the
route.config, then route.app.config.'''
for conf in (self.config, self.app.conifg):
if key in conf: return conf[key]
return default | [
"def",
"get_config",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"for",
"conf",
"in",
"(",
"self",
".",
"config",
",",
"self",
".",
"app",
".",
"conifg",
")",
":",
"if",
"key",
"in",
"conf",
":",
"return",
"conf",
"[",
"key",
... | Lookup a config field and return its value, first checking the
route.config, then route.app.config. | [
"Lookup",
"a",
"config",
"field",
"and",
"return",
"its",
"value",
"first",
"checking",
"the",
"route",
".",
"config",
"then",
"route",
".",
"app",
".",
"config",
"."
] | python | train |
AltSchool/dynamic-rest | dynamic_rest/filters.py | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/filters.py#L73-L140 | def generate_query_key(self, serializer):
"""Get the key that can be passed to Django's filter method.
To account for serialier field name rewrites, this method
translates serializer field names to model field names
by inspecting `serializer`.
For example, a query like `filter{... | [
"def",
"generate_query_key",
"(",
"self",
",",
"serializer",
")",
":",
"rewritten",
"=",
"[",
"]",
"last",
"=",
"len",
"(",
"self",
".",
"field",
")",
"-",
"1",
"s",
"=",
"serializer",
"field",
"=",
"None",
"for",
"i",
",",
"field_name",
"in",
"enume... | Get the key that can be passed to Django's filter method.
To account for serialier field name rewrites, this method
translates serializer field names to model field names
by inspecting `serializer`.
For example, a query like `filter{users.events}` would be
returned as `users__e... | [
"Get",
"the",
"key",
"that",
"can",
"be",
"passed",
"to",
"Django",
"s",
"filter",
"method",
"."
] | python | train |
quantmind/pulsar | examples/chat/manage.py | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/chat/manage.py#L70-L75 | def encode(self, message):
'''Encode a message when publishing.'''
if not isinstance(message, dict):
message = {'message': message}
message['time'] = time.time()
return json.dumps(message) | [
"def",
"encode",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"dict",
")",
":",
"message",
"=",
"{",
"'message'",
":",
"message",
"}",
"message",
"[",
"'time'",
"]",
"=",
"time",
".",
"time",
"(",
")",
"ret... | Encode a message when publishing. | [
"Encode",
"a",
"message",
"when",
"publishing",
"."
] | python | train |
pyviz/holoviews | holoviews/core/data/__init__.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/data/__init__.py#L269-L294 | def range(self, dim, data_range=True, dimension_range=True):
"""Return the lower and upper bounds of values along dimension.
Args:
dimension: The dimension to compute the range on.
data_range (bool): Compute range from data values
dimension_range (bool): Include Dime... | [
"def",
"range",
"(",
"self",
",",
"dim",
",",
"data_range",
"=",
"True",
",",
"dimension_range",
"=",
"True",
")",
":",
"dim",
"=",
"self",
".",
"get_dimension",
"(",
"dim",
")",
"if",
"dim",
"is",
"None",
"or",
"(",
"not",
"data_range",
"and",
"not"... | Return the lower and upper bounds of values along dimension.
Args:
dimension: The dimension to compute the range on.
data_range (bool): Compute range from data values
dimension_range (bool): Include Dimension ranges
Whether to include Dimension range and soft... | [
"Return",
"the",
"lower",
"and",
"upper",
"bounds",
"of",
"values",
"along",
"dimension",
"."
] | python | train |
KarchinLab/probabilistic2020 | scripts/check_mutations.py | https://github.com/KarchinLab/probabilistic2020/blob/5d70583b0a7c07cfe32e95f3a70e05df412acb84/scripts/check_mutations.py#L23-L35 | def correct_chrom_names(chroms):
"""Make sure chromosome names follow UCSC chr convention."""
chrom_list = []
for chrom in chroms:
# fix chrom numbering
chrom = str(chrom)
chrom = chrom.replace('23', 'X')
chrom = chrom.replace('24', 'Y')
chrom = chrom.replace('25', 'M... | [
"def",
"correct_chrom_names",
"(",
"chroms",
")",
":",
"chrom_list",
"=",
"[",
"]",
"for",
"chrom",
"in",
"chroms",
":",
"# fix chrom numbering",
"chrom",
"=",
"str",
"(",
"chrom",
")",
"chrom",
"=",
"chrom",
".",
"replace",
"(",
"'23'",
",",
"'X'",
")",... | Make sure chromosome names follow UCSC chr convention. | [
"Make",
"sure",
"chromosome",
"names",
"follow",
"UCSC",
"chr",
"convention",
"."
] | python | train |
wilson-eft/wilson | wilson/translate/wet.py | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/translate/wet.py#L973-L984 | def JMS_to_Fierz_nunu(C, ddll):
"""From JMS to semileptonic Fierz basis for Class V.
`ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc."""
s = dflav[ddll[0]]
b = dflav[ddll[1]]
l = lflav[ddll[4:ddll.find('n')]]
lp = lflav[ddll[ddll.find('_',5)+1:len(ddll)]]
ind = ddll.replace('l_'... | [
"def",
"JMS_to_Fierz_nunu",
"(",
"C",
",",
"ddll",
")",
":",
"s",
"=",
"dflav",
"[",
"ddll",
"[",
"0",
"]",
"]",
"b",
"=",
"dflav",
"[",
"ddll",
"[",
"1",
"]",
"]",
"l",
"=",
"lflav",
"[",
"ddll",
"[",
"4",
":",
"ddll",
".",
"find",
"(",
"'... | From JMS to semileptonic Fierz basis for Class V.
`ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc. | [
"From",
"JMS",
"to",
"semileptonic",
"Fierz",
"basis",
"for",
"Class",
"V",
".",
"ddll",
"should",
"be",
"of",
"the",
"form",
"sbl_enu_tau",
"dbl_munu_e",
"etc",
"."
] | python | train |
kata198/NamedAtomicLock | NamedAtomicLock/__init__.py | https://github.com/kata198/NamedAtomicLock/blob/82d480b81daf4deea926964f18bb2e47d4f30f6c/NamedAtomicLock/__init__.py#L165-L185 | def __checkExpiration(self, mtime=None):
'''
__checkExpiration - Check if we have expired
@param mtime <int> - Optional mtime if known, otherwise will be gathered
@return <bool> - True if we did expire, otherwise False
'''
if not self.maxLockAge:... | [
"def",
"__checkExpiration",
"(",
"self",
",",
"mtime",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"maxLockAge",
":",
"return",
"False",
"if",
"mtime",
"is",
"None",
":",
"try",
":",
"mtime",
"=",
"os",
".",
"stat",
"(",
"self",
".",
"lockPath",... | __checkExpiration - Check if we have expired
@param mtime <int> - Optional mtime if known, otherwise will be gathered
@return <bool> - True if we did expire, otherwise False | [
"__checkExpiration",
"-",
"Check",
"if",
"we",
"have",
"expired",
"@param",
"mtime",
"<int",
">",
"-",
"Optional",
"mtime",
"if",
"known",
"otherwise",
"will",
"be",
"gathered"
] | python | train |
futurecolors/django-geoip | django_geoip/management/ipgeobase.py | https://github.com/futurecolors/django-geoip/blob/f9eee4bcad40508089b184434b79826f842d7bd0/django_geoip/management/ipgeobase.py#L31-L39 | def clear_database(self):
""" Removes all geodata stored in database.
Useful for development, never use on production.
"""
self.logger.info('Removing obsolete geoip from database...')
IpRange.objects.all().delete()
City.objects.all().delete()
Region.objects.al... | [
"def",
"clear_database",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Removing obsolete geoip from database...'",
")",
"IpRange",
".",
"objects",
".",
"all",
"(",
")",
".",
"delete",
"(",
")",
"City",
".",
"objects",
".",
"all",
"(",
... | Removes all geodata stored in database.
Useful for development, never use on production. | [
"Removes",
"all",
"geodata",
"stored",
"in",
"database",
".",
"Useful",
"for",
"development",
"never",
"use",
"on",
"production",
"."
] | python | train |
manahl/arctic | arctic/store/_ndarray_store.py | https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/store/_ndarray_store.py#L75-L113 | def _resize_with_dtype(arr, dtype):
"""
This function will transform arr into an array with the same type as dtype. It will do this by
filling new columns with zeros (or NaNs, if it is a float column). Also, columns that are not
in the new dtype will be dropped.
"""
structured_arrays = dtype.nam... | [
"def",
"_resize_with_dtype",
"(",
"arr",
",",
"dtype",
")",
":",
"structured_arrays",
"=",
"dtype",
".",
"names",
"is",
"not",
"None",
"and",
"arr",
".",
"dtype",
".",
"names",
"is",
"not",
"None",
"old_columns",
"=",
"arr",
".",
"dtype",
".",
"names",
... | This function will transform arr into an array with the same type as dtype. It will do this by
filling new columns with zeros (or NaNs, if it is a float column). Also, columns that are not
in the new dtype will be dropped. | [
"This",
"function",
"will",
"transform",
"arr",
"into",
"an",
"array",
"with",
"the",
"same",
"type",
"as",
"dtype",
".",
"It",
"will",
"do",
"this",
"by",
"filling",
"new",
"columns",
"with",
"zeros",
"(",
"or",
"NaNs",
"if",
"it",
"is",
"a",
"float",... | python | train |
rorr73/LifeSOSpy | lifesospy/baseunit.py | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L539-L548 | def as_dict(self) -> Dict[str, Any]:
"""Converts to a dict of attributes for easier serialization."""
def _on_filter(obj: Any, name: str) -> bool:
# Filter out any callbacks
if isinstance(obj, BaseUnit):
if name.startswith('on_'):
return False
... | [
"def",
"as_dict",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"def",
"_on_filter",
"(",
"obj",
":",
"Any",
",",
"name",
":",
"str",
")",
"->",
"bool",
":",
"# Filter out any callbacks",
"if",
"isinstance",
"(",
"obj",
",",
"Base... | Converts to a dict of attributes for easier serialization. | [
"Converts",
"to",
"a",
"dict",
"of",
"attributes",
"for",
"easier",
"serialization",
"."
] | python | train |
vaexio/vaex | packages/vaex-core/vaex/expression.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/expression.py#L371-L434 | def value_counts(self, dropna=False, dropnull=True, ascending=False, progress=False):
"""Computes counts of unique values.
WARNING:
* If the expression/column is not categorical, it will be converted on the fly
* dropna is False by default, it is True by default in pandas
... | [
"def",
"value_counts",
"(",
"self",
",",
"dropna",
"=",
"False",
",",
"dropnull",
"=",
"True",
",",
"ascending",
"=",
"False",
",",
"progress",
"=",
"False",
")",
":",
"from",
"pandas",
"import",
"Series",
"dtype",
"=",
"self",
".",
"dtype",
"transient",... | Computes counts of unique values.
WARNING:
* If the expression/column is not categorical, it will be converted on the fly
* dropna is False by default, it is True by default in pandas
:param dropna: when True, it will not report the missing values
:param ascending: when Fa... | [
"Computes",
"counts",
"of",
"unique",
"values",
"."
] | python | test |
SavinaRoja/PyUserInput | pykeyboard/mac.py | https://github.com/SavinaRoja/PyUserInput/blob/153c1d39b1a41b467b235fd182392d6dcbf07947/pykeyboard/mac.py#L174-L193 | def _press_special_key(self, key, down):
""" Helper method for special keys.
Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac
"""
key_code = special_key_translate_table[key]
ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_wind... | [
"def",
"_press_special_key",
"(",
"self",
",",
"key",
",",
"down",
")",
":",
"key_code",
"=",
"special_key_translate_table",
"[",
"key",
"]",
"ev",
"=",
"NSEvent",
".",
"otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_",
"(",
"... | Helper method for special keys.
Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac | [
"Helper",
"method",
"for",
"special",
"keys",
"."
] | python | train |
apache/airflow | airflow/contrib/hooks/gcp_vision_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_vision_hook.py#L311-L349 | def create_reference_image(
self,
location,
product_id,
reference_image,
reference_image_id=None,
project_id=None,
retry=None,
timeout=None,
metadata=None,
):
"""
For the documentation see:
:py:class:`~airflow.contrib.op... | [
"def",
"create_reference_image",
"(",
"self",
",",
"location",
",",
"product_id",
",",
"reference_image",
",",
"reference_image_id",
"=",
"None",
",",
"project_id",
"=",
"None",
",",
"retry",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"metadata",
"=",
"N... | For the documentation see:
:py:class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionReferenceImageCreateOperator` | [
"For",
"the",
"documentation",
"see",
":",
":",
"py",
":",
"class",
":",
"~airflow",
".",
"contrib",
".",
"operators",
".",
"gcp_vision_operator",
".",
"CloudVisionReferenceImageCreateOperator"
] | python | test |
jorisroovers/gitlint | gitlint/lint.py | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/lint.py#L70-L96 | def lint(self, commit):
""" Lint the last commit in a given git context by applying all ignore, title, body and commit rules. """
LOG.debug("Linting commit %s", commit.sha or "[SHA UNKNOWN]")
LOG.debug("Commit Object\n" + ustr(commit))
# Apply config rules
for rule in self.confi... | [
"def",
"lint",
"(",
"self",
",",
"commit",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Linting commit %s\"",
",",
"commit",
".",
"sha",
"or",
"\"[SHA UNKNOWN]\"",
")",
"LOG",
".",
"debug",
"(",
"\"Commit Object\\n\"",
"+",
"ustr",
"(",
"commit",
")",
")",
"# ... | Lint the last commit in a given git context by applying all ignore, title, body and commit rules. | [
"Lint",
"the",
"last",
"commit",
"in",
"a",
"given",
"git",
"context",
"by",
"applying",
"all",
"ignore",
"title",
"body",
"and",
"commit",
"rules",
"."
] | python | train |
ipfs/py-ipfs-api | ipfsapi/client.py | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1775-L1803 | def log_level(self, subsystem, level, **kwargs):
r"""Changes the logging output of a running daemon.
.. code-block:: python
>>> c.log_level("path", "info")
{'Message': "Changed log level of 'path' to 'info'\n"}
Parameters
----------
subsystem : str
... | [
"def",
"log_level",
"(",
"self",
",",
"subsystem",
",",
"level",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"subsystem",
",",
"level",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/log/level'",
",",
"args",
",",
"decoder",
... | r"""Changes the logging output of a running daemon.
.. code-block:: python
>>> c.log_level("path", "info")
{'Message': "Changed log level of 'path' to 'info'\n"}
Parameters
----------
subsystem : str
The subsystem logging identifier (Use ``"all"`` f... | [
"r",
"Changes",
"the",
"logging",
"output",
"of",
"a",
"running",
"daemon",
"."
] | python | train |
tilezen/tilequeue | tilequeue/query/rawr.py | https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/query/rawr.py#L616-L632 | def _orient(shape):
"""
The Shapely version of the orient function appears to only work on
Polygons, and fails on MultiPolygons. This is a quick wrapper to allow
orienting of either.
"""
assert shape.geom_type in ('Polygon', 'MultiPolygon')
if shape.geom_type == 'Polygon':
return o... | [
"def",
"_orient",
"(",
"shape",
")",
":",
"assert",
"shape",
".",
"geom_type",
"in",
"(",
"'Polygon'",
",",
"'MultiPolygon'",
")",
"if",
"shape",
".",
"geom_type",
"==",
"'Polygon'",
":",
"return",
"orient",
"(",
"shape",
")",
"else",
":",
"polys",
"=",
... | The Shapely version of the orient function appears to only work on
Polygons, and fails on MultiPolygons. This is a quick wrapper to allow
orienting of either. | [
"The",
"Shapely",
"version",
"of",
"the",
"orient",
"function",
"appears",
"to",
"only",
"work",
"on",
"Polygons",
"and",
"fails",
"on",
"MultiPolygons",
".",
"This",
"is",
"a",
"quick",
"wrapper",
"to",
"allow",
"orienting",
"of",
"either",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L870-L880 | def update_subnet_db_info(self, tenant_id, direc, net_id, subnet_id):
"""Update the subnet DB with Net and Subnet ID, given the subnet. """
subnet_dict = self.retrieve_dcnm_subnet_info(tenant_id, direc)
if not subnet_dict:
LOG.error("Subnet dict not found for tenant %s", tenant_id)
... | [
"def",
"update_subnet_db_info",
"(",
"self",
",",
"tenant_id",
",",
"direc",
",",
"net_id",
",",
"subnet_id",
")",
":",
"subnet_dict",
"=",
"self",
".",
"retrieve_dcnm_subnet_info",
"(",
"tenant_id",
",",
"direc",
")",
"if",
"not",
"subnet_dict",
":",
"LOG",
... | Update the subnet DB with Net and Subnet ID, given the subnet. | [
"Update",
"the",
"subnet",
"DB",
"with",
"Net",
"and",
"Subnet",
"ID",
"given",
"the",
"subnet",
"."
] | python | train |
vsudilov/flask-consulate | flask_consulate/consul.py | https://github.com/vsudilov/flask-consulate/blob/514f8754e7186f960237ed2836206993d5d3d3b6/flask_consulate/consul.py#L78-L109 | def apply_remote_config(self, namespace=None):
"""
Applies all config values defined in consul's kv store to self.app.
There is no guarantee that these values will not be overwritten later
elsewhere.
:param namespace: kv namespace/directory. Defaults to
DEFAULT_... | [
"def",
"apply_remote_config",
"(",
"self",
",",
"namespace",
"=",
"None",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"namespace",
"=",
"\"config/{service}/{environment}/\"",
".",
"format",
"(",
"service",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'SE... | Applies all config values defined in consul's kv store to self.app.
There is no guarantee that these values will not be overwritten later
elsewhere.
:param namespace: kv namespace/directory. Defaults to
DEFAULT_KV_NAMESPACE
:return: None | [
"Applies",
"all",
"config",
"values",
"defined",
"in",
"consul",
"s",
"kv",
"store",
"to",
"self",
".",
"app",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/symmetry/analyzer.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/symmetry/analyzer.py#L1151-L1187 | def _find_spherical_axes(self):
"""
Looks for R5, R4, R3 and R2 axes in spherical top molecules. Point
group T molecules have only one unique 3-fold and one unique 2-fold
axis. O molecules have one unique 4, 3 and 2-fold axes. I molecules
have a unique 5-fold axis.
"""
... | [
"def",
"_find_spherical_axes",
"(",
"self",
")",
":",
"rot_present",
"=",
"defaultdict",
"(",
"bool",
")",
"origin_site",
",",
"dist_el_sites",
"=",
"cluster_sites",
"(",
"self",
".",
"centered_mol",
",",
"self",
".",
"tol",
")",
"test_set",
"=",
"min",
"(",... | Looks for R5, R4, R3 and R2 axes in spherical top molecules. Point
group T molecules have only one unique 3-fold and one unique 2-fold
axis. O molecules have one unique 4, 3 and 2-fold axes. I molecules
have a unique 5-fold axis. | [
"Looks",
"for",
"R5",
"R4",
"R3",
"and",
"R2",
"axes",
"in",
"spherical",
"top",
"molecules",
".",
"Point",
"group",
"T",
"molecules",
"have",
"only",
"one",
"unique",
"3",
"-",
"fold",
"and",
"one",
"unique",
"2",
"-",
"fold",
"axis",
".",
"O",
"mol... | python | train |
zsethna/OLGA | olga/generation_probability.py | https://github.com/zsethna/OLGA/blob/e825c333f0f9a4eb02132e0bcf86f0dca9123114/olga/generation_probability.py#L377-L470 | def format_usage_masks(self, V_usage_mask_in, J_usage_mask_in, print_warnings = True):
"""Format raw usage masks into lists of indices.
Usage masks allows the Pgen computation to be conditioned on the V and J
gene/allele identities. The inputted masks are lists of strings, or a
si... | [
"def",
"format_usage_masks",
"(",
"self",
",",
"V_usage_mask_in",
",",
"J_usage_mask_in",
",",
"print_warnings",
"=",
"True",
")",
":",
"#Format the V usage mask",
"if",
"V_usage_mask_in",
"is",
"None",
":",
"#Default case, use all productive V genes with non-zero probability... | Format raw usage masks into lists of indices.
Usage masks allows the Pgen computation to be conditioned on the V and J
gene/allele identities. The inputted masks are lists of strings, or a
single string, of the names of the genes or alleles to be conditioned on.
The default mask ... | [
"Format",
"raw",
"usage",
"masks",
"into",
"lists",
"of",
"indices",
".",
"Usage",
"masks",
"allows",
"the",
"Pgen",
"computation",
"to",
"be",
"conditioned",
"on",
"the",
"V",
"and",
"J",
"gene",
"/",
"allele",
"identities",
".",
"The",
"inputted",
"masks... | python | train |
blockstack/blockstack-core | blockstack/lib/client.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/client.py#L648-L717 | def get_atlas_peers(hostport, timeout=30, my_hostport=None, proxy=None):
"""
Get an atlas peer's neighbors.
Return {'status': True, 'peers': [peers]} on success.
Return {'error': ...} on error
"""
assert hostport or proxy, 'need either hostport or proxy'
peers_schema = {
'type': 'o... | [
"def",
"get_atlas_peers",
"(",
"hostport",
",",
"timeout",
"=",
"30",
",",
"my_hostport",
"=",
"None",
",",
"proxy",
"=",
"None",
")",
":",
"assert",
"hostport",
"or",
"proxy",
",",
"'need either hostport or proxy'",
"peers_schema",
"=",
"{",
"'type'",
":",
... | Get an atlas peer's neighbors.
Return {'status': True, 'peers': [peers]} on success.
Return {'error': ...} on error | [
"Get",
"an",
"atlas",
"peer",
"s",
"neighbors",
".",
"Return",
"{",
"status",
":",
"True",
"peers",
":",
"[",
"peers",
"]",
"}",
"on",
"success",
".",
"Return",
"{",
"error",
":",
"...",
"}",
"on",
"error"
] | python | train |
jor-/util | util/cache/memory.py | https://github.com/jor-/util/blob/0eb0be84430f88885f4d48335596ca8881f85587/util/cache/memory.py#L35-L51 | def attribute_dependend_key(key_function, *dependencies):
"""Return a cache key for the specified hashable arguments with additional dependent arguments."""
def dependend_key_function(self, *args, **kwargs):
key = hash_key(*args, **kwargs)
if len(dependencies) > 0:
dependec... | [
"def",
"attribute_dependend_key",
"(",
"key_function",
",",
"*",
"dependencies",
")",
":",
"def",
"dependend_key_function",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"hash_key",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs... | Return a cache key for the specified hashable arguments with additional dependent arguments. | [
"Return",
"a",
"cache",
"key",
"for",
"the",
"specified",
"hashable",
"arguments",
"with",
"additional",
"dependent",
"arguments",
"."
] | python | train |
juju/charm-helpers | charmhelpers/contrib/hardening/host/checks/minimize_access.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/minimize_access.py#L22-L50 | def get_audits():
"""Get OS hardening access audits.
:returns: dictionary of audits
"""
audits = []
settings = utils.get_settings('os')
# Remove write permissions from $PATH folders for all regular users.
# This prevents changing system-wide commands from normal users.
path_folders = ... | [
"def",
"get_audits",
"(",
")",
":",
"audits",
"=",
"[",
"]",
"settings",
"=",
"utils",
".",
"get_settings",
"(",
"'os'",
")",
"# Remove write permissions from $PATH folders for all regular users.",
"# This prevents changing system-wide commands from normal users.",
"path_folder... | Get OS hardening access audits.
:returns: dictionary of audits | [
"Get",
"OS",
"hardening",
"access",
"audits",
"."
] | python | train |
siemens/django-dingos | dingos/import_handling.py | https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/import_handling.py#L318-L766 | def xml_import(self,
xml_fname=None,
xml_content=None,
ns_mapping=None,
embedded_predicate=None,
id_and_revision_extractor=None,
extract_empty_embedded=False,
keep_attrs_in_created_refere... | [
"def",
"xml_import",
"(",
"self",
",",
"xml_fname",
"=",
"None",
",",
"xml_content",
"=",
"None",
",",
"ns_mapping",
"=",
"None",
",",
"embedded_predicate",
"=",
"None",
",",
"id_and_revision_extractor",
"=",
"None",
",",
"extract_empty_embedded",
"=",
"False",
... | This is the generic XML import function for dingos. Its parameters
are as follows:
- xml_fname: Filename of the XML file to be read
- xml_content: Alternatively, the xml_content can be provided as string
or as XMLNode (i.e., a piece of XML that has already been parsed)
- ns_ma... | [
"This",
"is",
"the",
"generic",
"XML",
"import",
"function",
"for",
"dingos",
".",
"Its",
"parameters",
"are",
"as",
"follows",
":"
] | python | train |
safarijv/sbo-selenium | sbo_selenium/management/commands/selenium.py | https://github.com/safarijv/sbo-selenium/blob/16539f1b17cda18270033db3b64ab25bc05c5664/sbo_selenium/management/commands/selenium.py#L67-L71 | def clean():
"""Clear out any old screenshots"""
screenshot_dir = settings.SELENIUM_SCREENSHOT_DIR
if screenshot_dir and os.path.isdir(screenshot_dir):
rmtree(screenshot_dir, ignore_errors=True) | [
"def",
"clean",
"(",
")",
":",
"screenshot_dir",
"=",
"settings",
".",
"SELENIUM_SCREENSHOT_DIR",
"if",
"screenshot_dir",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"screenshot_dir",
")",
":",
"rmtree",
"(",
"screenshot_dir",
",",
"ignore_errors",
"=",
"True... | Clear out any old screenshots | [
"Clear",
"out",
"any",
"old",
"screenshots"
] | python | train |
soravux/scoop | examples/dependency/sortingnetwork.py | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/examples/dependency/sortingnetwork.py#L88-L116 | def draw(self):
"""Return an ASCII representation of the network."""
str_wires = [["-"]*7 * self.depth]
str_wires[0][0] = "0"
str_wires[0][1] = " o"
str_spaces = []
for i in range(1, self.dimension):
str_wires.append(["-"]*7 * self.depth)
str_spac... | [
"def",
"draw",
"(",
"self",
")",
":",
"str_wires",
"=",
"[",
"[",
"\"-\"",
"]",
"*",
"7",
"*",
"self",
".",
"depth",
"]",
"str_wires",
"[",
"0",
"]",
"[",
"0",
"]",
"=",
"\"0\"",
"str_wires",
"[",
"0",
"]",
"[",
"1",
"]",
"=",
"\" o\"",
"str_... | Return an ASCII representation of the network. | [
"Return",
"an",
"ASCII",
"representation",
"of",
"the",
"network",
"."
] | python | train |
numenta/htmresearch | htmresearch/frameworks/layers/object_machine_factory.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/object_machine_factory.py#L62-L76 | def createObjectMachine(machineType, **kwargs):
"""
Return an object machine of the appropriate type.
@param machineType (str) A supported ObjectMachine type
@param kwargs (dict) Constructor argument for the class that will be
instantiated. Keyword parameters specific to each... | [
"def",
"createObjectMachine",
"(",
"machineType",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"machineType",
"not",
"in",
"ObjectMachineTypes",
".",
"getTypes",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Unknown model type: \"",
"+",
"machineType",
")",
"retur... | Return an object machine of the appropriate type.
@param machineType (str) A supported ObjectMachine type
@param kwargs (dict) Constructor argument for the class that will be
instantiated. Keyword parameters specific to each
model type should be passed... | [
"Return",
"an",
"object",
"machine",
"of",
"the",
"appropriate",
"type",
"."
] | python | train |
bloomreach/s4cmd | s4cmd.py | https://github.com/bloomreach/s4cmd/blob/bb51075bf43703e7cd95aa39288cf7732ec13a6d/s4cmd.py#L1208-L1223 | def conditional(self, result, obj):
'''Check all file item with given conditions.'''
fileonly = (self.opt.last_modified_before is not None) or (self.opt.last_modified_after is not None)
if obj['is_dir']:
if not fileonly:
result.append(obj)
return
if (self.opt.last_modified_before i... | [
"def",
"conditional",
"(",
"self",
",",
"result",
",",
"obj",
")",
":",
"fileonly",
"=",
"(",
"self",
".",
"opt",
".",
"last_modified_before",
"is",
"not",
"None",
")",
"or",
"(",
"self",
".",
"opt",
".",
"last_modified_after",
"is",
"not",
"None",
")"... | Check all file item with given conditions. | [
"Check",
"all",
"file",
"item",
"with",
"given",
"conditions",
"."
] | python | test |
google/openhtf | openhtf/util/data.py | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L42-L47 | def pprint_diff(first, second, first_name='first', second_name='second'):
"""Compare the pprint representation of two objects and yield diff lines."""
return difflib.unified_diff(
pprint.pformat(first).splitlines(),
pprint.pformat(second).splitlines(),
fromfile=first_name, tofile=second_name, line... | [
"def",
"pprint_diff",
"(",
"first",
",",
"second",
",",
"first_name",
"=",
"'first'",
",",
"second_name",
"=",
"'second'",
")",
":",
"return",
"difflib",
".",
"unified_diff",
"(",
"pprint",
".",
"pformat",
"(",
"first",
")",
".",
"splitlines",
"(",
")",
... | Compare the pprint representation of two objects and yield diff lines. | [
"Compare",
"the",
"pprint",
"representation",
"of",
"two",
"objects",
"and",
"yield",
"diff",
"lines",
"."
] | python | train |
mitsei/dlkit | dlkit/handcar/repository/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/repository/objects.py#L837-L858 | def set_distribute_compositions(self, distribute_comps=None):
"""Sets the distribution rights.
This sets distribute verbatim to ``true``.
:param distribute_comps: right to distribute modifications
:type distribute_comps: ``boolean``
:raise: ``InvalidArgument`` -- ``distribute_c... | [
"def",
"set_distribute_compositions",
"(",
"self",
",",
"distribute_comps",
"=",
"None",
")",
":",
"if",
"distribute_comps",
"is",
"None",
":",
"raise",
"NullArgument",
"(",
")",
"metadata",
"=",
"Metadata",
"(",
"*",
"*",
"settings",
".",
"METADATA",
"[",
"... | Sets the distribution rights.
This sets distribute verbatim to ``true``.
:param distribute_comps: right to distribute modifications
:type distribute_comps: ``boolean``
:raise: ``InvalidArgument`` -- ``distribute_comps`` is invalid
:raise: ``NoAccess`` -- authorization failure
... | [
"Sets",
"the",
"distribution",
"rights",
"."
] | python | train |
mfitzp/padua | padua/visualize.py | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/visualize.py#L1495-L1605 | def kegg_pathway(df, pathway, a, b=None, ids_from="Proteins", cmap=cm.PuOr_r, is_log2=False, fillna=None, z_score=1):
"""
Visualize data on a kegg pathway.
:param df:
:param pathway:
:param a:
:param b:
:param ids_from:
:param cmap:
:param is_log2:
:param fillna:
:param z_s... | [
"def",
"kegg_pathway",
"(",
"df",
",",
"pathway",
",",
"a",
",",
"b",
"=",
"None",
",",
"ids_from",
"=",
"\"Proteins\"",
",",
"cmap",
"=",
"cm",
".",
"PuOr_r",
",",
"is_log2",
"=",
"False",
",",
"fillna",
"=",
"None",
",",
"z_score",
"=",
"1",
")",... | Visualize data on a kegg pathway.
:param df:
:param pathway:
:param a:
:param b:
:param ids_from:
:param cmap:
:param is_log2:
:param fillna:
:param z_score:
:return: | [
"Visualize",
"data",
"on",
"a",
"kegg",
"pathway",
"."
] | python | train |
archman/beamline | beamline/ui/myappframe.py | https://github.com/archman/beamline/blob/417bc5dc13e754bc89d246427984590fced64d07/beamline/ui/myappframe.py#L752-L764 | def pack_found_items(self, s_text, target):
""" pack up found items for search ctrl
:param target: treectrl obj
:param s_text: text to search, lower case
return list of found items
"""
all_children = self.all_children
all_text = [target.GetItemText(i).... | [
"def",
"pack_found_items",
"(",
"self",
",",
"s_text",
",",
"target",
")",
":",
"all_children",
"=",
"self",
".",
"all_children",
"all_text",
"=",
"[",
"target",
".",
"GetItemText",
"(",
"i",
")",
".",
"lower",
"(",
")",
"for",
"i",
"in",
"all_children",... | pack up found items for search ctrl
:param target: treectrl obj
:param s_text: text to search, lower case
return list of found items | [
"pack",
"up",
"found",
"items",
"for",
"search",
"ctrl",
":",
"param",
"target",
":",
"treectrl",
"obj",
":",
"param",
"s_text",
":",
"text",
"to",
"search",
"lower",
"case",
"return",
"list",
"of",
"found",
"items"
] | python | train |
tjkessler/PyGenetics | pygenetics/selection_functions.py | https://github.com/tjkessler/PyGenetics/blob/b78ee6393605d6e85d2279fb05f3983f5833df40/pygenetics/selection_functions.py#L10-L23 | def minimize_best_n(Members):
'''
Orders population members from lowest fitness to highest fitness
Args:
Members (list): list of PyGenetics Member objects
Returns:
lsit: ordered lsit of Members, from highest fitness to lowest fitness
'''
return(list(reversed(sorted(
Me... | [
"def",
"minimize_best_n",
"(",
"Members",
")",
":",
"return",
"(",
"list",
"(",
"reversed",
"(",
"sorted",
"(",
"Members",
",",
"key",
"=",
"lambda",
"Member",
":",
"Member",
".",
"fitness_score",
")",
")",
")",
")"
] | Orders population members from lowest fitness to highest fitness
Args:
Members (list): list of PyGenetics Member objects
Returns:
lsit: ordered lsit of Members, from highest fitness to lowest fitness | [
"Orders",
"population",
"members",
"from",
"lowest",
"fitness",
"to",
"highest",
"fitness"
] | python | test |
sdispater/cachy | cachy/tagged_cache.py | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L153-L179 | def remember(self, key, minutes, callback):
"""
Get an item from the cache, or store the default value.
:param key: The cache key
:type key: str
:param minutes: The lifetime in minutes of the cached value
:type minutes: int or datetime
:param callback: The defa... | [
"def",
"remember",
"(",
"self",
",",
"key",
",",
"minutes",
",",
"callback",
")",
":",
"# If the item exists in the cache we will just return this immediately",
"# otherwise we will execute the given callback and cache the result",
"# of that execution for the given number of minutes in ... | Get an item from the cache, or store the default value.
:param key: The cache key
:type key: str
:param minutes: The lifetime in minutes of the cached value
:type minutes: int or datetime
:param callback: The default function
:type callback: mixed
:rtype: mixe... | [
"Get",
"an",
"item",
"from",
"the",
"cache",
"or",
"store",
"the",
"default",
"value",
"."
] | python | train |
liftoff/pyminifier | pyminifier/minification.py | https://github.com/liftoff/pyminifier/blob/087ea7b0c8c964f1f907c3f350f5ce281798db86/pyminifier/minification.py#L401-L419 | def minify(tokens, options):
"""
Performs minification on *tokens* according to the values in *options*
"""
# Remove comments
remove_comments(tokens)
# Remove docstrings
remove_docstrings(tokens)
result = token_utils.untokenize(tokens)
# Minify our input script
result = multiline... | [
"def",
"minify",
"(",
"tokens",
",",
"options",
")",
":",
"# Remove comments",
"remove_comments",
"(",
"tokens",
")",
"# Remove docstrings",
"remove_docstrings",
"(",
"tokens",
")",
"result",
"=",
"token_utils",
".",
"untokenize",
"(",
"tokens",
")",
"# Minify our... | Performs minification on *tokens* according to the values in *options* | [
"Performs",
"minification",
"on",
"*",
"tokens",
"*",
"according",
"to",
"the",
"values",
"in",
"*",
"options",
"*"
] | python | train |
fastai/fastai | fastai/vision/gan.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L219-L223 | def from_learners(cls, learn_gen:Learner, learn_crit:Learner, switcher:Callback=None,
weights_gen:Tuple[float,float]=None, **learn_kwargs):
"Create a GAN from `learn_gen` and `learn_crit`."
losses = gan_loss_from_func(learn_gen.loss_func, learn_crit.loss_func, weights_gen=weights_g... | [
"def",
"from_learners",
"(",
"cls",
",",
"learn_gen",
":",
"Learner",
",",
"learn_crit",
":",
"Learner",
",",
"switcher",
":",
"Callback",
"=",
"None",
",",
"weights_gen",
":",
"Tuple",
"[",
"float",
",",
"float",
"]",
"=",
"None",
",",
"*",
"*",
"lear... | Create a GAN from `learn_gen` and `learn_crit`. | [
"Create",
"a",
"GAN",
"from",
"learn_gen",
"and",
"learn_crit",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.