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 |
|---|---|---|---|---|---|---|---|---|
jlaine/python-netfilter | netfilter/table.py | https://github.com/jlaine/python-netfilter/blob/e4942c0f6a654a985049b629ead3dc6dcdb30145/netfilter/table.py#L75-L82 | def flush_chain(self, chainname=None):
"""Flushes the specified chain (all the chains in the table if
none is given). This is equivalent to deleting all the rules
one by one.
"""
args = ['-F']
if chainname: args.append(chainname)
self.__run_iptables(args) | [
"def",
"flush_chain",
"(",
"self",
",",
"chainname",
"=",
"None",
")",
":",
"args",
"=",
"[",
"'-F'",
"]",
"if",
"chainname",
":",
"args",
".",
"append",
"(",
"chainname",
")",
"self",
".",
"__run_iptables",
"(",
"args",
")"
] | Flushes the specified chain (all the chains in the table if
none is given). This is equivalent to deleting all the rules
one by one. | [
"Flushes",
"the",
"specified",
"chain",
"(",
"all",
"the",
"chains",
"in",
"the",
"table",
"if",
"none",
"is",
"given",
")",
".",
"This",
"is",
"equivalent",
"to",
"deleting",
"all",
"the",
"rules",
"one",
"by",
"one",
"."
] | python | train |
vaexio/vaex | packages/vaex-core/vaex/dataframe.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/dataframe.py#L1595-L1631 | def plot_widget(self, x, y, z=None, grid=None, shape=256, limits=None, what="count(*)", figsize=None,
f="identity", figure_key=None, fig=None, axes=None, xlabel=None, ylabel=None, title=None,
show=True, selection=[None, True], colormap="afmhot", grid_limits=None, normalize="norma... | [
"def",
"plot_widget",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
"=",
"None",
",",
"grid",
"=",
"None",
",",
"shape",
"=",
"256",
",",
"limits",
"=",
"None",
",",
"what",
"=",
"\"count(*)\"",
",",
"figsize",
"=",
"None",
",",
"f",
"=",
"\"identit... | Viz 1d, 2d or 3d in a Jupyter notebook
.. note::
This API is not fully settled and may change in the future
Example:
>>> df.plot_widget(df.x, df.y, backend='bqplot')
>>> df.plot_widget(df.pickup_longitude, df.pickup_latitude, backend='ipyleaflet')
:param backend: ... | [
"Viz",
"1d",
"2d",
"or",
"3d",
"in",
"a",
"Jupyter",
"notebook"
] | python | test |
Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph_transformer.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph_transformer.py#L38-L55 | def to_wider_graph(graph):
''' wider graph
'''
weighted_layer_ids = graph.wide_layer_ids()
weighted_layer_ids = list(
filter(lambda x: graph.layer_list[x].output.shape[-1], weighted_layer_ids)
)
wider_layers = sample(weighted_layer_ids, 1)
for layer_id in wider_layers:
layer... | [
"def",
"to_wider_graph",
"(",
"graph",
")",
":",
"weighted_layer_ids",
"=",
"graph",
".",
"wide_layer_ids",
"(",
")",
"weighted_layer_ids",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"graph",
".",
"layer_list",
"[",
"x",
"]",
".",
"output",
".",
... | wider graph | [
"wider",
"graph"
] | python | train |
hvac/hvac | hvac/api/secrets_engines/kv_v1.py | https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/api/secrets_engines/kv_v1.py#L36-L58 | def list_secrets(self, path, mount_point=DEFAULT_MOUNT_POINT):
"""Return a list of key names at the specified location.
Folders are suffixed with /. The input must be a folder; list on a file will not return a value. Note that no
policy-based filtering is performed on keys; do not encode sensit... | [
"def",
"list_secrets",
"(",
"self",
",",
"path",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"api_path",
"=",
"'/v1/{mount_point}/{path}'",
".",
"format",
"(",
"mount_point",
"=",
"mount_point",
",",
"path",
"=",
"path",
")",
"response",
"=",
"se... | Return a list of key names at the specified location.
Folders are suffixed with /. The input must be a folder; list on a file will not return a value. Note that no
policy-based filtering is performed on keys; do not encode sensitive information in key names. The values
themselves are not access... | [
"Return",
"a",
"list",
"of",
"key",
"names",
"at",
"the",
"specified",
"location",
"."
] | python | train |
cltl/KafNafParserPy | KafNafParserPy/term_data.py | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/term_data.py#L338-L348 | def add_term(self,term_obj):
"""
Adds a term object to the layer
@type term_obj: L{Cterm}
@param term_obj: the term object
"""
if term_obj.get_id() in self.idx:
raise ValueError("Term with id {} already exists!"
.format(term_obj.ge... | [
"def",
"add_term",
"(",
"self",
",",
"term_obj",
")",
":",
"if",
"term_obj",
".",
"get_id",
"(",
")",
"in",
"self",
".",
"idx",
":",
"raise",
"ValueError",
"(",
"\"Term with id {} already exists!\"",
".",
"format",
"(",
"term_obj",
".",
"get_id",
"(",
")",... | Adds a term object to the layer
@type term_obj: L{Cterm}
@param term_obj: the term object | [
"Adds",
"a",
"term",
"object",
"to",
"the",
"layer"
] | python | train |
PolyJIT/benchbuild | benchbuild/likwid.py | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/likwid.py#L126-L152 | def get_measurements(region, core_info, data, extra_offset=0):
"""
Get the complete measurement info from likwid's region info.
Args:
region: The region we took a measurement in.
core_info: The core information.
data: The raw data.
extra_offset (int): default = 0
Return... | [
"def",
"get_measurements",
"(",
"region",
",",
"core_info",
",",
"data",
",",
"extra_offset",
"=",
"0",
")",
":",
"measurements",
"=",
"[",
"]",
"clean_core_info",
"=",
"[",
"x",
"for",
"x",
"in",
"core_info",
"if",
"x",
"]",
"cores",
"=",
"len",
"(",
... | Get the complete measurement info from likwid's region info.
Args:
region: The region we took a measurement in.
core_info: The core information.
data: The raw data.
extra_offset (int): default = 0
Returns (list((region, metric, core, value))):
A list of measurement tupl... | [
"Get",
"the",
"complete",
"measurement",
"info",
"from",
"likwid",
"s",
"region",
"info",
"."
] | python | train |
saltstack/salt | salt/cli/support/collector.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/collector.py#L203-L220 | def _setup_fun_config(self, fun_conf):
'''
Setup function configuration.
:param conf:
:return:
'''
conf = copy.deepcopy(self.config)
conf['file_client'] = 'local'
conf['fun'] = ''
conf['arg'] = []
conf['kwarg'] = {}
conf['cache_job... | [
"def",
"_setup_fun_config",
"(",
"self",
",",
"fun_conf",
")",
":",
"conf",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"config",
")",
"conf",
"[",
"'file_client'",
"]",
"=",
"'local'",
"conf",
"[",
"'fun'",
"]",
"=",
"''",
"conf",
"[",
"'arg'",
... | Setup function configuration.
:param conf:
:return: | [
"Setup",
"function",
"configuration",
"."
] | python | train |
Dallinger/Dallinger | dallinger/models.py | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1415-L1424 | def fail(self):
"""Fail a vector."""
if self.failed is True:
raise AttributeError("Cannot fail {} - it has already failed.".format(self))
else:
self.failed = True
self.time_of_death = timenow()
for t in self.transmissions():
t.fail... | [
"def",
"fail",
"(",
"self",
")",
":",
"if",
"self",
".",
"failed",
"is",
"True",
":",
"raise",
"AttributeError",
"(",
"\"Cannot fail {} - it has already failed.\"",
".",
"format",
"(",
"self",
")",
")",
"else",
":",
"self",
".",
"failed",
"=",
"True",
"sel... | Fail a vector. | [
"Fail",
"a",
"vector",
"."
] | python | train |
lpantano/seqcluster | seqcluster/seqbuster/__init__.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L130-L146 | def _read_gtf(gtf):
"""
Load GTF file with precursor positions on genome
"""
if not gtf:
return gtf
db = defaultdict(list)
with open(gtf) as in_handle:
for line in in_handle:
if line.startswith("#"):
continue
cols = line.strip().split("\t")... | [
"def",
"_read_gtf",
"(",
"gtf",
")",
":",
"if",
"not",
"gtf",
":",
"return",
"gtf",
"db",
"=",
"defaultdict",
"(",
"list",
")",
"with",
"open",
"(",
"gtf",
")",
"as",
"in_handle",
":",
"for",
"line",
"in",
"in_handle",
":",
"if",
"line",
".",
"star... | Load GTF file with precursor positions on genome | [
"Load",
"GTF",
"file",
"with",
"precursor",
"positions",
"on",
"genome"
] | python | train |
rodluger/everest | everest/missions/k2/k2.py | https://github.com/rodluger/everest/blob/6779591f9f8b3556847e2fbf761bdfac7520eaea/everest/missions/k2/k2.py#L1766-L1785 | def TargetDirectory(ID, season, relative=False, **kwargs):
'''
Returns the location of the :py:mod:`everest` data on disk
for a given target.
:param ID: The target ID
:param int season: The target season number
:param bool relative: Relative path? Default :py:obj:`False`
'''
if season... | [
"def",
"TargetDirectory",
"(",
"ID",
",",
"season",
",",
"relative",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"season",
"is",
"None",
":",
"return",
"None",
"if",
"relative",
":",
"path",
"=",
"''",
"else",
":",
"path",
"=",
"EVEREST_DA... | Returns the location of the :py:mod:`everest` data on disk
for a given target.
:param ID: The target ID
:param int season: The target season number
:param bool relative: Relative path? Default :py:obj:`False` | [
"Returns",
"the",
"location",
"of",
"the",
":",
"py",
":",
"mod",
":",
"everest",
"data",
"on",
"disk",
"for",
"a",
"given",
"target",
"."
] | python | train |
senaite/senaite.core | bika/lims/browser/worksheet/views/analyses.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/worksheet/views/analyses.py#L374-L397 | def fill_slots_headers(self, items):
"""Generates the header cell for each slot. For each slot, the first
cell displays information about the parent all analyses within that
given slot have in common, such as the AR Id, SampleType, etc.
:param items: dictionary with items to be rendered... | [
"def",
"fill_slots_headers",
"(",
"self",
",",
"items",
")",
":",
"prev_position",
"=",
"0",
"for",
"item",
"in",
"items",
":",
"item_position",
"=",
"item",
"[",
"\"Pos\"",
"]",
"if",
"item_position",
"==",
"prev_position",
":",
"item",
"=",
"self",
".",
... | Generates the header cell for each slot. For each slot, the first
cell displays information about the parent all analyses within that
given slot have in common, such as the AR Id, SampleType, etc.
:param items: dictionary with items to be rendered in the list | [
"Generates",
"the",
"header",
"cell",
"for",
"each",
"slot",
".",
"For",
"each",
"slot",
"the",
"first",
"cell",
"displays",
"information",
"about",
"the",
"parent",
"all",
"analyses",
"within",
"that",
"given",
"slot",
"have",
"in",
"common",
"such",
"as",
... | python | train |
bheinzerling/pyrouge | pyrouge/Rouge155.py | https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L208-L235 | def convert_text_to_rouge_format(text, title="dummy title"):
"""
Convert a text to a format ROUGE understands. The text is
assumed to contain one sentence per line.
text: The text to convert, containg one sentence per line.
title: Optional title for the text. The titl... | [
"def",
"convert_text_to_rouge_format",
"(",
"text",
",",
"title",
"=",
"\"dummy title\"",
")",
":",
"sentences",
"=",
"text",
".",
"split",
"(",
"\"\\n\"",
")",
"sent_elems",
"=",
"[",
"\"<a name=\\\"{i}\\\">[{i}]</a> <a href=\\\"#{i}\\\" id={i}>\"",
"\"{text}</a>\"",
"... | Convert a text to a format ROUGE understands. The text is
assumed to contain one sentence per line.
text: The text to convert, containg one sentence per line.
title: Optional title for the text. The title will appear
in the converted file, but doesn't seem to have... | [
"Convert",
"a",
"text",
"to",
"a",
"format",
"ROUGE",
"understands",
".",
"The",
"text",
"is",
"assumed",
"to",
"contain",
"one",
"sentence",
"per",
"line",
"."
] | python | train |
zetaops/zengine | zengine/messaging/lib.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/messaging/lib.py#L89-L92 | def encrypt_password(self):
""" encrypt password if not already encrypted """
if self.password and not self.password.startswith('$pbkdf2'):
self.set_password(self.password) | [
"def",
"encrypt_password",
"(",
"self",
")",
":",
"if",
"self",
".",
"password",
"and",
"not",
"self",
".",
"password",
".",
"startswith",
"(",
"'$pbkdf2'",
")",
":",
"self",
".",
"set_password",
"(",
"self",
".",
"password",
")"
] | encrypt password if not already encrypted | [
"encrypt",
"password",
"if",
"not",
"already",
"encrypted"
] | python | train |
jaywink/federation | federation/protocols/diaspora/protocol.py | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L33-L52 | def identify_request(request: RequestType):
"""Try to identify whether this is a Diaspora request.
Try first public message. Then private message. The check if this is a legacy payload.
"""
# Private encrypted JSON payload
try:
data = json.loads(decode_if_bytes(request.body))
if "en... | [
"def",
"identify_request",
"(",
"request",
":",
"RequestType",
")",
":",
"# Private encrypted JSON payload",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"decode_if_bytes",
"(",
"request",
".",
"body",
")",
")",
"if",
"\"encrypted_magic_envelope\"",
"in",
... | Try to identify whether this is a Diaspora request.
Try first public message. Then private message. The check if this is a legacy payload. | [
"Try",
"to",
"identify",
"whether",
"this",
"is",
"a",
"Diaspora",
"request",
"."
] | python | train |
inveniosoftware/invenio-files-rest | invenio_files_rest/models.py | https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1353-L1365 | def delete(cls, object_version, key=None):
"""Delete tags.
:param object_version: The object version instance or id.
:param key: Key of the tag to delete.
Default: delete all tags.
"""
with db.session.begin_nested():
q = cls.query.filter_by(
... | [
"def",
"delete",
"(",
"cls",
",",
"object_version",
",",
"key",
"=",
"None",
")",
":",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"q",
"=",
"cls",
".",
"query",
".",
"filter_by",
"(",
"version_id",
"=",
"as_object_version_id",
"(... | Delete tags.
:param object_version: The object version instance or id.
:param key: Key of the tag to delete.
Default: delete all tags. | [
"Delete",
"tags",
"."
] | python | train |
PlaidWeb/Pushl | pushl/feeds.py | https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/feeds.py#L95-L137 | async def get_feed(config, url):
""" Get a feed
Arguments:
config -- the configuration
url -- The URL of the feed
retval -- a tuple of feed,previous_version,changed
"""
LOGGER.debug("++WAIT: cache get feed %s", url)
previous = config.cache.get(
'feed', url, schema_version=SCH... | [
"async",
"def",
"get_feed",
"(",
"config",
",",
"url",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"++WAIT: cache get feed %s\"",
",",
"url",
")",
"previous",
"=",
"config",
".",
"cache",
".",
"get",
"(",
"'feed'",
",",
"url",
",",
"schema_version",
"=",
"S... | Get a feed
Arguments:
config -- the configuration
url -- The URL of the feed
retval -- a tuple of feed,previous_version,changed | [
"Get",
"a",
"feed"
] | python | train |
aschn/drf-tracking | rest_framework_tracking/base_mixins.py | https://github.com/aschn/drf-tracking/blob/1910f413bd5166bbeaf694c7c0101f331af4f47d/rest_framework_tracking/base_mixins.py#L100-L106 | def _get_ip_address(self, request):
"""Get the remote ip address the request was generated from. """
ipaddr = request.META.get("HTTP_X_FORWARDED_FOR", None)
if ipaddr:
# X_FORWARDED_FOR returns client1, proxy1, proxy2,...
return ipaddr.split(",")[0].strip()
return... | [
"def",
"_get_ip_address",
"(",
"self",
",",
"request",
")",
":",
"ipaddr",
"=",
"request",
".",
"META",
".",
"get",
"(",
"\"HTTP_X_FORWARDED_FOR\"",
",",
"None",
")",
"if",
"ipaddr",
":",
"# X_FORWARDED_FOR returns client1, proxy1, proxy2,...",
"return",
"ipaddr",
... | Get the remote ip address the request was generated from. | [
"Get",
"the",
"remote",
"ip",
"address",
"the",
"request",
"was",
"generated",
"from",
"."
] | python | train |
pmuller/versions | versions/packages.py | https://github.com/pmuller/versions/blob/951bc3fd99b6a675190f11ee0752af1d7ff5b440/versions/packages.py#L84-L93 | def build_options(self):
"""The package build options.
:returns: :func:`set` of build options strings.
"""
if self.version.build_metadata:
return set(self.version.build_metadata.split('.'))
else:
return set() | [
"def",
"build_options",
"(",
"self",
")",
":",
"if",
"self",
".",
"version",
".",
"build_metadata",
":",
"return",
"set",
"(",
"self",
".",
"version",
".",
"build_metadata",
".",
"split",
"(",
"'.'",
")",
")",
"else",
":",
"return",
"set",
"(",
")"
] | The package build options.
:returns: :func:`set` of build options strings. | [
"The",
"package",
"build",
"options",
"."
] | python | train |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/subscribe/channels/channel.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/subscribe/channels/channel.py#L109-L123 | def _filter_optional_keys(self, data):
"""Filtering for this channel, based on key-value matching"""
for filter_key, filter_value in (self._optional_filters or {}).items():
data_value = data.get(filter_key)
LOG.debug(
'optional keys filter %s: %s (%s)',
... | [
"def",
"_filter_optional_keys",
"(",
"self",
",",
"data",
")",
":",
"for",
"filter_key",
",",
"filter_value",
"in",
"(",
"self",
".",
"_optional_filters",
"or",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"data_value",
"=",
"data",
".",
"get",
"(",
"fi... | Filtering for this channel, based on key-value matching | [
"Filtering",
"for",
"this",
"channel",
"based",
"on",
"key",
"-",
"value",
"matching"
] | python | train |
crytic/slither | slither/printers/summary/variable_order.py | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/printers/summary/variable_order.py#L15-L31 | def output(self, _filename):
"""
_filename is not used
Args:
_filename(string)
"""
txt = ''
for contract in self.slither.contracts_derived:
txt += '\n{}:\n'.format(contract.name)
table = PrettyTable(['Name', 'Type'])
... | [
"def",
"output",
"(",
"self",
",",
"_filename",
")",
":",
"txt",
"=",
"''",
"for",
"contract",
"in",
"self",
".",
"slither",
".",
"contracts_derived",
":",
"txt",
"+=",
"'\\n{}:\\n'",
".",
"format",
"(",
"contract",
".",
"name",
")",
"table",
"=",
"Pre... | _filename is not used
Args:
_filename(string) | [
"_filename",
"is",
"not",
"used",
"Args",
":",
"_filename",
"(",
"string",
")"
] | python | train |
polyaxon/polyaxon-cli | polyaxon_cli/cli/run.py | https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/run.py#L48-L211 | def run(ctx, project, file, name, tags, description, ttl, u, l): # pylint:disable=redefined-builtin
"""Run polyaxonfile specification.
Examples:
\b
```bash
$ polyaxon run -f file -f file_override ...
```
Upload before running
\b
```bash
$ polyaxon run -f file -u
```
... | [
"def",
"run",
"(",
"ctx",
",",
"project",
",",
"file",
",",
"name",
",",
"tags",
",",
"description",
",",
"ttl",
",",
"u",
",",
"l",
")",
":",
"# pylint:disable=redefined-builtin",
"if",
"not",
"file",
":",
"file",
"=",
"PolyaxonFile",
".",
"check_defaul... | Run polyaxonfile specification.
Examples:
\b
```bash
$ polyaxon run -f file -f file_override ...
```
Upload before running
\b
```bash
$ polyaxon run -f file -u
```
Run and set description and tags for this run
\b
```bash
$ polyaxon run -f file -u --descripti... | [
"Run",
"polyaxonfile",
"specification",
"."
] | python | valid |
Neurita/boyle | boyle/nifti/sets.py | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/sets.py#L100-L132 | def check_compatibility(self, one_img, another_img=None):
"""
Parameters
----------
one_img: str or img-like object.
See NeuroImage constructor docstring.
anoter_img: str or img-like object.
See NeuroImage constructor docstring.
If None will u... | [
"def",
"check_compatibility",
"(",
"self",
",",
"one_img",
",",
"another_img",
"=",
"None",
")",
":",
"if",
"another_img",
"is",
"None",
":",
"if",
"len",
"(",
"self",
".",
"items",
")",
">",
"0",
":",
"another_img",
"=",
"self",
".",
"items",
"[",
"... | Parameters
----------
one_img: str or img-like object.
See NeuroImage constructor docstring.
anoter_img: str or img-like object.
See NeuroImage constructor docstring.
If None will use the first image of self.images, if there is any.
Raises
--... | [
"Parameters",
"----------",
"one_img",
":",
"str",
"or",
"img",
"-",
"like",
"object",
".",
"See",
"NeuroImage",
"constructor",
"docstring",
"."
] | python | valid |
jhermann/rituals | src/rituals/util/scm/__init__.py | https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/scm/__init__.py#L33-L42 | def auto_detect(workdir):
""" Return string signifying the SCM used in the given directory.
Currently, 'git' is supported. Anything else returns 'unknown'.
"""
# Any additions here also need a change to `SCM_PROVIDERS`!
if os.path.isdir(os.path.join(workdir, '.git')) and os.path.isfile(os.path.... | [
"def",
"auto_detect",
"(",
"workdir",
")",
":",
"# Any additions here also need a change to `SCM_PROVIDERS`!",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"workdir",
",",
"'.git'",
")",
")",
"and",
"os",
".",
"path",
".",... | Return string signifying the SCM used in the given directory.
Currently, 'git' is supported. Anything else returns 'unknown'. | [
"Return",
"string",
"signifying",
"the",
"SCM",
"used",
"in",
"the",
"given",
"directory",
"."
] | python | valid |
log2timeline/plaso | plaso/parsers/olecf_plugins/dtfabric_plugin.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/olecf_plugins/dtfabric_plugin.py#L103-L142 | def _ReadData(self, file_object, file_offset, data_size):
"""Reads data.
Args:
file_object (dvfvs.FileIO): a file-like object to read.
file_offset (int): offset of the data relative to the start of
the file-like object.
data_size (int): size of the data. The resulting data size much... | [
"def",
"_ReadData",
"(",
"self",
",",
"file_object",
",",
"file_offset",
",",
"data_size",
")",
":",
"if",
"not",
"file_object",
":",
"raise",
"ValueError",
"(",
"'Missing file-like object.'",
")",
"file_object",
".",
"seek",
"(",
"file_offset",
",",
"os",
"."... | Reads data.
Args:
file_object (dvfvs.FileIO): a file-like object to read.
file_offset (int): offset of the data relative to the start of
the file-like object.
data_size (int): size of the data. The resulting data size much match
the requested data size so that dtFabric can map... | [
"Reads",
"data",
"."
] | python | train |
ranaroussi/pywallet | pywallet/utils/ethereum.py | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/ethereum.py#L638-L664 | def from_signature(message, signature):
""" Attempts to create PublicKey object by deriving it
from the message and signature.
Args:
message (bytes): The message to be verified.
signature (Signature): The signature for message.
The recovery_id must not be ... | [
"def",
"from_signature",
"(",
"message",
",",
"signature",
")",
":",
"if",
"signature",
".",
"recovery_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"The signature must have a recovery_id.\"",
")",
"msg",
"=",
"get_bytes",
"(",
"message",
")",
"pub_keys",
... | Attempts to create PublicKey object by deriving it
from the message and signature.
Args:
message (bytes): The message to be verified.
signature (Signature): The signature for message.
The recovery_id must not be None!
Returns:
PublicKey:
... | [
"Attempts",
"to",
"create",
"PublicKey",
"object",
"by",
"deriving",
"it",
"from",
"the",
"message",
"and",
"signature",
"."
] | python | train |
CI-WATER/gsshapy | gsshapy/orm/idx.py | https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/orm/idx.py#L137-L168 | def write(self, directory, name=None, session=None, replaceParamFile=None):
"""
Index Map Write to File Method
"""
# Initiate file
if name != None:
filename = '%s.%s' % (name, self.fileExtension)
filePath = os.path.join(directory, filename)
else:
... | [
"def",
"write",
"(",
"self",
",",
"directory",
",",
"name",
"=",
"None",
",",
"session",
"=",
"None",
",",
"replaceParamFile",
"=",
"None",
")",
":",
"# Initiate file",
"if",
"name",
"!=",
"None",
":",
"filename",
"=",
"'%s.%s'",
"%",
"(",
"name",
",",... | Index Map Write to File Method | [
"Index",
"Map",
"Write",
"to",
"File",
"Method"
] | python | train |
bitesofcode/projexui | projexui/widgets/xnodewidget/xnodescene.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodescene.py#L1436-L1446 | def setModified( self, state = True ):
"""
Flags the scene as being modified based on the inputed value.
:param state <bool>
"""
if ( state == self._modified ):
return
self._modified = state
self.emitModifiedStateChanged() | [
"def",
"setModified",
"(",
"self",
",",
"state",
"=",
"True",
")",
":",
"if",
"(",
"state",
"==",
"self",
".",
"_modified",
")",
":",
"return",
"self",
".",
"_modified",
"=",
"state",
"self",
".",
"emitModifiedStateChanged",
"(",
")"
] | Flags the scene as being modified based on the inputed value.
:param state <bool> | [
"Flags",
"the",
"scene",
"as",
"being",
"modified",
"based",
"on",
"the",
"inputed",
"value",
".",
":",
"param",
"state",
"<bool",
">"
] | python | train |
waqasbhatti/astrobase | astrobase/services/mast.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/mast.py#L342-L448 | def tic_conesearch(
ra,
decl,
radius_arcmin=5.0,
apiversion='v0',
forcefetch=False,
cachedir='~/.astrobase/mast-cache',
verbose=True,
timeout=10.0,
refresh=5.0,
maxtimeout=90.0,
maxtries=3,
jitter=5.0,
raiseonfail=Fa... | [
"def",
"tic_conesearch",
"(",
"ra",
",",
"decl",
",",
"radius_arcmin",
"=",
"5.0",
",",
"apiversion",
"=",
"'v0'",
",",
"forcefetch",
"=",
"False",
",",
"cachedir",
"=",
"'~/.astrobase/mast-cache'",
",",
"verbose",
"=",
"True",
",",
"timeout",
"=",
"10.0",
... | This runs a TESS Input Catalog cone search on MAST.
If you use this, please cite the TIC paper (Stassun et al 2018;
http://adsabs.harvard.edu/abs/2018AJ....156..102S). Also see the "living"
TESS input catalog docs:
https://docs.google.com/document/d/1zdiKMs4Ld4cXZ2DW4lMX-fuxAF6hPHTjqjIwGqnfjqI
Al... | [
"This",
"runs",
"a",
"TESS",
"Input",
"Catalog",
"cone",
"search",
"on",
"MAST",
"."
] | python | valid |
pilosus/ForgeryPy3 | forgery_py/forgery/credit_card.py | https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/credit_card.py#L73-L107 | def number(type=None, length=None, prefixes=None):
"""
Return a random credit card number.
:param type: credit card type. Defaults to a random selection.
:param length: length of the credit card number.
Defaults to the length for the selected card type.
:param prefixes: allowed p... | [
"def",
"number",
"(",
"type",
"=",
"None",
",",
"length",
"=",
"None",
",",
"prefixes",
"=",
"None",
")",
":",
"# select credit card type",
"if",
"type",
"and",
"type",
"in",
"CARDS",
":",
"card",
"=",
"type",
"else",
":",
"card",
"=",
"random",
".",
... | Return a random credit card number.
:param type: credit card type. Defaults to a random selection.
:param length: length of the credit card number.
Defaults to the length for the selected card type.
:param prefixes: allowed prefixes for the card number.
Defaults to p... | [
"Return",
"a",
"random",
"credit",
"card",
"number",
"."
] | python | valid |
maikelboogerd/eventcore | eventcore/decorators.py | https://github.com/maikelboogerd/eventcore/blob/3675f15344d70111874e0f5e5d3305c925dd38d4/eventcore/decorators.py#L18-L36 | def dispatch_event(event, subject='id'):
"""
Dispatch an event when the decorated method is called.
:param event: the event class to instantiate and dispatch.
:param subject_property: the property name to get the subject.
"""
def wrapper(method):
def inner_wrapper(*args, **kwargs):
... | [
"def",
"dispatch_event",
"(",
"event",
",",
"subject",
"=",
"'id'",
")",
":",
"def",
"wrapper",
"(",
"method",
")",
":",
"def",
"inner_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"resource",
"=",
"method",
"(",
"*",
"args",
",",
... | Dispatch an event when the decorated method is called.
:param event: the event class to instantiate and dispatch.
:param subject_property: the property name to get the subject. | [
"Dispatch",
"an",
"event",
"when",
"the",
"decorated",
"method",
"is",
"called",
".",
":",
"param",
"event",
":",
"the",
"event",
"class",
"to",
"instantiate",
"and",
"dispatch",
".",
":",
"param",
"subject_property",
":",
"the",
"property",
"name",
"to",
... | python | train |
GMadorell/abris | abris_transform/abris.py | https://github.com/GMadorell/abris/blob/0d8ab7ec506835a45fae6935d129f5d7e6937bb2/abris_transform/abris.py#L32-L40 | def apply(self, data_source):
"""
Called with the predict data (new information).
@param data_source: Either a pandas.DataFrame or a file-like object.
"""
dataframe = self.__get_dataframe(data_source, use_target=False)
dataframe = self.__cleaner.apply(dataframe)
d... | [
"def",
"apply",
"(",
"self",
",",
"data_source",
")",
":",
"dataframe",
"=",
"self",
".",
"__get_dataframe",
"(",
"data_source",
",",
"use_target",
"=",
"False",
")",
"dataframe",
"=",
"self",
".",
"__cleaner",
".",
"apply",
"(",
"dataframe",
")",
"datafra... | Called with the predict data (new information).
@param data_source: Either a pandas.DataFrame or a file-like object. | [
"Called",
"with",
"the",
"predict",
"data",
"(",
"new",
"information",
")",
"."
] | python | train |
blockstack/blockstack-core | blockstack/blockstackd.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2431-L2484 | def genesis_block_load(module_path=None):
"""
Make sure the genesis block is good to go.
Load and instantiate it.
"""
if os.environ.get('BLOCKSTACK_GENESIS_BLOCK_PATH') is not None:
log.warning('Using envar-given genesis block')
module_path = os.environ['BLOCKSTACK_GENESIS_BLOCK_PATH... | [
"def",
"genesis_block_load",
"(",
"module_path",
"=",
"None",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'BLOCKSTACK_GENESIS_BLOCK_PATH'",
")",
"is",
"not",
"None",
":",
"log",
".",
"warning",
"(",
"'Using envar-given genesis block'",
")",
"module_p... | Make sure the genesis block is good to go.
Load and instantiate it. | [
"Make",
"sure",
"the",
"genesis",
"block",
"is",
"good",
"to",
"go",
".",
"Load",
"and",
"instantiate",
"it",
"."
] | python | train |
bjodah/pyodesys | pyodesys/symbolic.py | https://github.com/bjodah/pyodesys/blob/0034a6165b550d8d9808baef58678dca5a493ab7/pyodesys/symbolic.py#L466-L508 | def from_other(cls, ori, **kwargs):
""" Creates a new instance with an existing one as a template.
Parameters
----------
ori : SymbolicSys instance
\\*\\*kwargs:
Keyword arguments used to create the new instance.
Returns
-------
A new instanc... | [
"def",
"from_other",
"(",
"cls",
",",
"ori",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"k",
"in",
"cls",
".",
"_attrs_to_copy",
"+",
"(",
"'params'",
",",
"'roots'",
",",
"'init_indep'",
",",
"'init_dep'",
")",
":",
"if",
"k",
"not",
"in",
"kwargs",
... | Creates a new instance with an existing one as a template.
Parameters
----------
ori : SymbolicSys instance
\\*\\*kwargs:
Keyword arguments used to create the new instance.
Returns
-------
A new instance of the class. | [
"Creates",
"a",
"new",
"instance",
"with",
"an",
"existing",
"one",
"as",
"a",
"template",
"."
] | python | train |
mouse-reeve/horoscope-generator | horoscope_generator/HoroscopeGenerator.py | https://github.com/mouse-reeve/horoscope-generator/blob/01acf298116745ded5819d348c28a98a7492ccf3/horoscope_generator/HoroscopeGenerator.py#L17-L38 | def get_sentence(start=None, depth=7):
''' follow the grammatical patterns to generate a random sentence '''
if not GRAMMAR:
return 'Please set a GRAMMAR file'
start = start if start else GRAMMAR.start()
if isinstance(start, Nonterminal):
productions = GRAMMAR.productions(start)
... | [
"def",
"get_sentence",
"(",
"start",
"=",
"None",
",",
"depth",
"=",
"7",
")",
":",
"if",
"not",
"GRAMMAR",
":",
"return",
"'Please set a GRAMMAR file'",
"start",
"=",
"start",
"if",
"start",
"else",
"GRAMMAR",
".",
"start",
"(",
")",
"if",
"isinstance",
... | follow the grammatical patterns to generate a random sentence | [
"follow",
"the",
"grammatical",
"patterns",
"to",
"generate",
"a",
"random",
"sentence"
] | python | train |
square/pylink | pylink/jlink.py | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3411-L3459 | def num_available_breakpoints(self, arm=False, thumb=False, ram=False, flash=False, hw=False):
"""Returns the number of available breakpoints of the specified type.
If ``arm`` is set, gets the number of available ARM breakpoint units.
If ``thumb`` is set, gets the number of available THUMB brea... | [
"def",
"num_available_breakpoints",
"(",
"self",
",",
"arm",
"=",
"False",
",",
"thumb",
"=",
"False",
",",
"ram",
"=",
"False",
",",
"flash",
"=",
"False",
",",
"hw",
"=",
"False",
")",
":",
"flags",
"=",
"[",
"enums",
".",
"JLinkBreakpoint",
".",
"... | Returns the number of available breakpoints of the specified type.
If ``arm`` is set, gets the number of available ARM breakpoint units.
If ``thumb`` is set, gets the number of available THUMB breakpoint
units. If ``ram`` is set, gets the number of available software RAM
breakpoint uni... | [
"Returns",
"the",
"number",
"of",
"available",
"breakpoints",
"of",
"the",
"specified",
"type",
"."
] | python | train |
spyder-ide/pywinpty | winpty/ptyprocess.py | https://github.com/spyder-ide/pywinpty/blob/f4461cde9f0c53047e61e9eff7f7ec21ecbc4573/winpty/ptyprocess.py#L227-L241 | def terminate(self, force=False):
"""This forces a child process to terminate."""
if not self.isalive():
return True
self.kill(signal.SIGINT)
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
if force:
self.kill(si... | [
"def",
"terminate",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"isalive",
"(",
")",
":",
"return",
"True",
"self",
".",
"kill",
"(",
"signal",
".",
"SIGINT",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"delayafter... | This forces a child process to terminate. | [
"This",
"forces",
"a",
"child",
"process",
"to",
"terminate",
"."
] | python | train |
Fire-Proof/cuepy | cuepy/cuepy.py | https://github.com/Fire-Proof/cuepy/blob/5add7d62a31589bcdc7d2103c9c482bf718556ec/cuepy/cuepy.py#L48-L58 | def device_count(self):
"""
Find amount of CUE devices
:returns: amount of CUE devices
:rtype: int
"""
device_count = get_device_count(self.corsair_sdk)
if device_count == -1:
self._raise_corsair_error()
return device_count | [
"def",
"device_count",
"(",
"self",
")",
":",
"device_count",
"=",
"get_device_count",
"(",
"self",
".",
"corsair_sdk",
")",
"if",
"device_count",
"==",
"-",
"1",
":",
"self",
".",
"_raise_corsair_error",
"(",
")",
"return",
"device_count"
] | Find amount of CUE devices
:returns: amount of CUE devices
:rtype: int | [
"Find",
"amount",
"of",
"CUE",
"devices"
] | python | train |
ttu/ruuvitag-sensor | examples/post_to_influxdb.py | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/examples/post_to_influxdb.py#L35-L63 | def convert_to_influx(mac, payload):
'''
Convert data into RuuviCollector naming schme and scale
returns:
Object to be written to InfluxDB
'''
dataFormat = payload["data_format"] if ('data_format' in payload) else None
fields = {}
fields["temperature"] = payload["tempe... | [
"def",
"convert_to_influx",
"(",
"mac",
",",
"payload",
")",
":",
"dataFormat",
"=",
"payload",
"[",
"\"data_format\"",
"]",
"if",
"(",
"'data_format'",
"in",
"payload",
")",
"else",
"None",
"fields",
"=",
"{",
"}",
"fields",
"[",
"\"temperature\"",
"]",
"... | Convert data into RuuviCollector naming schme and scale
returns:
Object to be written to InfluxDB | [
"Convert",
"data",
"into",
"RuuviCollector",
"naming",
"schme",
"and",
"scale"
] | python | train |
cuihantao/andes | andes/models/base.py | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1211-L1218 | def _param_to_list(self):
"""
Convert parameters defined in `self._param` to list
:return None
"""
for item in self._params:
self.__dict__[item] = list(self.__dict__[item]) | [
"def",
"_param_to_list",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"_params",
":",
"self",
".",
"__dict__",
"[",
"item",
"]",
"=",
"list",
"(",
"self",
".",
"__dict__",
"[",
"item",
"]",
")"
] | Convert parameters defined in `self._param` to list
:return None | [
"Convert",
"parameters",
"defined",
"in",
"self",
".",
"_param",
"to",
"list"
] | python | train |
codeinn/vcs | vcs/cli.py | https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/cli.py#L319-L326 | def handle(self, *args, **options):
"""
Runs ``pre_process``, ``handle_repo`` and ``post_process`` methods, in
that order.
"""
self.pre_process(self.repo)
self.handle_repo(self.repo, *args, **options)
self.post_process(self.repo, **options) | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"pre_process",
"(",
"self",
".",
"repo",
")",
"self",
".",
"handle_repo",
"(",
"self",
".",
"repo",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
... | Runs ``pre_process``, ``handle_repo`` and ``post_process`` methods, in
that order. | [
"Runs",
"pre_process",
"handle_repo",
"and",
"post_process",
"methods",
"in",
"that",
"order",
"."
] | python | train |
geronimp/graftM | graftm/unpack_sequences.py | https://github.com/geronimp/graftM/blob/c82576517290167f605fd0bc4facd009cee29f48/graftm/unpack_sequences.py#L108-L111 | def basename(self):
'''Return the name of the file with the '.fasta' or 'fq.gz' etc
removed'''
return os.path.basename(self.read_file)[:-len(self._get_extension(self.read_file))] | [
"def",
"basename",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"read_file",
")",
"[",
":",
"-",
"len",
"(",
"self",
".",
"_get_extension",
"(",
"self",
".",
"read_file",
")",
")",
"]"
] | Return the name of the file with the '.fasta' or 'fq.gz' etc
removed | [
"Return",
"the",
"name",
"of",
"the",
"file",
"with",
"the",
".",
"fasta",
"or",
"fq",
".",
"gz",
"etc",
"removed"
] | python | train |
blackecho/Deep-Learning-TensorFlow | yadlt/utils/utilities.py | https://github.com/blackecho/Deep-Learning-TensorFlow/blob/ddeb1f2848da7b7bee166ad2152b4afc46bb2086/yadlt/utils/utilities.py#L156-L170 | def masking_noise(data, sess, v):
"""Apply masking noise to data in X.
In other words a fraction v of elements of X
(chosen at random) is forced to zero.
:param data: array_like, Input data
:param sess: TensorFlow session
:param v: fraction of elements to distort, float
:return: transformed... | [
"def",
"masking_noise",
"(",
"data",
",",
"sess",
",",
"v",
")",
":",
"data_noise",
"=",
"data",
".",
"copy",
"(",
")",
"rand",
"=",
"tf",
".",
"random_uniform",
"(",
"data",
".",
"shape",
")",
"data_noise",
"[",
"sess",
".",
"run",
"(",
"tf",
".",... | Apply masking noise to data in X.
In other words a fraction v of elements of X
(chosen at random) is forced to zero.
:param data: array_like, Input data
:param sess: TensorFlow session
:param v: fraction of elements to distort, float
:return: transformed data | [
"Apply",
"masking",
"noise",
"to",
"data",
"in",
"X",
"."
] | python | train |
pyviz/imagen | imagen/transferfn/__init__.py | https://github.com/pyviz/imagen/blob/53c5685c880f54b42795964d8db50b02e8590e88/imagen/transferfn/__init__.py#L31-L42 | def initialize(self, **kwargs):
"""
Transfer functions may need additional information before the
supplied numpy array can be modified in place. For instance,
transfer functions may have state which needs to be allocated
in memory with a certain size. In other cases, the transfe... | [
"def",
"initialize",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"set",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
".",
"issuperset",
"(",
"self",
".",
"init_keys",
")",
":",
"raise",
"Exception",
"(",
"\"TransferFn needs to be initializ... | Transfer functions may need additional information before the
supplied numpy array can be modified in place. For instance,
transfer functions may have state which needs to be allocated
in memory with a certain size. In other cases, the transfer
function may need to know about the coordin... | [
"Transfer",
"functions",
"may",
"need",
"additional",
"information",
"before",
"the",
"supplied",
"numpy",
"array",
"can",
"be",
"modified",
"in",
"place",
".",
"For",
"instance",
"transfer",
"functions",
"may",
"have",
"state",
"which",
"needs",
"to",
"be",
"... | python | train |
draperjames/qtpandas | qtpandas/views/CustomDelegates.py | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CustomDelegates.py#L238-L248 | def setModelData(self, editor, model, index):
"""Gets data from the editor widget and stores it in the specified model at the item index.
Args:
editor (QtGui.QLineEdit): editor widget.
model (QAbstractItemModel): parent model.
index (QModelIndex): model data index.
... | [
"def",
"setModelData",
"(",
"self",
",",
"editor",
",",
"model",
",",
"index",
")",
":",
"if",
"index",
".",
"isValid",
"(",
")",
":",
"value",
"=",
"editor",
".",
"text",
"(",
")",
"model",
".",
"setData",
"(",
"index",
",",
"value",
",",
"QtCore"... | Gets data from the editor widget and stores it in the specified model at the item index.
Args:
editor (QtGui.QLineEdit): editor widget.
model (QAbstractItemModel): parent model.
index (QModelIndex): model data index. | [
"Gets",
"data",
"from",
"the",
"editor",
"widget",
"and",
"stores",
"it",
"in",
"the",
"specified",
"model",
"at",
"the",
"item",
"index",
"."
] | python | train |
klmitch/appathy | appathy/actions.py | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/actions.py#L129-L162 | def serializer(self, req):
"""
Selects and returns the serializer to use, based on the
serializers declared on the action method and its extensions.
The returned content type is selected based on the types
available and the best match generated from the HTTP `Accept`
head... | [
"def",
"serializer",
"(",
"self",
",",
"req",
")",
":",
"# Select the best match serializer",
"content_types",
"=",
"self",
".",
"method",
".",
"serializers",
".",
"get_types",
"(",
")",
"content_type",
"=",
"req",
".",
"accept",
".",
"best_match",
"(",
"conte... | Selects and returns the serializer to use, based on the
serializers declared on the action method and its extensions.
The returned content type is selected based on the types
available and the best match generated from the HTTP `Accept`
header. Raises `HTTPNotAcceptable` if the request ... | [
"Selects",
"and",
"returns",
"the",
"serializer",
"to",
"use",
"based",
"on",
"the",
"serializers",
"declared",
"on",
"the",
"action",
"method",
"and",
"its",
"extensions",
".",
"The",
"returned",
"content",
"type",
"is",
"selected",
"based",
"on",
"the",
"t... | python | train |
ddorn/GUI | GUI/draw.py | https://github.com/ddorn/GUI/blob/e1fcb5286d24e0995f280d5180222e51895c368c/GUI/draw.py#L71-L122 | def ring(surf, xy, r, width, color):
"""Draws a ring"""
r2 = r - width
x0, y0 = xy
x = r2
y = 0
err = 0
# collect points of the inner circle
right = {}
while x >= y:
right[x] = y
right[y] = x
right[-x] = y
right[-y] = x
y += 1
if er... | [
"def",
"ring",
"(",
"surf",
",",
"xy",
",",
"r",
",",
"width",
",",
"color",
")",
":",
"r2",
"=",
"r",
"-",
"width",
"x0",
",",
"y0",
"=",
"xy",
"x",
"=",
"r2",
"y",
"=",
"0",
"err",
"=",
"0",
"# collect points of the inner circle",
"right",
"=",... | Draws a ring | [
"Draws",
"a",
"ring"
] | python | train |
briancappello/flask-unchained | flask_unchained/bundles/security/services/security_utils_service.py | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_utils_service.py#L45-L65 | def verify_password(self, user, password):
"""
Returns ``True`` if the password is valid for the specified user.
Additionally, the hashed password in the database is updated if the
hashing algorithm happens to have changed.
:param user: The user to verify against
:param... | [
"def",
"verify_password",
"(",
"self",
",",
"user",
",",
"password",
")",
":",
"if",
"self",
".",
"use_double_hash",
"(",
"user",
".",
"password",
")",
":",
"verified",
"=",
"self",
".",
"security",
".",
"pwd_context",
".",
"verify",
"(",
"self",
".",
... | Returns ``True`` if the password is valid for the specified user.
Additionally, the hashed password in the database is updated if the
hashing algorithm happens to have changed.
:param user: The user to verify against
:param password: The plaintext password to verify | [
"Returns",
"True",
"if",
"the",
"password",
"is",
"valid",
"for",
"the",
"specified",
"user",
"."
] | python | train |
ArchiveTeam/wpull | wpull/protocol/http/web.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/web.py#L133-L152 | def _process_response(self, response: Response):
'''Handle the response and update the internal state.'''
_logger.debug('Handling response')
self._redirect_tracker.load(response)
if self._redirect_tracker.is_redirect():
self._process_redirect()
self._loop_type =... | [
"def",
"_process_response",
"(",
"self",
",",
"response",
":",
"Response",
")",
":",
"_logger",
".",
"debug",
"(",
"'Handling response'",
")",
"self",
".",
"_redirect_tracker",
".",
"load",
"(",
"response",
")",
"if",
"self",
".",
"_redirect_tracker",
".",
"... | Handle the response and update the internal state. | [
"Handle",
"the",
"response",
"and",
"update",
"the",
"internal",
"state",
"."
] | python | train |
aichaos/rivescript-python | rivescript/rivescript.py | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L521-L555 | def sort_replies(self, thats=False):
"""Sort the loaded triggers in memory.
After you have finished loading your RiveScript code, call this method
to populate the various internal sort buffers. This is absolutely
necessary for reply matching to work efficiently!
"""
# (R... | [
"def",
"sort_replies",
"(",
"self",
",",
"thats",
"=",
"False",
")",
":",
"# (Re)initialize the sort cache.",
"self",
".",
"_sorted",
"[",
"\"topics\"",
"]",
"=",
"{",
"}",
"self",
".",
"_sorted",
"[",
"\"thats\"",
"]",
"=",
"{",
"}",
"self",
".",
"_say"... | Sort the loaded triggers in memory.
After you have finished loading your RiveScript code, call this method
to populate the various internal sort buffers. This is absolutely
necessary for reply matching to work efficiently! | [
"Sort",
"the",
"loaded",
"triggers",
"in",
"memory",
"."
] | python | train |
wright-group/WrightTools | WrightTools/kit/_list.py | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_list.py#L17-L52 | def flatten_list(items, seqtypes=(list, tuple), in_place=True):
"""Flatten an irregular sequence.
Works generally but may be slower than it could
be if you can make assumptions about your list.
`Source`__
__ https://stackoverflow.com/a/10824086
Parameters
----------
items : iterable
... | [
"def",
"flatten_list",
"(",
"items",
",",
"seqtypes",
"=",
"(",
"list",
",",
"tuple",
")",
",",
"in_place",
"=",
"True",
")",
":",
"if",
"not",
"in_place",
":",
"items",
"=",
"items",
"[",
":",
"]",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"... | Flatten an irregular sequence.
Works generally but may be slower than it could
be if you can make assumptions about your list.
`Source`__
__ https://stackoverflow.com/a/10824086
Parameters
----------
items : iterable
The irregular sequence to flatten.
seqtypes : iterable of t... | [
"Flatten",
"an",
"irregular",
"sequence",
"."
] | python | train |
Karaage-Cluster/karaage | karaage/datastores/__init__.py | https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/datastores/__init__.py#L251-L258 | def get_institute_details(institute):
""" Get details for this user. """
result = []
for datastore in _get_datastores():
value = datastore.get_institute_details(institute)
value['datastore'] = datastore.config['DESCRIPTION']
result.append(value)
return result | [
"def",
"get_institute_details",
"(",
"institute",
")",
":",
"result",
"=",
"[",
"]",
"for",
"datastore",
"in",
"_get_datastores",
"(",
")",
":",
"value",
"=",
"datastore",
".",
"get_institute_details",
"(",
"institute",
")",
"value",
"[",
"'datastore'",
"]",
... | Get details for this user. | [
"Get",
"details",
"for",
"this",
"user",
"."
] | python | train |
blockstack/blockstack-core | blockstack/lib/operations/register.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/register.py#L999-L1091 | def parse(bin_payload, block_height):
"""
Interpret a block's nulldata back into a name. The first three bytes (2 magic + 1 opcode)
will not be present in bin_payload.
The name will be directly represented by the bytes given.
This works for registrations and renewals.
Record format (pre... | [
"def",
"parse",
"(",
"bin_payload",
",",
"block_height",
")",
":",
"# pre F-day 2017: bin_payload is the name.",
"# post F-day 2017: bin_payload is the name and possibly the update hash",
"# STACKs phase 1: bin_payload possibly has a token burn attached to the end",
"epoch_features",
"=",
... | Interpret a block's nulldata back into a name. The first three bytes (2 magic + 1 opcode)
will not be present in bin_payload.
The name will be directly represented by the bytes given.
This works for registrations and renewals.
Record format (pre F-day 2017):
0 2 3 ... | [
"Interpret",
"a",
"block",
"s",
"nulldata",
"back",
"into",
"a",
"name",
".",
"The",
"first",
"three",
"bytes",
"(",
"2",
"magic",
"+",
"1",
"opcode",
")",
"will",
"not",
"be",
"present",
"in",
"bin_payload",
".",
"The",
"name",
"will",
"be",
"directly... | python | train |
consbio/gis-metadata-parser | gis_metadata/arcgis_metadata_parser.py | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/arcgis_metadata_parser.py#L407-L440 | def _update_report_item(self, **update_props):
""" Update the text for each element at the configured path if attribute matches """
tree_to_update = update_props['tree_to_update']
prop = update_props['prop']
values = wrap_value(update_props['values'])
xroot = self._get_xroot_for... | [
"def",
"_update_report_item",
"(",
"self",
",",
"*",
"*",
"update_props",
")",
":",
"tree_to_update",
"=",
"update_props",
"[",
"'tree_to_update'",
"]",
"prop",
"=",
"update_props",
"[",
"'prop'",
"]",
"values",
"=",
"wrap_value",
"(",
"update_props",
"[",
"'v... | Update the text for each element at the configured path if attribute matches | [
"Update",
"the",
"text",
"for",
"each",
"element",
"at",
"the",
"configured",
"path",
"if",
"attribute",
"matches"
] | python | train |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L19165-L19222 | def directory_create_temp(self, template_name, mode, path, secure):
"""Creates a temporary directory in the guest.
in template_name of type str
Template for the name of the directory to create. This must
contain at least one 'X' character. The first group of consecutive
... | [
"def",
"directory_create_temp",
"(",
"self",
",",
"template_name",
",",
"mode",
",",
"path",
",",
"secure",
")",
":",
"if",
"not",
"isinstance",
"(",
"template_name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"template_name can only be an instance ... | Creates a temporary directory in the guest.
in template_name of type str
Template for the name of the directory to create. This must
contain at least one 'X' character. The first group of consecutive
'X' characters in the template will be replaced by a random
alp... | [
"Creates",
"a",
"temporary",
"directory",
"in",
"the",
"guest",
"."
] | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_resources.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L312-L362 | def association_custom(self, association_name, association_resource=None):
"""Custom Indicator association for this resource with resource value.
**Example Endpoints URI's**
+--------+--------------------------------------------------------------------------+
| HTTP | API Endpoint UR... | [
"def",
"association_custom",
"(",
"self",
",",
"association_name",
",",
"association_resource",
"=",
"None",
")",
":",
"resource",
"=",
"self",
".",
"copy",
"(",
")",
"association_api_branch",
"=",
"self",
".",
"tcex",
".",
"indicator_associations_types_data",
"."... | Custom Indicator association for this resource with resource value.
**Example Endpoints URI's**
+--------+--------------------------------------------------------------------------+
| HTTP | API Endpoint URI's |
+========+========... | [
"Custom",
"Indicator",
"association",
"for",
"this",
"resource",
"with",
"resource",
"value",
"."
] | python | train |
spyder-ide/spyder | spyder/app/mainwindow.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L192-L210 | def get_python_doc_path():
"""
Return Python documentation path
(Windows: return the PythonXX.chm path if available)
"""
if os.name == 'nt':
doc_path = osp.join(sys.prefix, "Doc")
if not osp.isdir(doc_path):
return
python_chm = [path for path in os.listdi... | [
"def",
"get_python_doc_path",
"(",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"doc_path",
"=",
"osp",
".",
"join",
"(",
"sys",
".",
"prefix",
",",
"\"Doc\"",
")",
"if",
"not",
"osp",
".",
"isdir",
"(",
"doc_path",
")",
":",
"return",
"py... | Return Python documentation path
(Windows: return the PythonXX.chm path if available) | [
"Return",
"Python",
"documentation",
"path",
"(",
"Windows",
":",
"return",
"the",
"PythonXX",
".",
"chm",
"path",
"if",
"available",
")"
] | python | train |
econ-ark/HARK | HARK/interpolation.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/interpolation.py#L2017-L2037 | def derivativeY(self,x,y):
'''
Evaluate the first derivative with respect to y of the function at given
state space points.
Parameters
----------
x : np.array
First input values.
y : np.array
Second input values; should be of same shape ... | [
"def",
"derivativeY",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"xShift",
",",
"xShiftDer",
"=",
"self",
".",
"lowerBound",
".",
"eval_with_derivative",
"(",
"y",
")",
"dfdy_out",
"=",
"self",
".",
"func",
".",
"derivativeY",
"(",
"x",
"-",
"xShift",
... | Evaluate the first derivative with respect to y of the function at given
state space points.
Parameters
----------
x : np.array
First input values.
y : np.array
Second input values; should be of same shape as x.
Returns
-------
... | [
"Evaluate",
"the",
"first",
"derivative",
"with",
"respect",
"to",
"y",
"of",
"the",
"function",
"at",
"given",
"state",
"space",
"points",
"."
] | python | train |
Pylons/hupper | src/hupper/worker.py | https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/worker.py#L50-L60 | def search_traceback(self, tb):
""" Inspect a traceback for new paths to add to our path set."""
new_paths = []
with self.lock:
for filename, line, funcname, txt in traceback.extract_tb(tb):
path = os.path.abspath(filename)
if path not in self.paths:
... | [
"def",
"search_traceback",
"(",
"self",
",",
"tb",
")",
":",
"new_paths",
"=",
"[",
"]",
"with",
"self",
".",
"lock",
":",
"for",
"filename",
",",
"line",
",",
"funcname",
",",
"txt",
"in",
"traceback",
".",
"extract_tb",
"(",
"tb",
")",
":",
"path",... | Inspect a traceback for new paths to add to our path set. | [
"Inspect",
"a",
"traceback",
"for",
"new",
"paths",
"to",
"add",
"to",
"our",
"path",
"set",
"."
] | python | train |
DistrictDataLabs/yellowbrick | yellowbrick/classifier/rocauc.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/classifier/rocauc.py#L399-L503 | def roc_auc(model, X, y=None, ax=None, **kwargs):
"""ROCAUC Quick method:
Receiver Operating Characteristic (ROC) curves are a measure of a
classifier's predictive quality that compares and visualizes the tradeoff
between the models' sensitivity and specificity. The ROC curve displays
the true posi... | [
"def",
"roc_auc",
"(",
"model",
",",
"X",
",",
"y",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Instantiate the visualizer",
"visualizer",
"=",
"ROCAUC",
"(",
"model",
",",
"ax",
",",
"*",
"*",
"kwargs",
")",
"# Create ... | ROCAUC Quick method:
Receiver Operating Characteristic (ROC) curves are a measure of a
classifier's predictive quality that compares and visualizes the tradeoff
between the models' sensitivity and specificity. The ROC curve displays
the true positive rate on the Y axis and the false positive rate on th... | [
"ROCAUC",
"Quick",
"method",
":"
] | python | train |
empymod/empymod | empymod/transform.py | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/transform.py#L766-L806 | def fft(fEM, time, freq, ftarg):
r"""Fourier Transform using the Fast Fourier Transform.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
Returns
-------
tEM : array
Ret... | [
"def",
"fft",
"(",
"fEM",
",",
"time",
",",
"freq",
",",
"ftarg",
")",
":",
"# Get ftarg values",
"dfreq",
",",
"nfreq",
",",
"ntot",
",",
"pts_per_dec",
"=",
"ftarg",
"# If pts_per_dec, we have first to interpolate fEM to required freqs",
"if",
"pts_per_dec",
":",
... | r"""Fourier Transform using the Fast Fourier Transform.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
Returns
-------
tEM : array
Returns time-domain EM response of ``fEM... | [
"r",
"Fourier",
"Transform",
"using",
"the",
"Fast",
"Fourier",
"Transform",
"."
] | python | train |
pkgw/pwkit | pwkit/numutil.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/numutil.py#L423-L470 | def dfsmooth (window, df, ucol, k=None):
"""Smooth a :class:`pandas.DataFrame` according to a window, weighting based on
uncertainties.
Arguments are:
window
The smoothing window.
df
The :class:`pandas.DataFrame`.
ucol
The name of the column in *df* that contains the uncertai... | [
"def",
"dfsmooth",
"(",
"window",
",",
"df",
",",
"ucol",
",",
"k",
"=",
"None",
")",
":",
"import",
"pandas",
"as",
"pd",
"if",
"k",
"is",
"None",
":",
"k",
"=",
"window",
".",
"size",
"conv",
"=",
"lambda",
"q",
",",
"r",
":",
"np",
".",
"c... | Smooth a :class:`pandas.DataFrame` according to a window, weighting based on
uncertainties.
Arguments are:
window
The smoothing window.
df
The :class:`pandas.DataFrame`.
ucol
The name of the column in *df* that contains the uncertainties to weight
by.
k = None
If ... | [
"Smooth",
"a",
":",
"class",
":",
"pandas",
".",
"DataFrame",
"according",
"to",
"a",
"window",
"weighting",
"based",
"on",
"uncertainties",
"."
] | python | train |
data-8/datascience | datascience/maps.py | https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/maps.py#L370-L373 | def _set_folium_map(self):
"""A map containing only the feature."""
m = Map(features=[self], width=self._width, height=self._height)
self._folium_map = m.draw() | [
"def",
"_set_folium_map",
"(",
"self",
")",
":",
"m",
"=",
"Map",
"(",
"features",
"=",
"[",
"self",
"]",
",",
"width",
"=",
"self",
".",
"_width",
",",
"height",
"=",
"self",
".",
"_height",
")",
"self",
".",
"_folium_map",
"=",
"m",
".",
"draw",
... | A map containing only the feature. | [
"A",
"map",
"containing",
"only",
"the",
"feature",
"."
] | python | train |
pudo-attic/scrapekit | scrapekit/tasks.py | https://github.com/pudo-attic/scrapekit/blob/cfd258120922fcd571430cdf00ba50f3cf18dc15/scrapekit/tasks.py#L163-L174 | def chain(self, other_task):
""" Add a chain listener to the execution of this task. Whenever
an item has been processed by the task, the registered listener
task will be queued to be executed with the output of this task.
Can also be written as::
pipeline = task1 > task2
... | [
"def",
"chain",
"(",
"self",
",",
"other_task",
")",
":",
"other_task",
".",
"_source",
"=",
"self",
"self",
".",
"_listeners",
".",
"append",
"(",
"ChainListener",
"(",
"other_task",
")",
")",
"return",
"other_task"
] | Add a chain listener to the execution of this task. Whenever
an item has been processed by the task, the registered listener
task will be queued to be executed with the output of this task.
Can also be written as::
pipeline = task1 > task2 | [
"Add",
"a",
"chain",
"listener",
"to",
"the",
"execution",
"of",
"this",
"task",
".",
"Whenever",
"an",
"item",
"has",
"been",
"processed",
"by",
"the",
"task",
"the",
"registered",
"listener",
"task",
"will",
"be",
"queued",
"to",
"be",
"executed",
"with"... | python | train |
mozilla/crontabber | crontabber/app.py | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L876-L921 | def nagios(self, stream=sys.stdout):
"""
return 0 (OK) if there are no errors in the state.
return 1 (WARNING) if a backfill app only has 1 error.
return 2 (CRITICAL) if a backfill app has > 1 error.
return 2 (CRITICAL) if a non-backfill app has 1 error.
"""
warni... | [
"def",
"nagios",
"(",
"self",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"warnings",
"=",
"[",
"]",
"criticals",
"=",
"[",
"]",
"for",
"class_name",
",",
"job_class",
"in",
"self",
".",
"config",
".",
"crontabber",
".",
"jobs",
".",
"class_l... | return 0 (OK) if there are no errors in the state.
return 1 (WARNING) if a backfill app only has 1 error.
return 2 (CRITICAL) if a backfill app has > 1 error.
return 2 (CRITICAL) if a non-backfill app has 1 error. | [
"return",
"0",
"(",
"OK",
")",
"if",
"there",
"are",
"no",
"errors",
"in",
"the",
"state",
".",
"return",
"1",
"(",
"WARNING",
")",
"if",
"a",
"backfill",
"app",
"only",
"has",
"1",
"error",
".",
"return",
"2",
"(",
"CRITICAL",
")",
"if",
"a",
"b... | python | train |
BeyondTheClouds/enoslib | enoslib/api.py | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L45-L96 | def _load_defaults(inventory_path=None, roles=None, extra_vars=None, tags=None,
basedir=False):
"""Load common defaults data structures.
For factorization purpose."""
extra_vars = extra_vars or {}
tags = tags or []
loader = DataLoader()
if basedir:
loader.set_basedir... | [
"def",
"_load_defaults",
"(",
"inventory_path",
"=",
"None",
",",
"roles",
"=",
"None",
",",
"extra_vars",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"basedir",
"=",
"False",
")",
":",
"extra_vars",
"=",
"extra_vars",
"or",
"{",
"}",
"tags",
"=",
"tag... | Load common defaults data structures.
For factorization purpose. | [
"Load",
"common",
"defaults",
"data",
"structures",
"."
] | python | train |
mikedh/trimesh | trimesh/path/path.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/path/path.py#L954-L982 | def rasterize(self,
pitch,
origin,
resolution=None,
fill=True,
width=None,
**kwargs):
"""
Rasterize a Path2D object into a boolean image ("mode 1").
Parameters
------------
... | [
"def",
"rasterize",
"(",
"self",
",",
"pitch",
",",
"origin",
",",
"resolution",
"=",
"None",
",",
"fill",
"=",
"True",
",",
"width",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"image",
"=",
"raster",
".",
"rasterize",
"(",
"self",
",",
"pitch... | Rasterize a Path2D object into a boolean image ("mode 1").
Parameters
------------
pitch: float, length in model space of a pixel edge
origin: (2,) float, origin position in model space
resolution: (2,) int, resolution in pixel space
fill: bool, if True wi... | [
"Rasterize",
"a",
"Path2D",
"object",
"into",
"a",
"boolean",
"image",
"(",
"mode",
"1",
")",
"."
] | python | train |
saltstack/salt | salt/proxy/esxi.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxi.py#L508-L531 | def find_credentials(host):
'''
Cycle through all the possible credentials and return the first one that
works.
'''
user_names = [__pillar__['proxy'].get('username', 'root')]
passwords = __pillar__['proxy']['passwords']
for user in user_names:
for password in passwords:
t... | [
"def",
"find_credentials",
"(",
"host",
")",
":",
"user_names",
"=",
"[",
"__pillar__",
"[",
"'proxy'",
"]",
".",
"get",
"(",
"'username'",
",",
"'root'",
")",
"]",
"passwords",
"=",
"__pillar__",
"[",
"'proxy'",
"]",
"[",
"'passwords'",
"]",
"for",
"use... | Cycle through all the possible credentials and return the first one that
works. | [
"Cycle",
"through",
"all",
"the",
"possible",
"credentials",
"and",
"return",
"the",
"first",
"one",
"that",
"works",
"."
] | python | train |
MisterY/asset-allocation | asset_allocation/loader.py | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L161-L180 | def __load_child_classes(self, ac: AssetClass):
""" Loads child classes/stocks """
# load child classes for ac
db = self.__get_session()
entities = (
db.query(dal.AssetClass)
.filter(dal.AssetClass.parentid == ac.id)
.order_by(dal.AssetClass.sortorder)... | [
"def",
"__load_child_classes",
"(",
"self",
",",
"ac",
":",
"AssetClass",
")",
":",
"# load child classes for ac",
"db",
"=",
"self",
".",
"__get_session",
"(",
")",
"entities",
"=",
"(",
"db",
".",
"query",
"(",
"dal",
".",
"AssetClass",
")",
".",
"filter... | Loads child classes/stocks | [
"Loads",
"child",
"classes",
"/",
"stocks"
] | python | train |
foremast/foremast | src/foremast/autoscaling_policy/create_policy.py | https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/autoscaling_policy/create_policy.py#L129-L153 | def delete_existing_policy(self, scaling_policy, server_group):
"""Given a scaling_policy and server_group, deletes the existing scaling_policy.
Scaling policies need to be deleted instead of upserted for consistency.
Args:
scaling_policy (json): the scaling_policy json from Spinnak... | [
"def",
"delete_existing_policy",
"(",
"self",
",",
"scaling_policy",
",",
"server_group",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Deleting policy %s on %s\"",
",",
"scaling_policy",
"[",
"'policyName'",
"]",
",",
"server_group",
")",
"delete_dict",
"=",... | Given a scaling_policy and server_group, deletes the existing scaling_policy.
Scaling policies need to be deleted instead of upserted for consistency.
Args:
scaling_policy (json): the scaling_policy json from Spinnaker that should be deleted
server_group (str): the affected serv... | [
"Given",
"a",
"scaling_policy",
"and",
"server_group",
"deletes",
"the",
"existing",
"scaling_policy",
".",
"Scaling",
"policies",
"need",
"to",
"be",
"deleted",
"instead",
"of",
"upserted",
"for",
"consistency",
"."
] | python | train |
splunk/splunk-sdk-python | examples/analytics/bottle.py | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L1350-L1355 | def _ekey(self, key):
''' Translate header field name to CGI/WSGI environ key. '''
key = key.replace('-','_').upper()
if key in self.cgikeys:
return key
return 'HTTP_' + key | [
"def",
"_ekey",
"(",
"self",
",",
"key",
")",
":",
"key",
"=",
"key",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
".",
"upper",
"(",
")",
"if",
"key",
"in",
"self",
".",
"cgikeys",
":",
"return",
"key",
"return",
"'HTTP_'",
"+",
"key"
] | Translate header field name to CGI/WSGI environ key. | [
"Translate",
"header",
"field",
"name",
"to",
"CGI",
"/",
"WSGI",
"environ",
"key",
"."
] | python | train |
Fantomas42/django-blog-zinnia | zinnia/views/mixins/templates.py | https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/views/mixins/templates.py#L137-L148 | def get_archive_part_value(self, part):
"""Return archive part for today"""
parts_dict = {'year': '%Y',
'month': self.month_format,
'week': self.week_format,
'day': '%d'}
if self.today is None:
today = timezone.now()
... | [
"def",
"get_archive_part_value",
"(",
"self",
",",
"part",
")",
":",
"parts_dict",
"=",
"{",
"'year'",
":",
"'%Y'",
",",
"'month'",
":",
"self",
".",
"month_format",
",",
"'week'",
":",
"self",
".",
"week_format",
",",
"'day'",
":",
"'%d'",
"}",
"if",
... | Return archive part for today | [
"Return",
"archive",
"part",
"for",
"today"
] | python | train |
secdev/scapy | scapy/layers/tls/crypto/cipher_aead.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/tls/crypto/cipher_aead.py#L335-L370 | def auth_decrypt(self, A, C, seq_num):
"""
Decrypt the data and verify the authentication code (in this order).
Note that TLS 1.3 is not supposed to use any additional data A.
If the verification fails, an AEADTagError is raised. It is the user's
responsibility to catch it if dee... | [
"def",
"auth_decrypt",
"(",
"self",
",",
"A",
",",
"C",
",",
"seq_num",
")",
":",
"C",
",",
"mac",
"=",
"C",
"[",
":",
"-",
"self",
".",
"tag_len",
"]",
",",
"C",
"[",
"-",
"self",
".",
"tag_len",
":",
"]",
"if",
"False",
"in",
"six",
".",
... | Decrypt the data and verify the authentication code (in this order).
Note that TLS 1.3 is not supposed to use any additional data A.
If the verification fails, an AEADTagError is raised. It is the user's
responsibility to catch it if deemed useful. If we lack the key, we
raise a CipherEr... | [
"Decrypt",
"the",
"data",
"and",
"verify",
"the",
"authentication",
"code",
"(",
"in",
"this",
"order",
")",
".",
"Note",
"that",
"TLS",
"1",
".",
"3",
"is",
"not",
"supposed",
"to",
"use",
"any",
"additional",
"data",
"A",
".",
"If",
"the",
"verificat... | python | train |
seung-lab/cloud-volume | cloudvolume/lib.py | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/lib.py#L740-L790 | def generate_slices(slices, minsize, maxsize, bounded=True):
"""Assisting function for __getitem__. e.g. vol[:,:,:,:]"""
if isinstance(slices, integer_types) or isinstance(slices, floating_types):
slices = [ slice(int(slices), int(slices)+1, 1) ]
elif type(slices) == slice:
slices = [ slices ]
elif sli... | [
"def",
"generate_slices",
"(",
"slices",
",",
"minsize",
",",
"maxsize",
",",
"bounded",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"slices",
",",
"integer_types",
")",
"or",
"isinstance",
"(",
"slices",
",",
"floating_types",
")",
":",
"slices",
"=",... | Assisting function for __getitem__. e.g. vol[:,:,:,:] | [
"Assisting",
"function",
"for",
"__getitem__",
".",
"e",
".",
"g",
".",
"vol",
"[",
":",
":",
":",
":",
"]"
] | python | train |
saltstack/salt | salt/cli/support/__init__.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/__init__.py#L15-L22 | def _render_profile(path, caller, runner):
'''
Render profile as Jinja2.
:param path:
:return:
'''
env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(path)), trim_blocks=False)
return env.get_template(os.path.basename(path)).render(salt=caller, runners=runner).strip() | [
"def",
"_render_profile",
"(",
"path",
",",
"caller",
",",
"runner",
")",
":",
"env",
"=",
"jinja2",
".",
"Environment",
"(",
"loader",
"=",
"jinja2",
".",
"FileSystemLoader",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
")",
",",
"trim_bl... | Render profile as Jinja2.
:param path:
:return: | [
"Render",
"profile",
"as",
"Jinja2",
".",
":",
"param",
"path",
":",
":",
"return",
":"
] | python | train |
ArchiveTeam/wpull | wpull/document/html.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/document/html.py#L214-L226 | def is_file(cls, file):
'''Return whether the file is likely to be HTML.'''
peeked_data = wpull.string.printable_bytes(
wpull.util.peek_file(file)).lower()
if b'<!doctype html' in peeked_data \
or b'<head' in peeked_data \
or b'<title' in peeked_data \
... | [
"def",
"is_file",
"(",
"cls",
",",
"file",
")",
":",
"peeked_data",
"=",
"wpull",
".",
"string",
".",
"printable_bytes",
"(",
"wpull",
".",
"util",
".",
"peek_file",
"(",
"file",
")",
")",
".",
"lower",
"(",
")",
"if",
"b'<!doctype html'",
"in",
"peeke... | Return whether the file is likely to be HTML. | [
"Return",
"whether",
"the",
"file",
"is",
"likely",
"to",
"be",
"HTML",
"."
] | python | train |
remram44/rpaths | rpaths.py | https://github.com/remram44/rpaths/blob/e4ff55d985c4d643d9fd214539d45af39ae5a7cd/rpaths.py#L937-L940 | def move(self, target):
"""Recursively moves a file or directory to the given target location.
"""
shutil.move(self.path, self._to_backend(target)) | [
"def",
"move",
"(",
"self",
",",
"target",
")",
":",
"shutil",
".",
"move",
"(",
"self",
".",
"path",
",",
"self",
".",
"_to_backend",
"(",
"target",
")",
")"
] | Recursively moves a file or directory to the given target location. | [
"Recursively",
"moves",
"a",
"file",
"or",
"directory",
"to",
"the",
"given",
"target",
"location",
"."
] | python | train |
taskcluster/taskcluster-client.py | taskcluster/aio/hooks.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/aio/hooks.py#L190-L202 | async def resetTriggerToken(self, *args, **kwargs):
"""
Reset a trigger token
Reset the token for triggering a given hook. This invalidates token that
may have been issued via getTriggerToken with a new token.
This method gives output: ``v1/trigger-token-response.json#``
... | [
"async",
"def",
"resetTriggerToken",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"resetTriggerToken\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kw... | Reset a trigger token
Reset the token for triggering a given hook. This invalidates token that
may have been issued via getTriggerToken with a new token.
This method gives output: ``v1/trigger-token-response.json#``
This method is ``stable`` | [
"Reset",
"a",
"trigger",
"token"
] | python | train |
chop-dbhi/varify-data-warehouse | vdw/raw/utils/stream.py | https://github.com/chop-dbhi/varify-data-warehouse/blob/1600ee1bc5fae6c68fd03b23624467298570cca8/vdw/raw/utils/stream.py#L119-L137 | def read(self, size=-1):
"""Read `size` bytes from the reader relative to the parsed output.
This is generally acceptable in practice since VCF lines are
condensed, but if the output line <<< record, this means the actual
memory used will be much greater than `size`.
"""
... | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"lines",
"=",
"[",
"]",
"parsed_size",
"=",
"0",
"while",
"True",
":",
"line",
"=",
"self",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"lines",
".",
"append",
... | Read `size` bytes from the reader relative to the parsed output.
This is generally acceptable in practice since VCF lines are
condensed, but if the output line <<< record, this means the actual
memory used will be much greater than `size`. | [
"Read",
"size",
"bytes",
"from",
"the",
"reader",
"relative",
"to",
"the",
"parsed",
"output",
".",
"This",
"is",
"generally",
"acceptable",
"in",
"practice",
"since",
"VCF",
"lines",
"are",
"condensed",
"but",
"if",
"the",
"output",
"line",
"<<<",
"record",... | python | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_function_provider.py | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_function_provider.py#L81-L108 | def _extract_functions(resources):
"""
Extracts and returns function information from the given dictionary of SAM/CloudFormation resources. This
method supports functions defined with AWS::Serverless::Function and AWS::Lambda::Function
:param dict resources: Dictionary of SAM/CloudForma... | [
"def",
"_extract_functions",
"(",
"resources",
")",
":",
"result",
"=",
"{",
"}",
"for",
"name",
",",
"resource",
"in",
"resources",
".",
"items",
"(",
")",
":",
"resource_type",
"=",
"resource",
".",
"get",
"(",
"\"Type\"",
")",
"resource_properties",
"="... | Extracts and returns function information from the given dictionary of SAM/CloudFormation resources. This
method supports functions defined with AWS::Serverless::Function and AWS::Lambda::Function
:param dict resources: Dictionary of SAM/CloudFormation resources
:return dict(string : samcli.com... | [
"Extracts",
"and",
"returns",
"function",
"information",
"from",
"the",
"given",
"dictionary",
"of",
"SAM",
"/",
"CloudFormation",
"resources",
".",
"This",
"method",
"supports",
"functions",
"defined",
"with",
"AWS",
"::",
"Serverless",
"::",
"Function",
"and",
... | python | train |
geophysics-ubonn/crtomo_tools | lib/crtomo/tdManager.py | https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/tdManager.py#L577-L589 | def get_sensitivity(self, config_nr):
"""return a sensitivity, as well as corresponding metadata, for a given
measurement configuration. Indices start at zero.
"""
if self.assignments['sensitivities'] is None:
self._check_state()
if self.can_model:
... | [
"def",
"get_sensitivity",
"(",
"self",
",",
"config_nr",
")",
":",
"if",
"self",
".",
"assignments",
"[",
"'sensitivities'",
"]",
"is",
"None",
":",
"self",
".",
"_check_state",
"(",
")",
"if",
"self",
".",
"can_model",
":",
"self",
".",
"model",
"(",
... | return a sensitivity, as well as corresponding metadata, for a given
measurement configuration. Indices start at zero. | [
"return",
"a",
"sensitivity",
"as",
"well",
"as",
"corresponding",
"metadata",
"for",
"a",
"given",
"measurement",
"configuration",
".",
"Indices",
"start",
"at",
"zero",
"."
] | python | train |
geophysics-ubonn/crtomo_tools | src/td_correct_temperature.py | https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/src/td_correct_temperature.py#L27-L89 | def handle_options():
'''Handle options.
'''
parser = OptionParser()
parser.set_defaults(add=False)
parser.set_defaults(rhofile=False)
parser.set_defaults(aniso=False)
parser.add_option("-m",
dest="m",
type="float",
help="Use... | [
"def",
"handle_options",
"(",
")",
":",
"parser",
"=",
"OptionParser",
"(",
")",
"parser",
".",
"set_defaults",
"(",
"add",
"=",
"False",
")",
"parser",
".",
"set_defaults",
"(",
"rhofile",
"=",
"False",
")",
"parser",
".",
"set_defaults",
"(",
"aniso",
... | Handle options. | [
"Handle",
"options",
"."
] | python | train |
ultrabug/py3status | py3status/modules/player_control.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/player_control.py#L137-L142 | def _change_volume(self, increase):
"""Change volume using amixer
"""
sign = "+" if increase else "-"
delta = "%d%%%s" % (self.volume_tick, sign)
self._run(["amixer", "-q", "sset", "Master", delta]) | [
"def",
"_change_volume",
"(",
"self",
",",
"increase",
")",
":",
"sign",
"=",
"\"+\"",
"if",
"increase",
"else",
"\"-\"",
"delta",
"=",
"\"%d%%%s\"",
"%",
"(",
"self",
".",
"volume_tick",
",",
"sign",
")",
"self",
".",
"_run",
"(",
"[",
"\"amixer\"",
"... | Change volume using amixer | [
"Change",
"volume",
"using",
"amixer"
] | python | train |
hayd/pep8radius | pep8radius/radius.py | https://github.com/hayd/pep8radius/blob/0c1d14835d390f7feeb602f35a768e52ce306a0a/pep8radius/radius.py#L265-L270 | def _maybe_print(something_to_print, end=None, min_=1, max_=99, verbose=0):
"""Print if verbose is within min_ and max_."""
if min_ <= verbose <= max_:
import sys
print(something_to_print, end=end)
sys.stdout.flush() | [
"def",
"_maybe_print",
"(",
"something_to_print",
",",
"end",
"=",
"None",
",",
"min_",
"=",
"1",
",",
"max_",
"=",
"99",
",",
"verbose",
"=",
"0",
")",
":",
"if",
"min_",
"<=",
"verbose",
"<=",
"max_",
":",
"import",
"sys",
"print",
"(",
"something_... | Print if verbose is within min_ and max_. | [
"Print",
"if",
"verbose",
"is",
"within",
"min_",
"and",
"max_",
"."
] | python | train |
brainiak/brainiak | brainiak/utils/utils.py | https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/utils/utils.py#L342-L487 | def gen_design(stimtime_files, scan_duration, TR, style='FSL',
temp_res=0.01,
hrf_para={'response_delay': 6, 'undershoot_delay': 12,
'response_dispersion': 0.9,
'undershoot_dispersion': 0.9,
'undershoot_scale': 0.03... | [
"def",
"gen_design",
"(",
"stimtime_files",
",",
"scan_duration",
",",
"TR",
",",
"style",
"=",
"'FSL'",
",",
"temp_res",
"=",
"0.01",
",",
"hrf_para",
"=",
"{",
"'response_delay'",
":",
"6",
",",
"'undershoot_delay'",
":",
"12",
",",
"'response_dispersion'",
... | Generate design matrix based on a list of names of stimulus
timing files. The function will read each file, and generate
a numpy array of size [time_points \\* condition], where
time_points equals duration / TR, and condition is the size of
stimtime_filenames. Each column is the hypothet... | [
"Generate",
"design",
"matrix",
"based",
"on",
"a",
"list",
"of",
"names",
"of",
"stimulus",
"timing",
"files",
".",
"The",
"function",
"will",
"read",
"each",
"file",
"and",
"generate",
"a",
"numpy",
"array",
"of",
"size",
"[",
"time_points",
"\\\\",
"*",... | python | train |
PredixDev/predixpy | predix/data/timeseries.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/data/timeseries.py#L85-L95 | def _get_query_zone_id(self):
"""
Returns the ZoneId for performing queries of a Predix
Time Series instance from environment inspection.
"""
if 'VCAP_SERVICES' in os.environ:
services = json.loads(os.getenv('VCAP_SERVICES'))
predix_timeseries = services['... | [
"def",
"_get_query_zone_id",
"(",
"self",
")",
":",
"if",
"'VCAP_SERVICES'",
"in",
"os",
".",
"environ",
":",
"services",
"=",
"json",
".",
"loads",
"(",
"os",
".",
"getenv",
"(",
"'VCAP_SERVICES'",
")",
")",
"predix_timeseries",
"=",
"services",
"[",
"'pr... | Returns the ZoneId for performing queries of a Predix
Time Series instance from environment inspection. | [
"Returns",
"the",
"ZoneId",
"for",
"performing",
"queries",
"of",
"a",
"Predix",
"Time",
"Series",
"instance",
"from",
"environment",
"inspection",
"."
] | python | train |
higlass/higlass-python | higlass/server.py | https://github.com/higlass/higlass-python/blob/0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7/higlass/server.py#L339-L386 | def start(self, log_file="/tmp/hgserver.log", log_level=logging.INFO):
"""
Start a lightweight higlass server.
Parameters
----------
log_file: string
Where to place diagnostic log files
log_level: logging.*
What level to log at
"""
... | [
"def",
"start",
"(",
"self",
",",
"log_file",
"=",
"\"/tmp/hgserver.log\"",
",",
"log_level",
"=",
"logging",
".",
"INFO",
")",
":",
"for",
"puid",
"in",
"list",
"(",
"self",
".",
"processes",
".",
"keys",
"(",
")",
")",
":",
"print",
"(",
"\"terminati... | Start a lightweight higlass server.
Parameters
----------
log_file: string
Where to place diagnostic log files
log_level: logging.*
What level to log at | [
"Start",
"a",
"lightweight",
"higlass",
"server",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xrichtextedit/xrichtextedit.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xrichtextedit/xrichtextedit.py#L188-L196 | def blockSignals(self, state):
"""
Propagates the block signals for this editor down to the text
editor.
:param state | <bool>
"""
super(XRichTextEdit, self).blockSignals(state)
self.uiEditTXT.blockSignals(state) | [
"def",
"blockSignals",
"(",
"self",
",",
"state",
")",
":",
"super",
"(",
"XRichTextEdit",
",",
"self",
")",
".",
"blockSignals",
"(",
"state",
")",
"self",
".",
"uiEditTXT",
".",
"blockSignals",
"(",
"state",
")"
] | Propagates the block signals for this editor down to the text
editor.
:param state | <bool> | [
"Propagates",
"the",
"block",
"signals",
"for",
"this",
"editor",
"down",
"to",
"the",
"text",
"editor",
".",
":",
"param",
"state",
"|",
"<bool",
">"
] | python | train |
apache/incubator-mxnet | python/mxnet/autograd.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/autograd.py#L223-L240 | def _parse_head(heads, head_grads):
"""parse head gradient for backward and grad."""
if isinstance(heads, NDArray):
heads = [heads]
if isinstance(head_grads, NDArray):
head_grads = [head_grads]
head_handles = c_handle_array(heads)
if head_grads is None:
hgrad_handles = ctyp... | [
"def",
"_parse_head",
"(",
"heads",
",",
"head_grads",
")",
":",
"if",
"isinstance",
"(",
"heads",
",",
"NDArray",
")",
":",
"heads",
"=",
"[",
"heads",
"]",
"if",
"isinstance",
"(",
"head_grads",
",",
"NDArray",
")",
":",
"head_grads",
"=",
"[",
"head... | parse head gradient for backward and grad. | [
"parse",
"head",
"gradient",
"for",
"backward",
"and",
"grad",
"."
] | python | train |
llllllllll/codetransformer | codetransformer/transformers/literals.py | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/literals.py#L237-L268 | def overloaded_constants(type_, __doc__=None):
"""A factory for transformers that apply functions to literals.
Parameters
----------
type_ : type
The type to overload.
__doc__ : str, optional
Docstring for the generated transformer.
Returns
-------
transformer : subclas... | [
"def",
"overloaded_constants",
"(",
"type_",
",",
"__doc__",
"=",
"None",
")",
":",
"typename",
"=",
"type_",
".",
"__name__",
"if",
"typename",
".",
"endswith",
"(",
"'x'",
")",
":",
"typename",
"+=",
"'es'",
"elif",
"not",
"typename",
".",
"endswith",
... | A factory for transformers that apply functions to literals.
Parameters
----------
type_ : type
The type to overload.
__doc__ : str, optional
Docstring for the generated transformer.
Returns
-------
transformer : subclass of CodeTransformer
A new code transformer cl... | [
"A",
"factory",
"for",
"transformers",
"that",
"apply",
"functions",
"to",
"literals",
"."
] | python | train |
swistakm/graceful | src/graceful/validators.py | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/validators.py#L31-L45 | def max_validator(max_value):
"""Return validator function that ensures upper bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check.
Args:
max_value: maximum value for new validator
"""
def valid... | [
"def",
"max_validator",
"(",
"max_value",
")",
":",
"def",
"validator",
"(",
"value",
")",
":",
"if",
"value",
">",
"max_value",
":",
"raise",
"ValidationError",
"(",
"\"{} is not <= {}\"",
".",
"format",
"(",
"value",
",",
"max_value",
")",
")",
"return",
... | Return validator function that ensures upper bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check.
Args:
max_value: maximum value for new validator | [
"Return",
"validator",
"function",
"that",
"ensures",
"upper",
"bound",
"of",
"a",
"number",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/allen_brain.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/allen_brain.py#L81-L121 | def _get_case_file_paths(tmp_dir, case, training_fraction=0.95):
"""Obtain a list of image paths corresponding to training or eval case.
Args:
tmp_dir: str, the root path to which raw images were written, at the
top level having meta/ and raw/ subdirs.
case: bool, whether obtaining file paths for tra... | [
"def",
"_get_case_file_paths",
"(",
"tmp_dir",
",",
"case",
",",
"training_fraction",
"=",
"0.95",
")",
":",
"paths",
"=",
"tf",
".",
"gfile",
".",
"Glob",
"(",
"\"%s/*.jpg\"",
"%",
"tmp_dir",
")",
"if",
"not",
"paths",
":",
"raise",
"ValueError",
"(",
"... | Obtain a list of image paths corresponding to training or eval case.
Args:
tmp_dir: str, the root path to which raw images were written, at the
top level having meta/ and raw/ subdirs.
case: bool, whether obtaining file paths for training (true) or eval
(false).
training_fraction: float, the ... | [
"Obtain",
"a",
"list",
"of",
"image",
"paths",
"corresponding",
"to",
"training",
"or",
"eval",
"case",
"."
] | python | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/encrypted/item.py | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/encrypted/item.py#L122-L147 | def encrypt_python_item(item, crypto_config):
# type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM
"""Encrypt a dictionary for DynamoDB.
>>> from dynamodb_encryption_sdk.encrypted.item import encrypt_python_item
>>> plaintext_item = {
... 'some': 'data',
... 'more': 5
... | [
"def",
"encrypt_python_item",
"(",
"item",
",",
"crypto_config",
")",
":",
"# type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM",
"ddb_item",
"=",
"dict_to_ddb",
"(",
"item",
")",
"encrypted_ddb_item",
"=",
"encrypt_dynamodb_item",
"(",
"ddb_item",
",",
"cryp... | Encrypt a dictionary for DynamoDB.
>>> from dynamodb_encryption_sdk.encrypted.item import encrypt_python_item
>>> plaintext_item = {
... 'some': 'data',
... 'more': 5
... }
>>> encrypted_item = encrypt_python_item(
... item=plaintext_item,
... crypto_config=my_crypto_con... | [
"Encrypt",
"a",
"dictionary",
"for",
"DynamoDB",
"."
] | python | train |
pybel/pybel | src/pybel/parser/parse_metadata.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_metadata.py#L200-L206 | def raise_for_redefined_annotation(self, line: str, position: int, annotation: str) -> None:
"""Raise an exception if the given annotation is already defined.
:raises: RedefinedAnnotationError
"""
if self.disallow_redefinition and self.has_annotation(annotation):
raise Redef... | [
"def",
"raise_for_redefined_annotation",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"annotation",
":",
"str",
")",
"->",
"None",
":",
"if",
"self",
".",
"disallow_redefinition",
"and",
"self",
".",
"has_annotation",
"(",
"annotat... | Raise an exception if the given annotation is already defined.
:raises: RedefinedAnnotationError | [
"Raise",
"an",
"exception",
"if",
"the",
"given",
"annotation",
"is",
"already",
"defined",
"."
] | python | train |
fboender/ansible-cmdb | lib/mako/util.py | https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/lib/mako/util.py#L265-L338 | def restore__ast(_ast):
"""Attempt to restore the required classes to the _ast module if it
appears to be missing them
"""
if hasattr(_ast, 'AST'):
return
_ast.PyCF_ONLY_AST = 2 << 9
m = compile("""\
def foo(): pass
class Bar(object): pass
if False: pass
baz = 'mako'
1 + 2 - 3 * 4 / 5
6 ... | [
"def",
"restore__ast",
"(",
"_ast",
")",
":",
"if",
"hasattr",
"(",
"_ast",
",",
"'AST'",
")",
":",
"return",
"_ast",
".",
"PyCF_ONLY_AST",
"=",
"2",
"<<",
"9",
"m",
"=",
"compile",
"(",
"\"\"\"\\\ndef foo(): pass\nclass Bar(object): pass\nif False: pass\nbaz = 'm... | Attempt to restore the required classes to the _ast module if it
appears to be missing them | [
"Attempt",
"to",
"restore",
"the",
"required",
"classes",
"to",
"the",
"_ast",
"module",
"if",
"it",
"appears",
"to",
"be",
"missing",
"them"
] | python | train |
graphql-python/graphql-core | graphql/utils/suggestion_list.py | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/utils/suggestion_list.py#L23-L52 | def lexical_distance(a, b):
"""
Computes the lexical distance between strings A and B.
The "distance" between two strings is given by counting the minimum number
of edits needed to transform string A into string B. An edit can be an
insertion, deletion, or substitution of a single character, or ... | [
"def",
"lexical_distance",
"(",
"a",
",",
"b",
")",
":",
"d",
"=",
"[",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a",
")",
"+",
"1",
")",
"]",
"or",
"[",
"]",
"d_len",
"=",
"len",
"(",
"d",
")",
"or",
"1",
"for",
"i",
... | Computes the lexical distance between strings A and B.
The "distance" between two strings is given by counting the minimum number
of edits needed to transform string A into string B. An edit can be an
insertion, deletion, or substitution of a single character, or a swap of two
adjacent characters.
... | [
"Computes",
"the",
"lexical",
"distance",
"between",
"strings",
"A",
"and",
"B",
".",
"The",
"distance",
"between",
"two",
"strings",
"is",
"given",
"by",
"counting",
"the",
"minimum",
"number",
"of",
"edits",
"needed",
"to",
"transform",
"string",
"A",
"int... | python | train |
chaoss/grimoirelab-cereslib | cereslib/enrich/enrich.py | https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L489-L506 | def enrich(self, columns):
""" This method convert to utf-8 the provided columns
:param columns: list of columns to convert to
:type columns: list of strings
:return: original dataframe with converted strings
:rtype: pandas.DataFrame
"""
for column in columns:
... | [
"def",
"enrich",
"(",
"self",
",",
"columns",
")",
":",
"for",
"column",
"in",
"columns",
":",
"if",
"column",
"not",
"in",
"self",
".",
"data",
".",
"columns",
":",
"return",
"self",
".",
"data",
"for",
"column",
"in",
"columns",
":",
"a",
"=",
"s... | This method convert to utf-8 the provided columns
:param columns: list of columns to convert to
:type columns: list of strings
:return: original dataframe with converted strings
:rtype: pandas.DataFrame | [
"This",
"method",
"convert",
"to",
"utf",
"-",
"8",
"the",
"provided",
"columns"
] | python | train |
pyblish/pyblish-houdini | pyblish_houdini/lib.py | https://github.com/pyblish/pyblish-houdini/blob/661b08696f04b4c5d8b03aa0c75cba3ca72f1e8d/pyblish_houdini/lib.py#L20-L38 | def setup(console=False, port=None):
"""Setup integration
Register plug-ins and integrate into the host
Arguments:
console (bool): DEPRECATED
port (int, optional): DEPRECATED
"""
if self._has_been_setup:
teardown()
register_plugins()
register_host()
self._ha... | [
"def",
"setup",
"(",
"console",
"=",
"False",
",",
"port",
"=",
"None",
")",
":",
"if",
"self",
".",
"_has_been_setup",
":",
"teardown",
"(",
")",
"register_plugins",
"(",
")",
"register_host",
"(",
")",
"self",
".",
"_has_been_setup",
"=",
"True",
"prin... | Setup integration
Register plug-ins and integrate into the host
Arguments:
console (bool): DEPRECATED
port (int, optional): DEPRECATED | [
"Setup",
"integration"
] | python | train |
d0c-s4vage/pfp | pfp/fields.py | https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/fields.py#L247-L268 | def _pfp__process_metadata(self):
"""Process the metadata once the entire struct has been
declared.
"""
if self._pfp__metadata_processor is None:
return
metadata_info = self._pfp__metadata_processor()
if isinstance(metadata_info, list):
for metada... | [
"def",
"_pfp__process_metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"_pfp__metadata_processor",
"is",
"None",
":",
"return",
"metadata_info",
"=",
"self",
".",
"_pfp__metadata_processor",
"(",
")",
"if",
"isinstance",
"(",
"metadata_info",
",",
"list",
")... | Process the metadata once the entire struct has been
declared. | [
"Process",
"the",
"metadata",
"once",
"the",
"entire",
"struct",
"has",
"been",
"declared",
"."
] | python | train |
devassistant/devassistant | devassistant/gui/main_window.py | https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/main_window.py#L110-L115 | def tooltip_queries(self, item, x_coord, y_coord, key_mode, tooltip, text):
"""
The function is used for setting tooltip on menus and submenus
"""
tooltip.set_text(text)
return True | [
"def",
"tooltip_queries",
"(",
"self",
",",
"item",
",",
"x_coord",
",",
"y_coord",
",",
"key_mode",
",",
"tooltip",
",",
"text",
")",
":",
"tooltip",
".",
"set_text",
"(",
"text",
")",
"return",
"True"
] | The function is used for setting tooltip on menus and submenus | [
"The",
"function",
"is",
"used",
"for",
"setting",
"tooltip",
"on",
"menus",
"and",
"submenus"
] | python | train |
inasafe/inasafe | safe/metadata35/impact_layer_metadata.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata35/impact_layer_metadata.py#L312-L339 | def _read_provenance_from_xml(self, root):
"""
read metadata provenance from xml.
:param root: container in which we search
:type root: ElementTree.Element
"""
path = self._special_properties['provenance']
provenance = root.find(path, XML_NS)
for step in ... | [
"def",
"_read_provenance_from_xml",
"(",
"self",
",",
"root",
")",
":",
"path",
"=",
"self",
".",
"_special_properties",
"[",
"'provenance'",
"]",
"provenance",
"=",
"root",
".",
"find",
"(",
"path",
",",
"XML_NS",
")",
"for",
"step",
"in",
"provenance",
"... | read metadata provenance from xml.
:param root: container in which we search
:type root: ElementTree.Element | [
"read",
"metadata",
"provenance",
"from",
"xml",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.