repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
mosdef-hub/mbuild | mbuild/coordinate_transform.py | https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L308-L348 | def equivalence_transform(compound, from_positions, to_positions, add_bond=True):
"""Computes an affine transformation that maps the from_positions to the
respective to_positions, and applies this transformation to the compound.
Parameters
----------
compound : mb.Compound
The Compound to b... | [
"def",
"equivalence_transform",
"(",
"compound",
",",
"from_positions",
",",
"to_positions",
",",
"add_bond",
"=",
"True",
")",
":",
"warn",
"(",
"'The `equivalence_transform` function is being phased out in favor of'",
"' `force_overlap`.'",
",",
"DeprecationWarning",
")",
... | Computes an affine transformation that maps the from_positions to the
respective to_positions, and applies this transformation to the compound.
Parameters
----------
compound : mb.Compound
The Compound to be transformed.
from_positions : np.ndarray, shape=(n, 3), dtype=float
Origina... | [
"Computes",
"an",
"affine",
"transformation",
"that",
"maps",
"the",
"from_positions",
"to",
"the",
"respective",
"to_positions",
"and",
"applies",
"this",
"transformation",
"to",
"the",
"compound",
"."
] | python | train | 44.731707 |
materialsproject/pymatgen | pymatgen/core/structure.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/structure.py#L1228-L1272 | def copy(self, site_properties=None, sanitize=False):
"""
Convenience method to get a copy of the structure, with options to add
site properties.
Args:
site_properties (dict): Properties to add or override. The
properties are specified in the same way as the ... | [
"def",
"copy",
"(",
"self",
",",
"site_properties",
"=",
"None",
",",
"sanitize",
"=",
"False",
")",
":",
"props",
"=",
"self",
".",
"site_properties",
"if",
"site_properties",
":",
"props",
".",
"update",
"(",
"site_properties",
")",
"if",
"not",
"sanitiz... | Convenience method to get a copy of the structure, with options to add
site properties.
Args:
site_properties (dict): Properties to add or override. The
properties are specified in the same way as the constructor,
i.e., as a dict of the form {property: [value... | [
"Convenience",
"method",
"to",
"get",
"a",
"copy",
"of",
"the",
"structure",
"with",
"options",
"to",
"add",
"site",
"properties",
"."
] | python | train | 48.111111 |
edx/completion | completion/utilities.py | https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/utilities.py#L13-L29 | def get_key_to_last_completed_course_block(user, course_key):
"""
Returns the last block a "user" completed in a course (stated as "course_key").
raises UnavailableCompletionData when the user has not completed blocks in
the course.
raises UnavailableCompletionData when the visual progress waffle ... | [
"def",
"get_key_to_last_completed_course_block",
"(",
"user",
",",
"course_key",
")",
":",
"last_completed_block",
"=",
"BlockCompletion",
".",
"get_latest_block_completed",
"(",
"user",
",",
"course_key",
")",
"if",
"last_completed_block",
"is",
"not",
"None",
":",
"... | Returns the last block a "user" completed in a course (stated as "course_key").
raises UnavailableCompletionData when the user has not completed blocks in
the course.
raises UnavailableCompletionData when the visual progress waffle flag is
disabled. | [
"Returns",
"the",
"last",
"block",
"a",
"user",
"completed",
"in",
"a",
"course",
"(",
"stated",
"as",
"course_key",
")",
"."
] | python | train | 32.882353 |
Jajcus/pyxmpp2 | pyxmpp2/stanzaprocessor.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L302-L312 | def process_presence(self, stanza):
"""Process presence stanza.
Pass it to a handler of the stanza's type and payload namespace.
:Parameters:
- `stanza`: presence stanza to be handled
"""
stanza_type = stanza.stanza_type
return self.__try_handlers(self._pre... | [
"def",
"process_presence",
"(",
"self",
",",
"stanza",
")",
":",
"stanza_type",
"=",
"stanza",
".",
"stanza_type",
"return",
"self",
".",
"__try_handlers",
"(",
"self",
".",
"_presence_handlers",
",",
"stanza",
",",
"stanza_type",
")"
] | Process presence stanza.
Pass it to a handler of the stanza's type and payload namespace.
:Parameters:
- `stanza`: presence stanza to be handled | [
"Process",
"presence",
"stanza",
"."
] | python | valid | 31.454545 |
jasonrollins/shareplum | shareplum/ListDict.py | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/ListDict.py#L4-L33 | def changes(new_cmp_dict, old_cmp_dict, id_column, columns):
"""Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict
"""
update_ldict = []
same_keys = set(new_cmp_dict).intersection(set(old_cmp_dict))
for same_ke... | [
"def",
"changes",
"(",
"new_cmp_dict",
",",
"old_cmp_dict",
",",
"id_column",
",",
"columns",
")",
":",
"update_ldict",
"=",
"[",
"]",
"same_keys",
"=",
"set",
"(",
"new_cmp_dict",
")",
".",
"intersection",
"(",
"set",
"(",
"old_cmp_dict",
")",
")",
"for",... | Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict | [
"Return",
"a",
"list",
"dict",
"of",
"the",
"changes",
"of",
"the",
"rows",
"that",
"exist",
"in",
"both",
"dictionaries",
"User",
"must",
"provide",
"an",
"ID",
"column",
"for",
"old_cmp_dict"
] | python | train | 39.233333 |
Alveo/pyalveo | pyalveo/objects.py | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/objects.py#L361-L377 | def append(self, items):
""" Add some items to this ItemList and save the changes to the server
:param items: the items to add, either as a List of Item objects, an
ItemList, a List of item URLs as Strings, a single item URL as a
String, or a single Item object
:rtype: ... | [
"def",
"append",
"(",
"self",
",",
"items",
")",
":",
"resp",
"=",
"self",
".",
"client",
".",
"add_to_item_list",
"(",
"items",
",",
"self",
".",
"url",
"(",
")",
")",
"self",
".",
"refresh",
"(",
")",
"return",
"resp"
] | Add some items to this ItemList and save the changes to the server
:param items: the items to add, either as a List of Item objects, an
ItemList, a List of item URLs as Strings, a single item URL as a
String, or a single Item object
:rtype: String
:returns: the server s... | [
"Add",
"some",
"items",
"to",
"this",
"ItemList",
"and",
"save",
"the",
"changes",
"to",
"the",
"server"
] | python | train | 31.705882 |
peri-source/peri | peri/comp/exactpsf.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/exactpsf.py#L661-L667 | def psffunc(self, *args, **kwargs):
"""Calculates a linescan psf"""
if self.polychromatic:
func = psfcalc.calculate_polychrome_linescan_psf
else:
func = psfcalc.calculate_linescan_psf
return func(*args, **kwargs) | [
"def",
"psffunc",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"polychromatic",
":",
"func",
"=",
"psfcalc",
".",
"calculate_polychrome_linescan_psf",
"else",
":",
"func",
"=",
"psfcalc",
".",
"calculate_linescan_psf",... | Calculates a linescan psf | [
"Calculates",
"a",
"linescan",
"psf"
] | python | valid | 37.428571 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py#L326-L342 | def get_interface_switchport_output_switchport_fcoe_port_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interf... | [
"def",
"get_interface_switchport_output_switchport_fcoe_port_enabled",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_interface_switchport",
"=",
"ET",
".",
"Element",
"(",
"\"get_interface_switchport\... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 52.294118 |
numenta/htmresearch | htmresearch/algorithms/TM.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1808-L1844 | def getBestMatchingCell(self, c, activeState):
"""Find weakly activated cell in column. Returns index and segment of most
activated segment above minThreshold.
"""
# Collect all cells in column c that have at least minThreshold in the most
# activated segment
bestActivityInCol = self.minThreshol... | [
"def",
"getBestMatchingCell",
"(",
"self",
",",
"c",
",",
"activeState",
")",
":",
"# Collect all cells in column c that have at least minThreshold in the most",
"# activated segment",
"bestActivityInCol",
"=",
"self",
".",
"minThreshold",
"bestSegIdxInCol",
"=",
"-",
"1",
... | Find weakly activated cell in column. Returns index and segment of most
activated segment above minThreshold. | [
"Find",
"weakly",
"activated",
"cell",
"in",
"column",
".",
"Returns",
"index",
"and",
"segment",
"of",
"most",
"activated",
"segment",
"above",
"minThreshold",
"."
] | python | train | 31.594595 |
radzak/rtv-downloader | rtv/extractors/common.py | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/common.py#L48-L52 | def update_entries(entries: Entries, data: dict) -> None:
"""Update each entry in the list with some data."""
# TODO: Is mutating the list okay, making copies is such a pain in the ass
for entry in entries:
entry.update(data) | [
"def",
"update_entries",
"(",
"entries",
":",
"Entries",
",",
"data",
":",
"dict",
")",
"->",
"None",
":",
"# TODO: Is mutating the list okay, making copies is such a pain in the ass",
"for",
"entry",
"in",
"entries",
":",
"entry",
".",
"update",
"(",
"data",
")"
] | Update each entry in the list with some data. | [
"Update",
"each",
"entry",
"in",
"the",
"list",
"with",
"some",
"data",
"."
] | python | train | 51.4 |
pydata/xarray | xarray/core/ops.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/ops.py#L135-L165 | def fillna(data, other, join="left", dataset_join="left"):
"""Fill missing values in this object with data from the other object.
Follows normal broadcasting and alignment rules.
Parameters
----------
join : {'outer', 'inner', 'left', 'right'}, optional
Method for joining the indexes of the... | [
"def",
"fillna",
"(",
"data",
",",
"other",
",",
"join",
"=",
"\"left\"",
",",
"dataset_join",
"=",
"\"left\"",
")",
":",
"from",
".",
"computation",
"import",
"apply_ufunc",
"return",
"apply_ufunc",
"(",
"duck_array_ops",
".",
"fillna",
",",
"data",
",",
... | Fill missing values in this object with data from the other object.
Follows normal broadcasting and alignment rules.
Parameters
----------
join : {'outer', 'inner', 'left', 'right'}, optional
Method for joining the indexes of the passed objects along each
dimension
- 'outer': us... | [
"Fill",
"missing",
"values",
"in",
"this",
"object",
"with",
"data",
"from",
"the",
"other",
"object",
".",
"Follows",
"normal",
"broadcasting",
"and",
"alignment",
"rules",
"."
] | python | train | 45.451613 |
MagicStack/asyncpg | asyncpg/connection.py | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connection.py#L532-L592 | async def copy_from_query(self, query, *args, output,
timeout=None, format=None, oids=None,
delimiter=None, null=None, header=None,
quote=None, escape=None, force_quote=None,
encoding=None):
"... | [
"async",
"def",
"copy_from_query",
"(",
"self",
",",
"query",
",",
"*",
"args",
",",
"output",
",",
"timeout",
"=",
"None",
",",
"format",
"=",
"None",
",",
"oids",
"=",
"None",
",",
"delimiter",
"=",
"None",
",",
"null",
"=",
"None",
",",
"header",
... | Copy the results of a query to a file or file-like object.
:param str query:
The query to copy the results of.
:param args:
Query arguments.
:param output:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <pytho... | [
"Copy",
"the",
"results",
"of",
"a",
"query",
"to",
"a",
"file",
"or",
"file",
"-",
"like",
"object",
"."
] | python | train | 35.672131 |
bhmm/bhmm | bhmm/hidden/api.py | https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L277-L302 | def sample_path(alpha, A, pobs, T=None):
""" Sample the hidden pathway S from the conditional distribution P ( S | Parameters, Observations )
Parameters
----------
alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of time t.
A : ndarra... | [
"def",
"sample_path",
"(",
"alpha",
",",
"A",
",",
"pobs",
",",
"T",
"=",
"None",
")",
":",
"if",
"__impl__",
"==",
"__IMPL_PYTHON__",
":",
"return",
"ip",
".",
"sample_path",
"(",
"alpha",
",",
"A",
",",
"pobs",
",",
"T",
"=",
"T",
",",
"dtype",
... | Sample the hidden pathway S from the conditional distribution P ( S | Parameters, Observations )
Parameters
----------
alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of time t.
A : ndarray((N,N), dtype = float)
transition matrix... | [
"Sample",
"the",
"hidden",
"pathway",
"S",
"from",
"the",
"conditional",
"distribution",
"P",
"(",
"S",
"|",
"Parameters",
"Observations",
")"
] | python | train | 36.5 |
zalando/patroni | patroni/postgresql.py | https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/postgresql.py#L1699-L1712 | def clone(self, clone_member):
"""
- initialize the replica from an existing member (master or replica)
- initialize the replica using the replica creation method that
works without the replication connection (i.e. restore from on-disk
base backup)
... | [
"def",
"clone",
"(",
"self",
",",
"clone_member",
")",
":",
"self",
".",
"_rewind_state",
"=",
"REWIND_STATUS",
".",
"INITIAL",
"ret",
"=",
"self",
".",
"create_replica",
"(",
"clone_member",
")",
"==",
"0",
"if",
"ret",
":",
"self",
".",
"_post_restore",
... | - initialize the replica from an existing member (master or replica)
- initialize the replica using the replica creation method that
works without the replication connection (i.e. restore from on-disk
base backup) | [
"-",
"initialize",
"the",
"replica",
"from",
"an",
"existing",
"member",
"(",
"master",
"or",
"replica",
")",
"-",
"initialize",
"the",
"replica",
"using",
"the",
"replica",
"creation",
"method",
"that",
"works",
"without",
"the",
"replication",
"connection",
... | python | train | 38 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsMarkovModel.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsMarkovModel.py#L820-L869 | def getShocks(self):
'''
Gets new Markov states and permanent and transitory income shocks for this period. Samples
from IncomeDstn for each period-state in the cycle.
Parameters
----------
None
Returns
-------
None
'''
# Get new... | [
"def",
"getShocks",
"(",
"self",
")",
":",
"# Get new Markov states for each agent",
"if",
"self",
".",
"global_markov",
":",
"base_draws",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"AgentCount",
")",
"*",
"drawUniform",
"(",
"1",
",",
"seed",
"=",
"self",
... | Gets new Markov states and permanent and transitory income shocks for this period. Samples
from IncomeDstn for each period-state in the cycle.
Parameters
----------
None
Returns
-------
None | [
"Gets",
"new",
"Markov",
"states",
"and",
"permanent",
"and",
"transitory",
"income",
"shocks",
"for",
"this",
"period",
".",
"Samples",
"from",
"IncomeDstn",
"for",
"each",
"period",
"-",
"state",
"in",
"the",
"cycle",
"."
] | python | train | 50.66 |
flyte/xbee-helper | xbee_helper/device.py | https://github.com/flyte/xbee-helper/blob/8b47675ad44d8a57defea459682d129379af348d/xbee_helper/device.py#L73-L82 | def convert_adc(value, output_type, max_volts):
"""
Converts the output from the ADC into the desired type.
"""
return {
const.ADC_RAW: lambda x: x,
const.ADC_PERCENTAGE: adc_to_percentage,
const.ADC_VOLTS: adc_to_volts,
const.ADC_MILLIVOLTS: adc_to_millivolts
}[outpu... | [
"def",
"convert_adc",
"(",
"value",
",",
"output_type",
",",
"max_volts",
")",
":",
"return",
"{",
"const",
".",
"ADC_RAW",
":",
"lambda",
"x",
":",
"x",
",",
"const",
".",
"ADC_PERCENTAGE",
":",
"adc_to_percentage",
",",
"const",
".",
"ADC_VOLTS",
":",
... | Converts the output from the ADC into the desired type. | [
"Converts",
"the",
"output",
"from",
"the",
"ADC",
"into",
"the",
"desired",
"type",
"."
] | python | train | 33.6 |
yahoo/TensorFlowOnSpark | tensorflowonspark/TFNode.py | https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/TFNode.py#L271-L284 | def batch_results(self, results):
"""Push a batch of output results to the Spark output RDD of ``TFCluster.inference()``.
Note: this currently expects a one-to-one mapping of input to output data, so the length of the ``results`` array should match the length of
the previously retrieved batch of input data... | [
"def",
"batch_results",
"(",
"self",
",",
"results",
")",
":",
"logging",
".",
"debug",
"(",
"\"batch_results() invoked\"",
")",
"queue",
"=",
"self",
".",
"mgr",
".",
"get_queue",
"(",
"self",
".",
"qname_out",
")",
"for",
"item",
"in",
"results",
":",
... | Push a batch of output results to the Spark output RDD of ``TFCluster.inference()``.
Note: this currently expects a one-to-one mapping of input to output data, so the length of the ``results`` array should match the length of
the previously retrieved batch of input data.
Args:
:results: array of out... | [
"Push",
"a",
"batch",
"of",
"output",
"results",
"to",
"the",
"Spark",
"output",
"RDD",
"of",
"TFCluster",
".",
"inference",
"()",
"."
] | python | train | 43.357143 |
DistrictDataLabs/yellowbrick | yellowbrick/features/importances.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/importances.py#L239-L256 | def finalize(self, **kwargs):
"""
Finalize the drawing setting labels and title.
"""
# Set the title
self.set_title('Feature Importances of {} Features using {}'.format(
len(self.features_), self.name))
# Set the xlabel
self.ax.set_xlabel(self._ge... | [
"def",
"finalize",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Set the title",
"self",
".",
"set_title",
"(",
"'Feature Importances of {} Features using {}'",
".",
"format",
"(",
"len",
"(",
"self",
".",
"features_",
")",
",",
"self",
".",
"name",
")"... | Finalize the drawing setting labels and title. | [
"Finalize",
"the",
"drawing",
"setting",
"labels",
"and",
"title",
"."
] | python | train | 29.888889 |
vhf/confusable_homoglyphs | confusable_homoglyphs/confusables.py | https://github.com/vhf/confusable_homoglyphs/blob/14f43ddd74099520ddcda29fac557c27a28190e6/confusable_homoglyphs/confusables.py#L13-L38 | def is_mixed_script(string, allowed_aliases=['COMMON']):
"""Checks if ``string`` contains mixed-scripts content, excluding script
blocks aliases in ``allowed_aliases``.
E.g. ``B. C`` is not considered mixed-scripts by default: it contains characters
from **Latin** and **Common**, but **Common** is excl... | [
"def",
"is_mixed_script",
"(",
"string",
",",
"allowed_aliases",
"=",
"[",
"'COMMON'",
"]",
")",
":",
"allowed_aliases",
"=",
"[",
"a",
".",
"upper",
"(",
")",
"for",
"a",
"in",
"allowed_aliases",
"]",
"cats",
"=",
"unique_aliases",
"(",
"string",
")",
"... | Checks if ``string`` contains mixed-scripts content, excluding script
blocks aliases in ``allowed_aliases``.
E.g. ``B. C`` is not considered mixed-scripts by default: it contains characters
from **Latin** and **Common**, but **Common** is excluded by default.
>>> confusables.is_mixed_script('Abç')
... | [
"Checks",
"if",
"string",
"contains",
"mixed",
"-",
"scripts",
"content",
"excluding",
"script",
"blocks",
"aliases",
"in",
"allowed_aliases",
"."
] | python | train | 36.269231 |
annoviko/pyclustering | pyclustering/cluster/optics.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/optics.py#L143-L182 | def calculate_connvectivity_radius(self, amount_clusters, maximum_iterations = 100):
"""!
@brief Calculates connectivity radius of allocation specified amount of clusters using ordering diagram and marks borders of clusters using indexes of values of ordering diagram.
@details Parameter 'maxi... | [
"def",
"calculate_connvectivity_radius",
"(",
"self",
",",
"amount_clusters",
",",
"maximum_iterations",
"=",
"100",
")",
":",
"maximum_distance",
"=",
"max",
"(",
"self",
".",
"__ordering",
")",
"upper_distance",
"=",
"maximum_distance",
"lower_distance",
"=",
"0.0... | !
@brief Calculates connectivity radius of allocation specified amount of clusters using ordering diagram and marks borders of clusters using indexes of values of ordering diagram.
@details Parameter 'maximum_iterations' is used to protect from hanging when it is impossible to allocate specified numbe... | [
"!"
] | python | valid | 49.525 |
marteinn/genres | genres/db.py | https://github.com/marteinn/genres/blob/4bbc90f7c2c527631380c08b4d99a4e40abed955/genres/db.py#L38-L86 | def parse(self, data):
"""
Split and iterate through the datafile to extract genres, tags
and points.
"""
categories = data.split("\n\n")
reference = {}
reference_points = {}
genre_index = []
tag_index = []
for category in categories:
... | [
"def",
"parse",
"(",
"self",
",",
"data",
")",
":",
"categories",
"=",
"data",
".",
"split",
"(",
"\"\\n\\n\"",
")",
"reference",
"=",
"{",
"}",
"reference_points",
"=",
"{",
"}",
"genre_index",
"=",
"[",
"]",
"tag_index",
"=",
"[",
"]",
"for",
"cate... | Split and iterate through the datafile to extract genres, tags
and points. | [
"Split",
"and",
"iterate",
"through",
"the",
"datafile",
"to",
"extract",
"genres",
"tags",
"and",
"points",
"."
] | python | train | 29.489796 |
tensorflow/probability | tensorflow_probability/python/optimizer/nelder_mead.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L765-L789 | def _prepare_args_with_initial_simplex(objective_function,
initial_simplex,
objective_at_initial_simplex,
batch_evaluate_objective):
"""Evaluates the objective function at the specified initial simplex... | [
"def",
"_prepare_args_with_initial_simplex",
"(",
"objective_function",
",",
"initial_simplex",
",",
"objective_at_initial_simplex",
",",
"batch_evaluate_objective",
")",
":",
"initial_simplex",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"value",
"=",
"initial_simplex",
")",... | Evaluates the objective function at the specified initial simplex. | [
"Evaluates",
"the",
"objective",
"function",
"at",
"the",
"specified",
"initial",
"simplex",
"."
] | python | test | 44.8 |
thebigmunch/gmusicapi-wrapper | gmusicapi_wrapper/decorators.py | https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/decorators.py#L12-L24 | def cast_to_list(position):
"""Cast the positional argument at given position into a list if not already a list."""
@wrapt.decorator
def wrapper(function, instance, args, kwargs):
if not isinstance(args[position], list):
args = list(args)
args[position] = [args[position]]
args = tuple(args)
return fun... | [
"def",
"cast_to_list",
"(",
"position",
")",
":",
"@",
"wrapt",
".",
"decorator",
"def",
"wrapper",
"(",
"function",
",",
"instance",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"args",
"[",
"position",
"]",
",",
"list",
")",
... | Cast the positional argument at given position into a list if not already a list. | [
"Cast",
"the",
"positional",
"argument",
"at",
"given",
"position",
"into",
"a",
"list",
"if",
"not",
"already",
"a",
"list",
"."
] | python | valid | 26.692308 |
sqlboy/fileseq | src/fileseq/filesequence.py | https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/filesequence.py#L636-L690 | def findSequenceOnDisk(cls, pattern, strictPadding=False):
"""
Search for a specific sequence on disk.
The padding characters used in the `pattern` are used to filter the
frame values of the files on disk (if `strictPadding` is True).
Examples:
Find sequence matchin... | [
"def",
"findSequenceOnDisk",
"(",
"cls",
",",
"pattern",
",",
"strictPadding",
"=",
"False",
")",
":",
"seq",
"=",
"cls",
"(",
"pattern",
")",
"if",
"seq",
".",
"frameRange",
"(",
")",
"==",
"''",
"and",
"seq",
".",
"padding",
"(",
")",
"==",
"''",
... | Search for a specific sequence on disk.
The padding characters used in the `pattern` are used to filter the
frame values of the files on disk (if `strictPadding` is True).
Examples:
Find sequence matching basename and extension, and a wildcard for
any frame.
... | [
"Search",
"for",
"a",
"specific",
"sequence",
"on",
"disk",
"."
] | python | train | 33.727273 |
JosuaKrause/quick_server | quick_server/quick_server.py | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1040-L1060 | def do_GET(self):
"""Handles a GET request."""
thread_local.clock_start = get_time()
thread_local.status_code = 200
thread_local.message = None
thread_local.headers = []
thread_local.end_headers = []
thread_local.size = -1
thread_local.method = 'GET'
... | [
"def",
"do_GET",
"(",
"self",
")",
":",
"thread_local",
".",
"clock_start",
"=",
"get_time",
"(",
")",
"thread_local",
".",
"status_code",
"=",
"200",
"thread_local",
".",
"message",
"=",
"None",
"thread_local",
".",
"headers",
"=",
"[",
"]",
"thread_local",... | Handles a GET request. | [
"Handles",
"a",
"GET",
"request",
"."
] | python | train | 34.047619 |
apache/incubator-mxnet | cpp-package/scripts/lint.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/cpp-package/scripts/lint.py#L123-L144 | def get_header_guard_dmlc(filename):
"""Get Header Guard Convention for DMLC Projects.
For headers in include, directly use the path
For headers in src, use project name plus path
Examples: with project-name = dmlc
include/dmlc/timer.h -> DMLC_TIMTER_H_
src/io/libsvm_parser.h -> DMLC_IO_... | [
"def",
"get_header_guard_dmlc",
"(",
"filename",
")",
":",
"fileinfo",
"=",
"cpplint",
".",
"FileInfo",
"(",
"filename",
")",
"file_path_from_root",
"=",
"fileinfo",
".",
"RepositoryName",
"(",
")",
"inc_list",
"=",
"[",
"'include'",
",",
"'api'",
",",
"'wrapp... | Get Header Guard Convention for DMLC Projects.
For headers in include, directly use the path
For headers in src, use project name plus path
Examples: with project-name = dmlc
include/dmlc/timer.h -> DMLC_TIMTER_H_
src/io/libsvm_parser.h -> DMLC_IO_LIBSVM_PARSER_H_ | [
"Get",
"Header",
"Guard",
"Convention",
"for",
"DMLC",
"Projects",
".",
"For",
"headers",
"in",
"include",
"directly",
"use",
"the",
"path",
"For",
"headers",
"in",
"src",
"use",
"project",
"name",
"plus",
"path",
"Examples",
":",
"with",
"project",
"-",
"... | python | train | 44.818182 |
mattupstate/flask-security | flask_security/views.py | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L67-L89 | def login():
"""View function for login view"""
form_class = _security.login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class(request.form)
if form.validate_on_submit():
login_user(form.user, remember=form.remember.data)
... | [
"def",
"login",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"login_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form",
"=",
"form_cl... | View function for login view | [
"View",
"function",
"for",
"login",
"view"
] | python | train | 30.608696 |
Bogdanp/dramatiq | dramatiq/brokers/stub.py | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/brokers/stub.py#L66-L81 | def declare_queue(self, queue_name):
"""Declare a queue. Has no effect if a queue with the given
name has already been declared.
Parameters:
queue_name(str): The name of the new queue.
"""
if queue_name not in self.queues:
self.emit_before("declare_queue",... | [
"def",
"declare_queue",
"(",
"self",
",",
"queue_name",
")",
":",
"if",
"queue_name",
"not",
"in",
"self",
".",
"queues",
":",
"self",
".",
"emit_before",
"(",
"\"declare_queue\"",
",",
"queue_name",
")",
"self",
".",
"queues",
"[",
"queue_name",
"]",
"=",... | Declare a queue. Has no effect if a queue with the given
name has already been declared.
Parameters:
queue_name(str): The name of the new queue. | [
"Declare",
"a",
"queue",
".",
"Has",
"no",
"effect",
"if",
"a",
"queue",
"with",
"the",
"given",
"name",
"has",
"already",
"been",
"declared",
"."
] | python | train | 39.3125 |
aarongarrett/inspyred | inspyred/ec/variators/mutators.py | https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/mutators.py#L141-L171 | def scramble_mutation(random, candidate, args):
"""Return the mutants created by scramble mutation on the candidates.
This function performs scramble mutation. It randomly chooses two
locations along the candidate and scrambles the values within that
slice.
.. Arguments:
random -- the rand... | [
"def",
"scramble_mutation",
"(",
"random",
",",
"candidate",
",",
"args",
")",
":",
"rate",
"=",
"args",
".",
"setdefault",
"(",
"'mutation_rate'",
",",
"0.1",
")",
"if",
"random",
".",
"random",
"(",
")",
"<",
"rate",
":",
"size",
"=",
"len",
"(",
"... | Return the mutants created by scramble mutation on the candidates.
This function performs scramble mutation. It randomly chooses two
locations along the candidate and scrambles the values within that
slice.
.. Arguments:
random -- the random number generator object
candidate -- the cand... | [
"Return",
"the",
"mutants",
"created",
"by",
"scramble",
"mutation",
"on",
"the",
"candidates",
"."
] | python | train | 33.806452 |
opencobra/memote | memote/support/biomass.py | https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/support/biomass.py#L129-L163 | def find_blocked_biomass_precursors(reaction, model):
"""
Return a list of all biomass precursors that cannot be produced.
Parameters
----------
reaction : cobra.core.reaction.Reaction
The biomass reaction of the model under investigation.
model : cobra.Model
The metabolic model... | [
"def",
"find_blocked_biomass_precursors",
"(",
"reaction",
",",
"model",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Finding blocked biomass precursors\"",
")",
"precursors",
"=",
"find_biomass_precursors",
"(",
"model",
",",
"reaction",
")",
"blocked_precursors",
"=",
... | Return a list of all biomass precursors that cannot be produced.
Parameters
----------
reaction : cobra.core.reaction.Reaction
The biomass reaction of the model under investigation.
model : cobra.Model
The metabolic model under investigation.
Returns
-------
list
Me... | [
"Return",
"a",
"list",
"of",
"all",
"biomass",
"precursors",
"that",
"cannot",
"be",
"produced",
"."
] | python | train | 32.771429 |
libtcod/python-tcod | tcod/libtcodpy.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1389-L1408 | def console_print_rect(
con: tcod.console.Console, x: int, y: int, w: int, h: int, fmt: str
) -> int:
"""Print a string constrained to a rectangle.
If h > 0 and the bottom of the rectangle is reached,
the string is truncated. If h = 0,
the string is only truncated if it reaches the bottom of the co... | [
"def",
"console_print_rect",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"w",
":",
"int",
",",
"h",
":",
"int",
",",
"fmt",
":",
"str",
")",
"->",
"int",
":",
"return",
"int",
"(",
... | Print a string constrained to a rectangle.
If h > 0 and the bottom of the rectangle is reached,
the string is truncated. If h = 0,
the string is only truncated if it reaches the bottom of the console.
Returns:
int: The number of lines of text once word-wrapped.
.. deprecated:: 8.5
... | [
"Print",
"a",
"string",
"constrained",
"to",
"a",
"rectangle",
"."
] | python | train | 28 |
aquatix/ns-api | ns_api.py | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L81-L88 | def list_to_json(source_list):
"""
Serialise all the items in source_list to json
"""
result = []
for item in source_list:
result.append(item.to_json())
return result | [
"def",
"list_to_json",
"(",
"source_list",
")",
":",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"source_list",
":",
"result",
".",
"append",
"(",
"item",
".",
"to_json",
"(",
")",
")",
"return",
"result"
] | Serialise all the items in source_list to json | [
"Serialise",
"all",
"the",
"items",
"in",
"source_list",
"to",
"json"
] | python | train | 23.875 |
chriso/timeseries | timeseries/data_frame.py | https://github.com/chriso/timeseries/blob/8b81e6cfd955a7cf75a421dfdb71b3f9e53be64d/timeseries/data_frame.py#L32-L52 | def plot(self, overlay=True, **labels): # pragma: no cover
'''Plot all time series in the group.'''
pylab = LazyImport.pylab()
colours = list('rgbymc')
colours_len = len(colours)
colours_pos = 0
plots = len(self.groups)
for name, series in self.groups.iteritems():... | [
"def",
"plot",
"(",
"self",
",",
"overlay",
"=",
"True",
",",
"*",
"*",
"labels",
")",
":",
"# pragma: no cover",
"pylab",
"=",
"LazyImport",
".",
"pylab",
"(",
")",
"colours",
"=",
"list",
"(",
"'rgbymc'",
")",
"colours_len",
"=",
"len",
"(",
"colours... | Plot all time series in the group. | [
"Plot",
"all",
"time",
"series",
"in",
"the",
"group",
"."
] | python | train | 37.714286 |
rainwoodman/kdcount | kdcount/correlate.py | https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/correlate.py#L317-L326 | def _update_mean_coords(self, dig, N, centers_sum, **paircoords):
"""
Update the mean coordinate sums
"""
if N is None or centers_sum is None: return
N.flat[:] += utils.bincount(dig, 1., minlength=N.size)
for i, dim in enumerate(self.dims):
size = centers_sum... | [
"def",
"_update_mean_coords",
"(",
"self",
",",
"dig",
",",
"N",
",",
"centers_sum",
",",
"*",
"*",
"paircoords",
")",
":",
"if",
"N",
"is",
"None",
"or",
"centers_sum",
"is",
"None",
":",
"return",
"N",
".",
"flat",
"[",
":",
"]",
"+=",
"utils",
"... | Update the mean coordinate sums | [
"Update",
"the",
"mean",
"coordinate",
"sums"
] | python | train | 41 |
echinopsii/net.echinopsii.ariane.community.cli.python3 | ariane_clip3/natsd/driver.py | https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/natsd/driver.py#L156-L202 | def on_stop(self):
"""
stop requester
"""
LOGGER.debug("natsd.Requester.on_stop")
self.is_started = False
try:
LOGGER.debug("natsd.Requester.on_stop - unsubscribe from " + str(self.responseQS))
next(self.nc.unsubscribe(self.responseQS))
exc... | [
"def",
"on_stop",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"natsd.Requester.on_stop\"",
")",
"self",
".",
"is_started",
"=",
"False",
"try",
":",
"LOGGER",
".",
"debug",
"(",
"\"natsd.Requester.on_stop - unsubscribe from \"",
"+",
"str",
"(",
"self"... | stop requester | [
"stop",
"requester"
] | python | train | 50.021277 |
aksas/pypo4sel | core/pypo4sel/core/waiter.py | https://github.com/aksas/pypo4sel/blob/935b5f9bfa6682aefdef8a43ebcbcf274dec752c/core/pypo4sel/core/waiter.py#L73-L83 | def wait_displayed(element, timeout=None, fail_on_timeout=None):
"""
Wait until element becomes visible or time out.
Returns true is element became visible, otherwise false.
If timeout is not specified or 0, then uses specific element wait timeout.
:param element:
:param timeout:
:param fail... | [
"def",
"wait_displayed",
"(",
"element",
",",
"timeout",
"=",
"None",
",",
"fail_on_timeout",
"=",
"None",
")",
":",
"return",
"wait",
"(",
"lambda",
":",
"element",
".",
"is_displayed",
"(",
")",
",",
"timeout",
"or",
"element",
".",
"wait_timeout",
",",
... | Wait until element becomes visible or time out.
Returns true is element became visible, otherwise false.
If timeout is not specified or 0, then uses specific element wait timeout.
:param element:
:param timeout:
:param fail_on_timeout:
:return: | [
"Wait",
"until",
"element",
"becomes",
"visible",
"or",
"time",
"out",
".",
"Returns",
"true",
"is",
"element",
"became",
"visible",
"otherwise",
"false",
".",
"If",
"timeout",
"is",
"not",
"specified",
"or",
"0",
"then",
"uses",
"specific",
"element",
"wait... | python | train | 40.090909 |
pybluez/pybluez | examples/advanced/write-inquiry-scan.py | https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/examples/advanced/write-inquiry-scan.py#L6-L36 | def read_inquiry_scan_activity(sock):
"""returns the current inquiry scan interval and window,
or -1 on failure"""
# save current filter
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
# Setup socket filter to receive only events related to the
# read_inquiry_mode command
... | [
"def",
"read_inquiry_scan_activity",
"(",
"sock",
")",
":",
"# save current filter",
"old_filter",
"=",
"sock",
".",
"getsockopt",
"(",
"bluez",
".",
"SOL_HCI",
",",
"bluez",
".",
"HCI_FILTER",
",",
"14",
")",
"# Setup socket filter to receive only events related to the... | returns the current inquiry scan interval and window,
or -1 on failure | [
"returns",
"the",
"current",
"inquiry",
"scan",
"interval",
"and",
"window",
"or",
"-",
"1",
"on",
"failure"
] | python | train | 37.645161 |
apriha/lineage | src/lineage/__init__.py | https://github.com/apriha/lineage/blob/13106a62a959a80ac26c68d1566422de08aa877b/src/lineage/__init__.py#L104-L265 | def remap_snps(self, individual, target_assembly, complement_bases=True):
""" Remap the SNP coordinates of an individual from one assembly to another.
This method uses the assembly map endpoint of the Ensembl REST API service (via
``Resources``'s ``EnsemblRestClient``) to convert SNP coordinate... | [
"def",
"remap_snps",
"(",
"self",
",",
"individual",
",",
"target_assembly",
",",
"complement_bases",
"=",
"True",
")",
":",
"chromosomes_remapped",
"=",
"[",
"]",
"chromosomes_not_remapped",
"=",
"[",
"]",
"snps",
"=",
"individual",
".",
"snps",
"if",
"snps",... | Remap the SNP coordinates of an individual from one assembly to another.
This method uses the assembly map endpoint of the Ensembl REST API service (via
``Resources``'s ``EnsemblRestClient``) to convert SNP coordinates / positions from one
assembly to another. After remapping, the coordinates /... | [
"Remap",
"the",
"SNP",
"coordinates",
"of",
"an",
"individual",
"from",
"one",
"assembly",
"to",
"another",
"."
] | python | train | 38.407407 |
sfstpala/pcr | pcr/maths.py | https://github.com/sfstpala/pcr/blob/313ec17585565a0b9740f7b3f47d7a93bf37a7fc/pcr/maths.py#L24-L31 | def check_candidate(a, d, n, s):
"""Part of the Miller-Rabin primality test in is_prime()."""
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2 ** i * d, n) == n - 1:
return False
return True | [
"def",
"check_candidate",
"(",
"a",
",",
"d",
",",
"n",
",",
"s",
")",
":",
"if",
"pow",
"(",
"a",
",",
"d",
",",
"n",
")",
"==",
"1",
":",
"return",
"False",
"for",
"i",
"in",
"range",
"(",
"s",
")",
":",
"if",
"pow",
"(",
"a",
",",
"2",... | Part of the Miller-Rabin primality test in is_prime(). | [
"Part",
"of",
"the",
"Miller",
"-",
"Rabin",
"primality",
"test",
"in",
"is_prime",
"()",
"."
] | python | train | 30.5 |
nerdvegas/rez | src/rez/vendor/sortedcontainers/sorteddict.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sorteddict.py#L676-L689 | def index(self, key, start=None, stop=None):
"""
Return the smallest *k* such that `itemssview[k] == key` and `start <= k
< end`. Raises `KeyError` if *key* is not present. *stop* defaults
to the end of the set. *start* defaults to the beginning. Negative
indexes are supporte... | [
"def",
"index",
"(",
"self",
",",
"key",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"temp",
",",
"value",
"=",
"key",
"pos",
"=",
"self",
".",
"_list",
".",
"index",
"(",
"temp",
",",
"start",
... | Return the smallest *k* such that `itemssview[k] == key` and `start <= k
< end`. Raises `KeyError` if *key* is not present. *stop* defaults
to the end of the set. *start* defaults to the beginning. Negative
indexes are supported, as for slice indices. | [
"Return",
"the",
"smallest",
"*",
"k",
"*",
"such",
"that",
"itemssview",
"[",
"k",
"]",
"==",
"key",
"and",
"start",
"<",
"=",
"k",
"<",
"end",
".",
"Raises",
"KeyError",
"if",
"*",
"key",
"*",
"is",
"not",
"present",
".",
"*",
"stop",
"*",
"def... | python | train | 43 |
ghukill/pyfc4 | pyfc4/models.py | https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/models.py#L357-L387 | def keep_alive(self):
'''
Keep current transaction alive, updates self.expires
Args:
None
Return:
None: sets new self.expires
'''
# keep transaction alive
txn_response = self.api.http_request('POST','%sfcr:tx' % self.root, data=None, headers=None)
# if 204, transaction kept alive
if txn_res... | [
"def",
"keep_alive",
"(",
"self",
")",
":",
"# keep transaction alive",
"txn_response",
"=",
"self",
".",
"api",
".",
"http_request",
"(",
"'POST'",
",",
"'%sfcr:tx'",
"%",
"self",
".",
"root",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
")",
... | Keep current transaction alive, updates self.expires
Args:
None
Return:
None: sets new self.expires | [
"Keep",
"current",
"transaction",
"alive",
"updates",
"self",
".",
"expires"
] | python | train | 24.806452 |
StackStorm/pybind | pybind/nos/v6_0_2f/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/__init__.py#L7434-L7457 | def _set_openflow_controller(self, v, load=False):
"""
Setter method for openflow_controller, mapped from YANG variable /openflow_controller (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_openflow_controller is considered as a private
method. Backends looking... | [
"def",
"_set_openflow_controller",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",... | Setter method for openflow_controller, mapped from YANG variable /openflow_controller (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_openflow_controller is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj... | [
"Setter",
"method",
"for",
"openflow_controller",
"mapped",
"from",
"YANG",
"variable",
"/",
"openflow_controller",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file"... | python | train | 130.541667 |
avalente/appmetrics | appmetrics/meter.py | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/meter.py#L112-L125 | def notify(self, value):
"""Add a new observation to the metric"""
with self.lock:
#TODO: this could slow down slow-rate incoming updates
# since the number of ticks depends on the actual time
# passed since the latest notification. Consider using
# a rea... | [
"def",
"notify",
"(",
"self",
",",
"value",
")",
":",
"with",
"self",
".",
"lock",
":",
"#TODO: this could slow down slow-rate incoming updates",
"# since the number of ticks depends on the actual time",
"# passed since the latest notification. Consider using",
"# a real timer to tic... | Add a new observation to the metric | [
"Add",
"a",
"new",
"observation",
"to",
"the",
"metric"
] | python | train | 34.785714 |
ajyoon/blur | examples/waves/amplitude.py | https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/examples/waves/amplitude.py#L90-L101 | def step_amp(self):
"""
Change the amplitude according to the change rate and drift target.
Returns: None
"""
difference = self.drift_target - self._raw_value
if abs(difference) < self.change_rate:
self.value = self.drift_target
else:
delt... | [
"def",
"step_amp",
"(",
"self",
")",
":",
"difference",
"=",
"self",
".",
"drift_target",
"-",
"self",
".",
"_raw_value",
"if",
"abs",
"(",
"difference",
")",
"<",
"self",
".",
"change_rate",
":",
"self",
".",
"value",
"=",
"self",
".",
"drift_target",
... | Change the amplitude according to the change rate and drift target.
Returns: None | [
"Change",
"the",
"amplitude",
"according",
"to",
"the",
"change",
"rate",
"and",
"drift",
"target",
"."
] | python | train | 33.583333 |
hmartiniano/faz | faz/task.py | https://github.com/hmartiniano/faz/blob/36a58c45e8c0718d38cb3c533542c8743e7e7a65/faz/task.py#L82-L101 | def expand_variables(self):
"""
Expand variables in the task code.
Only variables who use the $[<variable name>] format are expanded.
Variables using the $<variable name> and ${<variable name>} formats
are expanded by the shell (in the cases where bash is the interpreter.
... | [
"def",
"expand_variables",
"(",
"self",
")",
":",
"self",
".",
"environment",
"[",
"\"INPUTS\"",
"]",
"=",
"\" \"",
".",
"join",
"(",
"self",
".",
"inputs",
")",
"self",
".",
"environment",
"[",
"\"OUTPUTS\"",
"]",
"=",
"\" \"",
".",
"join",
"(",
"self... | Expand variables in the task code.
Only variables who use the $[<variable name>] format are expanded.
Variables using the $<variable name> and ${<variable name>} formats
are expanded by the shell (in the cases where bash is the interpreter. | [
"Expand",
"variables",
"in",
"the",
"task",
"code",
".",
"Only",
"variables",
"who",
"use",
"the",
"$",
"[",
"<variable",
"name",
">",
"]",
"format",
"are",
"expanded",
".",
"Variables",
"using",
"the",
"$<variable",
"name",
">",
"and",
"$",
"{",
"<varia... | python | train | 50.95 |
clalancette/pycdlib | pycdlib/pycdlib.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/pycdlib.py#L4065-L4119 | def get_file_from_iso(self, local_path, **kwargs):
# type: (str, Any) -> None
'''
A method to fetch a single file from the ISO and write it out
to a local file.
Parameters:
local_path - The local file to write to.
blocksize - The number of bytes in each transfe... | [
"def",
"get_file_from_iso",
"(",
"self",
",",
"local_path",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (str, Any) -> None",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInvalidInput",
"(",
"'This object is not yet initializ... | A method to fetch a single file from the ISO and write it out
to a local file.
Parameters:
local_path - The local file to write to.
blocksize - The number of bytes in each transfer.
iso_path - The absolute ISO9660 path to lookup on the ISO (exclusive
with ... | [
"A",
"method",
"to",
"fetch",
"a",
"single",
"file",
"from",
"the",
"ISO",
"and",
"write",
"it",
"out",
"to",
"a",
"local",
"file",
"."
] | python | train | 44.290909 |
ioos/compliance-checker | compliance_checker/util.py | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/util.py#L16-L25 | def datetime_is_iso(date_str):
"""Attempts to parse a date formatted in ISO 8601 format"""
try:
if len(date_str) > 10:
dt = isodate.parse_datetime(date_str)
else:
dt = isodate.parse_date(date_str)
return True, []
except: # Any error qualifies as not ISO forma... | [
"def",
"datetime_is_iso",
"(",
"date_str",
")",
":",
"try",
":",
"if",
"len",
"(",
"date_str",
")",
">",
"10",
":",
"dt",
"=",
"isodate",
".",
"parse_datetime",
"(",
"date_str",
")",
"else",
":",
"dt",
"=",
"isodate",
".",
"parse_date",
"(",
"date_str"... | Attempts to parse a date formatted in ISO 8601 format | [
"Attempts",
"to",
"parse",
"a",
"date",
"formatted",
"in",
"ISO",
"8601",
"format"
] | python | train | 39 |
caseyjlaw/rtpipe | rtpipe/interactive.py | https://github.com/caseyjlaw/rtpipe/blob/ac33e4332cf215091a63afbb3137850876d73ec0/rtpipe/interactive.py#L575-L588 | def calcontime(data, inds=None):
""" Given indices of good times, calculate total time per scan with indices. """
if not inds:
inds = range(len(data['time']))
logger.info('No indices provided. Assuming all are valid.')
scans = set([data['scan'][i] for i in inds])
total = 0.
for sca... | [
"def",
"calcontime",
"(",
"data",
",",
"inds",
"=",
"None",
")",
":",
"if",
"not",
"inds",
":",
"inds",
"=",
"range",
"(",
"len",
"(",
"data",
"[",
"'time'",
"]",
")",
")",
"logger",
".",
"info",
"(",
"'No indices provided. Assuming all are valid.'",
")"... | Given indices of good times, calculate total time per scan with indices. | [
"Given",
"indices",
"of",
"good",
"times",
"calculate",
"total",
"time",
"per",
"scan",
"with",
"indices",
"."
] | python | train | 32.071429 |
StackStorm/pybind | pybind/slxos/v17s_1_02/mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/rsvp/interface_refresh_reduction/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/rsvp/interface_refresh_reduction/__init__.py#L161-L182 | def _set_bundle_message(self, v, load=False):
"""
Setter method for bundle_message, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/rsvp/interface_refresh_reduction/bundle_message (container)
If this variable is read-only (config: false) in the
source YANG file, then _... | [
"def",
"_set_bundle_message",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | Setter method for bundle_message, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/rsvp/interface_refresh_reduction/bundle_message (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bundle_message is considered as a private
method. ... | [
"Setter",
"method",
"for",
"bundle_message",
"mapped",
"from",
"YANG",
"variable",
"/",
"mpls_config",
"/",
"router",
"/",
"mpls",
"/",
"mpls_cmds_holder",
"/",
"mpls_interface",
"/",
"rsvp",
"/",
"interface_refresh_reduction",
"/",
"bundle_message",
"(",
"container... | python | train | 82.772727 |
Ouranosinc/xclim | xclim/indices.py | https://github.com/Ouranosinc/xclim/blob/2080d139188bd8de2aeca097a025c2d89d6e0e09/xclim/indices.py#L2088-L2109 | def warm_night_frequency(tasmin, thresh='22 degC', freq='YS'):
r"""Frequency of extreme warm nights
Return the number of days with tasmin > thresh per period
Parameters
----------
tasmin : xarray.DataArray
Minimum daily temperature [℃] or [K]
thresh : str
Threshold temperature on w... | [
"def",
"warm_night_frequency",
"(",
"tasmin",
",",
"thresh",
"=",
"'22 degC'",
",",
"freq",
"=",
"'YS'",
")",
":",
"thresh",
"=",
"utils",
".",
"convert_units_to",
"(",
"thresh",
",",
"tasmin",
",",
")",
"events",
"=",
"(",
"tasmin",
">",
"thresh",
")",
... | r"""Frequency of extreme warm nights
Return the number of days with tasmin > thresh per period
Parameters
----------
tasmin : xarray.DataArray
Minimum daily temperature [℃] or [K]
thresh : str
Threshold temperature on which to base evaluation [℃] or [K]. Default : '22 degC'
freq : ... | [
"r",
"Frequency",
"of",
"extreme",
"warm",
"nights"
] | python | train | 30 |
pixelogik/NearPy | nearpy/storage/storage_mongo.py | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/storage/storage_mongo.py#L172-L180 | def store_hash_configuration(self, lshash):
"""
Stores hash configuration
"""
self.mongo_object.insert_one(
{'hash_conf_name': lshash.hash_name+'_conf',
'hash_configuration': pickle.dumps(lshash.get_config())
}
) | [
"def",
"store_hash_configuration",
"(",
"self",
",",
"lshash",
")",
":",
"self",
".",
"mongo_object",
".",
"insert_one",
"(",
"{",
"'hash_conf_name'",
":",
"lshash",
".",
"hash_name",
"+",
"'_conf'",
",",
"'hash_configuration'",
":",
"pickle",
".",
"dumps",
"(... | Stores hash configuration | [
"Stores",
"hash",
"configuration"
] | python | train | 31.333333 |
CloverHealth/temple | temple/cli.py | https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/cli.py#L114-L118 | def switch(template, version):
"""
Switch a project's template to a different template.
"""
temple.update.update(new_template=template, new_version=version) | [
"def",
"switch",
"(",
"template",
",",
"version",
")",
":",
"temple",
".",
"update",
".",
"update",
"(",
"new_template",
"=",
"template",
",",
"new_version",
"=",
"version",
")"
] | Switch a project's template to a different template. | [
"Switch",
"a",
"project",
"s",
"template",
"to",
"a",
"different",
"template",
"."
] | python | valid | 33.6 |
chaoss/grimoirelab-sirmordred | sirmordred/eclipse_projects_lib.py | https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L186-L200 | def compose_projects_json(projects, data):
""" Compose projects.json with all data sources
:param projects: projects.json
:param data: eclipse JSON
:return: projects.json with all data sources
"""
projects = compose_git(projects, data)
projects = compose_mailing_lists(projects, data)
pr... | [
"def",
"compose_projects_json",
"(",
"projects",
",",
"data",
")",
":",
"projects",
"=",
"compose_git",
"(",
"projects",
",",
"data",
")",
"projects",
"=",
"compose_mailing_lists",
"(",
"projects",
",",
"data",
")",
"projects",
"=",
"compose_bugzilla",
"(",
"p... | Compose projects.json with all data sources
:param projects: projects.json
:param data: eclipse JSON
:return: projects.json with all data sources | [
"Compose",
"projects",
".",
"json",
"with",
"all",
"data",
"sources"
] | python | valid | 32.8 |
googleapis/google-cloud-python | logging/google/cloud/logging/client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/client.py#L222-L243 | def sink(self, name, filter_=None, destination=None):
"""Creates a sink bound to the current client.
:type name: str
:param name: the name of the sink to be constructed.
:type filter_: str
:param filter_: (optional) the advanced logs filter expression
de... | [
"def",
"sink",
"(",
"self",
",",
"name",
",",
"filter_",
"=",
"None",
",",
"destination",
"=",
"None",
")",
":",
"return",
"Sink",
"(",
"name",
",",
"filter_",
",",
"destination",
",",
"client",
"=",
"self",
")"
] | Creates a sink bound to the current client.
:type name: str
:param name: the name of the sink to be constructed.
:type filter_: str
:param filter_: (optional) the advanced logs filter expression
defining the entries exported by the sink. If not
... | [
"Creates",
"a",
"sink",
"bound",
"to",
"the",
"current",
"client",
"."
] | python | train | 43.409091 |
googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/pool.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L162-L174 | def bind(self, database):
"""Associate the pool with a database.
:type database: :class:`~google.cloud.spanner_v1.database.Database`
:param database: database used by the pool: used to create sessions
when needed.
"""
self._database = database
... | [
"def",
"bind",
"(",
"self",
",",
"database",
")",
":",
"self",
".",
"_database",
"=",
"database",
"while",
"not",
"self",
".",
"_sessions",
".",
"full",
"(",
")",
":",
"session",
"=",
"self",
".",
"_new_session",
"(",
")",
"session",
".",
"create",
"... | Associate the pool with a database.
:type database: :class:`~google.cloud.spanner_v1.database.Database`
:param database: database used by the pool: used to create sessions
when needed. | [
"Associate",
"the",
"pool",
"with",
"a",
"database",
"."
] | python | train | 34.692308 |
alexhayes/django-toolkit | django_toolkit/db/models.py | https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/db/models.py#L77-L85 | def unlock(self):
"""
Unlock the table(s)
"""
cursor = connection.cursor()
cursor.execute("UNLOCK TABLES")
logger.debug('Unlocked tables')
row = cursor.fetchone()
return row | [
"def",
"unlock",
"(",
"self",
")",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"UNLOCK TABLES\"",
")",
"logger",
".",
"debug",
"(",
"'Unlocked tables'",
")",
"row",
"=",
"cursor",
".",
"fetchone",
"(",
")",... | Unlock the table(s) | [
"Unlock",
"the",
"table",
"(",
"s",
")"
] | python | train | 25.444444 |
bachiraoun/pyrep | Repository.py | https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/Repository.py#L2124-L2297 | def dump_file(self, value, relativePath,
description=None,
dump=None, pull=None,
replace=False, raiseError=True, ntrials=3):
"""
Dump a file using its value to the system and creates its
attribute in the Repository with utc ... | [
"def",
"dump_file",
"(",
"self",
",",
"value",
",",
"relativePath",
",",
"description",
"=",
"None",
",",
"dump",
"=",
"None",
",",
"pull",
"=",
"None",
",",
"replace",
"=",
"False",
",",
"raiseError",
"=",
"True",
",",
"ntrials",
"=",
"3",
")",
":",... | Dump a file using its value to the system and creates its
attribute in the Repository with utc timestamp.
:Parameters:
#. value (object): The value of a file to dump and add to the
repository. It is any python object or file.
#. relativePath (str): The relative to... | [
"Dump",
"a",
"file",
"using",
"its",
"value",
"to",
"the",
"system",
"and",
"creates",
"its",
"attribute",
"in",
"the",
"Repository",
"with",
"utc",
"timestamp",
"."
] | python | valid | 53.051724 |
ryukinix/decorating | decorating/animation.py | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/animation.py#L359-L364 | def stop(cls):
"""Change back the normal stdout after the end"""
if any(cls.streams):
sys.stdout = cls.streams.pop(-1)
else:
sys.stdout = sys.__stdout__ | [
"def",
"stop",
"(",
"cls",
")",
":",
"if",
"any",
"(",
"cls",
".",
"streams",
")",
":",
"sys",
".",
"stdout",
"=",
"cls",
".",
"streams",
".",
"pop",
"(",
"-",
"1",
")",
"else",
":",
"sys",
".",
"stdout",
"=",
"sys",
".",
"__stdout__"
] | Change back the normal stdout after the end | [
"Change",
"back",
"the",
"normal",
"stdout",
"after",
"the",
"end"
] | python | train | 32.5 |
lreis2415/PyGeoC | pygeoc/TauDEM.py | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L449-L465 | def connectdown(np, p, acc, outlet, wtsd=None, workingdir=None, mpiexedir=None,
exedir=None, log_file=None, runtime_file=None, hostfile=None):
"""Reads an ad8 contributing area file,
identifies the location of the largest ad8 value as the outlet of the largest watershed"""
# ... | [
"def",
"connectdown",
"(",
"np",
",",
"p",
",",
"acc",
",",
"outlet",
",",
"wtsd",
"=",
"None",
",",
"workingdir",
"=",
"None",
",",
"mpiexedir",
"=",
"None",
",",
"exedir",
"=",
"None",
",",
"log_file",
"=",
"None",
",",
"runtime_file",
"=",
"None",... | Reads an ad8 contributing area file,
identifies the location of the largest ad8 value as the outlet of the largest watershed | [
"Reads",
"an",
"ad8",
"contributing",
"area",
"file",
"identifies",
"the",
"location",
"of",
"the",
"largest",
"ad8",
"value",
"as",
"the",
"outlet",
"of",
"the",
"largest",
"watershed"
] | python | train | 63.058824 |
gwpy/gwpy | gwpy/detector/channel.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/detector/channel.py#L444-L479 | def query_nds2(cls, name, host=None, port=None, connection=None,
type=None):
"""Query an NDS server for channel information
Parameters
----------
name : `str`
name of requested channel
host : `str`, optional
name of NDS2 server.
... | [
"def",
"query_nds2",
"(",
"cls",
",",
"name",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"connection",
"=",
"None",
",",
"type",
"=",
"None",
")",
":",
"return",
"ChannelList",
".",
"query_nds2",
"(",
"[",
"name",
"]",
",",
"host",
"=... | Query an NDS server for channel information
Parameters
----------
name : `str`
name of requested channel
host : `str`, optional
name of NDS2 server.
port : `int`, optional
port number for NDS2 connection
connection : `nds2.connection`
... | [
"Query",
"an",
"NDS",
"server",
"for",
"channel",
"information"
] | python | train | 30.027778 |
tkarabela/pysubs2 | pysubs2/ssaevent.py | https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/ssaevent.py#L105-L114 | def shift(self, h=0, m=0, s=0, ms=0, frames=None, fps=None):
"""
Shift start and end times.
See :meth:`SSAFile.shift()` for full description.
"""
delta = make_time(h=h, m=m, s=s, ms=ms, frames=frames, fps=fps)
self.start += delta
self.end += delta | [
"def",
"shift",
"(",
"self",
",",
"h",
"=",
"0",
",",
"m",
"=",
"0",
",",
"s",
"=",
"0",
",",
"ms",
"=",
"0",
",",
"frames",
"=",
"None",
",",
"fps",
"=",
"None",
")",
":",
"delta",
"=",
"make_time",
"(",
"h",
"=",
"h",
",",
"m",
"=",
"... | Shift start and end times.
See :meth:`SSAFile.shift()` for full description. | [
"Shift",
"start",
"and",
"end",
"times",
"."
] | python | train | 29.6 |
fastai/fastai | fastai/callbacks/tensorboard.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L63-L65 | def _write_weight_histograms(self, iteration:int)->None:
"Writes model weight histograms to Tensorboard."
self.hist_writer.write(model=self.learn.model, iteration=iteration, tbwriter=self.tbwriter) | [
"def",
"_write_weight_histograms",
"(",
"self",
",",
"iteration",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"hist_writer",
".",
"write",
"(",
"model",
"=",
"self",
".",
"learn",
".",
"model",
",",
"iteration",
"=",
"iteration",
",",
"tbwriter",
"=... | Writes model weight histograms to Tensorboard. | [
"Writes",
"model",
"weight",
"histograms",
"to",
"Tensorboard",
"."
] | python | train | 70.333333 |
PolyJIT/benchbuild | benchbuild/utils/run.py | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L260-L282 | def exit_code_from_run_infos(run_infos: t.List[RunInfo]) -> int:
"""Generate a single exit code from a list of RunInfo objects.
Takes a list of RunInfos and returns the exit code that is furthest away
from 0.
Args:
run_infos (t.List[RunInfo]): [description]
Returns:
int: [descript... | [
"def",
"exit_code_from_run_infos",
"(",
"run_infos",
":",
"t",
".",
"List",
"[",
"RunInfo",
"]",
")",
"->",
"int",
":",
"assert",
"run_infos",
"is",
"not",
"None",
"if",
"not",
"hasattr",
"(",
"run_infos",
",",
"\"__iter__\"",
")",
":",
"return",
"run_info... | Generate a single exit code from a list of RunInfo objects.
Takes a list of RunInfos and returns the exit code that is furthest away
from 0.
Args:
run_infos (t.List[RunInfo]): [description]
Returns:
int: [description] | [
"Generate",
"a",
"single",
"exit",
"code",
"from",
"a",
"list",
"of",
"RunInfo",
"objects",
"."
] | python | train | 24.695652 |
capitalone/giraffez | giraffez/cmd.py | https://github.com/capitalone/giraffez/blob/6b4d27eb1a1eaf188c6885c7364ef27e92b1b957/giraffez/cmd.py#L343-L385 | def insert(self, table_name, rows, fields=None, delimiter=None, null='NULL', parse_dates=False, quotechar='"'):
"""
Load a text file into the specified :code:`table_name` or Insert Python :code:`list` rows into the specified :code:`table_name`
:param str table_name: The name of the destination ... | [
"def",
"insert",
"(",
"self",
",",
"table_name",
",",
"rows",
",",
"fields",
"=",
"None",
",",
"delimiter",
"=",
"None",
",",
"null",
"=",
"'NULL'",
",",
"parse_dates",
"=",
"False",
",",
"quotechar",
"=",
"'\"'",
")",
":",
"if",
"not",
"isfile",
"("... | Load a text file into the specified :code:`table_name` or Insert Python :code:`list` rows into the specified :code:`table_name`
:param str table_name: The name of the destination table
:param list/str rows: A list of rows **or** the name of an input file. Each row
must be a :code:`list` of ... | [
"Load",
"a",
"text",
"file",
"into",
"the",
"specified",
":",
"code",
":",
"table_name",
"or",
"Insert",
"Python",
":",
"code",
":",
"list",
"rows",
"into",
"the",
"specified",
":",
"code",
":",
"table_name"
] | python | test | 60.534884 |
pantsbuild/pants | src/python/pants/pantsd/process_manager.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L397-L407 | def purge_metadata(self, force=False):
"""Instance-based version of ProcessMetadataManager.purge_metadata_by_name() that checks
for process liveness before purging metadata.
:param bool force: If True, skip process liveness check before purging metadata.
:raises: `ProcessManager.MetadataError` when OSE... | [
"def",
"purge_metadata",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"force",
"and",
"self",
".",
"is_alive",
"(",
")",
":",
"raise",
"ProcessMetadataManager",
".",
"MetadataError",
"(",
"'cannot purge metadata for a running process!'",
")",
... | Instance-based version of ProcessMetadataManager.purge_metadata_by_name() that checks
for process liveness before purging metadata.
:param bool force: If True, skip process liveness check before purging metadata.
:raises: `ProcessManager.MetadataError` when OSError is encountered on metadata dir removal. | [
"Instance",
"-",
"based",
"version",
"of",
"ProcessMetadataManager",
".",
"purge_metadata_by_name",
"()",
"that",
"checks",
"for",
"process",
"liveness",
"before",
"purging",
"metadata",
"."
] | python | train | 51.363636 |
bwohlberg/sporco | sporco/admm/tvl2.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/tvl2.py#L219-L236 | def xstep(self):
r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{x}`.
"""
ngsit = 0
gsrrs = np.inf
while gsrrs > self.opt['GSTol'] and ngsit < self.opt['MaxGSIter']:
self.X = self.GaussSeidelStep(self.S, self.X,
... | [
"def",
"xstep",
"(",
"self",
")",
":",
"ngsit",
"=",
"0",
"gsrrs",
"=",
"np",
".",
"inf",
"while",
"gsrrs",
">",
"self",
".",
"opt",
"[",
"'GSTol'",
"]",
"and",
"ngsit",
"<",
"self",
".",
"opt",
"[",
"'MaxGSIter'",
"]",
":",
"self",
".",
"X",
"... | r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{x}`. | [
"r",
"Minimise",
"Augmented",
"Lagrangian",
"with",
"respect",
"to",
":",
"math",
":",
"\\",
"mathbf",
"{",
"x",
"}",
"."
] | python | train | 37.277778 |
kenjoe41/ghostpaste | ghostpaste/ghostpaste.py | https://github.com/kenjoe41/ghostpaste/blob/7811878fb06c661eb0e7fe2cf5601a87aa858d30/ghostpaste/ghostpaste.py#L84-L92 | def detect_lang(path):
"""Detect the language used in the given file."""
blob = FileBlob(path, os.getcwd())
if blob.is_text:
print('Programming language of the file detected: {0}'.format(blob.language.name))
return blob.language.name
else:#images, binary and what-have-you won't be pasted
print('File not a tex... | [
"def",
"detect_lang",
"(",
"path",
")",
":",
"blob",
"=",
"FileBlob",
"(",
"path",
",",
"os",
".",
"getcwd",
"(",
")",
")",
"if",
"blob",
".",
"is_text",
":",
"print",
"(",
"'Programming language of the file detected: {0}'",
".",
"format",
"(",
"blob",
"."... | Detect the language used in the given file. | [
"Detect",
"the",
"language",
"used",
"in",
"the",
"given",
"file",
"."
] | python | train | 38.333333 |
rstoneback/pysatMagVect | pysatMagVect/_core.py | https://github.com/rstoneback/pysatMagVect/blob/3fdc87ffbe05be58123f80f880d1237c2f34c7be/pysatMagVect/_core.py#L82-L110 | def geodetic_to_ecef(latitude, longitude, altitude):
"""Convert WGS84 geodetic coordinates into ECEF
Parameters
----------
latitude : float or array_like
Geodetic latitude (degrees)
longitude : float or array_like
Geodetic longitude (degrees)
altitude : float or array_like
... | [
"def",
"geodetic_to_ecef",
"(",
"latitude",
",",
"longitude",
",",
"altitude",
")",
":",
"ellip",
"=",
"np",
".",
"sqrt",
"(",
"1.",
"-",
"earth_b",
"**",
"2",
"/",
"earth_a",
"**",
"2",
")",
"r_n",
"=",
"earth_a",
"/",
"np",
".",
"sqrt",
"(",
"1."... | Convert WGS84 geodetic coordinates into ECEF
Parameters
----------
latitude : float or array_like
Geodetic latitude (degrees)
longitude : float or array_like
Geodetic longitude (degrees)
altitude : float or array_like
Geodetic Height (km) above WGS84 reference ellipsoid.... | [
"Convert",
"WGS84",
"geodetic",
"coordinates",
"into",
"ECEF",
"Parameters",
"----------",
"latitude",
":",
"float",
"or",
"array_like",
"Geodetic",
"latitude",
"(",
"degrees",
")",
"longitude",
":",
"float",
"or",
"array_like",
"Geodetic",
"longitude",
"(",
"degr... | python | train | 31.241379 |
bibanon/BASC-py4chan | basc_py4chan/util.py | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/util.py#L16-L26 | def clean_comment_body(body):
"""Returns given comment HTML as plaintext.
Converts all HTML tags and entities within 4chan comments
into human-readable text equivalents.
"""
body = _parser.unescape(body)
body = re.sub(r'<a [^>]+>(.+?)</a>', r'\1', body)
body = body.replace('<br>', '\n')
... | [
"def",
"clean_comment_body",
"(",
"body",
")",
":",
"body",
"=",
"_parser",
".",
"unescape",
"(",
"body",
")",
"body",
"=",
"re",
".",
"sub",
"(",
"r'<a [^>]+>(.+?)</a>'",
",",
"r'\\1'",
",",
"body",
")",
"body",
"=",
"body",
".",
"replace",
"(",
"'<br... | Returns given comment HTML as plaintext.
Converts all HTML tags and entities within 4chan comments
into human-readable text equivalents. | [
"Returns",
"given",
"comment",
"HTML",
"as",
"plaintext",
"."
] | python | train | 32.727273 |
sander76/aio-powerview-api | aiopvapi/helpers/powerview_util.py | https://github.com/sander76/aio-powerview-api/blob/08b6ac747aba9de19842359a981a7ff1292f5a6c/aiopvapi/helpers/powerview_util.py#L95-L103 | async def activate_scene(self, scene_id: int):
"""Activate a scene
:param scene_id: Scene id.
:return:
"""
_scene = await self.get_scene(scene_id)
await _scene.activate() | [
"async",
"def",
"activate_scene",
"(",
"self",
",",
"scene_id",
":",
"int",
")",
":",
"_scene",
"=",
"await",
"self",
".",
"get_scene",
"(",
"scene_id",
")",
"await",
"_scene",
".",
"activate",
"(",
")"
] | Activate a scene
:param scene_id: Scene id.
:return: | [
"Activate",
"a",
"scene"
] | python | train | 23.555556 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L769-L774 | def add_route(self, route):
''' Add a route object, but do not change the :data:`Route.app`
attribute.'''
self.routes.append(route)
self.router.add(route.rule, route.method, route, name=route.name)
if DEBUG: route.prepare() | [
"def",
"add_route",
"(",
"self",
",",
"route",
")",
":",
"self",
".",
"routes",
".",
"append",
"(",
"route",
")",
"self",
".",
"router",
".",
"add",
"(",
"route",
".",
"rule",
",",
"route",
".",
"method",
",",
"route",
",",
"name",
"=",
"route",
... | Add a route object, but do not change the :data:`Route.app`
attribute. | [
"Add",
"a",
"route",
"object",
"but",
"do",
"not",
"change",
"the",
":",
"data",
":",
"Route",
".",
"app",
"attribute",
"."
] | python | train | 43.666667 |
intel-analytics/BigDL | pyspark/bigdl/optim/optimizer.py | https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/optim/optimizer.py#L914-L923 | def set_traindata(self, training_rdd, batch_size):
"""
Set new training dataset, for optimizer reuse
:param training_rdd: the training dataset
:param batch_size: training batch size
:return:
"""
callBigDlFunc(self.bigdl_type, "setTrainData", self.value,
... | [
"def",
"set_traindata",
"(",
"self",
",",
"training_rdd",
",",
"batch_size",
")",
":",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"setTrainData\"",
",",
"self",
".",
"value",
",",
"training_rdd",
",",
"batch_size",
")"
] | Set new training dataset, for optimizer reuse
:param training_rdd: the training dataset
:param batch_size: training batch size
:return: | [
"Set",
"new",
"training",
"dataset",
"for",
"optimizer",
"reuse"
] | python | test | 34.8 |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/deserialize.py | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/deserialize.py#L127-L152 | def _deserialize_encrypted_data_keys(stream):
# type: (IO) -> Set[EncryptedDataKey]
"""Deserialize some encrypted data keys from a stream.
:param stream: Stream from which to read encrypted data keys
:return: Loaded encrypted data keys
:rtype: set of :class:`EncryptedDataKey`
"""
(encrypted... | [
"def",
"_deserialize_encrypted_data_keys",
"(",
"stream",
")",
":",
"# type: (IO) -> Set[EncryptedDataKey]",
"(",
"encrypted_data_key_count",
",",
")",
"=",
"unpack_values",
"(",
"\">H\"",
",",
"stream",
")",
"encrypted_data_keys",
"=",
"set",
"(",
"[",
"]",
")",
"f... | Deserialize some encrypted data keys from a stream.
:param stream: Stream from which to read encrypted data keys
:return: Loaded encrypted data keys
:rtype: set of :class:`EncryptedDataKey` | [
"Deserialize",
"some",
"encrypted",
"data",
"keys",
"from",
"a",
"stream",
"."
] | python | train | 47.269231 |
serge-sans-paille/pythran | pythran/analyses/aliases.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/aliases.py#L127-L145 | def visit_BoolOp(self, node):
'''
Resulting node may alias to either operands:
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return a or b')
>>> result = pm.gather(Aliases, module)
>>> Aliases.... | [
"def",
"visit_BoolOp",
"(",
"self",
",",
"node",
")",
":",
"return",
"self",
".",
"add",
"(",
"node",
",",
"set",
".",
"union",
"(",
"*",
"[",
"self",
".",
"visit",
"(",
"n",
")",
"for",
"n",
"in",
"node",
".",
"values",
"]",
")",
")"
] | Resulting node may alias to either operands:
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return a or b')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.BoolOp)
(a or b) =... | [
"Resulting",
"node",
"may",
"alias",
"to",
"either",
"operands",
":"
] | python | train | 37.894737 |
raamana/mrivis | mrivis/workflow.py | https://github.com/raamana/mrivis/blob/199ad096b8a1d825f69109e7218a81b2f1cec756/mrivis/workflow.py#L22-L107 | def checkerboard(img_spec1=None,
img_spec2=None,
patch_size=10,
view_set=(0, 1, 2),
num_slices=(10,),
num_rows=2,
rescale_method='global',
background_threshold=0.05,
annot=None,
... | [
"def",
"checkerboard",
"(",
"img_spec1",
"=",
"None",
",",
"img_spec2",
"=",
"None",
",",
"patch_size",
"=",
"10",
",",
"view_set",
"=",
"(",
"0",
",",
"1",
",",
"2",
")",
",",
"num_slices",
"=",
"(",
"10",
",",
")",
",",
"num_rows",
"=",
"2",
",... | Checkerboard mixer.
Parameters
----------
img_spec1 : str or nibabel image-like object
MR image (or path to one) to be visualized
img_spec2 : str or nibabel image-like object
MR image (or path to one) to be visualized
patch_size : int or list or (int, int) or None
size of ... | [
"Checkerboard",
"mixer",
"."
] | python | train | 36.511628 |
pydanny/django-tagging-ext | tagging_ext/views.py | https://github.com/pydanny/django-tagging-ext/blob/a25a79ddcd760c5ab272713178f40fedd9146b41/tagging_ext/views.py#L37-L82 | def index(request, template_name="tagging_ext/index.html", min_size=0,limit=10):
"""
min_size: Smallest size count accepted for a tag
order_by: asc or desc by count
limit: maximum number of tags to display
TODO: convert the hand-written query to an ORM call. Right now I kno... | [
"def",
"index",
"(",
"request",
",",
"template_name",
"=",
"\"tagging_ext/index.html\"",
",",
"min_size",
"=",
"0",
",",
"limit",
"=",
"10",
")",
":",
"query",
"=",
"\"\"\"\n SELECT tag_item.tag_id as tag_id, COUNT(tag_item.tag_id) as counter \n FROM tagging_tag... | min_size: Smallest size count accepted for a tag
order_by: asc or desc by count
limit: maximum number of tags to display
TODO: convert the hand-written query to an ORM call. Right now I know
this works with Sqlite3 and PostGreSQL. | [
"min_size",
":",
"Smallest",
"size",
"count",
"accepted",
"for",
"a",
"tag",
"order_by",
":",
"asc",
"or",
"desc",
"by",
"count",
"limit",
":",
"maximum",
"number",
"of",
"tags",
"to",
"display",
"TODO",
":",
"convert",
"the",
"hand",
"-",
"written",
"qu... | python | train | 26.347826 |
fuzeman/trakt.py | trakt/objects/show.py | https://github.com/fuzeman/trakt.py/blob/14c6b72e3c13ea2975007aeac0c01ad2222b67f3/trakt/objects/show.py#L138-L148 | def episodes(self):
"""Return a flat episode iterator.
:returns: Iterator :code:`((season_num, episode_num), Episode)`
:rtype: iterator
"""
for sk, season in iteritems(self.seasons):
# Yield each episode in season
for ek, episode in iteritems(season.epis... | [
"def",
"episodes",
"(",
"self",
")",
":",
"for",
"sk",
",",
"season",
"in",
"iteritems",
"(",
"self",
".",
"seasons",
")",
":",
"# Yield each episode in season",
"for",
"ek",
",",
"episode",
"in",
"iteritems",
"(",
"season",
".",
"episodes",
")",
":",
"y... | Return a flat episode iterator.
:returns: Iterator :code:`((season_num, episode_num), Episode)`
:rtype: iterator | [
"Return",
"a",
"flat",
"episode",
"iterator",
"."
] | python | train | 32.363636 |
bunq/sdk_python | bunq/sdk/model/generated/endpoint.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L1494-L1516 | def get(cls, attachment_public_uuid, custom_headers=None):
"""
Get a specific attachment's metadata through its UUID. The Content-Type
header of the response will describe the MIME type of the attachment
file.
:type api_context: context.ApiContext
:type attachment_public... | [
"def",
"get",
"(",
"cls",
",",
"attachment_public_uuid",
",",
"custom_headers",
"=",
"None",
")",
":",
"if",
"custom_headers",
"is",
"None",
":",
"custom_headers",
"=",
"{",
"}",
"api_client",
"=",
"client",
".",
"ApiClient",
"(",
"cls",
".",
"_get_api_conte... | Get a specific attachment's metadata through its UUID. The Content-Type
header of the response will describe the MIME type of the attachment
file.
:type api_context: context.ApiContext
:type attachment_public_uuid: str
:type custom_headers: dict[str, str]|None
:rtype: B... | [
"Get",
"a",
"specific",
"attachment",
"s",
"metadata",
"through",
"its",
"UUID",
".",
"The",
"Content",
"-",
"Type",
"header",
"of",
"the",
"response",
"will",
"describe",
"the",
"MIME",
"type",
"of",
"the",
"attachment",
"file",
"."
] | python | train | 36.478261 |
OCHA-DAP/hdx-python-api | src/hdx/data/hdxobject.py | https://github.com/OCHA-DAP/hdx-python-api/blob/212440f54f73805826a16db77dbcb6033b18a313/src/hdx/data/hdxobject.py#L365-L383 | def _addupdate_hdxobject(self, hdxobjects, id_field, new_hdxobject):
# type: (List[HDXObjectUpperBound], str, HDXObjectUpperBound) -> HDXObjectUpperBound
"""Helper function to add a new HDX object to a supplied list of HDX objects or update existing metadata if the object
already exists in the l... | [
"def",
"_addupdate_hdxobject",
"(",
"self",
",",
"hdxobjects",
",",
"id_field",
",",
"new_hdxobject",
")",
":",
"# type: (List[HDXObjectUpperBound], str, HDXObjectUpperBound) -> HDXObjectUpperBound",
"for",
"hdxobject",
"in",
"hdxobjects",
":",
"if",
"hdxobject",
"[",
"id_f... | Helper function to add a new HDX object to a supplied list of HDX objects or update existing metadata if the object
already exists in the list
Args:
hdxobjects (List[T <= HDXObject]): list of HDX objects to which to add new objects or update existing ones
id_field (str): Field o... | [
"Helper",
"function",
"to",
"add",
"a",
"new",
"HDX",
"object",
"to",
"a",
"supplied",
"list",
"of",
"HDX",
"objects",
"or",
"update",
"existing",
"metadata",
"if",
"the",
"object",
"already",
"exists",
"in",
"the",
"list"
] | python | train | 51.789474 |
sublee/zeronimo | zeronimo/helpers.py | https://github.com/sublee/zeronimo/blob/b216638232932718d2cbc5eabd870c8f5b5e83fb/zeronimo/helpers.py#L42-L71 | def make_repr(obj, params=None, keywords=None, data=None, name=None,
reprs=None):
"""Generates a string of object initialization code style. It is useful
for custom __repr__ methods::
class Example(object):
def __init__(self, param, keyword=None):
self.param = p... | [
"def",
"make_repr",
"(",
"obj",
",",
"params",
"=",
"None",
",",
"keywords",
"=",
"None",
",",
"data",
"=",
"None",
",",
"name",
"=",
"None",
",",
"reprs",
"=",
"None",
")",
":",
"opts",
"=",
"[",
"]",
"if",
"params",
"is",
"not",
"None",
":",
... | Generates a string of object initialization code style. It is useful
for custom __repr__ methods::
class Example(object):
def __init__(self, param, keyword=None):
self.param = param
self.keyword = keyword
def __repr__(self):
return make_r... | [
"Generates",
"a",
"string",
"of",
"object",
"initialization",
"code",
"style",
".",
"It",
"is",
"useful",
"for",
"custom",
"__repr__",
"methods",
"::"
] | python | test | 32.266667 |
aiven/pghoard | pghoard/transfer.py | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/transfer.py#L80-L101 | def transmit_metrics(self):
"""
Keep metrics updated about how long time ago each filetype was successfully uploaded.
Transmits max once per ten seconds, regardless of how many threads are running.
"""
global _last_stats_transmit_time # pylint: disable=global-statement
w... | [
"def",
"transmit_metrics",
"(",
"self",
")",
":",
"global",
"_last_stats_transmit_time",
"# pylint: disable=global-statement",
"with",
"_STATS_LOCK",
":",
"# pylint: disable=not-context-manager",
"if",
"time",
".",
"monotonic",
"(",
")",
"-",
"_last_stats_transmit_time",
"<... | Keep metrics updated about how long time ago each filetype was successfully uploaded.
Transmits max once per ten seconds, regardless of how many threads are running. | [
"Keep",
"metrics",
"updated",
"about",
"how",
"long",
"time",
"ago",
"each",
"filetype",
"was",
"successfully",
"uploaded",
".",
"Transmits",
"max",
"once",
"per",
"ten",
"seconds",
"regardless",
"of",
"how",
"many",
"threads",
"are",
"running",
"."
] | python | train | 46.045455 |
AguaClara/aguaclara | aguaclara/research/floc_model.py | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L505-L513 | def dens_floc(ConcAl, ConcClay, DIM_FRACTAL, DiamTarget, coag, material, Temp):
"""Calculate floc density as a function of size."""
WaterDensity = pc.density_water(Temp).magnitude
return ((dens_floc_init(ConcAl, ConcClay, coag, material).magnitude
- WaterDensity
)
* (ma... | [
"def",
"dens_floc",
"(",
"ConcAl",
",",
"ConcClay",
",",
"DIM_FRACTAL",
",",
"DiamTarget",
",",
"coag",
",",
"material",
",",
"Temp",
")",
":",
"WaterDensity",
"=",
"pc",
".",
"density_water",
"(",
"Temp",
")",
".",
"magnitude",
"return",
"(",
"(",
"dens... | Calculate floc density as a function of size. | [
"Calculate",
"floc",
"density",
"as",
"a",
"function",
"of",
"size",
"."
] | python | train | 44.555556 |
clalancette/pycdlib | pycdlib/eltorito.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/eltorito.py#L218-L235 | def new(self, platform_id):
# type: (int) -> None
'''
A method to create a new El Torito Validation Entry.
Parameters:
platform_id - The platform ID to set for this validation entry.
Returns:
Nothing.
'''
if self._initialized:
raise ... | [
"def",
"new",
"(",
"self",
",",
"platform_id",
")",
":",
"# type: (int) -> None",
"if",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'El Torito Validation Entry already initialized'",
")",
"self",
".",
"platform_id",
... | A method to create a new El Torito Validation Entry.
Parameters:
platform_id - The platform ID to set for this validation entry.
Returns:
Nothing. | [
"A",
"method",
"to",
"create",
"a",
"new",
"El",
"Torito",
"Validation",
"Entry",
"."
] | python | train | 35.333333 |
OpenGov/python_data_wrap | datawrap/listwrap.py | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/listwrap.py#L463-L476 | def compress_ranges_to_lists(self):
'''
Converts the internal dimension ranges on lists into
list of the restricted size. Thus all dimension rules
are applied to all dimensions of the list wrapper
and returned as a list (of lists).
'''
clist = []
for elem ... | [
"def",
"compress_ranges_to_lists",
"(",
"self",
")",
":",
"clist",
"=",
"[",
"]",
"for",
"elem",
"in",
"self",
":",
"if",
"isinstance",
"(",
"elem",
",",
"FixedListSubset",
")",
":",
"clist",
".",
"append",
"(",
"elem",
".",
"compress_ranges_to_lists",
"("... | Converts the internal dimension ranges on lists into
list of the restricted size. Thus all dimension rules
are applied to all dimensions of the list wrapper
and returned as a list (of lists). | [
"Converts",
"the",
"internal",
"dimension",
"ranges",
"on",
"lists",
"into",
"list",
"of",
"the",
"restricted",
"size",
".",
"Thus",
"all",
"dimension",
"rules",
"are",
"applied",
"to",
"all",
"dimensions",
"of",
"the",
"list",
"wrapper",
"and",
"returned",
... | python | train | 35.785714 |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L425-L451 | def info(name, m, p, b, w, **kwargs):
"""
Show information about cocaine runtime.
Return json-like string with information about cocaine-runtime.
If the name option is not specified, shows information about all applications. Flags can be
specified for fine-grained control of the output verbosity.
... | [
"def",
"info",
"(",
"name",
",",
"m",
",",
"p",
",",
"b",
",",
"w",
",",
"*",
"*",
"kwargs",
")",
":",
"m",
"=",
"(",
"m",
"<<",
"1",
")",
"&",
"0b010",
"p",
"=",
"(",
"p",
"<<",
"2",
")",
"&",
"0b100",
"# Brief disables all further flags.",
... | Show information about cocaine runtime.
Return json-like string with information about cocaine-runtime.
If the name option is not specified, shows information about all applications. Flags can be
specified for fine-grained control of the output verbosity. | [
"Show",
"information",
"about",
"cocaine",
"runtime",
"."
] | python | train | 26.962963 |
wbond/asn1crypto | asn1crypto/util.py | https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/util.py#L295-L320 | def replace(self, year=None, month=None, day=None):
"""
Returns a new datetime.date or asn1crypto.util.extended_date
object with the specified components replaced
:return:
A datetime.date or asn1crypto.util.extended_date object
"""
if year is None:
... | [
"def",
"replace",
"(",
"self",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
",",
"day",
"=",
"None",
")",
":",
"if",
"year",
"is",
"None",
":",
"year",
"=",
"self",
".",
"year",
"if",
"month",
"is",
"None",
":",
"month",
"=",
"self",
".... | Returns a new datetime.date or asn1crypto.util.extended_date
object with the specified components replaced
:return:
A datetime.date or asn1crypto.util.extended_date object | [
"Returns",
"a",
"new",
"datetime",
".",
"date",
"or",
"asn1crypto",
".",
"util",
".",
"extended_date",
"object",
"with",
"the",
"specified",
"components",
"replaced"
] | python | train | 22.961538 |
elyase/masstable | masstable/masstable.py | https://github.com/elyase/masstable/blob/3eb72b22cd3337bc5c6bb95bb7bb73fdbe6ae9e2/masstable/masstable.py#L500-L507 | def ds2p(self):
"""Calculates the derivative of the neutron separation energies:
ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2)
"""
idx = [(x[0] + 2, x[1]) for x in self.df.index]
values = self.s2p.values - self.s2p.loc[idx].values
return Table(df=pd.Series(values, index=self.df.inde... | [
"def",
"ds2p",
"(",
"self",
")",
":",
"idx",
"=",
"[",
"(",
"x",
"[",
"0",
"]",
"+",
"2",
",",
"x",
"[",
"1",
"]",
")",
"for",
"x",
"in",
"self",
".",
"df",
".",
"index",
"]",
"values",
"=",
"self",
".",
"s2p",
".",
"values",
"-",
"self",... | Calculates the derivative of the neutron separation energies:
ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2) | [
"Calculates",
"the",
"derivative",
"of",
"the",
"neutron",
"separation",
"energies",
":"
] | python | test | 44.125 |
googleapis/google-cloud-python | core/google/cloud/_http.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_http.py#L194-L221 | def _do_request(
self, method, url, headers, data, target_object
): # pylint: disable=unused-argument
"""Low-level helper: perform the actual API request over HTTP.
Allows batch context managers to override and defer a request.
:type method: str
:param method: The HTTP me... | [
"def",
"_do_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"headers",
",",
"data",
",",
"target_object",
")",
":",
"# pylint: disable=unused-argument",
"return",
"self",
".",
"http",
".",
"request",
"(",
"url",
"=",
"url",
",",
"method",
"=",
"meth... | Low-level helper: perform the actual API request over HTTP.
Allows batch context managers to override and defer a request.
:type method: str
:param method: The HTTP method to use in the request.
:type url: str
:param url: The URL to send the request to.
:type headers... | [
"Low",
"-",
"level",
"helper",
":",
"perform",
"the",
"actual",
"API",
"request",
"over",
"HTTP",
"."
] | python | train | 33.5 |
alvinwan/TexSoup | TexSoup/data.py | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/data.py#L366-L384 | def count(self, name=None, **attrs):
r"""Number of descendants matching criteria.
:param Union[None,str] name: name of LaTeX expression
:param attrs: LaTeX expression attributes, such as item text.
:return: number of matching expressions
:rtype: int
>>> from TexSoup imp... | [
"def",
"count",
"(",
"self",
",",
"name",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"return",
"len",
"(",
"list",
"(",
"self",
".",
"find_all",
"(",
"name",
",",
"*",
"*",
"attrs",
")",
")",
")"
] | r"""Number of descendants matching criteria.
:param Union[None,str] name: name of LaTeX expression
:param attrs: LaTeX expression attributes, such as item text.
:return: number of matching expressions
:rtype: int
>>> from TexSoup import TexSoup
>>> soup = TexSoup(r'''
... | [
"r",
"Number",
"of",
"descendants",
"matching",
"criteria",
"."
] | python | train | 30.684211 |
joealcorn/laboratory | laboratory/experiment.py | https://github.com/joealcorn/laboratory/blob/e7af560c69d9dbb8f8cf4ca93c3c03523f8fb83d/laboratory/experiment.py#L40-L65 | def decorator(cls, candidate, *exp_args, **exp_kwargs):
'''
Decorate a control function in order to conduct an experiment when called.
:param callable candidate: your candidate function
:param iterable exp_args: positional arguments passed to :class:`Experiment`
:param dict exp_... | [
"def",
"decorator",
"(",
"cls",
",",
"candidate",
",",
"*",
"exp_args",
",",
"*",
"*",
"exp_kwargs",
")",
":",
"def",
"wrapper",
"(",
"control",
")",
":",
"@",
"wraps",
"(",
"control",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",... | Decorate a control function in order to conduct an experiment when called.
:param callable candidate: your candidate function
:param iterable exp_args: positional arguments passed to :class:`Experiment`
:param dict exp_kwargs: keyword arguments passed to :class:`Experiment`
Usage::
... | [
"Decorate",
"a",
"control",
"function",
"in",
"order",
"to",
"conduct",
"an",
"experiment",
"when",
"called",
"."
] | python | train | 35.615385 |
ktbyers/netmiko | netmiko/paloalto/paloalto_panos.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/paloalto/paloalto_panos.py#L164-L167 | def send_command(self, *args, **kwargs):
"""Palo Alto requires an extra delay"""
kwargs["delay_factor"] = kwargs.get("delay_factor", 2.5)
return super(PaloAltoPanosBase, self).send_command(*args, **kwargs) | [
"def",
"send_command",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"delay_factor\"",
"]",
"=",
"kwargs",
".",
"get",
"(",
"\"delay_factor\"",
",",
"2.5",
")",
"return",
"super",
"(",
"PaloAltoPanosBase",
",",
"self"... | Palo Alto requires an extra delay | [
"Palo",
"Alto",
"requires",
"an",
"extra",
"delay"
] | python | train | 56.5 |
SpriteLink/NIPAP | nipap-www/nipapwww/controllers/pool.py | https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap-www/nipapwww/controllers/pool.py#L52-L79 | def edit(self, id):
""" Edit a pool.
"""
c.pool = Pool.get(int(id))
c.prefix_list = Prefix.list({ 'pool_id': c.pool.id })
c.prefix = ''
# save changes to NIPAP
if request.method == 'POST':
c.pool.name = request.params['name']
c.pool.descr... | [
"def",
"edit",
"(",
"self",
",",
"id",
")",
":",
"c",
".",
"pool",
"=",
"Pool",
".",
"get",
"(",
"int",
"(",
"id",
")",
")",
"c",
".",
"prefix_list",
"=",
"Prefix",
".",
"list",
"(",
"{",
"'pool_id'",
":",
"c",
".",
"pool",
".",
"id",
"}",
... | Edit a pool. | [
"Edit",
"a",
"pool",
"."
] | python | train | 39.107143 |
atlassian-api/atlassian-python-api | atlassian/service_desk.py | https://github.com/atlassian-api/atlassian-python-api/blob/540d269905c3e7547b666fe30c647b2d512cf358/atlassian/service_desk.py#L395-L413 | def add_attachment(self, issue_id_or_key, temp_attachment_id, public=True, comment=None):
"""
Adds temporary attachment that were created using attach_temporary_file function to a customer request
:param issue_id_or_key: str
:param temp_attachment_id: str, ID from result attach_temporar... | [
"def",
"add_attachment",
"(",
"self",
",",
"issue_id_or_key",
",",
"temp_attachment_id",
",",
"public",
"=",
"True",
",",
"comment",
"=",
"None",
")",
":",
"log",
".",
"warning",
"(",
"'Adding attachment'",
")",
"data",
"=",
"{",
"'temporaryAttachmentIds'",
":... | Adds temporary attachment that were created using attach_temporary_file function to a customer request
:param issue_id_or_key: str
:param temp_attachment_id: str, ID from result attach_temporary_file function
:param public: bool (default is True)
:param comment: str (default is None)
... | [
"Adds",
"temporary",
"attachment",
"that",
"were",
"created",
"using",
"attach_temporary_file",
"function",
"to",
"a",
"customer",
"request"
] | python | train | 42.421053 |
tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L810-L833 | def combine(self, expert_out, multiply_by_gates=True):
"""Sum together the expert output, weighted by the gates.
The slice corresponding to a particular batch element `b` is computed
as the sum over all experts `i` of the expert output, weighted by the
corresponding gate values. If `multiply_by_gates`... | [
"def",
"combine",
"(",
"self",
",",
"expert_out",
",",
"multiply_by_gates",
"=",
"True",
")",
":",
"# see comments on convert_gradient_to_tensor",
"stitched",
"=",
"common_layers",
".",
"convert_gradient_to_tensor",
"(",
"tf",
".",
"concat",
"(",
"expert_out",
",",
... | Sum together the expert output, weighted by the gates.
The slice corresponding to a particular batch element `b` is computed
as the sum over all experts `i` of the expert output, weighted by the
corresponding gate values. If `multiply_by_gates` is set to False, the
gate values are ignored.
Args:
... | [
"Sum",
"together",
"the",
"expert",
"output",
"weighted",
"by",
"the",
"gates",
"."
] | python | train | 40.791667 |
lvieirajr/mongorest | mongorest/collection.py | https://github.com/lvieirajr/mongorest/blob/00f4487ded33254434bc51ff09d48c7a936bd465/mongorest/collection.py#L307-L312 | def update_one(cls, filter, update, upsert=False):
"""
Updates a document that passes the filter with the update value
Will upsert a new document if upsert=True and no document is filtered
"""
return cls.collection.update_one(filter, update, upsert).raw_result | [
"def",
"update_one",
"(",
"cls",
",",
"filter",
",",
"update",
",",
"upsert",
"=",
"False",
")",
":",
"return",
"cls",
".",
"collection",
".",
"update_one",
"(",
"filter",
",",
"update",
",",
"upsert",
")",
".",
"raw_result"
] | Updates a document that passes the filter with the update value
Will upsert a new document if upsert=True and no document is filtered | [
"Updates",
"a",
"document",
"that",
"passes",
"the",
"filter",
"with",
"the",
"update",
"value",
"Will",
"upsert",
"a",
"new",
"document",
"if",
"upsert",
"=",
"True",
"and",
"no",
"document",
"is",
"filtered"
] | python | train | 49.166667 |
mlperf/training | reinforcement/tensorflow/minigo/oneoffs/heatmap.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/heatmap.py#L45-L85 | def eval_policy(eval_positions):
"""Evaluate all positions with all models save the policy heatmaps as CSVs
CSV name is "heatmap-<position_name>-<model-index>.csv"
CSV format is: model number, value network output, policy network outputs
position_name is taken from the SGF file
Policy network outp... | [
"def",
"eval_policy",
"(",
"eval_positions",
")",
":",
"model_paths",
"=",
"oneoff_utils",
".",
"get_model_paths",
"(",
"fsdb",
".",
"models_dir",
"(",
")",
")",
"idx_start",
"=",
"FLAGS",
".",
"idx_start",
"eval_every",
"=",
"FLAGS",
".",
"eval_every",
"print... | Evaluate all positions with all models save the policy heatmaps as CSVs
CSV name is "heatmap-<position_name>-<model-index>.csv"
CSV format is: model number, value network output, policy network outputs
position_name is taken from the SGF file
Policy network outputs (19x19) are saved in flat order (see... | [
"Evaluate",
"all",
"positions",
"with",
"all",
"models",
"save",
"the",
"policy",
"heatmaps",
"as",
"CSVs"
] | python | train | 37.097561 |
gmr/rejected | rejected/mcp.py | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L616-L626 | def setup_consumers(self):
"""Iterate through each consumer in the configuration and kick off the
minimal amount of processes, setting up the runtime data as well.
"""
if not self.consumer_cfg:
LOGGER.warning('No consumers are configured')
for name in self.consumer_c... | [
"def",
"setup_consumers",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"consumer_cfg",
":",
"LOGGER",
".",
"warning",
"(",
"'No consumers are configured'",
")",
"for",
"name",
"in",
"self",
".",
"consumer_cfg",
".",
"keys",
"(",
")",
":",
"self",
".",
... | Iterate through each consumer in the configuration and kick off the
minimal amount of processes, setting up the runtime data as well. | [
"Iterate",
"through",
"each",
"consumer",
"in",
"the",
"configuration",
"and",
"kick",
"off",
"the",
"minimal",
"amount",
"of",
"processes",
"setting",
"up",
"the",
"runtime",
"data",
"as",
"well",
"."
] | python | train | 44.181818 |
CLARIAH/grlc | src/gquery.py | https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/gquery.py#L196-L209 | def get_enumeration(rq, v, endpoint, metadata={}, auth=None):
"""
Returns a list of enumerated values for variable 'v' in query 'rq'
"""
# glogger.debug("Metadata before processing enums: {}".format(metadata))
# We only fire the enum filling queries if indicated by the query metadata
if 'enumera... | [
"def",
"get_enumeration",
"(",
"rq",
",",
"v",
",",
"endpoint",
",",
"metadata",
"=",
"{",
"}",
",",
"auth",
"=",
"None",
")",
":",
"# glogger.debug(\"Metadata before processing enums: {}\".format(metadata))",
"# We only fire the enum filling queries if indicated by the query... | Returns a list of enumerated values for variable 'v' in query 'rq' | [
"Returns",
"a",
"list",
"of",
"enumerated",
"values",
"for",
"variable",
"v",
"in",
"query",
"rq"
] | python | train | 40 |
uploadcare/pyuploadcare | pyuploadcare/api_resources.py | https://github.com/uploadcare/pyuploadcare/blob/cefddc0306133a71e37b18e8700df5948ef49b37/pyuploadcare/api_resources.py#L361-L391 | def upload(cls, file_obj, store=None):
"""Uploads a file and returns ``File`` instance.
Args:
- file_obj: file object to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to None.
- False - do not st... | [
"def",
"upload",
"(",
"cls",
",",
"file_obj",
",",
"store",
"=",
"None",
")",
":",
"if",
"store",
"is",
"None",
":",
"store",
"=",
"'auto'",
"elif",
"store",
":",
"store",
"=",
"'1'",
"else",
":",
"store",
"=",
"'0'",
"data",
"=",
"{",
"'UPLOADCARE... | Uploads a file and returns ``File`` instance.
Args:
- file_obj: file object to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to None.
- False - do not store file
- True - store file (can ... | [
"Uploads",
"a",
"file",
"and",
"returns",
"File",
"instance",
"."
] | python | test | 29.419355 |
appknox/google-chartwrapper | GChartWrapper/GChart.py | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L331-L341 | def line(self, *args):
"""
Called one at a time for each dataset
args are of the form::
<data set n line thickness>,
<length of line segment>,
<length of blank segment>
APIPARAM: chls
"""
self.lines.append(','.join(['%.1f'%x for x in ma... | [
"def",
"line",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"lines",
".",
"append",
"(",
"','",
".",
"join",
"(",
"[",
"'%.1f'",
"%",
"x",
"for",
"x",
"in",
"map",
"(",
"float",
",",
"args",
")",
"]",
")",
")",
"return",
"self"
] | Called one at a time for each dataset
args are of the form::
<data set n line thickness>,
<length of line segment>,
<length of blank segment>
APIPARAM: chls | [
"Called",
"one",
"at",
"a",
"time",
"for",
"each",
"dataset",
"args",
"are",
"of",
"the",
"form",
"::",
"<data",
"set",
"n",
"line",
"thickness",
">",
"<length",
"of",
"line",
"segment",
">",
"<length",
"of",
"blank",
"segment",
">",
"APIPARAM",
":",
"... | python | test | 31.454545 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.