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 |
|---|---|---|---|---|---|---|---|---|
COLORFULBOARD/revision | revision/orchestrator.py | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/orchestrator.py#L111-L136 | def has_commit(self, client_key=None):
"""
Return True if client has new commit.
:param client_key: The client key
:type client_key: str
:return:
:rtype: boolean
"""
if client_key is None and self.current_client is None:
raise ClientNotExist()... | [
"def",
"has_commit",
"(",
"self",
",",
"client_key",
"=",
"None",
")",
":",
"if",
"client_key",
"is",
"None",
"and",
"self",
".",
"current_client",
"is",
"None",
":",
"raise",
"ClientNotExist",
"(",
")",
"if",
"client_key",
":",
"if",
"not",
"self",
".",... | Return True if client has new commit.
:param client_key: The client key
:type client_key: str
:return:
:rtype: boolean | [
"Return",
"True",
"if",
"client",
"has",
"new",
"commit",
"."
] | python | train |
richardchien/nonebot | nonebot/command/__init__.py | https://github.com/richardchien/nonebot/blob/13ed9e4e87d9824b61592520aabda6d2737c8848/nonebot/command/__init__.py#L408-L412 | def finish(self, message: Optional[Message_T] = None, **kwargs) -> None:
"""Finish the session."""
if message:
asyncio.ensure_future(self.send(message, **kwargs))
raise _FinishException | [
"def",
"finish",
"(",
"self",
",",
"message",
":",
"Optional",
"[",
"Message_T",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"if",
"message",
":",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"send",
"(",
"message",
",",
... | Finish the session. | [
"Finish",
"the",
"session",
"."
] | python | train |
numenta/htmresearch | projects/sdr_paper/poirazi_neuron_model/run_dim_classification_experiment.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/poirazi_neuron_model/run_dim_classification_experiment.py#L32-L113 | def run_false_positive_experiment_dim(
numActive = 128,
dim = 500,
numSamples = 1000,
numDendrites = 500,
synapses = 24,
numTrials = 10000,
... | [
"def",
"run_false_positive_experiment_dim",
"(",
"numActive",
"=",
"128",
",",
"dim",
"=",
"500",
",",
"numSamples",
"=",
"1000",
",",
"numDendrites",
"=",
"500",
",",
"synapses",
"=",
"24",
",",
"numTrials",
"=",
"10000",
",",
"seed",
"=",
"42",
",",
"n... | Run an experiment to test the false positive rate based on number of synapses
per dendrite, dimension and sparsity. Uses two competing neurons, along the
P&M model.
Based on figure 5B in the original SDR paper. | [
"Run",
"an",
"experiment",
"to",
"test",
"the",
"false",
"positive",
"rate",
"based",
"on",
"number",
"of",
"synapses",
"per",
"dendrite",
"dimension",
"and",
"sparsity",
".",
"Uses",
"two",
"competing",
"neurons",
"along",
"the",
"P&M",
"model",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_lldp_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_lldp_ext.py#L320-L336 | def get_lldp_neighbor_detail_output_lldp_neighbor_detail_lldp_pdu_transmitted(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail")
config = get_lldp_neighbor_detail
output = ET.SubEleme... | [
"def",
"get_lldp_neighbor_detail_output_lldp_neighbor_detail_lldp_pdu_transmitted",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_lldp_neighbor_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_lldp_nei... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
jbittel/django-mama-cas | mama_cas/services/__init__.py | https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/services/__init__.py#L8-L18 | def _get_backends():
"""Retrieve the list of configured service backends."""
backends = []
backend_paths = getattr(
settings, 'MAMA_CAS_SERVICE_BACKENDS',
['mama_cas.services.backends.SettingsBackend']
)
for backend_path in backend_paths:
backend = import_string(backend_path)... | [
"def",
"_get_backends",
"(",
")",
":",
"backends",
"=",
"[",
"]",
"backend_paths",
"=",
"getattr",
"(",
"settings",
",",
"'MAMA_CAS_SERVICE_BACKENDS'",
",",
"[",
"'mama_cas.services.backends.SettingsBackend'",
"]",
")",
"for",
"backend_path",
"in",
"backend_paths",
... | Retrieve the list of configured service backends. | [
"Retrieve",
"the",
"list",
"of",
"configured",
"service",
"backends",
"."
] | python | train |
yamcs/yamcs-python | yamcs-client/yamcs/tmtc/client.py | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/tmtc/client.py#L219-L232 | def get_command_history(self, issued_command):
"""
Gets locally cached CommandHistory for the specified command.
:param .IssuedCommand issued_command: object representing a
previously issued command.
:rtype: .CommandHistory
"""
... | [
"def",
"get_command_history",
"(",
"self",
",",
"issued_command",
")",
":",
"#pylint: disable=protected-access",
"entry",
"=",
"issued_command",
".",
"_proto",
".",
"commandQueueEntry",
"key",
"=",
"self",
".",
"_cache_key",
"(",
"entry",
".",
"cmdId",
")",
"if",
... | Gets locally cached CommandHistory for the specified command.
:param .IssuedCommand issued_command: object representing a
previously issued command.
:rtype: .CommandHistory | [
"Gets",
"locally",
"cached",
"CommandHistory",
"for",
"the",
"specified",
"command",
"."
] | python | train |
readbeyond/aeneas | aeneas/container.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L322-L341 | def compress(self, input_path):
"""
Compress the contents of the given directory.
:param string input_path: path of the input directory
:raises: TypeError: if the container path has not been set
:raises: ValueError: if ``input_path`` is not an existing directory
:raises:... | [
"def",
"compress",
"(",
"self",
",",
"input_path",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Compressing '%s' into this container\"",
",",
"input_path",
"]",
")",
"if",
"self",
".",
"file_path",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"The conta... | Compress the contents of the given directory.
:param string input_path: path of the input directory
:raises: TypeError: if the container path has not been set
:raises: ValueError: if ``input_path`` is not an existing directory
:raises: OSError: if an error occurred compressing the given... | [
"Compress",
"the",
"contents",
"of",
"the",
"given",
"directory",
"."
] | python | train |
sys-git/certifiable | certifiable/utils.py | https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/utils.py#L123-L146 | def certify_parameter(certifier, name, value, kwargs=None):
"""
Internal certifier for kwargs passed to Certifiable public methods.
:param callable certifier:
The certifier to use
:param str name:
The name of the kwargs
:param object value:
The value of the kwarg.
:param... | [
"def",
"certify_parameter",
"(",
"certifier",
",",
"name",
",",
"value",
",",
"kwargs",
"=",
"None",
")",
":",
"try",
":",
"certifier",
"(",
"value",
",",
"*",
"*",
"kwargs",
"or",
"{",
"}",
")",
"except",
"CertifierError",
"as",
"err",
":",
"six",
"... | Internal certifier for kwargs passed to Certifiable public methods.
:param callable certifier:
The certifier to use
:param str name:
The name of the kwargs
:param object value:
The value of the kwarg.
:param bool required:
Is the param required. Default=False.
:raise... | [
"Internal",
"certifier",
"for",
"kwargs",
"passed",
"to",
"Certifiable",
"public",
"methods",
"."
] | python | train |
inasafe/inasafe | safe/gui/tools/multi_exposure_dialog.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_exposure_dialog.py#L360-L468 | def _create_exposure_combos(self):
"""Create one combobox for each exposure and insert them in the UI."""
# Map registry may be invalid if QGIS is shutting down
project = QgsProject.instance()
canvas_layers = self.iface.mapCanvas().layers()
# MapLayers returns a QMap<QString id, ... | [
"def",
"_create_exposure_combos",
"(",
"self",
")",
":",
"# Map registry may be invalid if QGIS is shutting down",
"project",
"=",
"QgsProject",
".",
"instance",
"(",
")",
"canvas_layers",
"=",
"self",
".",
"iface",
".",
"mapCanvas",
"(",
")",
".",
"layers",
"(",
... | Create one combobox for each exposure and insert them in the UI. | [
"Create",
"one",
"combobox",
"for",
"each",
"exposure",
"and",
"insert",
"them",
"in",
"the",
"UI",
"."
] | python | train |
Othernet-Project/bottle-fdsend | setup.py | https://github.com/Othernet-Project/bottle-fdsend/blob/5ff27e605e8cf878e24c71c1446dcf5c8caf4898/setup.py#L12-L21 | def read(fname):
""" Return content of specified file """
path = os.path.join(SCRIPTDIR, fname)
if PY3:
f = open(path, 'r', encoding='utf8')
else:
f = open(path, 'r')
content = f.read()
f.close()
return content | [
"def",
"read",
"(",
"fname",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SCRIPTDIR",
",",
"fname",
")",
"if",
"PY3",
":",
"f",
"=",
"open",
"(",
"path",
",",
"'r'",
",",
"encoding",
"=",
"'utf8'",
")",
"else",
":",
"f",
"=",
... | Return content of specified file | [
"Return",
"content",
"of",
"specified",
"file"
] | python | train |
AutomatedTester/Bugsy | bugsy/search.py | https://github.com/AutomatedTester/Bugsy/blob/ac14df84e744a148e81aeaae20a144bc5f3cebf1/bugsy/search.py#L48-L57 | def component(self, *components):
r"""
When search() is called it will limit results to items in a component.
:param component: items passed in will be turned into a list
:returns: :class:`Search`
"""
for component in components:
self._component.a... | [
"def",
"component",
"(",
"self",
",",
"*",
"components",
")",
":",
"for",
"component",
"in",
"components",
":",
"self",
".",
"_component",
".",
"append",
"(",
"component",
")",
"return",
"self"
] | r"""
When search() is called it will limit results to items in a component.
:param component: items passed in will be turned into a list
:returns: :class:`Search` | [
"r",
"When",
"search",
"()",
"is",
"called",
"it",
"will",
"limit",
"results",
"to",
"items",
"in",
"a",
"component",
"."
] | python | train |
stuaxo/vext | vext/env/__init__.py | https://github.com/stuaxo/vext/blob/fa98a21ecfbbc1c3d1b84085d69ec42defdd2f69/vext/env/__init__.py#L49-L81 | def in_venv():
"""
:return: True if in running from a virtualenv
Has to detect the case where the python binary is run
directly, so VIRTUAL_ENV may not be set
"""
global _in_venv
if _in_venv is not None:
return _in_venv
if not (os.path.isfile(ORIG_PREFIX_TXT) or os.path.isfile(... | [
"def",
"in_venv",
"(",
")",
":",
"global",
"_in_venv",
"if",
"_in_venv",
"is",
"not",
"None",
":",
"return",
"_in_venv",
"if",
"not",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"ORIG_PREFIX_TXT",
")",
"or",
"os",
".",
"path",
".",
"isfile",
"(",
"PY... | :return: True if in running from a virtualenv
Has to detect the case where the python binary is run
directly, so VIRTUAL_ENV may not be set | [
":",
"return",
":",
"True",
"if",
"in",
"running",
"from",
"a",
"virtualenv"
] | python | train |
goshuirc/irc | girc/events.py | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/events.py#L186-L386 | def message_to_event(direction, message):
"""Prepare an ``RFC1459Message`` for event dispatch.
We do this because we have to handle special things as well, such as CTCP
and deconstructing verbs properly.
"""
server = message.server
# change numerics into nice names
if message.verb in numer... | [
"def",
"message_to_event",
"(",
"direction",
",",
"message",
")",
":",
"server",
"=",
"message",
".",
"server",
"# change numerics into nice names",
"if",
"message",
".",
"verb",
"in",
"numerics",
":",
"message",
".",
"verb",
"=",
"numerics",
"[",
"message",
"... | Prepare an ``RFC1459Message`` for event dispatch.
We do this because we have to handle special things as well, such as CTCP
and deconstructing verbs properly. | [
"Prepare",
"an",
"RFC1459Message",
"for",
"event",
"dispatch",
"."
] | python | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network.py#L723-L764 | def add_upsample(self, name, scaling_factor_h, scaling_factor_w, input_name, output_name, mode = 'NN'):
"""
Add upsample layer to the model.
Parameters
----------
name: str
The name of this layer.
scaling_factor_h: int
Scaling factor on the vertic... | [
"def",
"add_upsample",
"(",
"self",
",",
"name",
",",
"scaling_factor_h",
",",
"scaling_factor_w",
",",
"input_name",
",",
"output_name",
",",
"mode",
"=",
"'NN'",
")",
":",
"spec",
"=",
"self",
".",
"spec",
"nn_spec",
"=",
"self",
".",
"nn_spec",
"# Add a... | Add upsample layer to the model.
Parameters
----------
name: str
The name of this layer.
scaling_factor_h: int
Scaling factor on the vertical direction.
scaling_factor_w: int
Scaling factor on the horizontal direction.
input_name: str
... | [
"Add",
"upsample",
"layer",
"to",
"the",
"model",
"."
] | python | train |
PixxxeL/python-html-purifier | purifier/purifier.py | https://github.com/PixxxeL/python-html-purifier/blob/00f38b6e7f66be02aa21100949f9ffa5be661e8d/purifier/purifier.py#L105-L120 | def __set_whitelist(self, whitelist=None):
"""
Update default white list by customer white list
"""
# add tag's names as key and list of enabled attributes as value for defaults
self.whitelist = {}
# tags that removed with contents
self.sanitizelist = ['script', '... | [
"def",
"__set_whitelist",
"(",
"self",
",",
"whitelist",
"=",
"None",
")",
":",
"# add tag's names as key and list of enabled attributes as value for defaults",
"self",
".",
"whitelist",
"=",
"{",
"}",
"# tags that removed with contents",
"self",
".",
"sanitizelist",
"=",
... | Update default white list by customer white list | [
"Update",
"default",
"white",
"list",
"by",
"customer",
"white",
"list"
] | python | train |
annoviko/pyclustering | pyclustering/container/kdtree.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/container/kdtree.py#L520-L544 | def __recursive_nearest_nodes(self, point, distance, sqrt_distance, node_head, best_nodes):
"""!
@brief Returns list of neighbors such as tuple (distance, node) that is located in area that is covered by distance.
@param[in] point (list): Coordinates that is considered as centroind ... | [
"def",
"__recursive_nearest_nodes",
"(",
"self",
",",
"point",
",",
"distance",
",",
"sqrt_distance",
",",
"node_head",
",",
"best_nodes",
")",
":",
"if",
"node_head",
".",
"right",
"is",
"not",
"None",
":",
"minimum",
"=",
"node_head",
".",
"data",
"[",
"... | !
@brief Returns list of neighbors such as tuple (distance, node) that is located in area that is covered by distance.
@param[in] point (list): Coordinates that is considered as centroind for searching
@param[in] distance (double): Distance from the center where seaching is performe... | [
"!"
] | python | valid |
dbcli/athenacli | athenacli/packages/parseutils.py | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/parseutils.py#L137-L151 | def extract_tables(sql):
"""Extract the table names from an SQL statment.
Returns a list of (schema, table, alias) tuples
"""
parsed = sqlparse.parse(sql)
if not parsed:
return []
# INSERT statements must stop looking for tables at the sign of first
# Punctuation. eg: INSERT INTO ab... | [
"def",
"extract_tables",
"(",
"sql",
")",
":",
"parsed",
"=",
"sqlparse",
".",
"parse",
"(",
"sql",
")",
"if",
"not",
"parsed",
":",
"return",
"[",
"]",
"# INSERT statements must stop looking for tables at the sign of first",
"# Punctuation. eg: INSERT INTO abc (col1, col... | Extract the table names from an SQL statment.
Returns a list of (schema, table, alias) tuples | [
"Extract",
"the",
"table",
"names",
"from",
"an",
"SQL",
"statment",
".",
"Returns",
"a",
"list",
"of",
"(",
"schema",
"table",
"alias",
")",
"tuples"
] | python | train |
sebp/scikit-survival | sksurv/kernels/clinical.py | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/kernels/clinical.py#L61-L107 | def clinical_kernel(x, y=None):
"""Computes clinical kernel
The clinical kernel distinguishes between continuous
ordinal,and nominal variables.
Parameters
----------
x : pandas.DataFrame, shape = (n_samples_x, n_features)
Training data
y : pandas.DataFrame, shape = (n_samples_y, n... | [
"def",
"clinical_kernel",
"(",
"x",
",",
"y",
"=",
"None",
")",
":",
"if",
"y",
"is",
"not",
"None",
":",
"if",
"x",
".",
"shape",
"[",
"1",
"]",
"!=",
"y",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"'x and y have different numb... | Computes clinical kernel
The clinical kernel distinguishes between continuous
ordinal,and nominal variables.
Parameters
----------
x : pandas.DataFrame, shape = (n_samples_x, n_features)
Training data
y : pandas.DataFrame, shape = (n_samples_y, n_features)
Testing data
Re... | [
"Computes",
"clinical",
"kernel"
] | python | train |
glormph/msstitch | src/app/actions/mzidtsv/percolator.py | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mzidtsv/percolator.py#L6-L39 | def add_percolator_to_mzidtsv(mzidfn, tsvfn, multipsm, oldheader):
"""Takes a MSGF+ tsv and corresponding mzId, adds percolatordata
to tsv lines. Generator yields the lines. Multiple PSMs per scan
can be delivered, in which case rank is also reported.
"""
namespace = readers.get_mzid_namespace(mzidf... | [
"def",
"add_percolator_to_mzidtsv",
"(",
"mzidfn",
",",
"tsvfn",
",",
"multipsm",
",",
"oldheader",
")",
":",
"namespace",
"=",
"readers",
".",
"get_mzid_namespace",
"(",
"mzidfn",
")",
"try",
":",
"xmlns",
"=",
"'{%s}'",
"%",
"namespace",
"[",
"'xmlns'",
"]... | Takes a MSGF+ tsv and corresponding mzId, adds percolatordata
to tsv lines. Generator yields the lines. Multiple PSMs per scan
can be delivered, in which case rank is also reported. | [
"Takes",
"a",
"MSGF",
"+",
"tsv",
"and",
"corresponding",
"mzId",
"adds",
"percolatordata",
"to",
"tsv",
"lines",
".",
"Generator",
"yields",
"the",
"lines",
".",
"Multiple",
"PSMs",
"per",
"scan",
"can",
"be",
"delivered",
"in",
"which",
"case",
"rank",
"... | python | train |
tanghaibao/goatools | goatools/grouper/sorter.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter.py#L178-L187 | def get_fields(desc2nts):
"""Return grouped, sorted namedtuples in either format: flat, sections."""
if 'flat' in desc2nts:
nts_flat = desc2nts.get('flat')
if nts_flat:
return nts_flat[0]._fields
if 'sections' in desc2nts:
nts_sections = desc2n... | [
"def",
"get_fields",
"(",
"desc2nts",
")",
":",
"if",
"'flat'",
"in",
"desc2nts",
":",
"nts_flat",
"=",
"desc2nts",
".",
"get",
"(",
"'flat'",
")",
"if",
"nts_flat",
":",
"return",
"nts_flat",
"[",
"0",
"]",
".",
"_fields",
"if",
"'sections'",
"in",
"d... | Return grouped, sorted namedtuples in either format: flat, sections. | [
"Return",
"grouped",
"sorted",
"namedtuples",
"in",
"either",
"format",
":",
"flat",
"sections",
"."
] | python | train |
janpipek/physt | physt/histogram1d.py | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram1d.py#L222-L236 | def std(self) -> Optional[float]: #, ddof=0):
"""Standard deviation of all values entered into histogram.
This number is precise, because we keep the necessary data
separate from bin contents.
Returns
-------
float
"""
# TODO: Add DOF
if self._s... | [
"def",
"std",
"(",
"self",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"#, ddof=0):",
"# TODO: Add DOF",
"if",
"self",
".",
"_stats",
":",
"return",
"np",
".",
"sqrt",
"(",
"self",
".",
"variance",
"(",
")",
")",
"else",
":",
"return",
"None"
] | Standard deviation of all values entered into histogram.
This number is precise, because we keep the necessary data
separate from bin contents.
Returns
-------
float | [
"Standard",
"deviation",
"of",
"all",
"values",
"entered",
"into",
"histogram",
"."
] | python | train |
Erotemic/utool | utool/util_numpy.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_numpy.py#L368-L372 | def deterministic_sample(list_, nSample, seed=0, rng=None, strict=False):
""" Grabs data randomly, but in a repeatable way """
rng = ensure_rng(seed if rng is None else rng)
sample_list = random_sample(list_, nSample, strict=strict, rng=rng)
return sample_list | [
"def",
"deterministic_sample",
"(",
"list_",
",",
"nSample",
",",
"seed",
"=",
"0",
",",
"rng",
"=",
"None",
",",
"strict",
"=",
"False",
")",
":",
"rng",
"=",
"ensure_rng",
"(",
"seed",
"if",
"rng",
"is",
"None",
"else",
"rng",
")",
"sample_list",
"... | Grabs data randomly, but in a repeatable way | [
"Grabs",
"data",
"randomly",
"but",
"in",
"a",
"repeatable",
"way"
] | python | train |
gmr/rejected | rejected/mcp.py | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L196-L217 | def collect_results(self, data_values):
"""Receive the data from the consumers polled and process it.
:param dict data_values: The poll data returned from the consumer
:type data_values: dict
"""
self.last_poll_results['timestamp'] = self.poll_data['timestamp']
# Get t... | [
"def",
"collect_results",
"(",
"self",
",",
"data_values",
")",
":",
"self",
".",
"last_poll_results",
"[",
"'timestamp'",
"]",
"=",
"self",
".",
"poll_data",
"[",
"'timestamp'",
"]",
"# Get the name and consumer name and remove it from what is reported",
"consumer_name",... | Receive the data from the consumers polled and process it.
:param dict data_values: The poll data returned from the consumer
:type data_values: dict | [
"Receive",
"the",
"data",
"from",
"the",
"consumers",
"polled",
"and",
"process",
"it",
"."
] | python | train |
peerplays-network/python-peerplays | peerplays/cli/info.py | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplays/cli/info.py#L19-L98 | def info(ctx, objects):
""" Obtain all kinds of information
"""
if not objects:
t = PrettyTable(["Key", "Value"])
t.align = "l"
info = ctx.peerplays.rpc.get_dynamic_global_properties()
for key in info:
t.add_row([key, info[key]])
click.echo(t.get_string(so... | [
"def",
"info",
"(",
"ctx",
",",
"objects",
")",
":",
"if",
"not",
"objects",
":",
"t",
"=",
"PrettyTable",
"(",
"[",
"\"Key\"",
",",
"\"Value\"",
"]",
")",
"t",
".",
"align",
"=",
"\"l\"",
"info",
"=",
"ctx",
".",
"peerplays",
".",
"rpc",
".",
"g... | Obtain all kinds of information | [
"Obtain",
"all",
"kinds",
"of",
"information"
] | python | train |
hellock/icrawler | icrawler/utils/proxy_pool.py | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L468-L479 | def scan_cnproxy(self):
"""Scan candidate (mainland) proxies from http://cn-proxy.com"""
self.logger.info(
'start scanning http://cn-proxy.com for proxy list...')
response = requests.get('http://cn-proxy.com')
soup = BeautifulSoup(response.content, 'lxml')
tables = so... | [
"def",
"scan_cnproxy",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'start scanning http://cn-proxy.com for proxy list...'",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"'http://cn-proxy.com'",
")",
"soup",
"=",
"BeautifulSoup",
"(",
"re... | Scan candidate (mainland) proxies from http://cn-proxy.com | [
"Scan",
"candidate",
"(",
"mainland",
")",
"proxies",
"from",
"http",
":",
"//",
"cn",
"-",
"proxy",
".",
"com"
] | python | train |
peri-source/peri | peri/comp/exactpsf.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/exactpsf.py#L321-L323 | def _p2k(self, v):
""" Convert from pixel to 1/k_incoming (laser_wavelength/(2\pi)) units """
return 2*np.pi*self.pxsize*v/self.param_dict['psf-laser-wavelength'] | [
"def",
"_p2k",
"(",
"self",
",",
"v",
")",
":",
"return",
"2",
"*",
"np",
".",
"pi",
"*",
"self",
".",
"pxsize",
"*",
"v",
"/",
"self",
".",
"param_dict",
"[",
"'psf-laser-wavelength'",
"]"
] | Convert from pixel to 1/k_incoming (laser_wavelength/(2\pi)) units | [
"Convert",
"from",
"pixel",
"to",
"1",
"/",
"k_incoming",
"(",
"laser_wavelength",
"/",
"(",
"2",
"\\",
"pi",
"))",
"units"
] | python | valid |
saltstack/salt | salt/platform/win.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/platform/win.py#L1131-L1144 | def dup_token(th):
'''
duplicate the access token
'''
# TODO: is `duplicate_token` the same?
sec_attr = win32security.SECURITY_ATTRIBUTES()
sec_attr.bInheritHandle = True
return win32security.DuplicateTokenEx(
th,
win32security.SecurityImpersonation,
win32con.MAXIMUM_ALL... | [
"def",
"dup_token",
"(",
"th",
")",
":",
"# TODO: is `duplicate_token` the same?",
"sec_attr",
"=",
"win32security",
".",
"SECURITY_ATTRIBUTES",
"(",
")",
"sec_attr",
".",
"bInheritHandle",
"=",
"True",
"return",
"win32security",
".",
"DuplicateTokenEx",
"(",
"th",
... | duplicate the access token | [
"duplicate",
"the",
"access",
"token"
] | python | train |
StanfordBioinformatics/loom | server/loomengine_server/api/models/data_nodes.py | https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/server/loomengine_server/api/models/data_nodes.py#L328-L339 | def _check_index(self, index):
"""Verify that the given index is consistent with the degree of the node.
"""
if self.degree is None:
raise UnknownDegreeError(
'Cannot access child DataNode on a parent with degree of None. '\
'Set the degree on the pare... | [
"def",
"_check_index",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
".",
"degree",
"is",
"None",
":",
"raise",
"UnknownDegreeError",
"(",
"'Cannot access child DataNode on a parent with degree of None. '",
"'Set the degree on the parent first.'",
")",
"if",
"index",... | Verify that the given index is consistent with the degree of the node. | [
"Verify",
"that",
"the",
"given",
"index",
"is",
"consistent",
"with",
"the",
"degree",
"of",
"the",
"node",
"."
] | python | train |
myaooo/pysbrl | pysbrl/rule_list.py | https://github.com/myaooo/pysbrl/blob/74bba8c6913a7f82e32313108f8c3e025b89d9c7/pysbrl/rule_list.py#L227-L242 | def from_raw(self, rule_ids, outputs, raw_rules):
"""
A helper function that converts the results returned from C function
:param rule_ids:
:param outputs:
:param raw_rules:
:return:
"""
self._rule_pool = [([], [])] + raw_rules
self._rule_list = []... | [
"def",
"from_raw",
"(",
"self",
",",
"rule_ids",
",",
"outputs",
",",
"raw_rules",
")",
":",
"self",
".",
"_rule_pool",
"=",
"[",
"(",
"[",
"]",
",",
"[",
"]",
")",
"]",
"+",
"raw_rules",
"self",
".",
"_rule_list",
"=",
"[",
"]",
"for",
"i",
",",... | A helper function that converts the results returned from C function
:param rule_ids:
:param outputs:
:param raw_rules:
:return: | [
"A",
"helper",
"function",
"that",
"converts",
"the",
"results",
"returned",
"from",
"C",
"function",
":",
"param",
"rule_ids",
":",
":",
"param",
"outputs",
":",
":",
"param",
"raw_rules",
":",
":",
"return",
":"
] | python | train |
django-py/django-doberman | doberman/auth.py | https://github.com/django-py/django-doberman/blob/2e5959737a1b64234ed5a179c93f96a0de1c3e5c/doberman/auth.py#L97-L137 | def inspect(self):
"""
Inspect access attempt, used for catpcha flow
:return:
"""
last_attempt = self.get_last_failed_access_attempt(
ip_address=self.ip,
captcha_enabled=True,
captcha_passed=False,
is_expired=False
)
... | [
"def",
"inspect",
"(",
"self",
")",
":",
"last_attempt",
"=",
"self",
".",
"get_last_failed_access_attempt",
"(",
"ip_address",
"=",
"self",
".",
"ip",
",",
"captcha_enabled",
"=",
"True",
",",
"captcha_passed",
"=",
"False",
",",
"is_expired",
"=",
"False",
... | Inspect access attempt, used for catpcha flow
:return: | [
"Inspect",
"access",
"attempt",
"used",
"for",
"catpcha",
"flow",
":",
"return",
":"
] | python | train |
sdispater/orator | orator/dbal/platforms/platform.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/dbal/platforms/platform.py#L515-L527 | def get_drop_table_sql(self, table):
"""
Returns the SQL snippet to drop an existing table.
:param table: The table
:type table: Table or str
:rtype: str
"""
if isinstance(table, Table):
table = table.get_quoted_name(self)
return "DROP TABLE... | [
"def",
"get_drop_table_sql",
"(",
"self",
",",
"table",
")",
":",
"if",
"isinstance",
"(",
"table",
",",
"Table",
")",
":",
"table",
"=",
"table",
".",
"get_quoted_name",
"(",
"self",
")",
"return",
"\"DROP TABLE %s\"",
"%",
"table"
] | Returns the SQL snippet to drop an existing table.
:param table: The table
:type table: Table or str
:rtype: str | [
"Returns",
"the",
"SQL",
"snippet",
"to",
"drop",
"an",
"existing",
"table",
"."
] | python | train |
codeinn/vcs | vcs/backends/git/repository.py | https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/backends/git/repository.py#L636-L662 | def get_config_value(self, section, name, config_file=None):
"""
Returns configuration value for a given [``section``] and ``name``.
:param section: Section we want to retrieve value from
:param name: Name of configuration we want to retrieve
:param config_file: A path to file w... | [
"def",
"get_config_value",
"(",
"self",
",",
"section",
",",
"name",
",",
"config_file",
"=",
"None",
")",
":",
"if",
"config_file",
"is",
"None",
":",
"config_file",
"=",
"[",
"]",
"elif",
"isinstance",
"(",
"config_file",
",",
"basestring",
")",
":",
"... | Returns configuration value for a given [``section``] and ``name``.
:param section: Section we want to retrieve value from
:param name: Name of configuration we want to retrieve
:param config_file: A path to file which should be used to retrieve
configuration from (might also be a lis... | [
"Returns",
"configuration",
"value",
"for",
"a",
"given",
"[",
"section",
"]",
"and",
"name",
"."
] | python | train |
DLR-RM/RAFCON | source/rafcon/gui/models/abstract_state.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/abstract_state.py#L574-L601 | def _parse_for_element_meta_data(self, meta_data):
"""Load meta data for state elements
The meta data of the state meta data file also contains the meta data for state elements (data ports,
outcomes, etc). This method parses the loaded meta data for each state element model. The meta data of th... | [
"def",
"_parse_for_element_meta_data",
"(",
"self",
",",
"meta_data",
")",
":",
"# print(\"_parse meta data\", meta_data)",
"for",
"data_port_m",
"in",
"self",
".",
"input_data_ports",
":",
"self",
".",
"_copy_element_meta_data_from_meta_file_data",
"(",
"meta_data",
",",
... | Load meta data for state elements
The meta data of the state meta data file also contains the meta data for state elements (data ports,
outcomes, etc). This method parses the loaded meta data for each state element model. The meta data of the
elements is removed from the passed dictionary.
... | [
"Load",
"meta",
"data",
"for",
"state",
"elements"
] | python | train |
DataDog/integrations-core | postgres/datadog_checks/postgres/postgres.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/postgres/datadog_checks/postgres/postgres.py#L385-L390 | def _set_server_known(cls, host, port):
"""
Store the host/port combination for this server
"""
with PostgreSql._known_servers_lock:
PostgreSql._known_servers.add((host, port)) | [
"def",
"_set_server_known",
"(",
"cls",
",",
"host",
",",
"port",
")",
":",
"with",
"PostgreSql",
".",
"_known_servers_lock",
":",
"PostgreSql",
".",
"_known_servers",
".",
"add",
"(",
"(",
"host",
",",
"port",
")",
")"
] | Store the host/port combination for this server | [
"Store",
"the",
"host",
"/",
"port",
"combination",
"for",
"this",
"server"
] | python | train |
CityOfZion/neo-python | neo/Core/TX/StateTransaction.py | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/TX/StateTransaction.py#L46-L58 | def DeserializeExclusiveData(self, reader):
"""
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
Raises:
Exception: If the transaction type is incorrect or if there are no claims.
"""
self.Type = TransactionType.StateTransaction
... | [
"def",
"DeserializeExclusiveData",
"(",
"self",
",",
"reader",
")",
":",
"self",
".",
"Type",
"=",
"TransactionType",
".",
"StateTransaction",
"self",
".",
"Descriptors",
"=",
"reader",
".",
"ReadSerializableArray",
"(",
"'neo.Core.State.StateDescriptor.StateDescriptor'... | Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
Raises:
Exception: If the transaction type is incorrect or if there are no claims. | [
"Deserialize",
"full",
"object",
"."
] | python | train |
facebook/pyre-check | sapp/sapp/pysa_taint_parser.py | https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/pysa_taint_parser.py#L202-L204 | def _parse_leaves(self, leaves) -> List[Tuple[str, int]]:
"""Returns a list of pairs (leaf_name, distance)"""
return [(self._leaf_name(leaf), 0) for leaf in leaves] | [
"def",
"_parse_leaves",
"(",
"self",
",",
"leaves",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"int",
"]",
"]",
":",
"return",
"[",
"(",
"self",
".",
"_leaf_name",
"(",
"leaf",
")",
",",
"0",
")",
"for",
"leaf",
"in",
"leaves",
"]"
] | Returns a list of pairs (leaf_name, distance) | [
"Returns",
"a",
"list",
"of",
"pairs",
"(",
"leaf_name",
"distance",
")"
] | python | train |
lsst-sqre/ltd-conveyor | ltdconveyor/s3/upload.py | https://github.com/lsst-sqre/ltd-conveyor/blob/c492937c4c1e050ccc4a0b9dcc38f9980d57e305/ltdconveyor/s3/upload.py#L356-L407 | def list_dirnames_in_directory(self, dirname):
"""List all names of directories that exist at the root of this
bucket directory.
Note that *directories* don't exist in S3; rather directories are
inferred from path names.
Parameters
----------
dirname : `str`
... | [
"def",
"list_dirnames_in_directory",
"(",
"self",
",",
"dirname",
")",
":",
"prefix",
"=",
"self",
".",
"_create_prefix",
"(",
"dirname",
")",
"dirnames",
"=",
"[",
"]",
"for",
"obj",
"in",
"self",
".",
"_bucket",
".",
"objects",
".",
"filter",
"(",
"Pre... | List all names of directories that exist at the root of this
bucket directory.
Note that *directories* don't exist in S3; rather directories are
inferred from path names.
Parameters
----------
dirname : `str`
Directory name in the bucket relative to ``bucket... | [
"List",
"all",
"names",
"of",
"directories",
"that",
"exist",
"at",
"the",
"root",
"of",
"this",
"bucket",
"directory",
"."
] | python | test |
kako-nawao/django-group-by | django_group_by/mixin.py | https://github.com/kako-nawao/django-group-by/blob/0d901513620acebc736722b040cff83d6483789a/django_group_by/mixin.py#L23-L74 | def _expand_group_by_fields(cls, model, fields):
"""
Expand FK fields into all related object's fields to avoid future
lookups.
:param fields: fields to "group by"
:return: expanded fields
"""
# Containers for resulting fields and related model fields
res... | [
"def",
"_expand_group_by_fields",
"(",
"cls",
",",
"model",
",",
"fields",
")",
":",
"# Containers for resulting fields and related model fields",
"res",
"=",
"[",
"]",
"related",
"=",
"{",
"}",
"# Add own fields and populate related fields",
"for",
"field_name",
"in",
... | Expand FK fields into all related object's fields to avoid future
lookups.
:param fields: fields to "group by"
:return: expanded fields | [
"Expand",
"FK",
"fields",
"into",
"all",
"related",
"object",
"s",
"fields",
"to",
"avoid",
"future",
"lookups",
"."
] | python | train |
noxdafox/pebble | pebble/pool/process.py | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/process.py#L328-L340 | def inspect_workers(self):
"""Updates the workers status.
Returns the workers which have unexpectedly ended.
"""
workers = tuple(self.workers.values())
expired = tuple(w for w in workers if not w.is_alive())
for worker in expired:
self.workers.pop(worker.pi... | [
"def",
"inspect_workers",
"(",
"self",
")",
":",
"workers",
"=",
"tuple",
"(",
"self",
".",
"workers",
".",
"values",
"(",
")",
")",
"expired",
"=",
"tuple",
"(",
"w",
"for",
"w",
"in",
"workers",
"if",
"not",
"w",
".",
"is_alive",
"(",
")",
")",
... | Updates the workers status.
Returns the workers which have unexpectedly ended. | [
"Updates",
"the",
"workers",
"status",
"."
] | python | train |
dagwieers/vmguestlib | vmguestlib.py | https://github.com/dagwieers/vmguestlib/blob/2ba9333a745628cf9e6b4c767427a5bd997a71ad/vmguestlib.py#L385-L391 | def GetMemSharedMB(self):
'''Retrieves the amount of physical memory associated with this virtual
machine that is copy-on-write (COW) shared on the host.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemSharedMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ER... | [
"def",
"GetMemSharedMB",
"(",
"self",
")",
":",
"counter",
"=",
"c_uint",
"(",
")",
"ret",
"=",
"vmGuestLib",
".",
"VMGuestLib_GetMemSharedMB",
"(",
"self",
".",
"handle",
".",
"value",
",",
"byref",
"(",
"counter",
")",
")",
"if",
"ret",
"!=",
"VMGUESTL... | Retrieves the amount of physical memory associated with this virtual
machine that is copy-on-write (COW) shared on the host. | [
"Retrieves",
"the",
"amount",
"of",
"physical",
"memory",
"associated",
"with",
"this",
"virtual",
"machine",
"that",
"is",
"copy",
"-",
"on",
"-",
"write",
"(",
"COW",
")",
"shared",
"on",
"the",
"host",
"."
] | python | train |
chrislit/abydos | abydos/fingerprint/_phonetic.py | https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/fingerprint/_phonetic.py#L49-L97 | def fingerprint(
self,
phrase,
phonetic_algorithm=double_metaphone,
joiner=' ',
*args,
**kwargs
):
"""Return the phonetic fingerprint of a phrase.
Parameters
----------
phrase : str
The string from which to calculate the ph... | [
"def",
"fingerprint",
"(",
"self",
",",
"phrase",
",",
"phonetic_algorithm",
"=",
"double_metaphone",
",",
"joiner",
"=",
"' '",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"phonetic",
"=",
"''",
"for",
"word",
"in",
"phrase",
".",
"split",
"(... | Return the phonetic fingerprint of a phrase.
Parameters
----------
phrase : str
The string from which to calculate the phonetic fingerprint
phonetic_algorithm : function
A phonetic algorithm that takes a string and returns a string
(presumably a phone... | [
"Return",
"the",
"phonetic",
"fingerprint",
"of",
"a",
"phrase",
"."
] | python | valid |
kieferk/dfply | dfply/reshape.py | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/reshape.py#L46-L58 | def rename(df, **kwargs):
"""Renames columns, where keyword argument values are the current names
of columns and keys are the new names.
Args:
df (:obj:`pandas.DataFrame`): DataFrame passed in via `>>` pipe.
Kwargs:
**kwargs: key:value pairs where keys are new names for columns and
... | [
"def",
"rename",
"(",
"df",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"df",
".",
"rename",
"(",
"columns",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"}",
")"
] | Renames columns, where keyword argument values are the current names
of columns and keys are the new names.
Args:
df (:obj:`pandas.DataFrame`): DataFrame passed in via `>>` pipe.
Kwargs:
**kwargs: key:value pairs where keys are new names for columns and
values are current names... | [
"Renames",
"columns",
"where",
"keyword",
"argument",
"values",
"are",
"the",
"current",
"names",
"of",
"columns",
"and",
"keys",
"are",
"the",
"new",
"names",
"."
] | python | train |
hollenstein/maspy | maspy/core.py | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/core.py#L935-L953 | def jsonHook(encoded):
"""Custom JSON decoder that allows construction of a new ``Smi``
instance from a decoded JSON object.
:param encoded: a JSON decoded object literal (a dict)
:returns: "encoded" or one of the these objects: :class:`Smi`,
:class:`MzmlScan`, :class:`Mzml... | [
"def",
"jsonHook",
"(",
"encoded",
")",
":",
"if",
"'__Smi__'",
"in",
"encoded",
":",
"return",
"Smi",
".",
"_fromJSON",
"(",
"encoded",
"[",
"'__Smi__'",
"]",
")",
"elif",
"'__MzmlScan__'",
"in",
"encoded",
":",
"return",
"MzmlScan",
".",
"_fromJSON",
"("... | Custom JSON decoder that allows construction of a new ``Smi``
instance from a decoded JSON object.
:param encoded: a JSON decoded object literal (a dict)
:returns: "encoded" or one of the these objects: :class:`Smi`,
:class:`MzmlScan`, :class:`MzmlProduct`, :class:`MzmlPrecursor` | [
"Custom",
"JSON",
"decoder",
"that",
"allows",
"construction",
"of",
"a",
"new",
"Smi",
"instance",
"from",
"a",
"decoded",
"JSON",
"object",
"."
] | python | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L965-L978 | def init_types_collection(filter_filename=default_filter_filename):
# type: (Callable[[Optional[str]], Optional[str]]) -> None
"""
Setup profiler hooks to enable type collection.
Call this one time from the main thread.
The optional argument is a filter that maps a filename (from
code.co_filena... | [
"def",
"init_types_collection",
"(",
"filter_filename",
"=",
"default_filter_filename",
")",
":",
"# type: (Callable[[Optional[str]], Optional[str]]) -> None",
"global",
"_filter_filename",
"_filter_filename",
"=",
"filter_filename",
"sys",
".",
"setprofile",
"(",
"_trace_dispatc... | Setup profiler hooks to enable type collection.
Call this one time from the main thread.
The optional argument is a filter that maps a filename (from
code.co_filename) to either a normalized filename or None.
For the default filter see default_filter_filename(). | [
"Setup",
"profiler",
"hooks",
"to",
"enable",
"type",
"collection",
".",
"Call",
"this",
"one",
"time",
"from",
"the",
"main",
"thread",
"."
] | python | train |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/settings_v1alpha1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/settings_v1alpha1_api.py#L499-L528 | def list_namespaced_pod_preset(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_pod_preset # noqa: E501
list or watch objects of kind PodPreset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req... | [
"def",
"list_namespaced_pod_preset",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".... | list_namespaced_pod_preset # noqa: E501
list or watch objects of kind PodPreset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_pod_preset(namespace, async_req=True)... | [
"list_namespaced_pod_preset",
"#",
"noqa",
":",
"E501"
] | python | train |
joopert/nad_receiver | nad_receiver/__init__.py | https://github.com/joopert/nad_receiver/blob/416de0173a330c75cc73f9c90b0c5df32e5e0ba3/nad_receiver/__init__.py#L183-L213 | def _send(self, message, read_reply=False):
"""Send a command string to the amplifier."""
sock = None
for tries in range(0, 3):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self._host, self.PORT))
break
... | [
"def",
"_send",
"(",
"self",
",",
"message",
",",
"read_reply",
"=",
"False",
")",
":",
"sock",
"=",
"None",
"for",
"tries",
"in",
"range",
"(",
"0",
",",
"3",
")",
":",
"try",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_IN... | Send a command string to the amplifier. | [
"Send",
"a",
"command",
"string",
"to",
"the",
"amplifier",
"."
] | python | test |
flashingpumpkin/django-socialregistration | socialregistration/views.py | https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/views.py#L85-L115 | def generate_username_and_redirect(self, request, user, profile, client):
"""
Generate a username and then redirect the user to the correct place.
This method is called when ``SOCIALREGISTRATION_GENERATE_USERNAME``
is set.
:param request: The current request object
:pa... | [
"def",
"generate_username_and_redirect",
"(",
"self",
",",
"request",
",",
"user",
",",
"profile",
",",
"client",
")",
":",
"func",
"=",
"self",
".",
"get_username_function",
"(",
")",
"user",
".",
"username",
"=",
"func",
"(",
"user",
",",
"profile",
",",... | Generate a username and then redirect the user to the correct place.
This method is called when ``SOCIALREGISTRATION_GENERATE_USERNAME``
is set.
:param request: The current request object
:param user: The unsaved user object
:param profile: The unsaved profile object
:... | [
"Generate",
"a",
"username",
"and",
"then",
"redirect",
"the",
"user",
"to",
"the",
"correct",
"place",
".",
"This",
"method",
"is",
"called",
"when",
"SOCIALREGISTRATION_GENERATE_USERNAME",
"is",
"set",
"."
] | python | train |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/api.py | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/api.py#L177-L197 | def change_password(username, new_password):
"""
Change password for given `username`.
Args:
username (str): User's name.
new_password (str): User's new password.
"""
assert username in passwd_reader.load_users(),\
"Username '%s' not found!" % username
sh.ftpasswd(
... | [
"def",
"change_password",
"(",
"username",
",",
"new_password",
")",
":",
"assert",
"username",
"in",
"passwd_reader",
".",
"load_users",
"(",
")",
",",
"\"Username '%s' not found!\"",
"%",
"username",
"sh",
".",
"ftpasswd",
"(",
"\"--change-password\"",
",",
"pas... | Change password for given `username`.
Args:
username (str): User's name.
new_password (str): User's new password. | [
"Change",
"password",
"for",
"given",
"username",
"."
] | python | train |
pydata/xarray | xarray/convert.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/convert.py#L125-L135 | def _get_iris_args(attrs):
""" Converts the xarray attrs into args that can be passed into Iris
"""
# iris.unit is deprecated in Iris v1.9
import cf_units
args = {'attributes': _filter_attrs(attrs, iris_forbidden_keys)}
args.update(_pick_attrs(attrs, ('standard_name', 'long_name',)))
unit_ar... | [
"def",
"_get_iris_args",
"(",
"attrs",
")",
":",
"# iris.unit is deprecated in Iris v1.9",
"import",
"cf_units",
"args",
"=",
"{",
"'attributes'",
":",
"_filter_attrs",
"(",
"attrs",
",",
"iris_forbidden_keys",
")",
"}",
"args",
".",
"update",
"(",
"_pick_attrs",
... | Converts the xarray attrs into args that can be passed into Iris | [
"Converts",
"the",
"xarray",
"attrs",
"into",
"args",
"that",
"can",
"be",
"passed",
"into",
"Iris"
] | python | train |
hubo1016/namedstruct | misc/openflow/nicira_ext.py | https://github.com/hubo1016/namedstruct/blob/5039026e0df4ce23003d212358918dbe1a6e1d76/misc/openflow/nicira_ext.py#L1130-L3077 | def create_extension(namespace, nicira_header, nx_action, nx_stats_request, nx_stats_reply,
msg_subtype, action_subtype, stats_subtype):
'''
/* This command enables or disables an Open vSwitch extension that allows a
* controller to specify the OpenFlow table to which a flow should be ... | [
"def",
"create_extension",
"(",
"namespace",
",",
"nicira_header",
",",
"nx_action",
",",
"nx_stats_request",
",",
"nx_stats_reply",
",",
"msg_subtype",
",",
"action_subtype",
",",
"stats_subtype",
")",
":",
"with",
"_warnings",
".",
"catch_warnings",
"(",
")",
":... | /* This command enables or disables an Open vSwitch extension that allows a
* controller to specify the OpenFlow table to which a flow should be added,
* instead of having the switch decide which table is most appropriate as
* required by OpenFlow 1.0. Because NXM was designed as an extension to
* ... | [
"/",
"*",
"This",
"command",
"enables",
"or",
"disables",
"an",
"Open",
"vSwitch",
"extension",
"that",
"allows",
"a",
"*",
"controller",
"to",
"specify",
"the",
"OpenFlow",
"table",
"to",
"which",
"a",
"flow",
"should",
"be",
"added",
"*",
"instead",
"of"... | python | train |
zvolsky/wfpdf | wfpdf.py | https://github.com/zvolsky/wfpdf/blob/d3625a6420ae1fb6722d81cddf0636af496c42bb/wfpdf.py#L129-L135 | def down(self, h, cr=True):
"""moves current vertical position h mm down
cr True will navigate to the left margin
"""
if cr:
self.oPdf.ln(h=0)
self.oPdf.set_y(self.oPdf.get_y() + h) | [
"def",
"down",
"(",
"self",
",",
"h",
",",
"cr",
"=",
"True",
")",
":",
"if",
"cr",
":",
"self",
".",
"oPdf",
".",
"ln",
"(",
"h",
"=",
"0",
")",
"self",
".",
"oPdf",
".",
"set_y",
"(",
"self",
".",
"oPdf",
".",
"get_y",
"(",
")",
"+",
"h... | moves current vertical position h mm down
cr True will navigate to the left margin | [
"moves",
"current",
"vertical",
"position",
"h",
"mm",
"down",
"cr",
"True",
"will",
"navigate",
"to",
"the",
"left",
"margin"
] | python | train |
quantmind/agile-toolkit | agiletoolkit/api/components.py | https://github.com/quantmind/agile-toolkit/blob/96028e36a842c57b171907c20583a60d1045fec1/agiletoolkit/api/components.py#L54-L62 | def update(self, id, data):
"""Update a component
"""
id = self.as_id(id)
response = self.http.patch(
'%s/%s' % (self, id), json=data, auth=self.auth
)
response.raise_for_status()
return response.json() | [
"def",
"update",
"(",
"self",
",",
"id",
",",
"data",
")",
":",
"id",
"=",
"self",
".",
"as_id",
"(",
"id",
")",
"response",
"=",
"self",
".",
"http",
".",
"patch",
"(",
"'%s/%s'",
"%",
"(",
"self",
",",
"id",
")",
",",
"json",
"=",
"data",
"... | Update a component | [
"Update",
"a",
"component"
] | python | train |
erikrose/parsimonious | parsimonious/expressions.py | https://github.com/erikrose/parsimonious/blob/12263be5ceca89344905c2c3eb9ac5a603e976e1/parsimonious/expressions.py#L278-L285 | def _uncached_match(self, text, pos, cache, error):
"""Return length of match, ``None`` if no match."""
m = self.re.match(text, pos)
if m is not None:
span = m.span()
node = RegexNode(self, text, pos, pos + span[1] - span[0])
node.match = m # TODO: A terrible... | [
"def",
"_uncached_match",
"(",
"self",
",",
"text",
",",
"pos",
",",
"cache",
",",
"error",
")",
":",
"m",
"=",
"self",
".",
"re",
".",
"match",
"(",
"text",
",",
"pos",
")",
"if",
"m",
"is",
"not",
"None",
":",
"span",
"=",
"m",
".",
"span",
... | Return length of match, ``None`` if no match. | [
"Return",
"length",
"of",
"match",
"None",
"if",
"no",
"match",
"."
] | python | train |
mozilla-services/python-dockerflow | src/dockerflow/flask/app.py | https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L232-L261 | def summary_extra(self):
"""
Build the extra data for the summary logger.
"""
out = {
'errno': 0,
'agent': request.headers.get('User-Agent', ''),
'lang': request.headers.get('Accept-Language', ''),
'method': request.method,
'pat... | [
"def",
"summary_extra",
"(",
"self",
")",
":",
"out",
"=",
"{",
"'errno'",
":",
"0",
",",
"'agent'",
":",
"request",
".",
"headers",
".",
"get",
"(",
"'User-Agent'",
",",
"''",
")",
",",
"'lang'",
":",
"request",
".",
"headers",
".",
"get",
"(",
"'... | Build the extra data for the summary logger. | [
"Build",
"the",
"extra",
"data",
"for",
"the",
"summary",
"logger",
"."
] | python | train |
raiden-network/raiden | raiden/network/proxies/payment_channel.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/payment_channel.py#L161-L168 | def can_transfer(self, block_identifier: BlockSpecification) -> bool:
""" Returns True if the channel is opened and the node has deposit in it. """
return self.token_network.can_transfer(
participant1=self.participant1,
participant2=self.participant2,
block_identifier... | [
"def",
"can_transfer",
"(",
"self",
",",
"block_identifier",
":",
"BlockSpecification",
")",
"->",
"bool",
":",
"return",
"self",
".",
"token_network",
".",
"can_transfer",
"(",
"participant1",
"=",
"self",
".",
"participant1",
",",
"participant2",
"=",
"self",
... | Returns True if the channel is opened and the node has deposit in it. | [
"Returns",
"True",
"if",
"the",
"channel",
"is",
"opened",
"and",
"the",
"node",
"has",
"deposit",
"in",
"it",
"."
] | python | train |
OLC-Bioinformatics/sipprverse | pointsippr/pointsippr.py | https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/pointsippr/pointsippr.py#L345-L403 | def write_table_report(summary_dict, seqid, genus):
"""
Parse the PointFinder table output, and write a summary report
:param summary_dict: nested dictionary containing data such as header strings, and paths to reports
:param seqid: name of the strain,
:param genus: MASH-calculat... | [
"def",
"write_table_report",
"(",
"summary_dict",
",",
"seqid",
",",
"genus",
")",
":",
"# Set the header string if the summary report doesn't already exist",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"summary_dict",
"[",
"genus",
"]",
"[",
"'table'",
"]",... | Parse the PointFinder table output, and write a summary report
:param summary_dict: nested dictionary containing data such as header strings, and paths to reports
:param seqid: name of the strain,
:param genus: MASH-calculated genus of current isolate | [
"Parse",
"the",
"PointFinder",
"table",
"output",
"and",
"write",
"a",
"summary",
"report",
":",
"param",
"summary_dict",
":",
"nested",
"dictionary",
"containing",
"data",
"such",
"as",
"header",
"strings",
"and",
"paths",
"to",
"reports",
":",
"param",
"seqi... | python | train |
lehins/python-wepay | wepay/calls/batch.py | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/batch.py#L8-L22 | def __create(self, client_id, client_secret, calls, **kwargs):
"""Call documentation: `/batch/create
<https://www.wepay.com/developer/reference/batch#create>`_, plus extra
keyword parameter:
:keyword str access_token: will be used instead of instance's
``access_token... | [
"def",
"__create",
"(",
"self",
",",
"client_id",
",",
"client_secret",
",",
"calls",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'client_id'",
":",
"client_id",
",",
"'client_secret'",
":",
"client_secret",
",",
"'calls'",
":",
"calls",
"}",
... | Call documentation: `/batch/create
<https://www.wepay.com/developer/reference/batch#create>`_, plus extra
keyword parameter:
:keyword str access_token: will be used instead of instance's
``access_token`` | [
"Call",
"documentation",
":",
"/",
"batch",
"/",
"create",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"batch#create",
">",
"_",
"plus",
"extra",
"keyword",
"parameter",
":",
":",
"keyword",
"str",
"acce... | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L492-L519 | def deep_diff(self, db_data, user_data):
"""Validate data in user data.
Args:
db_data (dict|str|list): The data store in Redis.
user_data (dict|str|list): The user provided data.
Returns:
bool: True if the data passed validation.
"""
# NOTE: ... | [
"def",
"deep_diff",
"(",
"self",
",",
"db_data",
",",
"user_data",
")",
":",
"# NOTE: tcex does include the deepdiff library as a dependencies since it is only",
"# required for local testing.",
"try",
":",
"from",
"deepdiff",
"import",
"DeepDiff",
"except",
"ImportError",
":... | Validate data in user data.
Args:
db_data (dict|str|list): The data store in Redis.
user_data (dict|str|list): The user provided data.
Returns:
bool: True if the data passed validation. | [
"Validate",
"data",
"in",
"user",
"data",
"."
] | python | train |
facelessuser/backrefs | backrefs/_bre_parse.py | https://github.com/facelessuser/backrefs/blob/3b3d60f5d57b02044f880aa29c9c5add0e31a34f/backrefs/_bre_parse.py#L533-L554 | def posix_props(self, prop, in_group=False):
"""
Insert POSIX properties.
Posix style properties are not as forgiving
as Unicode properties. Case does matter,
and whitespace and '-' and '_' will not be tolerated.
"""
try:
if self.is_bytes or not sel... | [
"def",
"posix_props",
"(",
"self",
",",
"prop",
",",
"in_group",
"=",
"False",
")",
":",
"try",
":",
"if",
"self",
".",
"is_bytes",
"or",
"not",
"self",
".",
"unicode",
":",
"pattern",
"=",
"_uniprops",
".",
"get_posix_property",
"(",
"prop",
",",
"(",... | Insert POSIX properties.
Posix style properties are not as forgiving
as Unicode properties. Case does matter,
and whitespace and '-' and '_' will not be tolerated. | [
"Insert",
"POSIX",
"properties",
"."
] | python | train |
bfrog/whizzer | whizzer/client.py | https://github.com/bfrog/whizzer/blob/a1e43084b3ac8c1f3fb4ada081777cdbf791fd77/whizzer/client.py#L162-L178 | def _connect(self, sock, addr, timeout):
"""Start watching the socket for it to be writtable."""
if self.connection:
raise SocketClientConnectedError()
if self.connector:
raise SocketClientConnectingError()
self.connect_deferred = Deferred(self.loop)
sel... | [
"def",
"_connect",
"(",
"self",
",",
"sock",
",",
"addr",
",",
"timeout",
")",
":",
"if",
"self",
".",
"connection",
":",
"raise",
"SocketClientConnectedError",
"(",
")",
"if",
"self",
".",
"connector",
":",
"raise",
"SocketClientConnectingError",
"(",
")",
... | Start watching the socket for it to be writtable. | [
"Start",
"watching",
"the",
"socket",
"for",
"it",
"to",
"be",
"writtable",
"."
] | python | train |
jsommers/switchyard | switchyard/llnetreal.py | https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/llnetreal.py#L149-L161 | def _make_pcaps(self):
'''
Internal method. Create libpcap devices
for every network interface we care about and
set them in non-blocking mode.
'''
self._pcaps = {}
for devname,intf in self._devinfo.items():
if intf.iftype == InterfaceType.Loopback:
... | [
"def",
"_make_pcaps",
"(",
"self",
")",
":",
"self",
".",
"_pcaps",
"=",
"{",
"}",
"for",
"devname",
",",
"intf",
"in",
"self",
".",
"_devinfo",
".",
"items",
"(",
")",
":",
"if",
"intf",
".",
"iftype",
"==",
"InterfaceType",
".",
"Loopback",
":",
... | Internal method. Create libpcap devices
for every network interface we care about and
set them in non-blocking mode. | [
"Internal",
"method",
".",
"Create",
"libpcap",
"devices",
"for",
"every",
"network",
"interface",
"we",
"care",
"about",
"and",
"set",
"them",
"in",
"non",
"-",
"blocking",
"mode",
"."
] | python | train |
necaris/python3-openid | openid/extensions/draft/pape5.py | https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/extensions/draft/pape5.py#L73-L80 | def _generateAlias(self):
"""Return an unused auth level alias"""
for i in range(1000):
alias = 'cust%d' % (i, )
if alias not in self.auth_level_aliases:
return alias
raise RuntimeError('Could not find an unused alias (tried 1000!)') | [
"def",
"_generateAlias",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"1000",
")",
":",
"alias",
"=",
"'cust%d'",
"%",
"(",
"i",
",",
")",
"if",
"alias",
"not",
"in",
"self",
".",
"auth_level_aliases",
":",
"return",
"alias",
"raise",
"Runt... | Return an unused auth level alias | [
"Return",
"an",
"unused",
"auth",
"level",
"alias"
] | python | train |
istresearch/scrapy-cluster | redis-monitor/plugins/stats_monitor.py | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stats_monitor.py#L162-L207 | def get_spider_stats(self):
'''
Gather spider based stats
'''
self.logger.debug("Gathering spider stats")
the_dict = {}
spider_set = set()
total_spider_count = 0
keys = self.redis_conn.keys('stats:crawler:*:*:*')
for key in keys:
# we ... | [
"def",
"get_spider_stats",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Gathering spider stats\"",
")",
"the_dict",
"=",
"{",
"}",
"spider_set",
"=",
"set",
"(",
")",
"total_spider_count",
"=",
"0",
"keys",
"=",
"self",
".",
"redis_c... | Gather spider based stats | [
"Gather",
"spider",
"based",
"stats"
] | python | train |
SHDShim/pytheos | pytheos/eqn_vinet.py | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_vinet.py#L53-L71 | def vinet_v_single(p, v0, k0, k0p, min_strain=0.01):
"""
find volume at given pressure using brenth in scipy.optimize
this is for single p value, not vectorized
:param p: pressure in GPa
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at reference conditions
:param k0p: ... | [
"def",
"vinet_v_single",
"(",
"p",
",",
"v0",
",",
"k0",
",",
"k0p",
",",
"min_strain",
"=",
"0.01",
")",
":",
"if",
"p",
"<=",
"1.e-5",
":",
"return",
"v0",
"def",
"f_diff",
"(",
"v",
",",
"v0",
",",
"k0",
",",
"k0p",
",",
"p",
")",
":",
"re... | find volume at given pressure using brenth in scipy.optimize
this is for single p value, not vectorized
:param p: pressure in GPa
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus at reference conditions
:... | [
"find",
"volume",
"at",
"given",
"pressure",
"using",
"brenth",
"in",
"scipy",
".",
"optimize",
"this",
"is",
"for",
"single",
"p",
"value",
"not",
"vectorized"
] | python | train |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L739-L784 | def query_db_reference():
"""
Returns list of cross references by query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Reference type
default: EMBL
- name: identifier
... | [
"def",
"query_db_reference",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'type_'",
",",
"'identifier'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
... | Returns list of cross references by query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Reference type
default: EMBL
- name: identifier
in: query
type: string... | [
"Returns",
"list",
"of",
"cross",
"references",
"by",
"query",
"parameters",
"---"
] | python | train |
cebel/pyuniprot | src/pyuniprot/manager/database.py | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L651-L694 | def get_pmids(self, entry):
"""
get `models.Pmid` objects from XML node entry
:param entry: XML node entry
:return: list of :class:`pyuniprot.manager.models.Pmid` objects
"""
pmids = []
for citation in entry.iterfind("./reference/citation"):
for pub... | [
"def",
"get_pmids",
"(",
"self",
",",
"entry",
")",
":",
"pmids",
"=",
"[",
"]",
"for",
"citation",
"in",
"entry",
".",
"iterfind",
"(",
"\"./reference/citation\"",
")",
":",
"for",
"pubmed_ref",
"in",
"citation",
".",
"iterfind",
"(",
"'dbReference[@type=\"... | get `models.Pmid` objects from XML node entry
:param entry: XML node entry
:return: list of :class:`pyuniprot.manager.models.Pmid` objects | [
"get",
"models",
".",
"Pmid",
"objects",
"from",
"XML",
"node",
"entry"
] | python | train |
scour-project/scour | scour/scour.py | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L1885-L1894 | def taint(taintedSet, taintedAttribute):
u"""Adds an attribute to a set of attributes.
Related attributes are also included."""
taintedSet.add(taintedAttribute)
if taintedAttribute == 'marker':
taintedSet |= set(['marker-start', 'marker-mid', 'marker-end'])
if taintedAttribute in ['marker-s... | [
"def",
"taint",
"(",
"taintedSet",
",",
"taintedAttribute",
")",
":",
"taintedSet",
".",
"add",
"(",
"taintedAttribute",
")",
"if",
"taintedAttribute",
"==",
"'marker'",
":",
"taintedSet",
"|=",
"set",
"(",
"[",
"'marker-start'",
",",
"'marker-mid'",
",",
"'ma... | u"""Adds an attribute to a set of attributes.
Related attributes are also included. | [
"u",
"Adds",
"an",
"attribute",
"to",
"a",
"set",
"of",
"attributes",
"."
] | python | train |
saltstack/salt | salt/states/azurearm_dns.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_dns.py#L619-L683 | def record_set_absent(name, zone_name, resource_group, connection_auth=None):
'''
.. versionadded:: Fluorine
Ensure a record set does not exist in the DNS zone.
:param name:
Name of the record set.
:param zone_name:
Name of the DNS zone.
:param resource_group:
The res... | [
"def",
"record_set_absent",
"(",
"name",
",",
"zone_name",
",",
"resource_group",
",",
"connection_auth",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{... | .. versionadded:: Fluorine
Ensure a record set does not exist in the DNS zone.
:param name:
Name of the record set.
:param zone_name:
Name of the DNS zone.
:param resource_group:
The resource group assigned to the DNS zone.
:param connection_auth:
A dict with sub... | [
"..",
"versionadded",
"::",
"Fluorine"
] | python | train |
dedupeio/dedupe | dedupe/canonical.py | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/canonical.py#L48-L71 | def getCanonicalRep(record_cluster):
"""
Given a list of records within a duplicate cluster, constructs a
canonical representation of the cluster by finding canonical
values for each field
"""
canonical_rep = {}
keys = record_cluster[0].keys()
for key in keys:
key_values = []
... | [
"def",
"getCanonicalRep",
"(",
"record_cluster",
")",
":",
"canonical_rep",
"=",
"{",
"}",
"keys",
"=",
"record_cluster",
"[",
"0",
"]",
".",
"keys",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"key_values",
"=",
"[",
"]",
"for",
"record",
"in",
"record... | Given a list of records within a duplicate cluster, constructs a
canonical representation of the cluster by finding canonical
values for each field | [
"Given",
"a",
"list",
"of",
"records",
"within",
"a",
"duplicate",
"cluster",
"constructs",
"a",
"canonical",
"representation",
"of",
"the",
"cluster",
"by",
"finding",
"canonical",
"values",
"for",
"each",
"field"
] | python | train |
tensorflow/cleverhans | cleverhans/attacks/bapp.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L353-L355 | def clip_image(image, clip_min, clip_max):
""" Clip an image, or an image batch, with upper and lower threshold. """
return np.minimum(np.maximum(clip_min, image), clip_max) | [
"def",
"clip_image",
"(",
"image",
",",
"clip_min",
",",
"clip_max",
")",
":",
"return",
"np",
".",
"minimum",
"(",
"np",
".",
"maximum",
"(",
"clip_min",
",",
"image",
")",
",",
"clip_max",
")"
] | Clip an image, or an image batch, with upper and lower threshold. | [
"Clip",
"an",
"image",
"or",
"an",
"image",
"batch",
"with",
"upper",
"and",
"lower",
"threshold",
"."
] | python | train |
ethereum/py-evm | eth/vm/logic/arithmetic.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/logic/arithmetic.py#L214-L226 | def sar(computation: BaseComputation) -> None:
"""
Arithmetic bitwise right shift
"""
shift_length, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256)
value = unsigned_to_signed(value)
if shift_length >= 256:
result = 0 if value >= 0 else constants.UINT_255_NEGATIVE... | [
"def",
"sar",
"(",
"computation",
":",
"BaseComputation",
")",
"->",
"None",
":",
"shift_length",
",",
"value",
"=",
"computation",
".",
"stack_pop",
"(",
"num_items",
"=",
"2",
",",
"type_hint",
"=",
"constants",
".",
"UINT256",
")",
"value",
"=",
"unsign... | Arithmetic bitwise right shift | [
"Arithmetic",
"bitwise",
"right",
"shift"
] | python | train |
pkgw/pwkit | pwkit/io.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/io.py#L189-L200 | def ensure_symlink (src, dst):
"""Ensure the existence of a symbolic link pointing to src named dst. Returns
a boolean indicating whether the symlink already existed.
"""
try:
os.symlink (src, dst)
except OSError as e:
if e.errno == 17: # EEXIST
return True
raise... | [
"def",
"ensure_symlink",
"(",
"src",
",",
"dst",
")",
":",
"try",
":",
"os",
".",
"symlink",
"(",
"src",
",",
"dst",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"17",
":",
"# EEXIST",
"return",
"True",
"raise",
"return"... | Ensure the existence of a symbolic link pointing to src named dst. Returns
a boolean indicating whether the symlink already existed. | [
"Ensure",
"the",
"existence",
"of",
"a",
"symbolic",
"link",
"pointing",
"to",
"src",
"named",
"dst",
".",
"Returns",
"a",
"boolean",
"indicating",
"whether",
"the",
"symlink",
"already",
"existed",
"."
] | python | train |
oceanprotocol/squid-py | squid_py/agreements/storage.py | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/storage.py#L63-L85 | def get_service_agreements(storage_path, status='pending'):
"""
Get service agreements pending to be executed.
:param storage_path: storage path for the internal db, str
:param status:
:return:
"""
conn = sqlite3.connect(storage_path)
try:
cursor = conn.cursor()
return [... | [
"def",
"get_service_agreements",
"(",
"storage_path",
",",
"status",
"=",
"'pending'",
")",
":",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"storage_path",
")",
"try",
":",
"cursor",
"=",
"conn",
".",
"cursor",
"(",
")",
"return",
"[",
"row",
"for",
"r... | Get service agreements pending to be executed.
:param storage_path: storage path for the internal db, str
:param status:
:return: | [
"Get",
"service",
"agreements",
"pending",
"to",
"be",
"executed",
"."
] | python | train |
RPi-Distro/python-gpiozero | gpiozero/pins/data.py | https://github.com/RPi-Distro/python-gpiozero/blob/7b67374fd0c8c4fde5586d9bad9531f076db9c0c/gpiozero/pins/data.py#L1121-L1139 | def physical_pin(self, function):
"""
Return the physical pin supporting the specified *function*. If no pins
support the desired *function*, this function raises :exc:`PinNoPins`.
If multiple pins support the desired *function*, :exc:`PinMultiplePins`
will be raised (use :func:`... | [
"def",
"physical_pin",
"(",
"self",
",",
"function",
")",
":",
"result",
"=",
"self",
".",
"physical_pins",
"(",
"function",
")",
"if",
"len",
"(",
"result",
")",
">",
"1",
":",
"raise",
"PinMultiplePins",
"(",
"'multiple pins can be used for %s'",
"%",
"fun... | Return the physical pin supporting the specified *function*. If no pins
support the desired *function*, this function raises :exc:`PinNoPins`.
If multiple pins support the desired *function*, :exc:`PinMultiplePins`
will be raised (use :func:`physical_pins` if you expect multiple pins
in ... | [
"Return",
"the",
"physical",
"pin",
"supporting",
"the",
"specified",
"*",
"function",
"*",
".",
"If",
"no",
"pins",
"support",
"the",
"desired",
"*",
"function",
"*",
"this",
"function",
"raises",
":",
"exc",
":",
"PinNoPins",
".",
"If",
"multiple",
"pins... | python | train |
kamikaze/webdav | src/webdav/client.py | https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L852-L863 | def parse_get_list_response(content):
"""Parses of response content XML from WebDAV server and extract file and directory names.
:param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path.
:return: list of extracted file or directory names.
... | [
"def",
"parse_get_list_response",
"(",
"content",
")",
":",
"try",
":",
"tree",
"=",
"etree",
".",
"fromstring",
"(",
"content",
")",
"hrees",
"=",
"[",
"Urn",
".",
"separate",
"+",
"unquote",
"(",
"urlsplit",
"(",
"hree",
".",
"text",
")",
".",
"path"... | Parses of response content XML from WebDAV server and extract file and directory names.
:param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path.
:return: list of extracted file or directory names. | [
"Parses",
"of",
"response",
"content",
"XML",
"from",
"WebDAV",
"server",
"and",
"extract",
"file",
"and",
"directory",
"names",
"."
] | python | train |
OCHA-DAP/hdx-python-utilities | src/hdx/utilities/dictandlist.py | https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/dictandlist.py#L16-L63 | def merge_two_dictionaries(a, b, merge_lists=False):
# type: (DictUpperBound, DictUpperBound, bool) -> DictUpperBound
"""Merges b into a and returns merged result
NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what should happen
Args:
a (DictUpperBound): dictiona... | [
"def",
"merge_two_dictionaries",
"(",
"a",
",",
"b",
",",
"merge_lists",
"=",
"False",
")",
":",
"# type: (DictUpperBound, DictUpperBound, bool) -> DictUpperBound",
"key",
"=",
"None",
"# ## debug output",
"# sys.stderr.write('DEBUG: %s to %s\\n' %(b,a))",
"try",
":",
"if",
... | Merges b into a and returns merged result
NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what should happen
Args:
a (DictUpperBound): dictionary to merge into
b (DictUpperBound): dictionary to merge from
merge_lists (bool): Whether to merge lists (True) o... | [
"Merges",
"b",
"into",
"a",
"and",
"returns",
"merged",
"result"
] | python | train |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_wp.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_wp.py#L190-L203 | def idle_task(self):
'''handle missing waypoints'''
if self.wp_period.trigger():
# cope with packet loss fetching mission
if self.master is not None and self.master.time_since('MISSION_ITEM') >= 2 and self.wploader.count() < getattr(self.wploader,'expected_count',0):
... | [
"def",
"idle_task",
"(",
"self",
")",
":",
"if",
"self",
".",
"wp_period",
".",
"trigger",
"(",
")",
":",
"# cope with packet loss fetching mission",
"if",
"self",
".",
"master",
"is",
"not",
"None",
"and",
"self",
".",
"master",
".",
"time_since",
"(",
"'... | handle missing waypoints | [
"handle",
"missing",
"waypoints"
] | python | train |
click-contrib/click-configfile | click_configfile.py | https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/click_configfile.py#L308-L320 | def select_config_sections(configfile_sections, desired_section_patterns):
"""Select a subset of the sections in a configuration file by using
a list of section names of list of section name patters
(supporting :mod:`fnmatch` wildcards).
:param configfile_sections: List of config section names (as stri... | [
"def",
"select_config_sections",
"(",
"configfile_sections",
",",
"desired_section_patterns",
")",
":",
"for",
"section_name",
"in",
"configfile_sections",
":",
"for",
"desired_section_pattern",
"in",
"desired_section_patterns",
":",
"if",
"fnmatch",
"(",
"section_name",
... | Select a subset of the sections in a configuration file by using
a list of section names of list of section name patters
(supporting :mod:`fnmatch` wildcards).
:param configfile_sections: List of config section names (as strings).
:param desired_section_patterns:
:return: List of selected section n... | [
"Select",
"a",
"subset",
"of",
"the",
"sections",
"in",
"a",
"configuration",
"file",
"by",
"using",
"a",
"list",
"of",
"section",
"names",
"of",
"list",
"of",
"section",
"name",
"patters",
"(",
"supporting",
":",
"mod",
":",
"fnmatch",
"wildcards",
")",
... | python | train |
wonambi-python/wonambi | wonambi/widgets/channels.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L442-L448 | def read_group_info(self):
"""Get information about groups directly from the widget."""
self.groups = []
for i in range(self.tabs.count()):
one_group = self.tabs.widget(i).get_info()
# one_group['name'] = self.tabs.tabText(i)
self.groups.append(one_group) | [
"def",
"read_group_info",
"(",
"self",
")",
":",
"self",
".",
"groups",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"tabs",
".",
"count",
"(",
")",
")",
":",
"one_group",
"=",
"self",
".",
"tabs",
".",
"widget",
"(",
"i",
")",
"... | Get information about groups directly from the widget. | [
"Get",
"information",
"about",
"groups",
"directly",
"from",
"the",
"widget",
"."
] | python | train |
tradenity/python-sdk | tradenity/resources/cash_on_delivery_payment.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/cash_on_delivery_payment.py#L700-L721 | def replace_cash_on_delivery_payment_by_id(cls, cash_on_delivery_payment_id, cash_on_delivery_payment, **kwargs):
"""Replace CashOnDeliveryPayment
Replace all attributes of CashOnDeliveryPayment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP reques... | [
"def",
"replace_cash_on_delivery_payment_by_id",
"(",
"cls",
",",
"cash_on_delivery_payment_id",
",",
"cash_on_delivery_payment",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async... | Replace CashOnDeliveryPayment
Replace all attributes of CashOnDeliveryPayment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_cash_on_delivery_payment_by_id(cash_on_delivery_payment_id, cash_o... | [
"Replace",
"CashOnDeliveryPayment"
] | python | train |
mfitzp/padua | padua/visualize.py | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/visualize.py#L1438-L1491 | def comparedist(df, *args, **kwargs):
"""
Compare the distributions of two DataFrames giving visualisations of:
- individual and combined distributions
- distribution of non-common values
- distribution of non-common values vs. each side
Plot distribution as area (fill_between) + mean, media... | [
"def",
"comparedist",
"(",
"df",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"bins",
"=",
"kwargs",
".",
"get",
"(",
"'bins'",
",",
"50",
")",
"xlabel",
"=",
"kwargs",
".",
"get",
"(",
"'xlabel'",
",",
"'Value'",
")",
"ylabel",
"=",
"kwa... | Compare the distributions of two DataFrames giving visualisations of:
- individual and combined distributions
- distribution of non-common values
- distribution of non-common values vs. each side
Plot distribution as area (fill_between) + mean, median vertical bars.
:param df1: `pandas.DataFram... | [
"Compare",
"the",
"distributions",
"of",
"two",
"DataFrames",
"giving",
"visualisations",
"of",
":",
"-",
"individual",
"and",
"combined",
"distributions",
"-",
"distribution",
"of",
"non",
"-",
"common",
"values",
"-",
"distribution",
"of",
"non",
"-",
"common"... | python | train |
ladybug-tools/ladybug | ladybug/_datacollectionbase.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L137-L140 | def convert_to_si(self):
"""Convert the Data Collection to SI units."""
self._values, self._header._unit = self._header.data_type.to_si(
self._values, self._header.unit) | [
"def",
"convert_to_si",
"(",
"self",
")",
":",
"self",
".",
"_values",
",",
"self",
".",
"_header",
".",
"_unit",
"=",
"self",
".",
"_header",
".",
"data_type",
".",
"to_si",
"(",
"self",
".",
"_values",
",",
"self",
".",
"_header",
".",
"unit",
")"
... | Convert the Data Collection to SI units. | [
"Convert",
"the",
"Data",
"Collection",
"to",
"SI",
"units",
"."
] | python | train |
brutasse/graphite-api | graphite_api/functions.py | https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L3857-L3963 | def summarize(requestContext, seriesList, intervalString, func='sum',
alignToFrom=False):
"""
Summarize the data into interval buckets of a certain size.
By default, the contents of each interval bucket are summed together.
This is useful for counters where each increment represents a dis... | [
"def",
"summarize",
"(",
"requestContext",
",",
"seriesList",
",",
"intervalString",
",",
"func",
"=",
"'sum'",
",",
"alignToFrom",
"=",
"False",
")",
":",
"results",
"=",
"[",
"]",
"delta",
"=",
"parseTimeOffset",
"(",
"intervalString",
")",
"interval",
"="... | Summarize the data into interval buckets of a certain size.
By default, the contents of each interval bucket are summed together.
This is useful for counters where each increment represents a discrete
event and retrieving a "per X" value requires summing all the events in
that interval.
Specifying... | [
"Summarize",
"the",
"data",
"into",
"interval",
"buckets",
"of",
"a",
"certain",
"size",
"."
] | python | train |
wheeler-microfluidics/dmf-control-board-firmware | dmf_control_board_firmware/calibrate/impedance_benchmarks.py | https://github.com/wheeler-microfluidics/dmf-control-board-firmware/blob/1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c/dmf_control_board_firmware/calibrate/impedance_benchmarks.py#L207-L250 | def plot_stat_summary(df, fig=None):
'''
Plot stats grouped by test capacitor load _and_ frequency.
In other words, we calculate the mean of all samples in the data
frame for each test capacitance and frequency pairing, plotting
the following stats:
- Root mean squared error
- Coefficien... | [
"def",
"plot_stat_summary",
"(",
"df",
",",
"fig",
"=",
"None",
")",
":",
"if",
"fig",
"is",
"None",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"8",
",",
"8",
")",
")",
"# Define a subplot layout, 3 rows, 2 columns",
"grid",
"=",
... | Plot stats grouped by test capacitor load _and_ frequency.
In other words, we calculate the mean of all samples in the data
frame for each test capacitance and frequency pairing, plotting
the following stats:
- Root mean squared error
- Coefficient of variation
- Bias
## [Coefficient o... | [
"Plot",
"stats",
"grouped",
"by",
"test",
"capacitor",
"load",
"_and_",
"frequency",
"."
] | python | train |
Kozea/cairocffi | cairocffi/fonts.py | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/fonts.py#L404-L409 | def copy(self):
"""Return a new :class:`FontOptions` with the same values."""
cls = type(self)
other = object.__new__(cls)
cls._init_pointer(other, cairo.cairo_font_options_copy(self._pointer))
return other | [
"def",
"copy",
"(",
"self",
")",
":",
"cls",
"=",
"type",
"(",
"self",
")",
"other",
"=",
"object",
".",
"__new__",
"(",
"cls",
")",
"cls",
".",
"_init_pointer",
"(",
"other",
",",
"cairo",
".",
"cairo_font_options_copy",
"(",
"self",
".",
"_pointer",
... | Return a new :class:`FontOptions` with the same values. | [
"Return",
"a",
"new",
":",
"class",
":",
"FontOptions",
"with",
"the",
"same",
"values",
"."
] | python | train |
mgedmin/check-manifest | check_manifest.py | https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L138-L160 | def run(command, encoding=None, decode=True, cwd=None):
"""Run a command [cmd, arg1, arg2, ...].
Returns the output (stdout + stderr).
Raises CommandFailed in cases of error.
"""
if not encoding:
encoding = locale.getpreferredencoding()
try:
with open(os.devnull, 'rb') as devnu... | [
"def",
"run",
"(",
"command",
",",
"encoding",
"=",
"None",
",",
"decode",
"=",
"True",
",",
"cwd",
"=",
"None",
")",
":",
"if",
"not",
"encoding",
":",
"encoding",
"=",
"locale",
".",
"getpreferredencoding",
"(",
")",
"try",
":",
"with",
"open",
"("... | Run a command [cmd, arg1, arg2, ...].
Returns the output (stdout + stderr).
Raises CommandFailed in cases of error. | [
"Run",
"a",
"command",
"[",
"cmd",
"arg1",
"arg2",
"...",
"]",
"."
] | python | train |
coleifer/walrus | walrus/containers.py | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1188-L1196 | def trim(self, count, approximate=True):
"""
Trim the stream to the given "count" of messages, discarding the oldest
messages first.
:param count: maximum size of stream
:param approximate: allow size to be approximate
"""
return self.database.xtrim(self.key, cou... | [
"def",
"trim",
"(",
"self",
",",
"count",
",",
"approximate",
"=",
"True",
")",
":",
"return",
"self",
".",
"database",
".",
"xtrim",
"(",
"self",
".",
"key",
",",
"count",
",",
"approximate",
")"
] | Trim the stream to the given "count" of messages, discarding the oldest
messages first.
:param count: maximum size of stream
:param approximate: allow size to be approximate | [
"Trim",
"the",
"stream",
"to",
"the",
"given",
"count",
"of",
"messages",
"discarding",
"the",
"oldest",
"messages",
"first",
"."
] | python | train |
475Cumulus/TBone | tbone/resources/mongo.py | https://github.com/475Cumulus/TBone/blob/5a6672d8bbac449a0ab9e99560609f671fe84d4d/tbone/resources/mongo.py#L169-L181 | async def update(self, **kwargs):
'''
Corresponds to PUT request with a resource identifier, updating a single document in the database
'''
try:
self.data[self.pk] = self.pk_type(kwargs['pk'])
updated_obj = await self._meta.object_class().update(self.db, data=self... | [
"async",
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"self",
".",
"data",
"[",
"self",
".",
"pk",
"]",
"=",
"self",
".",
"pk_type",
"(",
"kwargs",
"[",
"'pk'",
"]",
")",
"updated_obj",
"=",
"await",
"self",
".",
... | Corresponds to PUT request with a resource identifier, updating a single document in the database | [
"Corresponds",
"to",
"PUT",
"request",
"with",
"a",
"resource",
"identifier",
"updating",
"a",
"single",
"document",
"in",
"the",
"database"
] | python | train |
ConsenSys/mythril-classic | mythril/laser/smt/bool.py | https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/laser/smt/bool.py#L84-L90 | def And(*args: Union[Bool, bool]) -> Bool:
"""Create an And expression."""
union = []
args_list = [arg if isinstance(arg, Bool) else Bool(arg) for arg in args]
for arg in args_list:
union.append(arg.annotations)
return Bool(z3.And([a.raw for a in args_list]), union) | [
"def",
"And",
"(",
"*",
"args",
":",
"Union",
"[",
"Bool",
",",
"bool",
"]",
")",
"->",
"Bool",
":",
"union",
"=",
"[",
"]",
"args_list",
"=",
"[",
"arg",
"if",
"isinstance",
"(",
"arg",
",",
"Bool",
")",
"else",
"Bool",
"(",
"arg",
")",
"for",... | Create an And expression. | [
"Create",
"an",
"And",
"expression",
"."
] | python | train |
PythonCharmers/python-future | src/future/backports/datetime.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/datetime.py#L1208-L1215 | def utcoffset(self):
"""Return the timezone offset in minutes east of UTC (negative west of
UTC)."""
if self._tzinfo is None:
return None
offset = self._tzinfo.utcoffset(None)
_check_utc_offset("utcoffset", offset)
return offset | [
"def",
"utcoffset",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tzinfo",
"is",
"None",
":",
"return",
"None",
"offset",
"=",
"self",
".",
"_tzinfo",
".",
"utcoffset",
"(",
"None",
")",
"_check_utc_offset",
"(",
"\"utcoffset\"",
",",
"offset",
")",
"retur... | Return the timezone offset in minutes east of UTC (negative west of
UTC). | [
"Return",
"the",
"timezone",
"offset",
"in",
"minutes",
"east",
"of",
"UTC",
"(",
"negative",
"west",
"of",
"UTC",
")",
"."
] | python | train |
saltstack/salt | salt/client/api.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L236-L293 | def create_token(self, creds):
'''
Create token with creds.
Token authorizes salt access if successful authentication
with the credentials in creds.
creds format is as follows:
{
'username': 'namestring',
'password': 'passwordstring',
... | [
"def",
"create_token",
"(",
"self",
",",
"creds",
")",
":",
"try",
":",
"tokenage",
"=",
"self",
".",
"resolver",
".",
"mk_token",
"(",
"creds",
")",
"except",
"Exception",
"as",
"ex",
":",
"raise",
"EauthAuthenticationError",
"(",
"\"Authentication failed wit... | Create token with creds.
Token authorizes salt access if successful authentication
with the credentials in creds.
creds format is as follows:
{
'username': 'namestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
exam... | [
"Create",
"token",
"with",
"creds",
".",
"Token",
"authorizes",
"salt",
"access",
"if",
"successful",
"authentication",
"with",
"the",
"credentials",
"in",
"creds",
".",
"creds",
"format",
"is",
"as",
"follows",
":"
] | python | train |
sbg/sevenbridges-python | sevenbridges/models/volume.py | https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/models/volume.py#L167-L212 | def create_oss_volume(cls, name, bucket, endpoint, access_key_id,
secret_access_key, access_mode, description=None,
prefix=None, properties=None, api=None):
"""
Create oss volume.
:param name: Volume name.
:param bucket: Referenced buck... | [
"def",
"create_oss_volume",
"(",
"cls",
",",
"name",
",",
"bucket",
",",
"endpoint",
",",
"access_key_id",
",",
"secret_access_key",
",",
"access_mode",
",",
"description",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"properties",
"=",
"None",
",",
"api",
... | Create oss volume.
:param name: Volume name.
:param bucket: Referenced bucket.
:param access_key_id: Access key identifier.
:param secret_access_key: Secret access key.
:param access_mode: Access Mode.
:param endpoint: Volume Endpoint.
:param description: Volume d... | [
"Create",
"oss",
"volume",
".",
":",
"param",
"name",
":",
"Volume",
"name",
".",
":",
"param",
"bucket",
":",
"Referenced",
"bucket",
".",
":",
"param",
"access_key_id",
":",
"Access",
"key",
"identifier",
".",
":",
"param",
"secret_access_key",
":",
"Sec... | python | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L269-L295 | def get_bgcolor(self, index):
"""Background color depending on value."""
column = index.column()
if not self.bgcolor_enabled:
return
value = self.get_value(index.row(), column)
if self.max_min_col[column] is None or isna(value):
color = QColor(BACKG... | [
"def",
"get_bgcolor",
"(",
"self",
",",
"index",
")",
":",
"column",
"=",
"index",
".",
"column",
"(",
")",
"if",
"not",
"self",
".",
"bgcolor_enabled",
":",
"return",
"value",
"=",
"self",
".",
"get_value",
"(",
"index",
".",
"row",
"(",
")",
",",
... | Background color depending on value. | [
"Background",
"color",
"depending",
"on",
"value",
"."
] | python | train |
tjcsl/cslbot | cslbot/commands/s.py | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/s.py#L80-L124 | def cmd(send, msg, args):
"""Corrects a previous message.
Syntax: {command}/<msg>/<replacement>/<ig|nick>
"""
if not msg:
send("Invalid Syntax.")
return
char = msg[0]
msg = [x.replace(r'\/', '/') for x in re.split(r'(?<!\\)\%s' % char, msg[1:], maxsplit=2)]
# fix for people... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"Invalid Syntax.\"",
")",
"return",
"char",
"=",
"msg",
"[",
"0",
"]",
"msg",
"=",
"[",
"x",
".",
"replace",
"(",
"r'\\/'",
",",
"'/'",
")",
"... | Corrects a previous message.
Syntax: {command}/<msg>/<replacement>/<ig|nick> | [
"Corrects",
"a",
"previous",
"message",
"."
] | python | train |
wbond/oscrypto | oscrypto/_win/asymmetric.py | https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L3054-L3123 | def _bcrypt_encrypt(certificate_or_public_key, data, rsa_oaep_padding=False):
"""
Encrypts a value using an RSA public key via CNG
:param certificate_or_public_key:
A Certificate or PublicKey instance to encrypt with
:param data:
A byte string of the data to encrypt
:param rsa_oae... | [
"def",
"_bcrypt_encrypt",
"(",
"certificate_or_public_key",
",",
"data",
",",
"rsa_oaep_padding",
"=",
"False",
")",
":",
"flags",
"=",
"BcryptConst",
".",
"BCRYPT_PAD_PKCS1",
"if",
"rsa_oaep_padding",
"is",
"True",
":",
"flags",
"=",
"BcryptConst",
".",
"BCRYPT_P... | Encrypts a value using an RSA public key via CNG
:param certificate_or_public_key:
A Certificate or PublicKey instance to encrypt with
:param data:
A byte string of the data to encrypt
:param rsa_oaep_padding:
If OAEP padding should be used instead of PKCS#1 v1.5
:raises:
... | [
"Encrypts",
"a",
"value",
"using",
"an",
"RSA",
"public",
"key",
"via",
"CNG"
] | python | valid |
IS-ENES-Data/esgf-pid | esgfpid/rabbit/nodemanager.py | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/rabbit/nodemanager.py#L256-L316 | def __complete_info_dict(self, node_info_dict, is_open):
# Make pika credentials
creds = pika.PlainCredentials(
node_info_dict['username'],
node_info_dict['password']
)
node_info_dict['credentials'] = creds
if 'priority' in node_info_dict and node_info_di... | [
"def",
"__complete_info_dict",
"(",
"self",
",",
"node_info_dict",
",",
"is_open",
")",
":",
"# Make pika credentials",
"creds",
"=",
"pika",
".",
"PlainCredentials",
"(",
"node_info_dict",
"[",
"'username'",
"]",
",",
"node_info_dict",
"[",
"'password'",
"]",
")"... | https://pika.readthedocs.org/en/0.9.6/connecting.html
class pika.connection.ConnectionParameters(
host=None, port=None, virtual_host=None, credentials=None, channel_max=None,
frame_max=None, heartbeat_interval=None, ssl=None, ssl_options=None,
connection_attempts=None, retry_... | [
"https",
":",
"//",
"pika",
".",
"readthedocs",
".",
"org",
"/",
"en",
"/",
"0",
".",
"9",
".",
"6",
"/",
"connecting",
".",
"html",
"class",
"pika",
".",
"connection",
".",
"ConnectionParameters",
"(",
"host",
"=",
"None",
"port",
"=",
"None",
"virt... | python | train |
PmagPy/PmagPy | pmagpy/pmag.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmag.py#L9160-L9218 | def sortshaw(s, datablock):
"""
sorts data block in to ARM1,ARM2 NRM,TRM,ARM1,ARM2=[],[],[],[]
stick first zero field stuff into first_Z
"""
for rec in datablock:
methcodes = rec["magic_method_codes"].split(":")
step = float(rec["treatment_ac_field"])
str = float(rec["meas... | [
"def",
"sortshaw",
"(",
"s",
",",
"datablock",
")",
":",
"for",
"rec",
"in",
"datablock",
":",
"methcodes",
"=",
"rec",
"[",
"\"magic_method_codes\"",
"]",
".",
"split",
"(",
"\":\"",
")",
"step",
"=",
"float",
"(",
"rec",
"[",
"\"treatment_ac_field\"",
... | sorts data block in to ARM1,ARM2 NRM,TRM,ARM1,ARM2=[],[],[],[]
stick first zero field stuff into first_Z | [
"sorts",
"data",
"block",
"in",
"to",
"ARM1",
"ARM2",
"NRM",
"TRM",
"ARM1",
"ARM2",
"=",
"[]",
"[]",
"[]",
"[]",
"stick",
"first",
"zero",
"field",
"stuff",
"into",
"first_Z"
] | python | train |
RIPE-NCC/ripe.atlas.sagan | ripe/atlas/sagan/traceroute.py | https://github.com/RIPE-NCC/ripe.atlas.sagan/blob/f0e57221cf0ba3504baddd3ea460fc955bc41cc6/ripe/atlas/sagan/traceroute.py#L175-L180 | def set_last_hop_responded(self, last_hop):
"""Sets the flag if last hop responded."""
for packet in last_hop.packets:
if packet.rtt:
self.last_hop_responded = True
break | [
"def",
"set_last_hop_responded",
"(",
"self",
",",
"last_hop",
")",
":",
"for",
"packet",
"in",
"last_hop",
".",
"packets",
":",
"if",
"packet",
".",
"rtt",
":",
"self",
".",
"last_hop_responded",
"=",
"True",
"break"
] | Sets the flag if last hop responded. | [
"Sets",
"the",
"flag",
"if",
"last",
"hop",
"responded",
"."
] | python | train |
gdoermann/voicebase | voicebase/api/media.py | https://github.com/gdoermann/voicebase/blob/53cb4735327898a7a284dea3a60ace0b3956a8ec/voicebase/api/media.py#L153-L161 | def prediction_model_dict(self):
"""
Converts the list of prediction_models passed in into properly formatted dictionaries
:return: formatted prediction model dict
"""
models = {}
for model in self.predictions_models:
models[model.name] = model.keywords
... | [
"def",
"prediction_model_dict",
"(",
"self",
")",
":",
"models",
"=",
"{",
"}",
"for",
"model",
"in",
"self",
".",
"predictions_models",
":",
"models",
"[",
"model",
".",
"name",
"]",
"=",
"model",
".",
"keywords",
"return",
"models"
] | Converts the list of prediction_models passed in into properly formatted dictionaries
:return: formatted prediction model dict | [
"Converts",
"the",
"list",
"of",
"prediction_models",
"passed",
"in",
"into",
"properly",
"formatted",
"dictionaries",
":",
"return",
":",
"formatted",
"prediction",
"model",
"dict"
] | python | train |
mongolab/dex | dex/dex.py | https://github.com/mongolab/dex/blob/f6dc27321028ef1ffdb3d4b1165fdcce7c8f20aa/dex/dex.py#L231-L239 | def analyze_logfile(self, logfile_path):
self._run_stats['logSource'] = logfile_path
"""Analyzes queries from a given log file"""
with open(logfile_path) as obj:
self.analyze_logfile_object(obj)
self._output_aggregated_report(sys.stdout)
return 0 | [
"def",
"analyze_logfile",
"(",
"self",
",",
"logfile_path",
")",
":",
"self",
".",
"_run_stats",
"[",
"'logSource'",
"]",
"=",
"logfile_path",
"with",
"open",
"(",
"logfile_path",
")",
"as",
"obj",
":",
"self",
".",
"analyze_logfile_object",
"(",
"obj",
")",... | Analyzes queries from a given log file | [
"Analyzes",
"queries",
"from",
"a",
"given",
"log",
"file"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.