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 |
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/modules/capirca_acl.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L419-L427 | def _cleanup(lst):
'''
Return a list of non-empty dictionaries.
'''
clean = []
for ele in lst:
if ele and isinstance(ele, dict):
clean.append(ele)
return clean | [
"def",
"_cleanup",
"(",
"lst",
")",
":",
"clean",
"=",
"[",
"]",
"for",
"ele",
"in",
"lst",
":",
"if",
"ele",
"and",
"isinstance",
"(",
"ele",
",",
"dict",
")",
":",
"clean",
".",
"append",
"(",
"ele",
")",
"return",
"clean"
] | Return a list of non-empty dictionaries. | [
"Return",
"a",
"list",
"of",
"non",
"-",
"empty",
"dictionaries",
"."
] | python | train | 21.666667 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/core/prompts.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prompts.py#L407-L439 | def render(self, name, color=True, just=None, **kwargs):
"""
Render the selected prompt.
Parameters
----------
name : str
Which prompt to render. One of 'in', 'in2', 'out', 'rewrite'
color : bool
If True (default), include ANSI escape sequence... | [
"def",
"render",
"(",
"self",
",",
"name",
",",
"color",
"=",
"True",
",",
"just",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"self",
".",
"_render",
"(",
"name",
",",
"color",
"=",
"color",
",",
"*",
"*",
"kwargs",
")",
"# Han... | Render the selected prompt.
Parameters
----------
name : str
Which prompt to render. One of 'in', 'in2', 'out', 'rewrite'
color : bool
If True (default), include ANSI escape sequences for a coloured prompt.
just : bool
If True, justify the p... | [
"Render",
"the",
"selected",
"prompt",
".",
"Parameters",
"----------",
"name",
":",
"str",
"Which",
"prompt",
"to",
"render",
".",
"One",
"of",
"in",
"in2",
"out",
"rewrite",
"color",
":",
"bool",
"If",
"True",
"(",
"default",
")",
"include",
"ANSI",
"e... | python | test | 39.757576 |
andrefsp/pyflot | flot/__init__.py | https://github.com/andrefsp/pyflot/blob/f2dde10709aeed39074fcce8172184b5cd8bfd66/flot/__init__.py#L168-L186 | def _set_data(self):
"""
This method will be called to set Series data
"""
if getattr(self, 'data', False) and not getattr(self, '_x', False) and not getattr(self, '_y', False):
_x = XVariable()
_y = YVariable()
_x.contribute_to_class(self, 'X', self.d... | [
"def",
"_set_data",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'data'",
",",
"False",
")",
"and",
"not",
"getattr",
"(",
"self",
",",
"'_x'",
",",
"False",
")",
"and",
"not",
"getattr",
"(",
"self",
",",
"'_y'",
",",
"False",
")",
... | This method will be called to set Series data | [
"This",
"method",
"will",
"be",
"called",
"to",
"set",
"Series",
"data"
] | python | test | 43.473684 |
Netflix-Skunkworks/swag-client | swag_client/cli.py | https://github.com/Netflix-Skunkworks/swag-client/blob/e43816a85c4f48011cf497a4eae14f9df71fee0f/swag_client/cli.py#L296-L339 | def seed_aws_organization(ctx, owner):
"""Seeds SWAG from an AWS organziation."""
swag = create_swag_from_ctx(ctx)
accounts = swag.get_all()
_ids = [result.get('id') for result in accounts]
client = boto3.client('organizations')
paginator = client.get_paginator('list_accounts')
response_ite... | [
"def",
"seed_aws_organization",
"(",
"ctx",
",",
"owner",
")",
":",
"swag",
"=",
"create_swag_from_ctx",
"(",
"ctx",
")",
"accounts",
"=",
"swag",
".",
"get_all",
"(",
")",
"_ids",
"=",
"[",
"result",
".",
"get",
"(",
"'id'",
")",
"for",
"result",
"in"... | Seeds SWAG from an AWS organziation. | [
"Seeds",
"SWAG",
"from",
"an",
"AWS",
"organziation",
"."
] | python | train | 33.886364 |
googlemaps/google-maps-services-python | googlemaps/timezone.py | https://github.com/googlemaps/google-maps-services-python/blob/7ed40b4d8df63479794c46ce29d03ed6083071d7/googlemaps/timezone.py#L25-L54 | def timezone(client, location, timestamp=None, language=None):
"""Get time zone for a location on the earth, as well as that location's
time offset from UTC.
:param location: The latitude/longitude value representing the location to
look up.
:type location: string, dict, list, or tuple
:pa... | [
"def",
"timezone",
"(",
"client",
",",
"location",
",",
"timestamp",
"=",
"None",
",",
"language",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"location\"",
":",
"convert",
".",
"latlng",
"(",
"location",
")",
",",
"\"timestamp\"",
":",
"convert",
".",
... | Get time zone for a location on the earth, as well as that location's
time offset from UTC.
:param location: The latitude/longitude value representing the location to
look up.
:type location: string, dict, list, or tuple
:param timestamp: Timestamp specifies the desired time as seconds since
... | [
"Get",
"time",
"zone",
"for",
"a",
"location",
"on",
"the",
"earth",
"as",
"well",
"as",
"that",
"location",
"s",
"time",
"offset",
"from",
"UTC",
"."
] | python | train | 34.633333 |
SmokinCaterpillar/pypet | examples/example_24_large_scale_brian2_simulation/clusternet.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L820-L864 | def analyse(self, traj, network, current_subrun, subrun_list, network_dict):
"""Extracts monitor data and plots.
Data extraction is done if all subruns have been completed,
i.e. `len(subrun_list)==0`
First, extracts results from the monitors and stores them into `traj`.
Next, ... | [
"def",
"analyse",
"(",
"self",
",",
"traj",
",",
"network",
",",
"current_subrun",
",",
"subrun_list",
",",
"network_dict",
")",
":",
"if",
"len",
"(",
"subrun_list",
")",
"==",
"0",
":",
"traj",
".",
"f_add_result",
"(",
"Brian2MonitorResult",
",",
"'moni... | Extracts monitor data and plots.
Data extraction is done if all subruns have been completed,
i.e. `len(subrun_list)==0`
First, extracts results from the monitors and stores them into `traj`.
Next, uses the extracted data for plots.
:param traj:
Trajectory contain... | [
"Extracts",
"monitor",
"data",
"and",
"plots",
"."
] | python | test | 33.666667 |
pyhys/minimalmodbus | omegacn7500.py | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L464-L477 | def _checkSetpointValue( setpointvalue, maxvalue ):
"""Check that the given setpointvalue is valid.
Args:
* setpointvalue (numerical): The setpoint value to be checked. Must be positive.
* maxvalue (numerical): Upper limit for setpoint value. Must be positive.
Raises:
... | [
"def",
"_checkSetpointValue",
"(",
"setpointvalue",
",",
"maxvalue",
")",
":",
"if",
"maxvalue",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'The maxvalue (for the setpoint) must not be None!'",
")",
"minimalmodbus",
".",
"_checkNumerical",
"(",
"setpointvalue",
",",... | Check that the given setpointvalue is valid.
Args:
* setpointvalue (numerical): The setpoint value to be checked. Must be positive.
* maxvalue (numerical): Upper limit for setpoint value. Must be positive.
Raises:
TypeError, ValueError | [
"Check",
"that",
"the",
"given",
"setpointvalue",
"is",
"valid",
".",
"Args",
":",
"*",
"setpointvalue",
"(",
"numerical",
")",
":",
"The",
"setpoint",
"value",
"to",
"be",
"checked",
".",
"Must",
"be",
"positive",
".",
"*",
"maxvalue",
"(",
"numerical",
... | python | train | 39.642857 |
inveniosoftware/invenio-theme | invenio_theme/ext.py | https://github.com/inveniosoftware/invenio-theme/blob/4e07607b1a40805df1d8e4ab9cc2afd728579ca9/invenio_theme/ext.py#L76-L97 | def init_config(self, app):
"""Initialize configuration.
:param app: An instance of :class:`~flask.Flask`.
"""
_vars = ['BASE_TEMPLATE', 'COVER_TEMPLATE', 'SETTINGS_TEMPLATE']
# Sets RequireJS config and SASS binary as well if not already set.
for k in dir(config):
... | [
"def",
"init_config",
"(",
"self",
",",
"app",
")",
":",
"_vars",
"=",
"[",
"'BASE_TEMPLATE'",
",",
"'COVER_TEMPLATE'",
",",
"'SETTINGS_TEMPLATE'",
"]",
"# Sets RequireJS config and SASS binary as well if not already set.",
"for",
"k",
"in",
"dir",
"(",
"config",
")",... | Initialize configuration.
:param app: An instance of :class:`~flask.Flask`. | [
"Initialize",
"configuration",
"."
] | python | train | 38.909091 |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/pympler/garbagegraph.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/garbagegraph.py#L47-L61 | def print_stats(self, stream=None):
"""
Log annotated garbage objects to console or file.
:param stream: open file, uses sys.stdout if not given
"""
if not stream: # pragma: no cover
stream = sys.stdout
self.metadata.sort(key=lambda x: -x.size)
stream... | [
"def",
"print_stats",
"(",
"self",
",",
"stream",
"=",
"None",
")",
":",
"if",
"not",
"stream",
":",
"# pragma: no cover",
"stream",
"=",
"sys",
".",
"stdout",
"self",
".",
"metadata",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"-",
"x",
".",
... | Log annotated garbage objects to console or file.
:param stream: open file, uses sys.stdout if not given | [
"Log",
"annotated",
"garbage",
"objects",
"to",
"console",
"or",
"file",
"."
] | python | train | 45.666667 |
saltstack/salt | salt/modules/saltsupport.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltsupport.py#L169-L193 | def delete_archives(self, *archives):
'''
Delete archives
:return:
'''
# Remove paths
_archives = []
for archive in archives:
_archives.append(os.path.basename(archive))
archives = _archives[:]
ret = {'files': {}, 'errors': {}}
... | [
"def",
"delete_archives",
"(",
"self",
",",
"*",
"archives",
")",
":",
"# Remove paths",
"_archives",
"=",
"[",
"]",
"for",
"archive",
"in",
"archives",
":",
"_archives",
".",
"append",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"archive",
")",
")",
... | Delete archives
:return: | [
"Delete",
"archives",
":",
"return",
":"
] | python | train | 33 |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/derived_boxes.py | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/derived_boxes.py#L319-L362 | def multenterbox(msg="Fill in values for the fields.", title=" ",
fields=(), values=()):
r"""
Show screen with multiple data entry fields.
If there are fewer values than names, the list of values is padded with
empty strings until the number of values is the same as the number
of n... | [
"def",
"multenterbox",
"(",
"msg",
"=",
"\"Fill in values for the fields.\"",
",",
"title",
"=",
"\" \"",
",",
"fields",
"=",
"(",
")",
",",
"values",
"=",
"(",
")",
")",
":",
"return",
"bb",
".",
"__multfillablebox",
"(",
"msg",
",",
"title",
",",
"fiel... | r"""
Show screen with multiple data entry fields.
If there are fewer values than names, the list of values is padded with
empty strings until the number of values is the same as the number
of names.
If there are more values than names, the list of values
is truncated so that there are as many ... | [
"r",
"Show",
"screen",
"with",
"multiple",
"data",
"entry",
"fields",
"."
] | python | train | 38.954545 |
rwl/pylon | pyreto/roth_erev.py | https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/roth_erev.py#L254-L267 | def _forwardImplementation(self, inbuf, outbuf):
""" Proportional probability method.
"""
assert self.module
propensities = self.module.getActionValues(0)
summedProps = sum(propensities)
probabilities = propensities / summedProps
action = eventGenerator(probabi... | [
"def",
"_forwardImplementation",
"(",
"self",
",",
"inbuf",
",",
"outbuf",
")",
":",
"assert",
"self",
".",
"module",
"propensities",
"=",
"self",
".",
"module",
".",
"getActionValues",
"(",
"0",
")",
"summedProps",
"=",
"sum",
"(",
"propensities",
")",
"p... | Proportional probability method. | [
"Proportional",
"probability",
"method",
"."
] | python | train | 28.571429 |
saltstack/salt | salt/modules/http.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/http.py#L17-L44 | def query(url, **kwargs):
'''
Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
.. autofunction:: salt.utils.http.query
CLI Example:
.. code-block:: bash
salt '*' http.que... | [
"def",
"query",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"opts",
"=",
"__opts__",
".",
"copy",
"(",
")",
"if",
"'opts'",
"in",
"kwargs",
":",
"opts",
".",
"update",
"(",
"kwargs",
"[",
"'opts'",
"]",
")",
"del",
"kwargs",
"[",
"'opts'",
"]"... | Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
.. autofunction:: salt.utils.http.query
CLI Example:
.. code-block:: bash
salt '*' http.query http://somelink.com/
salt '... | [
"Query",
"a",
"resource",
"and",
"decode",
"the",
"return",
"data"
] | python | train | 29.5 |
ggaughan/pipe2py | pipe2py/modules/pipesubelement.py | https://github.com/ggaughan/pipe2py/blob/4767d6d1fd354d2a35e6528594b8deb8a033eed4/pipe2py/modules/pipesubelement.py#L14-L38 | def pipe_subelement(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator extracts select sub-elements from a feed. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : pipe2py.modules pipe like object (iterable of items)
conf : {'path': {'value': <element pat... | [
"def",
"pipe_subelement",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"DotDict",
"(",
"conf",
")",
".",
"get",
"(",
"'path'",
",",
"*",
"*",
"kwargs",
")",
"fo... | An operator extracts select sub-elements from a feed. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : pipe2py.modules pipe like object (iterable of items)
conf : {'path': {'value': <element path>}}
Yields
------
_OUTPUT : items | [
"An",
"operator",
"extracts",
"select",
"sub",
"-",
"elements",
"from",
"a",
"feed",
".",
"Not",
"loopable",
"."
] | python | train | 28 |
ellmetha/django-machina | machina/apps/forum_permission/handler.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L254-L258 | def get_target_forums_for_moved_topics(self, user):
""" Returns a list of forums in which the considered user can add topics that have been
moved from another forum.
"""
return [f for f in self._get_forums_for_user(user, ['can_move_topics', ]) if f.is_forum] | [
"def",
"get_target_forums_for_moved_topics",
"(",
"self",
",",
"user",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"self",
".",
"_get_forums_for_user",
"(",
"user",
",",
"[",
"'can_move_topics'",
",",
"]",
")",
"if",
"f",
".",
"is_forum",
"]"
] | Returns a list of forums in which the considered user can add topics that have been
moved from another forum. | [
"Returns",
"a",
"list",
"of",
"forums",
"in",
"which",
"the",
"considered",
"user",
"can",
"add",
"topics",
"that",
"have",
"been",
"moved",
"from",
"another",
"forum",
"."
] | python | train | 58 |
blazelibs/blazeutils | blazeutils/importing.py | https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/importing.py#L57-L75 | def import_split(import_name):
""" takes a dotted string path and returns the components:
import_split('path') == 'path', None, None
import_split('path.part.object') == 'path.part', 'object', None
import_split('path.part:object') == 'path.part', 'object', None
import_split('path.part... | [
"def",
"import_split",
"(",
"import_name",
")",
":",
"obj",
"=",
"None",
"attr",
"=",
"None",
"if",
"':'",
"in",
"import_name",
":",
"module",
",",
"obj",
"=",
"import_name",
".",
"split",
"(",
"':'",
",",
"1",
")",
"if",
"'.'",
"in",
"obj",
":",
"... | takes a dotted string path and returns the components:
import_split('path') == 'path', None, None
import_split('path.part.object') == 'path.part', 'object', None
import_split('path.part:object') == 'path.part', 'object', None
import_split('path.part:object.attribute')
== 'pat... | [
"takes",
"a",
"dotted",
"string",
"path",
"and",
"returns",
"the",
"components",
":",
"import_split",
"(",
"path",
")",
"==",
"path",
"None",
"None",
"import_split",
"(",
"path",
".",
"part",
".",
"object",
")",
"==",
"path",
".",
"part",
"object",
"None... | python | train | 36.684211 |
casacore/python-casacore | casacore/tables/tableutil.py | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tableutil.py#L244-L313 | def makescacoldesc(columnname, value,
datamanagertype='',
datamanagergroup='',
options=0, maxlen=0, comment='',
valuetype='', keywords={}):
"""Create description of a scalar column.
A description for a scalar column can be created from... | [
"def",
"makescacoldesc",
"(",
"columnname",
",",
"value",
",",
"datamanagertype",
"=",
"''",
",",
"datamanagergroup",
"=",
"''",
",",
"options",
"=",
"0",
",",
"maxlen",
"=",
"0",
",",
"comment",
"=",
"''",
",",
"valuetype",
"=",
"''",
",",
"keywords",
... | Create description of a scalar column.
A description for a scalar column can be created from a name for
the column and a data value, which is used only to determine the
type of the column. Note that a dict value is also possible.
It is possible to create the column description in more detail
by gi... | [
"Create",
"description",
"of",
"a",
"scalar",
"column",
"."
] | python | train | 38.628571 |
PyCQA/astroid | astroid/node_classes.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L2735-L2754 | def from_elements(cls, items=None):
"""Create a :class:`Dict` of constants from a live dictionary.
:param items: The items to store in the node.
:type items: dict
:returns: The created dictionary node.
:rtype: Dict
"""
node = cls()
if items is None:
... | [
"def",
"from_elements",
"(",
"cls",
",",
"items",
"=",
"None",
")",
":",
"node",
"=",
"cls",
"(",
")",
"if",
"items",
"is",
"None",
":",
"node",
".",
"items",
"=",
"[",
"]",
"else",
":",
"node",
".",
"items",
"=",
"[",
"(",
"const_factory",
"(",
... | Create a :class:`Dict` of constants from a live dictionary.
:param items: The items to store in the node.
:type items: dict
:returns: The created dictionary node.
:rtype: Dict | [
"Create",
"a",
":",
"class",
":",
"Dict",
"of",
"constants",
"from",
"a",
"live",
"dictionary",
"."
] | python | train | 29.85 |
pandas-dev/pandas | pandas/core/arrays/timedeltas.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/timedeltas.py#L819-L845 | def components(self):
"""
Return a dataframe of the components (days, hours, minutes,
seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.
Returns
-------
a DataFrame
"""
from pandas import DataFrame
columns = ['days', 'hours', 'm... | [
"def",
"components",
"(",
"self",
")",
":",
"from",
"pandas",
"import",
"DataFrame",
"columns",
"=",
"[",
"'days'",
",",
"'hours'",
",",
"'minutes'",
",",
"'seconds'",
",",
"'milliseconds'",
",",
"'microseconds'",
",",
"'nanoseconds'",
"]",
"hasnans",
"=",
"... | Return a dataframe of the components (days, hours, minutes,
seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.
Returns
-------
a DataFrame | [
"Return",
"a",
"dataframe",
"of",
"the",
"components",
"(",
"days",
"hours",
"minutes",
"seconds",
"milliseconds",
"microseconds",
"nanoseconds",
")",
"of",
"the",
"Timedeltas",
"."
] | python | train | 29.518519 |
pandas-dev/pandas | pandas/core/series.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/series.py#L1870-L1938 | def idxmin(self, axis=0, skipna=True, *args, **kwargs):
"""
Return the row label of the minimum value.
If multiple values equal the minimum, the first row label with that
value is returned.
Parameters
----------
skipna : bool, default True
Exclude NA... | [
"def",
"idxmin",
"(",
"self",
",",
"axis",
"=",
"0",
",",
"skipna",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"skipna",
"=",
"nv",
".",
"validate_argmin_with_skipna",
"(",
"skipna",
",",
"args",
",",
"kwargs",
")",
"i",
"=",... | Return the row label of the minimum value.
If multiple values equal the minimum, the first row label with that
value is returned.
Parameters
----------
skipna : bool, default True
Exclude NA/null values. If the entire Series is NA, the result
will be NA.... | [
"Return",
"the",
"row",
"label",
"of",
"the",
"minimum",
"value",
"."
] | python | train | 29.318841 |
cloudendpoints/endpoints-python | endpoints/api_config.py | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1438-L1503 | def __field_to_subfields(self, field):
"""Fully describes data represented by field, including the nested case.
In the case that the field is not a message field, we have no fields nested
within a message definition, so we can simply return that field. However, in
the nested case, we can't simply descr... | [
"def",
"__field_to_subfields",
"(",
"self",
",",
"field",
")",
":",
"# Termination condition",
"if",
"not",
"isinstance",
"(",
"field",
",",
"messages",
".",
"MessageField",
")",
":",
"return",
"[",
"[",
"field",
"]",
"]",
"result",
"=",
"[",
"]",
"for",
... | Fully describes data represented by field, including the nested case.
In the case that the field is not a message field, we have no fields nested
within a message definition, so we can simply return that field. However, in
the nested case, we can't simply describe the data with one field or even
with o... | [
"Fully",
"describes",
"data",
"represented",
"by",
"field",
"including",
"the",
"nested",
"case",
"."
] | python | train | 32.727273 |
basecrm/basecrm-python | basecrm/services.py | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1969-L1982 | def list(self, **params):
"""
Retrieve text messages
Returns Text Messages, according to the parameters provided
:calls: ``get /text_messages``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which repres... | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"text_messages",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/text_messages\"",
",",
"params",
"=",
"params",
")",
"return",
"text_messages"
] | Retrieve text messages
Returns Text Messages, according to the parameters provided
:calls: ``get /text_messages``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of TextMessages.
:rtype... | [
"Retrieve",
"text",
"messages"
] | python | train | 34.642857 |
nion-software/nionswift | nion/swift/Facade.py | https://github.com/nion-software/nionswift/blob/d43693eaf057b8683b9638e575000f055fede452/nion/swift/Facade.py#L1241-L1255 | def add_point_region(self, y: float, x: float) -> Graphic:
"""Add a point graphic to the data item.
:param x: The x coordinate, in relative units [0.0, 1.0]
:param y: The y coordinate, in relative units [0.0, 1.0]
:return: The :py:class:`nion.swift.Facade.Graphic` object that was added.... | [
"def",
"add_point_region",
"(",
"self",
",",
"y",
":",
"float",
",",
"x",
":",
"float",
")",
"->",
"Graphic",
":",
"graphic",
"=",
"Graphics",
".",
"PointGraphic",
"(",
")",
"graphic",
".",
"position",
"=",
"Geometry",
".",
"FloatPoint",
"(",
"y",
",",... | Add a point graphic to the data item.
:param x: The x coordinate, in relative units [0.0, 1.0]
:param y: The y coordinate, in relative units [0.0, 1.0]
:return: The :py:class:`nion.swift.Facade.Graphic` object that was added.
.. versionadded:: 1.0
Scriptable: Yes | [
"Add",
"a",
"point",
"graphic",
"to",
"the",
"data",
"item",
"."
] | python | train | 36.666667 |
pymupdf/PyMuPDF | fitz/fitz.py | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1518-L1549 | def getTJstr(text, glyphs, simple, ordering):
""" Return a PDF string enclosed in [] brackets, suitable for the PDF TJ
operator.
Notes:
The input string is converted to either 2 or 4 hex digits per character.
Args:
simple: no glyphs: 2-chars, use char codes as the glyph
... | [
"def",
"getTJstr",
"(",
"text",
",",
"glyphs",
",",
"simple",
",",
"ordering",
")",
":",
"if",
"text",
".",
"startswith",
"(",
"\"[<\"",
")",
"and",
"text",
".",
"endswith",
"(",
"\">]\"",
")",
":",
"# already done",
"return",
"text",
"if",
"not",
"boo... | Return a PDF string enclosed in [] brackets, suitable for the PDF TJ
operator.
Notes:
The input string is converted to either 2 or 4 hex digits per character.
Args:
simple: no glyphs: 2-chars, use char codes as the glyph
glyphs: 2-chars, use glyphs instead of char codes (Sym... | [
"Return",
"a",
"PDF",
"string",
"enclosed",
"in",
"[]",
"brackets",
"suitable",
"for",
"the",
"PDF",
"TJ",
"operator",
"."
] | python | train | 43.46875 |
peterbrittain/asciimatics | asciimatics/widgets.py | https://github.com/peterbrittain/asciimatics/blob/f471427d7786ce2d5f1eeb2dae0e67d19e46e085/asciimatics/widgets.py#L3142-L3151 | def clone(self, screen, scene):
"""
Create a clone of this Dialog into a new Screen.
:param screen: The new Screen object to clone into.
:param scene: The new Scene object to clone into.
"""
# Only clone the object if the function is safe to do so.
if self._on_cl... | [
"def",
"clone",
"(",
"self",
",",
"screen",
",",
"scene",
")",
":",
"# Only clone the object if the function is safe to do so.",
"if",
"self",
".",
"_on_close",
"is",
"None",
"or",
"isfunction",
"(",
"self",
".",
"_on_close",
")",
":",
"scene",
".",
"add_effect"... | Create a clone of this Dialog into a new Screen.
:param screen: The new Screen object to clone into.
:param scene: The new Scene object to clone into. | [
"Create",
"a",
"clone",
"of",
"this",
"Dialog",
"into",
"a",
"new",
"Screen",
"."
] | python | train | 44.6 |
guaix-ucm/numina | numina/core/recipes.py | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/recipes.py#L183-L188 | def set_base_headers(self, hdr):
"""Set metadata in FITS headers."""
hdr['NUMXVER'] = (__version__, 'Numina package version')
hdr['NUMRNAM'] = (self.__class__.__name__, 'Numina recipe name')
hdr['NUMRVER'] = (self.__version__, 'Numina recipe version')
return hdr | [
"def",
"set_base_headers",
"(",
"self",
",",
"hdr",
")",
":",
"hdr",
"[",
"'NUMXVER'",
"]",
"=",
"(",
"__version__",
",",
"'Numina package version'",
")",
"hdr",
"[",
"'NUMRNAM'",
"]",
"=",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"'Numina reci... | Set metadata in FITS headers. | [
"Set",
"metadata",
"in",
"FITS",
"headers",
"."
] | python | train | 49.5 |
sixty-north/cosmic-ray | src/cosmic_ray/work_db.py | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/work_db.py#L118-L125 | def clear(self):
"""Clear all work items from the session.
This removes any associated results as well.
"""
with self._conn:
self._conn.execute('DELETE FROM results')
self._conn.execute('DELETE FROM work_items') | [
"def",
"clear",
"(",
"self",
")",
":",
"with",
"self",
".",
"_conn",
":",
"self",
".",
"_conn",
".",
"execute",
"(",
"'DELETE FROM results'",
")",
"self",
".",
"_conn",
".",
"execute",
"(",
"'DELETE FROM work_items'",
")"
] | Clear all work items from the session.
This removes any associated results as well. | [
"Clear",
"all",
"work",
"items",
"from",
"the",
"session",
"."
] | python | train | 32.625 |
thiagopbueno/pyrddl | pyrddl/parser.py | https://github.com/thiagopbueno/pyrddl/blob/3bcfa850b1a7532c7744358f3c6b9e0f8ab978c9/pyrddl/parser.py#L383-L389 | def p_intermfluent_def(self, p):
'''intermfluent_def : IDENT LPAREN param_list RPAREN COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI
| IDENT COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI'''
... | [
"def",
"p_intermfluent_def",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"16",
":",
"p",
"[",
"0",
"]",
"=",
"PVariable",
"(",
"name",
"=",
"p",
"[",
"1",
"]",
",",
"fluent_type",
"=",
"'interm-fluent'",
",",
"range_type",
... | intermfluent_def : IDENT LPAREN param_list RPAREN COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI
| IDENT COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI | [
"intermfluent_def",
":",
"IDENT",
"LPAREN",
"param_list",
"RPAREN",
"COLON",
"LCURLY",
"INTERMEDIATE",
"COMMA",
"type_spec",
"COMMA",
"LEVEL",
"ASSIGN_EQUAL",
"range_const",
"RCURLY",
"SEMI",
"|",
"IDENT",
"COLON",
"LCURLY",
"INTERMEDIATE",
"COMMA",
"type_spec",
"COMM... | python | train | 80.428571 |
GemHQ/round-py | round/client.py | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/client.py#L71-L106 | def authenticate_device(self, api_token, device_token, email=None,
user_url=None, override=False, fetch=True):
"""Set credentials for Device authentication.
Args:
api_token (str): Token issued to your Application through the Gem
Developer Console.
... | [
"def",
"authenticate_device",
"(",
"self",
",",
"api_token",
",",
"device_token",
",",
"email",
"=",
"None",
",",
"user_url",
"=",
"None",
",",
"override",
"=",
"False",
",",
"fetch",
"=",
"True",
")",
":",
"if",
"(",
"self",
".",
"context",
".",
"has_... | Set credentials for Device authentication.
Args:
api_token (str): Token issued to your Application through the Gem
Developer Console.
device_token (str): Physical device identifier. You will receive this
from a user.devices.create call or from users.create.
... | [
"Set",
"credentials",
"for",
"Device",
"authentication",
"."
] | python | train | 42.861111 |
urinieto/msaf | msaf/algorithms/sf/segmenter.py | https://github.com/urinieto/msaf/blob/9dbb57d77a1310465a65cc40f1641d083ca74385/msaf/algorithms/sf/segmenter.py#L83-L90 | def circular_shift(X):
"""Shifts circularly the X squre matrix in order to get a
time-lag matrix."""
N = X.shape[0]
L = np.zeros(X.shape)
for i in range(N):
L[i, :] = np.asarray([X[(i + j) % N, j] for j in range(N)])
return L | [
"def",
"circular_shift",
"(",
"X",
")",
":",
"N",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"L",
"=",
"np",
".",
"zeros",
"(",
"X",
".",
"shape",
")",
"for",
"i",
"in",
"range",
"(",
"N",
")",
":",
"L",
"[",
"i",
",",
":",
"]",
"=",
"np",
... | Shifts circularly the X squre matrix in order to get a
time-lag matrix. | [
"Shifts",
"circularly",
"the",
"X",
"squre",
"matrix",
"in",
"order",
"to",
"get",
"a",
"time",
"-",
"lag",
"matrix",
"."
] | python | test | 31.75 |
pgjones/quart | quart/app.py | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1123-L1143 | def after_serving(self, func: Callable) -> Callable:
"""Add a after serving function.
This will allow the function provided to be called once after
anything is served (after last byte is sent).
This is designed to be used as a decorator. An example usage,
.. code-block:: pytho... | [
"def",
"after_serving",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"handler",
"=",
"ensure_coroutine",
"(",
"func",
")",
"self",
".",
"after_serving_funcs",
".",
"append",
"(",
"handler",
")",
"return",
"func"
] | Add a after serving function.
This will allow the function provided to be called once after
anything is served (after last byte is sent).
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.after_serving
def func():
... | [
"Add",
"a",
"after",
"serving",
"function",
"."
] | python | train | 26.619048 |
gitpython-developers/smmap | smmap/util.py | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L229-L238 | def file_size(self):
""":return: size of file we manager"""
if self._file_size is None:
if isinstance(self._path_or_fd, string_types()):
self._file_size = os.stat(self._path_or_fd).st_size
else:
self._file_size = os.fstat(self._path_or_fd).st_size
... | [
"def",
"file_size",
"(",
"self",
")",
":",
"if",
"self",
".",
"_file_size",
"is",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"_path_or_fd",
",",
"string_types",
"(",
")",
")",
":",
"self",
".",
"_file_size",
"=",
"os",
".",
"stat",
"(",
"self... | :return: size of file we manager | [
":",
"return",
":",
"size",
"of",
"file",
"we",
"manager"
] | python | train | 40.7 |
pyviz/holoviews | holoviews/core/util.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/util.py#L1639-L1641 | def iterkeys(obj):
"Get key iterator from dictionary for Python 2 and 3"
return iter(obj.keys()) if sys.version_info.major == 3 else obj.iterkeys() | [
"def",
"iterkeys",
"(",
"obj",
")",
":",
"return",
"iter",
"(",
"obj",
".",
"keys",
"(",
")",
")",
"if",
"sys",
".",
"version_info",
".",
"major",
"==",
"3",
"else",
"obj",
".",
"iterkeys",
"(",
")"
] | Get key iterator from dictionary for Python 2 and 3 | [
"Get",
"key",
"iterator",
"from",
"dictionary",
"for",
"Python",
"2",
"and",
"3"
] | python | train | 51 |
iterative/dvc | dvc/analytics.py | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/analytics.py#L196-L206 | def dump(self):
"""Save analytics report to a temporary file.
Returns:
str: path to the temporary file that contains the analytics report.
"""
import tempfile
with tempfile.NamedTemporaryFile(delete=False, mode="w") as fobj:
json.dump(self.info, fobj)
... | [
"def",
"dump",
"(",
"self",
")",
":",
"import",
"tempfile",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
",",
"mode",
"=",
"\"w\"",
")",
"as",
"fobj",
":",
"json",
".",
"dump",
"(",
"self",
".",
"info",
",",
"fobj",
")"... | Save analytics report to a temporary file.
Returns:
str: path to the temporary file that contains the analytics report. | [
"Save",
"analytics",
"report",
"to",
"a",
"temporary",
"file",
"."
] | python | train | 30.545455 |
romanvm/python-web-pdb | web_pdb/web_console.py | https://github.com/romanvm/python-web-pdb/blob/f2df2207e870dbf50a4bb30ca12a59cab39a809f/web_pdb/web_console.py#L176-L184 | def flush(self):
"""
Wait until history is read but no more than 10 cycles
in case a browser session is closed.
"""
i = 0
while self._frame_data.is_dirty and i < 10:
i += 1
time.sleep(0.1) | [
"def",
"flush",
"(",
"self",
")",
":",
"i",
"=",
"0",
"while",
"self",
".",
"_frame_data",
".",
"is_dirty",
"and",
"i",
"<",
"10",
":",
"i",
"+=",
"1",
"time",
".",
"sleep",
"(",
"0.1",
")"
] | Wait until history is read but no more than 10 cycles
in case a browser session is closed. | [
"Wait",
"until",
"history",
"is",
"read",
"but",
"no",
"more",
"than",
"10",
"cycles",
"in",
"case",
"a",
"browser",
"session",
"is",
"closed",
"."
] | python | train | 28 |
tarbell-project/tarbell | tarbell/cli.py | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L671-L687 | def _clean_suffix(string, suffix):
"""
If string endswith the suffix, remove it. Else leave it alone.
"""
suffix_len = len(suffix)
if len(string) < suffix_len:
# the string param was shorter than the suffix
raise ValueError("A suffix can not be bigger than string argument.")
if ... | [
"def",
"_clean_suffix",
"(",
"string",
",",
"suffix",
")",
":",
"suffix_len",
"=",
"len",
"(",
"suffix",
")",
"if",
"len",
"(",
"string",
")",
"<",
"suffix_len",
":",
"# the string param was shorter than the suffix",
"raise",
"ValueError",
"(",
"\"A suffix can not... | If string endswith the suffix, remove it. Else leave it alone. | [
"If",
"string",
"endswith",
"the",
"suffix",
"remove",
"it",
".",
"Else",
"leave",
"it",
"alone",
"."
] | python | train | 31.352941 |
hyperledger/sawtooth-core | rest_api/sawtooth_rest_api/route_handlers.py | https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/rest_api/sawtooth_rest_api/route_handlers.py#L377-L407 | async def list_batches(self, request):
"""Fetches list of batches from validator, optionally filtered by id.
Request:
query:
- head: The id of the block to use as the head of the chain
- id: Comma separated list of batch ids to include in results
Res... | [
"async",
"def",
"list_batches",
"(",
"self",
",",
"request",
")",
":",
"paging_controls",
"=",
"self",
".",
"_get_paging_controls",
"(",
"request",
")",
"validator_query",
"=",
"client_batch_pb2",
".",
"ClientBatchListRequest",
"(",
"head_id",
"=",
"self",
".",
... | Fetches list of batches from validator, optionally filtered by id.
Request:
query:
- head: The id of the block to use as the head of the chain
- id: Comma separated list of batch ids to include in results
Response:
data: JSON array of fully expan... | [
"Fetches",
"list",
"of",
"batches",
"from",
"validator",
"optionally",
"filtered",
"by",
"id",
"."
] | python | train | 43.419355 |
etal/biofrills | biofrills/consensus.py | https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/consensus.py#L215-L261 | def supported(aln):
"""Get only the supported consensus residues in each column.
Meaning:
- Omit majority-gap columns
- Omit columns where no residue type appears more than once
- In case of a tie, return all the top-scoring residue types
(no prioritization)
Returns a *list* -- not a str... | [
"def",
"supported",
"(",
"aln",
")",
":",
"def",
"col_consensus",
"(",
"columns",
")",
":",
"\"\"\"Calculate the consensus chars for an iterable of columns.\"\"\"",
"for",
"col",
"in",
"columns",
":",
"if",
"(",
"# Majority gap chars",
"(",
"col",
".",
"count",
"(",... | Get only the supported consensus residues in each column.
Meaning:
- Omit majority-gap columns
- Omit columns where no residue type appears more than once
- In case of a tie, return all the top-scoring residue types
(no prioritization)
Returns a *list* -- not a string! -- where elements are ... | [
"Get",
"only",
"the",
"supported",
"consensus",
"residues",
"in",
"each",
"column",
"."
] | python | train | 41.021277 |
houluy/chessboard | chessboard/__init__.py | https://github.com/houluy/chessboard/blob/b834819d93d71b492f27780a58dfbb3a107d7e85/chessboard/__init__.py#L361-L367 | def get_not_num(self, seq, num=0):
'''Find the index of first non num element'''
ind = next((i for i, x in enumerate(seq) if x != num), None)
if ind == None:
return self.board_size
else:
return ind | [
"def",
"get_not_num",
"(",
"self",
",",
"seq",
",",
"num",
"=",
"0",
")",
":",
"ind",
"=",
"next",
"(",
"(",
"i",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"seq",
")",
"if",
"x",
"!=",
"num",
")",
",",
"None",
")",
"if",
"ind",
"==",
"N... | Find the index of first non num element | [
"Find",
"the",
"index",
"of",
"first",
"non",
"num",
"element"
] | python | train | 35.285714 |
pypa/setuptools | setuptools/msvc.py | https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/msvc.py#L971-L1013 | def OSLibpath(self):
"""
Microsoft Windows SDK Libraries Paths
"""
ref = os.path.join(self.si.WindowsSdkDir, 'References')
libpath = []
if self.vc_ver <= 9.0:
libpath += self.OSLibraries
if self.vc_ver >= 11.0:
libpath += [os.path.join(re... | [
"def",
"OSLibpath",
"(",
"self",
")",
":",
"ref",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"si",
".",
"WindowsSdkDir",
",",
"'References'",
")",
"libpath",
"=",
"[",
"]",
"if",
"self",
".",
"vc_ver",
"<=",
"9.0",
":",
"libpath",
"+=",... | Microsoft Windows SDK Libraries Paths | [
"Microsoft",
"Windows",
"SDK",
"Libraries",
"Paths"
] | python | train | 30.837209 |
zabertech/python-swampyer | swampyer/__init__.py | https://github.com/zabertech/python-swampyer/blob/31b040e7570455718709a496d6d9faacfb372a00/swampyer/__init__.py#L559-L566 | def start(self):
""" Initialize websockets, say hello, and start listening for events
"""
self.connect()
if not self.isAlive():
super(WAMPClient,self).start()
self.hello()
return self | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"connect",
"(",
")",
"if",
"not",
"self",
".",
"isAlive",
"(",
")",
":",
"super",
"(",
"WAMPClient",
",",
"self",
")",
".",
"start",
"(",
")",
"self",
".",
"hello",
"(",
")",
"return",
"self"
] | Initialize websockets, say hello, and start listening for events | [
"Initialize",
"websockets",
"say",
"hello",
"and",
"start",
"listening",
"for",
"events"
] | python | train | 29.5 |
NLeSC/noodles | noodles/prov/workflow.py | https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/prov/workflow.py#L20-L68 | def set_global_provenance(wf: Workflow, registry: Registry):
"""Compute a global provenance key for the entire workflow
before evaluation. This key can be used to store and retrieve
results in a database. The key computed in this stage is different
from the (local) provenance key that can be computed fo... | [
"def",
"set_global_provenance",
"(",
"wf",
":",
"Workflow",
",",
"registry",
":",
"Registry",
")",
":",
"stack",
"=",
"[",
"wf",
".",
"root",
"]",
"while",
"stack",
":",
"i",
"=",
"stack",
".",
"pop",
"(",
")",
"n",
"=",
"wf",
".",
"nodes",
"[",
... | Compute a global provenance key for the entire workflow
before evaluation. This key can be used to store and retrieve
results in a database. The key computed in this stage is different
from the (local) provenance key that can be computed for a node
if all its arguments are known.
In cases where a r... | [
"Compute",
"a",
"global",
"provenance",
"key",
"for",
"the",
"entire",
"workflow",
"before",
"evaluation",
".",
"This",
"key",
"can",
"be",
"used",
"to",
"store",
"and",
"retrieve",
"results",
"in",
"a",
"database",
".",
"The",
"key",
"computed",
"in",
"th... | python | train | 37.020408 |
rmorshea/spectate | spectate/mvc/base.py | https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/base.py#L137-L149 | def before(self, callback: Union[Callable, str]) -> "Control":
"""Register a control method that reacts before the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If ... | [
"def",
"before",
"(",
"self",
",",
"callback",
":",
"Union",
"[",
"Callable",
",",
"str",
"]",
")",
"->",
"\"Control\"",
":",
"if",
"isinstance",
"(",
"callback",
",",
"Control",
")",
":",
"callback",
"=",
"callback",
".",
"_before",
"self",
".",
"_bef... | Register a control method that reacts before the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given as a string, then the control will look
up a method ... | [
"Register",
"a",
"control",
"method",
"that",
"reacts",
"before",
"the",
"trigger",
"method",
"is",
"called",
"."
] | python | train | 44.846154 |
dereneaton/ipyrad | ipyrad/assemble/cluster_across.py | https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L46-L287 | def persistent_popen_align3(data, samples, chunk):
""" notes """
## data are already chunked, read in the whole thing
with open(chunk, 'rb') as infile:
clusts = infile.read().split("//\n//\n")[:-1]
## snames to ensure sorted order
samples.sort(key=lambda x: x.name)
snames = [sampl... | [
"def",
"persistent_popen_align3",
"(",
"data",
",",
"samples",
",",
"chunk",
")",
":",
"## data are already chunked, read in the whole thing",
"with",
"open",
"(",
"chunk",
",",
"'rb'",
")",
"as",
"infile",
":",
"clusts",
"=",
"infile",
".",
"read",
"(",
")",
... | notes | [
"notes"
] | python | valid | 44.264463 |
nuagenetworks/bambou | bambou/nurest_object.py | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L853-L865 | def _did_receive_response(self, connection):
""" Receive a response from the connection """
if connection.has_timeouted:
bambou_logger.info("NURESTConnection has timeout.")
return
has_callbacks = connection.has_callbacks()
should_post = not has_callbacks
... | [
"def",
"_did_receive_response",
"(",
"self",
",",
"connection",
")",
":",
"if",
"connection",
".",
"has_timeouted",
":",
"bambou_logger",
".",
"info",
"(",
"\"NURESTConnection has timeout.\"",
")",
"return",
"has_callbacks",
"=",
"connection",
".",
"has_callbacks",
... | Receive a response from the connection | [
"Receive",
"a",
"response",
"from",
"the",
"connection"
] | python | train | 37.230769 |
earlzo/hfut | hfut/log.py | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/log.py#L20-L67 | def report_response(response,
request_headers=True, request_body=True,
response_headers=False, response_body=False,
redirection=False):
"""
生成响应报告
:param response: ``requests.models.Response`` 对象
:param request_headers: 是否加入请求头
:param requ... | [
"def",
"report_response",
"(",
"response",
",",
"request_headers",
"=",
"True",
",",
"request_body",
"=",
"True",
",",
"response_headers",
"=",
"False",
",",
"response_body",
"=",
"False",
",",
"redirection",
"=",
"False",
")",
":",
"# https://docs.python.org/3/li... | 生成响应报告
:param response: ``requests.models.Response`` 对象
:param request_headers: 是否加入请求头
:param request_body: 是否加入请求体
:param response_headers: 是否加入响应头
:param response_body: 是否加入响应体
:param redirection: 是否加入重定向响应
:return: str | [
"生成响应报告"
] | python | train | 37.9375 |
google/grr | grr/client_builder/grr_response_client_builder/client_build.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client_builder/grr_response_client_builder/client_build.py#L296-L384 | def RepackTemplates(self,
repack_configs,
templates,
output_dir,
config=None,
sign=False,
signed_template=False):
"""Call repacker in a subprocess."""
pool = multiprocessing.Pool(p... | [
"def",
"RepackTemplates",
"(",
"self",
",",
"repack_configs",
",",
"templates",
",",
"output_dir",
",",
"config",
"=",
"None",
",",
"sign",
"=",
"False",
",",
"signed_template",
"=",
"False",
")",
":",
"pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"pro... | Call repacker in a subprocess. | [
"Call",
"repacker",
"in",
"a",
"subprocess",
"."
] | python | train | 35.741573 |
fastai/fastai | fastai/callbacks/loss_metrics.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/loss_metrics.py#L22-L28 | def on_batch_end(self, last_target, train, **kwargs):
"Update the metrics if not `train`"
if train: return
bs = last_target.size(0)
for name in self.names:
self.metrics[name] += bs * self.learn.loss_func.metrics[name].detach().cpu()
self.nums += bs | [
"def",
"on_batch_end",
"(",
"self",
",",
"last_target",
",",
"train",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"train",
":",
"return",
"bs",
"=",
"last_target",
".",
"size",
"(",
"0",
")",
"for",
"name",
"in",
"self",
".",
"names",
":",
"self",
"."... | Update the metrics if not `train` | [
"Update",
"the",
"metrics",
"if",
"not",
"train"
] | python | train | 42 |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/menu.py | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/menu.py#L208-L219 | def delete_menu(self, menu):
""" Delete the specified menu
:param menu:
:type menu:
:returns:
:rtype:
:raises:
"""
if menu.parent is None:
del self.menus[menu.name()]
menu._delete() | [
"def",
"delete_menu",
"(",
"self",
",",
"menu",
")",
":",
"if",
"menu",
".",
"parent",
"is",
"None",
":",
"del",
"self",
".",
"menus",
"[",
"menu",
".",
"name",
"(",
")",
"]",
"menu",
".",
"_delete",
"(",
")"
] | Delete the specified menu
:param menu:
:type menu:
:returns:
:rtype:
:raises: | [
"Delete",
"the",
"specified",
"menu"
] | python | train | 21.25 |
apache/incubator-heron | heron/tools/explorer/src/python/args.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/explorer/src/python/args.py#L30-L40 | def add_config(parser):
""" add config """
# the default config path
default_config_path = config.get_heron_conf_dir()
parser.add_argument(
'--config-path',
metavar='(a string; path to cluster config; default: "' + default_config_path + '")',
default=os.path.join(config.get_heron_dir(), defau... | [
"def",
"add_config",
"(",
"parser",
")",
":",
"# the default config path",
"default_config_path",
"=",
"config",
".",
"get_heron_conf_dir",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--config-path'",
",",
"metavar",
"=",
"'(a string; path to cluster config; default: ... | add config | [
"add",
"config"
] | python | valid | 31.181818 |
MultipedRobotics/pyxl320 | pyxl320/Packet.py | https://github.com/MultipedRobotics/pyxl320/blob/1a56540e208b028ee47d5fa0a7c7babcee0d9214/pyxl320/Packet.py#L176-L188 | def makeResetPacket(ID, param):
"""
Resets a servo to one of 3 reset states:
XL320_RESET_ALL = 0xFF
XL320_RESET_ALL_BUT_ID = 0x01
XL320_RESET_ALL_BUT_ID_BAUD_RATE = 0x02
"""
if param not in [0x01, 0x02, 0xff]:
raise Exception('Packet.makeResetPacket invalide parameter {}'.format(par... | [
"def",
"makeResetPacket",
"(",
"ID",
",",
"param",
")",
":",
"if",
"param",
"not",
"in",
"[",
"0x01",
",",
"0x02",
",",
"0xff",
"]",
":",
"raise",
"Exception",
"(",
"'Packet.makeResetPacket invalide parameter {}'",
".",
"format",
"(",
"param",
")",
")",
"#... | Resets a servo to one of 3 reset states:
XL320_RESET_ALL = 0xFF
XL320_RESET_ALL_BUT_ID = 0x01
XL320_RESET_ALL_BUT_ID_BAUD_RATE = 0x02 | [
"Resets",
"a",
"servo",
"to",
"one",
"of",
"3",
"reset",
"states",
":"
] | python | train | 33.384615 |
DataDog/integrations-core | kubernetes/datadog_checks/kubernetes/kubernetes.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/kubernetes/datadog_checks/kubernetes/kubernetes.py#L514-L577 | def _update_kube_events(self, instance, pods_list, event_items):
"""
Process kube events and send ddog events
The namespace filtering is done here instead of KubeEventRetriever
to avoid interfering with service discovery
"""
node_ip, node_name = self.kubeutil.get_node_inf... | [
"def",
"_update_kube_events",
"(",
"self",
",",
"instance",
",",
"pods_list",
",",
"event_items",
")",
":",
"node_ip",
",",
"node_name",
"=",
"self",
".",
"kubeutil",
".",
"get_node_info",
"(",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Processing events ... | Process kube events and send ddog events
The namespace filtering is done here instead of KubeEventRetriever
to avoid interfering with service discovery | [
"Process",
"kube",
"events",
"and",
"send",
"ddog",
"events",
"The",
"namespace",
"filtering",
"is",
"done",
"here",
"instead",
"of",
"KubeEventRetriever",
"to",
"avoid",
"interfering",
"with",
"service",
"discovery"
] | python | train | 48.75 |
LPgenerator/django-db-mailer | dbmail/providers/parse_com/push.py | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/parse_com/push.py#L19-L59 | def send(device_id, description, **kwargs):
"""
Site: http://parse.com
API: https://www.parse.com/docs/push_guide#scheduled/REST
Desc: Best app for system administrators
"""
headers = {
"X-Parse-Application-Id": settings.PARSE_APP_ID,
"X-Parse-REST-API-Key": settings.PARSE_API_KE... | [
"def",
"send",
"(",
"device_id",
",",
"description",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"{",
"\"X-Parse-Application-Id\"",
":",
"settings",
".",
"PARSE_APP_ID",
",",
"\"X-Parse-REST-API-Key\"",
":",
"settings",
".",
"PARSE_API_KEY",
",",
"\"User-... | Site: http://parse.com
API: https://www.parse.com/docs/push_guide#scheduled/REST
Desc: Best app for system administrators | [
"Site",
":",
"http",
":",
"//",
"parse",
".",
"com",
"API",
":",
"https",
":",
"//",
"www",
".",
"parse",
".",
"com",
"/",
"docs",
"/",
"push_guide#scheduled",
"/",
"REST",
"Desc",
":",
"Best",
"app",
"for",
"system",
"administrators"
] | python | train | 25.658537 |
CygnusNetworks/pypureomapi | pypureomapi.py | https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1354-L1366 | def add_group(self, groupname, statements):
"""
Adds a group
@type groupname: bytes
@type statements: str
"""
msg = OmapiMessage.open(b"group")
msg.message.append(("create", struct.pack("!I", 1)))
msg.obj.append(("name", groupname))
msg.obj.append(("statements", statements))
response = self.query_se... | [
"def",
"add_group",
"(",
"self",
",",
"groupname",
",",
"statements",
")",
":",
"msg",
"=",
"OmapiMessage",
".",
"open",
"(",
"b\"group\"",
")",
"msg",
".",
"message",
".",
"append",
"(",
"(",
"\"create\"",
",",
"struct",
".",
"pack",
"(",
"\"!I\"",
",... | Adds a group
@type groupname: bytes
@type statements: str | [
"Adds",
"a",
"group"
] | python | train | 30.615385 |
Chilipp/psyplot | psyplot/project.py | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L346-L373 | def _register_plotter(cls, identifier, module, plotter_name,
plotter_cls=None):
"""
Register a plotter in the :class:`Project` class to easy access it
Parameters
----------
identifier: str
Name of the attribute that is used to filter for the... | [
"def",
"_register_plotter",
"(",
"cls",
",",
"identifier",
",",
"module",
",",
"plotter_name",
",",
"plotter_cls",
"=",
"None",
")",
":",
"if",
"plotter_cls",
"is",
"not",
"None",
":",
"# plotter has already been imported",
"def",
"get_x",
"(",
"self",
")",
":... | Register a plotter in the :class:`Project` class to easy access it
Parameters
----------
identifier: str
Name of the attribute that is used to filter for the instances
belonging to this plotter
module: str
The module from where to import the `plotter_... | [
"Register",
"a",
"plotter",
"in",
"the",
":",
"class",
":",
"Project",
"class",
"to",
"easy",
"access",
"it"
] | python | train | 41.321429 |
pyQode/pyqode.core | pyqode/core/panels/search_and_replace.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L443-L487 | def replace(self, text=None):
"""
Replaces the selected occurrence.
:param text: The replacement text. If it is None, the lineEditReplace's
text is used instead.
:return True if the text could be replace properly, False if there is
no more occurrenc... | [
"def",
"replace",
"(",
"self",
",",
"text",
"=",
"None",
")",
":",
"if",
"text",
"is",
"None",
"or",
"isinstance",
"(",
"text",
",",
"bool",
")",
":",
"text",
"=",
"self",
".",
"lineEditReplace",
".",
"text",
"(",
")",
"current_occurences",
"=",
"sel... | Replaces the selected occurrence.
:param text: The replacement text. If it is None, the lineEditReplace's
text is used instead.
:return True if the text could be replace properly, False if there is
no more occurrences to replace. | [
"Replaces",
"the",
"selected",
"occurrence",
"."
] | python | train | 40.244444 |
pandas-dev/pandas | pandas/core/indexes/numeric.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/numeric.py#L364-L373 | def get_value(self, series, key):
""" we always want to get an index value, never a value """
if not is_scalar(key):
raise InvalidIndexError
k = com.values_from_object(key)
loc = self.get_loc(k)
new_values = com.values_from_object(series)[loc]
return new_val... | [
"def",
"get_value",
"(",
"self",
",",
"series",
",",
"key",
")",
":",
"if",
"not",
"is_scalar",
"(",
"key",
")",
":",
"raise",
"InvalidIndexError",
"k",
"=",
"com",
".",
"values_from_object",
"(",
"key",
")",
"loc",
"=",
"self",
".",
"get_loc",
"(",
... | we always want to get an index value, never a value | [
"we",
"always",
"want",
"to",
"get",
"an",
"index",
"value",
"never",
"a",
"value"
] | python | train | 31.4 |
opinkerfi/nago | nago/core/__init__.py | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L66-L81 | def get_nodes():
""" Returns all nodes in a list of dicts format
"""
cfg_file = "/etc/nago/nago.ini"
config = ConfigParser.ConfigParser()
config.read(cfg_file)
result = {}
for section in config.sections():
if section in ['main']:
continue
token = section
n... | [
"def",
"get_nodes",
"(",
")",
":",
"cfg_file",
"=",
"\"/etc/nago/nago.ini\"",
"config",
"=",
"ConfigParser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"cfg_file",
")",
"result",
"=",
"{",
"}",
"for",
"section",
"in",
"config",
".",
"sectio... | Returns all nodes in a list of dicts format | [
"Returns",
"all",
"nodes",
"in",
"a",
"list",
"of",
"dicts",
"format"
] | python | train | 27.875 |
schettino72/import-deps | import_deps/__init__.py | https://github.com/schettino72/import-deps/blob/311f2badd2c93f743d09664397f21e7eaa16e1f1/import_deps/__init__.py#L119-L145 | def get_imports(self, module, return_fqn=False):
"""return set of imported modules that are in self
:param module: PyModule
:return: (set - str) of path names
"""
# print('####', module.fqn)
# print(self.by_name.keys(), '\n\n')
imports = set()
raw_imports ... | [
"def",
"get_imports",
"(",
"self",
",",
"module",
",",
"return_fqn",
"=",
"False",
")",
":",
"# print('####', module.fqn)",
"# print(self.by_name.keys(), '\\n\\n')",
"imports",
"=",
"set",
"(",
")",
"raw_imports",
"=",
"ast_imports",
"(",
"module",
".",
"path",
")... | return set of imported modules that are in self
:param module: PyModule
:return: (set - str) of path names | [
"return",
"set",
"of",
"imported",
"modules",
"that",
"are",
"in",
"self",
":",
"param",
"module",
":",
"PyModule",
":",
"return",
":",
"(",
"set",
"-",
"str",
")",
"of",
"path",
"names"
] | python | train | 37.481481 |
materialsvirtuallab/monty | monty/functools.py | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/functools.py#L81-L225 | def lru_cache(maxsize=128, typed=False):
"""
Least-recently-used cache decorator, which is a backport of the same
function in Python >= 3.2.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
If *typed* is True, arguments of different types will be... | [
"def",
"lru_cache",
"(",
"maxsize",
"=",
"128",
",",
"typed",
"=",
"False",
")",
":",
"# Users should only access the lru_cache through its public API:",
"# cache_info, cache_clear, and f.__wrapped__",
"# The internals of the lru_cache are encapsulated for thread safety and",
"# ... | Least-recently-used cache decorator, which is a backport of the same
function in Python >= 3.2.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
If *typed* is True, arguments of different types will be cached separately.
For example, f(3.0) and f(3) ... | [
"Least",
"-",
"recently",
"-",
"used",
"cache",
"decorator",
"which",
"is",
"a",
"backport",
"of",
"the",
"same",
"function",
"in",
"Python",
">",
"=",
"3",
".",
"2",
"."
] | python | train | 42.944828 |
tensorflow/tensorboard | tensorboard/plugins/core/core_plugin.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/core/core_plugin.py#L467-L485 | def fix_flags(self, flags):
"""Fixes standard TensorBoard CLI flags to parser."""
FlagsError = base_plugin.FlagsError
if flags.version_tb:
pass
elif flags.inspect:
if flags.logdir and flags.event_file:
raise FlagsError(
'Must specify either --logdir or --event_file, but n... | [
"def",
"fix_flags",
"(",
"self",
",",
"flags",
")",
":",
"FlagsError",
"=",
"base_plugin",
".",
"FlagsError",
"if",
"flags",
".",
"version_tb",
":",
"pass",
"elif",
"flags",
".",
"inspect",
":",
"if",
"flags",
".",
"logdir",
"and",
"flags",
".",
"event_f... | Fixes standard TensorBoard CLI flags to parser. | [
"Fixes",
"standard",
"TensorBoard",
"CLI",
"flags",
"to",
"parser",
"."
] | python | train | 44.947368 |
Kronuz/pyScss | yapps2.py | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/yapps2.py#L1098-L1157 | def generate(inputfilename, outputfilename='', dump=0, **flags):
"""Generate a grammar, given an input filename (X.g)
and an output filename (defaulting to X.py)."""
if not outputfilename:
if inputfilename[-2:] == '.g':
outputfilename = inputfilename[:-2] + '.py'
else:
... | [
"def",
"generate",
"(",
"inputfilename",
",",
"outputfilename",
"=",
"''",
",",
"dump",
"=",
"0",
",",
"*",
"*",
"flags",
")",
":",
"if",
"not",
"outputfilename",
":",
"if",
"inputfilename",
"[",
"-",
"2",
":",
"]",
"==",
"'.g'",
":",
"outputfilename",... | Generate a grammar, given an input filename (X.g)
and an output filename (defaulting to X.py). | [
"Generate",
"a",
"grammar",
"given",
"an",
"input",
"filename",
"(",
"X",
".",
"g",
")",
"and",
"an",
"output",
"filename",
"(",
"defaulting",
"to",
"X",
".",
"py",
")",
"."
] | python | train | 29.4 |
andsor/pypercolate | percolate/hpc.py | https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/hpc.py#L561-L635 | def bond_initialize_canonical_averages(
canonical_statistics, **kwargs
):
"""
Initialize the canonical averages from a single-run cluster statistics
Parameters
----------
canonical_statistics : 1-D structured ndarray
Typically contains the canonical statistics for a range of values
... | [
"def",
"bond_initialize_canonical_averages",
"(",
"canonical_statistics",
",",
"*",
"*",
"kwargs",
")",
":",
"# initialize return array",
"spanning_cluster",
"=",
"(",
"'percolation_probability'",
"in",
"canonical_statistics",
".",
"dtype",
".",
"names",
")",
"# array sho... | Initialize the canonical averages from a single-run cluster statistics
Parameters
----------
canonical_statistics : 1-D structured ndarray
Typically contains the canonical statistics for a range of values
of the occupation probability ``p``.
The dtype is the result of `canonical_sta... | [
"Initialize",
"the",
"canonical",
"averages",
"from",
"a",
"single",
"-",
"run",
"cluster",
"statistics"
] | python | valid | 30.386667 |
HazyResearch/pdftotree | pdftotree/utils/pdf/node.py | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/node.py#L118-L128 | def get_grid(self):
"""
Standardize the layout of the table into grids
"""
mentions, lines = _split_text_n_lines(self.elems)
# Sort mentions in reading order where y values are snapped to half
# height-sized grid
mentions.sort(key=lambda m: (m.yc_grid, m.xc))
... | [
"def",
"get_grid",
"(",
"self",
")",
":",
"mentions",
",",
"lines",
"=",
"_split_text_n_lines",
"(",
"self",
".",
"elems",
")",
"# Sort mentions in reading order where y values are snapped to half",
"# height-sized grid",
"mentions",
".",
"sort",
"(",
"key",
"=",
"lam... | Standardize the layout of the table into grids | [
"Standardize",
"the",
"layout",
"of",
"the",
"table",
"into",
"grids"
] | python | train | 33.545455 |
jonathf/chaospy | chaospy/poly/constructor/identifier.py | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/constructor/identifier.py#L46-L56 | def _identify_dict(core):
"""Specification for a dictionary."""
if not core:
return {}, 1, (), int
core = core.copy()
key = sorted(core.keys(), key=chaospy.poly.base.sort_key)[0]
shape = numpy.array(core[key]).shape
dtype = numpy.array(core[key]).dtype
dim = len(key)
return core... | [
"def",
"_identify_dict",
"(",
"core",
")",
":",
"if",
"not",
"core",
":",
"return",
"{",
"}",
",",
"1",
",",
"(",
")",
",",
"int",
"core",
"=",
"core",
".",
"copy",
"(",
")",
"key",
"=",
"sorted",
"(",
"core",
".",
"keys",
"(",
")",
",",
"key... | Specification for a dictionary. | [
"Specification",
"for",
"a",
"dictionary",
"."
] | python | train | 29.909091 |
collectiveacuity/labPack | labpack/storage/dropbox.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/storage/dropbox.py#L422-L462 | def load(self, record_key, secret_key=''):
'''
a method to retrieve byte data of appdata record
:param record_key: string with name of record
:param secret_key: [optional] string used to decrypt data
:return: byte data for record body
'''
title =... | [
"def",
"load",
"(",
"self",
",",
"record_key",
",",
"secret_key",
"=",
"''",
")",
":",
"title",
"=",
"'%s.load'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs\r",
"input_fields",
"=",
"{",
"'record_key'",
":",
"record_key",
",",
"'secre... | a method to retrieve byte data of appdata record
:param record_key: string with name of record
:param secret_key: [optional] string used to decrypt data
:return: byte data for record body | [
"a",
"method",
"to",
"retrieve",
"byte",
"data",
"of",
"appdata",
"record",
":",
"param",
"record_key",
":",
"string",
"with",
"name",
"of",
"record",
":",
"param",
"secret_key",
":",
"[",
"optional",
"]",
"string",
"used",
"to",
"decrypt",
"data",
":",
... | python | train | 33.658537 |
ihgazni2/elist | elist/elist.py | https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L5492-L5508 | def broken_seqs(ol,break_points):
'''
ol = initRange(0,20,1)
ol
break_points = [1,6,14,9]
secs = broken_seqs(ol,break_points)
forEach(secs,print)
'''
bps = list(break_points)
length = ol.__len__()
rgs = rangize(bps,length)
rslt = []
for i in range(0,rg... | [
"def",
"broken_seqs",
"(",
"ol",
",",
"break_points",
")",
":",
"bps",
"=",
"list",
"(",
"break_points",
")",
"length",
"=",
"ol",
".",
"__len__",
"(",
")",
"rgs",
"=",
"rangize",
"(",
"bps",
",",
"length",
")",
"rslt",
"=",
"[",
"]",
"for",
"i",
... | ol = initRange(0,20,1)
ol
break_points = [1,6,14,9]
secs = broken_seqs(ol,break_points)
forEach(secs,print) | [
"ol",
"=",
"initRange",
"(",
"0",
"20",
"1",
")",
"ol",
"break_points",
"=",
"[",
"1",
"6",
"14",
"9",
"]",
"secs",
"=",
"broken_seqs",
"(",
"ol",
"break_points",
")",
"forEach",
"(",
"secs",
"print",
")"
] | python | valid | 23.882353 |
google/grr | grr/core/grr_response_core/lib/util/compatibility.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/util/compatibility.py#L152-L179 | def MakeType(name, base_classes,
namespace):
"""A compatibility wrapper for the `type` built-in function.
In Python 2 `type` (used as a type constructor) requires the name argument to
be a `bytes` object whereas in Python 3 it is required to be an `unicode`
object. Since class name is human readab... | [
"def",
"MakeType",
"(",
"name",
",",
"base_classes",
",",
"namespace",
")",
":",
"precondition",
".",
"AssertType",
"(",
"name",
",",
"str",
")",
"if",
"PY2",
":",
"name",
"=",
"name",
".",
"encode",
"(",
"\"ascii\"",
")",
"return",
"type",
"(",
"name"... | A compatibility wrapper for the `type` built-in function.
In Python 2 `type` (used as a type constructor) requires the name argument to
be a `bytes` object whereas in Python 3 it is required to be an `unicode`
object. Since class name is human readable text rather than arbitrary stream
of bytes, the Python 3 b... | [
"A",
"compatibility",
"wrapper",
"for",
"the",
"type",
"built",
"-",
"in",
"function",
"."
] | python | train | 33.857143 |
mwickert/scikit-dsp-comm | sk_dsp_comm/sigsys.py | https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/sigsys.py#L474-L531 | def OS_filter(x,h,N,mode=0):
"""
Overlap and save transform domain FIR filtering.
This function implements the classical overlap and save method of
transform domain filtering using a length P FIR filter.
Parameters
----------
x : input signal to be filtered as an ndarray
h : FI... | [
"def",
"OS_filter",
"(",
"x",
",",
"h",
",",
"N",
",",
"mode",
"=",
"0",
")",
":",
"P",
"=",
"len",
"(",
"h",
")",
"# zero pad start of x so first frame can recover first true samples of x",
"x",
"=",
"np",
".",
"hstack",
"(",
"(",
"np",
".",
"zeros",
"(... | Overlap and save transform domain FIR filtering.
This function implements the classical overlap and save method of
transform domain filtering using a length P FIR filter.
Parameters
----------
x : input signal to be filtered as an ndarray
h : FIR filter coefficients as an ndarray of le... | [
"Overlap",
"and",
"save",
"transform",
"domain",
"FIR",
"filtering",
".",
"This",
"function",
"implements",
"the",
"classical",
"overlap",
"and",
"save",
"method",
"of",
"transform",
"domain",
"filtering",
"using",
"a",
"length",
"P",
"FIR",
"filter",
".",
"Pa... | python | valid | 29.431034 |
cogniteev/docido-python-sdk | docido_sdk/toolbox/date_ext.py | https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/date_ext.py#L38-L51 | def feeling_lucky(cls, obj):
"""Tries to convert given object to an UTC timestamp is ms, based
on its type.
"""
if isinstance(obj, six.string_types):
return cls.from_str(obj)
elif isinstance(obj, six.integer_types) and obj <= MAX_POSIX_TIMESTAMP:
return cl... | [
"def",
"feeling_lucky",
"(",
"cls",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
":",
"return",
"cls",
".",
"from_str",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"six",
".",
"integer_types",
... | Tries to convert given object to an UTC timestamp is ms, based
on its type. | [
"Tries",
"to",
"convert",
"given",
"object",
"to",
"an",
"UTC",
"timestamp",
"is",
"ms",
"based",
"on",
"its",
"type",
"."
] | python | train | 39.071429 |
datajoint/datajoint-python | datajoint/expression.py | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/expression.py#L606-L610 | def make_argument_subquery(arg):
"""
Decide when a Join argument needs to be wrapped in a subquery
"""
return Subquery.create(arg) if isinstance(arg, (GroupBy, Projection)) or arg.restriction else arg | [
"def",
"make_argument_subquery",
"(",
"arg",
")",
":",
"return",
"Subquery",
".",
"create",
"(",
"arg",
")",
"if",
"isinstance",
"(",
"arg",
",",
"(",
"GroupBy",
",",
"Projection",
")",
")",
"or",
"arg",
".",
"restriction",
"else",
"arg"
] | Decide when a Join argument needs to be wrapped in a subquery | [
"Decide",
"when",
"a",
"Join",
"argument",
"needs",
"to",
"be",
"wrapped",
"in",
"a",
"subquery"
] | python | train | 45.6 |
acutesoftware/virtual-AI-simulator | vais/worlds.py | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L304-L332 | def highlight_cell_surroundings(self, target_y, target_x):
"""
highlights the cells around a target to make it simpler
to see on a grid. Currently assumes the target is within
the boundary by 1 on all sides
"""
#print('SELF_WORLD', self.world)
#print('target_y, ta... | [
"def",
"highlight_cell_surroundings",
"(",
"self",
",",
"target_y",
",",
"target_x",
")",
":",
"#print('SELF_WORLD', self.world)",
"#print('target_y, target_x, self.world.grd.grid_height, self.world.grd.grid_width ', target_y, target_x, self.#world.grd.grid_height, self.world.grd.grid_width )"... | highlights the cells around a target to make it simpler
to see on a grid. Currently assumes the target is within
the boundary by 1 on all sides | [
"highlights",
"the",
"cells",
"around",
"a",
"target",
"to",
"make",
"it",
"simpler",
"to",
"see",
"on",
"a",
"grid",
".",
"Currently",
"assumes",
"the",
"target",
"is",
"within",
"the",
"boundary",
"by",
"1",
"on",
"all",
"sides"
] | python | train | 47.689655 |
mitsei/dlkit | dlkit/json_/learning/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/managers.py#L1673-L1690 | def get_objective_hierarchy_design_session(self, proxy):
"""Gets the session for designing objective hierarchies.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveHierarchyDesignSession) - an
``ObjectiveHierarchyDesignSession``
raise: NullArgume... | [
"def",
"get_objective_hierarchy_design_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_objective_hierarchy_design",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions"... | Gets the session for designing objective hierarchies.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveHierarchyDesignSession) - an
``ObjectiveHierarchyDesignSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable ... | [
"Gets",
"the",
"session",
"for",
"designing",
"objective",
"hierarchies",
"."
] | python | train | 48.111111 |
peopledoc/django-agnocomplete | agnocomplete/views.py | https://github.com/peopledoc/django-agnocomplete/blob/9bf21db2f2036ba5059b843acd32902a09192053/agnocomplete/views.py#L20-L46 | def get_error(exc):
"""
Return the appropriate HTTP status code according to the Exception/Error.
"""
if isinstance(exc, HTTPError):
# Returning the HTTP Error code coming from requests module
return exc.response.status_code, text(exc.response.content)
if isinstance(exc, Timeout):
... | [
"def",
"get_error",
"(",
"exc",
")",
":",
"if",
"isinstance",
"(",
"exc",
",",
"HTTPError",
")",
":",
"# Returning the HTTP Error code coming from requests module",
"return",
"exc",
".",
"response",
".",
"status_code",
",",
"text",
"(",
"exc",
".",
"response",
"... | Return the appropriate HTTP status code according to the Exception/Error. | [
"Return",
"the",
"appropriate",
"HTTP",
"status",
"code",
"according",
"to",
"the",
"Exception",
"/",
"Error",
"."
] | python | train | 27.444444 |
MartinThoma/hwrt | hwrt/partitions.py | https://github.com/MartinThoma/hwrt/blob/725c21a3d0f5a30b8492cbc184b3688ceb364e1c/hwrt/partitions.py#L160-L177 | def get_top_segmentations(table, n):
"""
Parameters
----------
table : matrix of probabilities
Each cell (i, j) of `table` gives the probability that i and j are in
the same symbol.
n : int
Number of best segmentations which get returned
"""
stroke_count = list(range(... | [
"def",
"get_top_segmentations",
"(",
"table",
",",
"n",
")",
":",
"stroke_count",
"=",
"list",
"(",
"range",
"(",
"len",
"(",
"table",
")",
")",
")",
"topf",
"=",
"TopFinder",
"(",
"n",
")",
"for",
"curr_segmentation",
"in",
"all_segmentations",
"(",
"st... | Parameters
----------
table : matrix of probabilities
Each cell (i, j) of `table` gives the probability that i and j are in
the same symbol.
n : int
Number of best segmentations which get returned | [
"Parameters",
"----------",
"table",
":",
"matrix",
"of",
"probabilities",
"Each",
"cell",
"(",
"i",
"j",
")",
"of",
"table",
"gives",
"the",
"probability",
"that",
"i",
"and",
"j",
"are",
"in",
"the",
"same",
"symbol",
".",
"n",
":",
"int",
"Number",
... | python | train | 33.444444 |
mitsei/dlkit | dlkit/authz_adapter/assessment_authoring/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/authz_adapter/assessment_authoring/sessions.py#L2039-L2045 | def get_sequence_rule_enablers_by_search(self, sequence_rule_enabler_query, sequence_rule_enabler_search):
"""Pass through to provider SequenceRuleEnablerSearchSession.get_sequence_rule_enablers_by_search"""
# Implemented from azosid template for -
# osid.resource.ResourceSearchSession.get_resou... | [
"def",
"get_sequence_rule_enablers_by_search",
"(",
"self",
",",
"sequence_rule_enabler_query",
",",
"sequence_rule_enabler_search",
")",
":",
"# Implemented from azosid template for -",
"# osid.resource.ResourceSearchSession.get_resources_by_search_template",
"if",
"not",
"self",
".",... | Pass through to provider SequenceRuleEnablerSearchSession.get_sequence_rule_enablers_by_search | [
"Pass",
"through",
"to",
"provider",
"SequenceRuleEnablerSearchSession",
".",
"get_sequence_rule_enablers_by_search"
] | python | train | 77.714286 |
coleifer/peewee | examples/analytics/reports.py | https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/examples/analytics/reports.py#L40-L47 | def cookies(self):
"""
Retrieve the cookies header from all the users who visited.
"""
return (self.get_query()
.select(PageView.ip, PageView.headers['Cookie'])
.where(PageView.headers['Cookie'].is_null(False))
.tuples()) | [
"def",
"cookies",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"get_query",
"(",
")",
".",
"select",
"(",
"PageView",
".",
"ip",
",",
"PageView",
".",
"headers",
"[",
"'Cookie'",
"]",
")",
".",
"where",
"(",
"PageView",
".",
"headers",
"[",
"... | Retrieve the cookies header from all the users who visited. | [
"Retrieve",
"the",
"cookies",
"header",
"from",
"all",
"the",
"users",
"who",
"visited",
"."
] | python | train | 36.75 |
secdev/scapy | scapy/layers/tls/record.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/tls/record.py#L83-L108 | def m2i(self, pkt, m):
"""
Try to parse one of the TLS subprotocols (ccs, alert, handshake or
application_data). This is used inside a loop managed by .getfield().
"""
cls = Raw
if pkt.type == 22:
if len(m) >= 1:
msgtype = orb(m[0])
... | [
"def",
"m2i",
"(",
"self",
",",
"pkt",
",",
"m",
")",
":",
"cls",
"=",
"Raw",
"if",
"pkt",
".",
"type",
"==",
"22",
":",
"if",
"len",
"(",
"m",
")",
">=",
"1",
":",
"msgtype",
"=",
"orb",
"(",
"m",
"[",
"0",
"]",
")",
"cls",
"=",
"_tls_ha... | Try to parse one of the TLS subprotocols (ccs, alert, handshake or
application_data). This is used inside a loop managed by .getfield(). | [
"Try",
"to",
"parse",
"one",
"of",
"the",
"TLS",
"subprotocols",
"(",
"ccs",
"alert",
"handshake",
"or",
"application_data",
")",
".",
"This",
"is",
"used",
"inside",
"a",
"loop",
"managed",
"by",
".",
"getfield",
"()",
"."
] | python | train | 30.692308 |
jplusplus/statscraper | statscraper/scrapers/VantetiderScraper.py | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/scrapers/VantetiderScraper.py#L550-L569 | def as_dictlist(self):
""" Returns a dictlist with values
[
{
"row": "row_a",
"col": "col_a",
"value": 1,
}
]
"""
data = []
for row_i, row in enumerate(self.row_index):
... | [
"def",
"as_dictlist",
"(",
"self",
")",
":",
"data",
"=",
"[",
"]",
"for",
"row_i",
",",
"row",
"in",
"enumerate",
"(",
"self",
".",
"row_index",
")",
":",
"for",
"col_i",
",",
"col",
"in",
"enumerate",
"(",
"self",
".",
"col_index",
")",
":",
"val... | Returns a dictlist with values
[
{
"row": "row_a",
"col": "col_a",
"value": 1,
}
] | [
"Returns",
"a",
"dictlist",
"with",
"values",
"[",
"{",
"row",
":",
"row_a",
"col",
":",
"col_a",
"value",
":",
"1",
"}",
"]"
] | python | train | 29.2 |
pvlib/pvlib-python | pvlib/pvsystem.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/pvsystem.py#L490-L522 | def sapm_effective_irradiance(self, poa_direct, poa_diffuse,
airmass_absolute, aoi,
reference_irradiance=1000):
"""
Use the :py:func:`sapm_effective_irradiance` function, the input
parameters, and ``self.module_parameters`` to c... | [
"def",
"sapm_effective_irradiance",
"(",
"self",
",",
"poa_direct",
",",
"poa_diffuse",
",",
"airmass_absolute",
",",
"aoi",
",",
"reference_irradiance",
"=",
"1000",
")",
":",
"return",
"sapm_effective_irradiance",
"(",
"poa_direct",
",",
"poa_diffuse",
",",
"airma... | Use the :py:func:`sapm_effective_irradiance` function, the input
parameters, and ``self.module_parameters`` to calculate
effective irradiance.
Parameters
----------
poa_direct : numeric
The direct irradiance incident upon the module.
poa_diffuse : numeric
... | [
"Use",
"the",
":",
"py",
":",
"func",
":",
"sapm_effective_irradiance",
"function",
"the",
"input",
"parameters",
"and",
"self",
".",
"module_parameters",
"to",
"calculate",
"effective",
"irradiance",
"."
] | python | train | 33.575758 |
czielinski/portfolioopt | example.py | https://github.com/czielinski/portfolioopt/blob/96ac25daab0c0dbc8933330a92ff31fb898112f2/example.py#L36-L46 | def print_portfolio_info(returns, avg_rets, weights):
"""
Print information on expected portfolio performance.
"""
ret = (weights * avg_rets).sum()
std = (weights * returns).sum(1).std()
sharpe = ret / std
print("Optimal weights:\n{}\n".format(weights))
print("Expected return: {}".form... | [
"def",
"print_portfolio_info",
"(",
"returns",
",",
"avg_rets",
",",
"weights",
")",
":",
"ret",
"=",
"(",
"weights",
"*",
"avg_rets",
")",
".",
"sum",
"(",
")",
"std",
"=",
"(",
"weights",
"*",
"returns",
")",
".",
"sum",
"(",
"1",
")",
".",
"std"... | Print information on expected portfolio performance. | [
"Print",
"information",
"on",
"expected",
"portfolio",
"performance",
"."
] | python | train | 38 |
xtrinch/fcm-django | fcm_django/fcm.py | https://github.com/xtrinch/fcm-django/blob/8480d1cf935bfb28e2ad6d86a0abf923c2ecb266/fcm_django/fcm.py#L65-L168 | def fcm_send_message(
registration_id,
title=None,
body=None,
icon=None,
data=None,
sound=None,
badge=None,
low_priority=False,
condition=None,
time_to_live=None,
click_action=None,
collapse_key=None,
delay_while_idl... | [
"def",
"fcm_send_message",
"(",
"registration_id",
",",
"title",
"=",
"None",
",",
"body",
"=",
"None",
",",
"icon",
"=",
"None",
",",
"data",
"=",
"None",
",",
"sound",
"=",
"None",
",",
"badge",
"=",
"None",
",",
"low_priority",
"=",
"False",
",",
... | Copied from https://github.com/olucurious/PyFCM/blob/master/pyfcm/fcm.py:
Send push notification to a single device
Args:
registration_id (str): FCM device registration IDs.
body (str): Message string to display in the notification tray
data (dict): Data message payload to send alone or... | [
"Copied",
"from",
"https",
":",
"//",
"github",
".",
"com",
"/",
"olucurious",
"/",
"PyFCM",
"/",
"blob",
"/",
"master",
"/",
"pyfcm",
"/",
"fcm",
".",
"py",
":"
] | python | train | 37 |
proycon/clam | clam/common/data.py | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L676-L682 | def parameter(self, parameter_id):
"""Return the specified global parameter (the entire object, not just the value)"""
for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable
for parameter in parameters:
if parameter.id == parameter_id:
... | [
"def",
"parameter",
"(",
"self",
",",
"parameter_id",
")",
":",
"for",
"parametergroup",
",",
"parameters",
"in",
"self",
".",
"parameters",
":",
"#pylint: disable=unused-variable",
"for",
"parameter",
"in",
"parameters",
":",
"if",
"parameter",
".",
"id",
"==",... | Return the specified global parameter (the entire object, not just the value) | [
"Return",
"the",
"specified",
"global",
"parameter",
"(",
"the",
"entire",
"object",
"not",
"just",
"the",
"value",
")"
] | python | train | 58.285714 |
ARMmbed/icetea | icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L316-L327 | def close_connection(self): # pylint: disable=C0103
"""
Closes serial port connection.
:return: Nothing
"""
if self.port:
self.stop()
self.logger.debug("Close port '%s'" % self.comport,
extra={'type': '<->'})
sel... | [
"def",
"close_connection",
"(",
"self",
")",
":",
"# pylint: disable=C0103",
"if",
"self",
".",
"port",
":",
"self",
".",
"stop",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Close port '%s'\"",
"%",
"self",
".",
"comport",
",",
"extra",
"=",
"... | Closes serial port connection.
:return: Nothing | [
"Closes",
"serial",
"port",
"connection",
"."
] | python | train | 29.416667 |
bjodah/pyneqsys | pyneqsys/core.py | https://github.com/bjodah/pyneqsys/blob/1c8f2fe1ab2b6cc6cb55b7a1328aca2e3a3c5c77/pyneqsys/core.py#L195-L204 | def plot_series_residuals(self, xres, varied_data, varied_idx, params, **kwargs):
""" Analogous to :meth:`plot_series` but will plot residuals. """
nf = len(self.f_cb(*self.pre_process(xres[0], params)))
xerr = np.empty((xres.shape[0], nf))
new_params = np.array(params)
for idx,... | [
"def",
"plot_series_residuals",
"(",
"self",
",",
"xres",
",",
"varied_data",
",",
"varied_idx",
",",
"params",
",",
"*",
"*",
"kwargs",
")",
":",
"nf",
"=",
"len",
"(",
"self",
".",
"f_cb",
"(",
"*",
"self",
".",
"pre_process",
"(",
"xres",
"[",
"0"... | Analogous to :meth:`plot_series` but will plot residuals. | [
"Analogous",
"to",
":",
"meth",
":",
"plot_series",
"but",
"will",
"plot",
"residuals",
"."
] | python | train | 53.1 |
oscarbranson/latools | latools/filtering/signal_optimiser.py | https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/filtering/signal_optimiser.py#L132-L389 | def signal_optimiser(d, analytes, min_points=5,
threshold_mode='kde_first_max',
threshold_mult=1., x_bias=0,
weights=None, ind=None, mode='minimise'):
"""
Optimise data selection based on specified analytes.
Identifies the longest possible cont... | [
"def",
"signal_optimiser",
"(",
"d",
",",
"analytes",
",",
"min_points",
"=",
"5",
",",
"threshold_mode",
"=",
"'kde_first_max'",
",",
"threshold_mult",
"=",
"1.",
",",
"x_bias",
"=",
"0",
",",
"weights",
"=",
"None",
",",
"ind",
"=",
"None",
",",
"mode"... | Optimise data selection based on specified analytes.
Identifies the longest possible contiguous data region in
the signal where the relative standard deviation (std) and
concentration of all analytes is minimised.
Optimisation is performed via a grid search of all possible
contiguous data regions... | [
"Optimise",
"data",
"selection",
"based",
"on",
"specified",
"analytes",
"."
] | python | test | 42.232558 |
tensorflow/tensor2tensor | tensor2tensor/utils/data_reader.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/data_reader.py#L292-L307 | def pad_batch(features, batch_multiple):
"""Pad batch dim of features to nearest multiple of batch_multiple."""
feature = list(features.items())[0][1]
batch_size = tf.shape(feature)[0]
mod = batch_size % batch_multiple
has_mod = tf.cast(tf.cast(mod, tf.bool), tf.int32)
batch_padding = batch_multiple * has_m... | [
"def",
"pad_batch",
"(",
"features",
",",
"batch_multiple",
")",
":",
"feature",
"=",
"list",
"(",
"features",
".",
"items",
"(",
")",
")",
"[",
"0",
"]",
"[",
"1",
"]",
"batch_size",
"=",
"tf",
".",
"shape",
"(",
"feature",
")",
"[",
"0",
"]",
"... | Pad batch dim of features to nearest multiple of batch_multiple. | [
"Pad",
"batch",
"dim",
"of",
"features",
"to",
"nearest",
"multiple",
"of",
"batch_multiple",
"."
] | python | train | 37.3125 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/lib/deepreload.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/deepreload.py#L262-L311 | def deep_reload_hook(m):
"""Replacement for reload()."""
if not isinstance(m, ModuleType):
raise TypeError("reload() argument must be module")
name = m.__name__
if name not in sys.modules:
raise ImportError("reload(): module %.200s not in sys.modules" % name)
global modules_reload... | [
"def",
"deep_reload_hook",
"(",
"m",
")",
":",
"if",
"not",
"isinstance",
"(",
"m",
",",
"ModuleType",
")",
":",
"raise",
"TypeError",
"(",
"\"reload() argument must be module\"",
")",
"name",
"=",
"m",
".",
"__name__",
"if",
"name",
"not",
"in",
"sys",
".... | Replacement for reload(). | [
"Replacement",
"for",
"reload",
"()",
"."
] | python | test | 29.68 |
SmartTeleMax/iktomi | iktomi/auth.py | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/auth.py#L33-L40 | def check_password(raw_password, enc_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
encryption formats behind the scenes.
"""
algo, salt, hsh = enc_password.split('$')
return enc_password == encrypt_password(raw_password, algorithm=algo,
... | [
"def",
"check_password",
"(",
"raw_password",
",",
"enc_password",
")",
":",
"algo",
",",
"salt",
",",
"hsh",
"=",
"enc_password",
".",
"split",
"(",
"'$'",
")",
"return",
"enc_password",
"==",
"encrypt_password",
"(",
"raw_password",
",",
"algorithm",
"=",
... | Returns a boolean of whether the raw_password was correct. Handles
encryption formats behind the scenes. | [
"Returns",
"a",
"boolean",
"of",
"whether",
"the",
"raw_password",
"was",
"correct",
".",
"Handles",
"encryption",
"formats",
"behind",
"the",
"scenes",
"."
] | python | train | 43 |
spatialaudio/python-pa-ringbuffer | src/pa_ringbuffer.py | https://github.com/spatialaudio/python-pa-ringbuffer/blob/b4a5eaa9b53a437c05d196ed59e1791db159e4b0/src/pa_ringbuffer.py#L177-L198 | def readinto(self, data):
"""Read data from the ring buffer into a user-provided buffer.
This advances the read index after reading;
calling :meth:`advance_read_index` is *not* necessary.
:param data: The memory where the data should be stored.
:type data: CData pointer or buff... | [
"def",
"readinto",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"_ffi",
".",
"from_buffer",
"(",
"data",
")",
"except",
"TypeError",
":",
"pass",
"# input is not a buffer",
"size",
",",
"rest",
"=",
"divmod",
"(",
"self",
"... | Read data from the ring buffer into a user-provided buffer.
This advances the read index after reading;
calling :meth:`advance_read_index` is *not* necessary.
:param data: The memory where the data should be stored.
:type data: CData pointer or buffer
:returns: The number of e... | [
"Read",
"data",
"from",
"the",
"ring",
"buffer",
"into",
"a",
"user",
"-",
"provided",
"buffer",
"."
] | python | train | 36.181818 |
RaRe-Technologies/smart_open | smart_open/smart_open_lib.py | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L658-L719 | def _parse_uri(uri_as_string):
"""
Parse the given URI from a string.
Supported URI schemes are:
* file
* hdfs
* http
* https
* s3
* s3a
* s3n
* s3u
* webhdfs
.s3, s3a and s3n are treated the same way. s3u is s3 but without SSL.
Valid URI ex... | [
"def",
"_parse_uri",
"(",
"uri_as_string",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# urlsplit doesn't work on Windows -- it parses the drive as the scheme...",
"if",
"'://'",
"not",
"in",
"uri_as_string",
":",
"# no protocol given => assume a local file",
"ur... | Parse the given URI from a string.
Supported URI schemes are:
* file
* hdfs
* http
* https
* s3
* s3a
* s3n
* s3u
* webhdfs
.s3, s3a and s3n are treated the same way. s3u is s3 but without SSL.
Valid URI examples::
* s3://my_bucket/my_key
... | [
"Parse",
"the",
"given",
"URI",
"from",
"a",
"string",
"."
] | python | train | 30.5 |
rene-aguirre/pywinusb | pywinusb/hid/winapi.py | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/winapi.py#L443-L454 | def open(self):
"""
Calls SetupDiGetClassDevs to obtain a handle to an opaque device
information set that describes the device interfaces supported by all
the USB collections currently installed in the system. The
application should specify DIGCF.PRESENT and DIGCF.INTERFACED... | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"h_info",
"=",
"SetupDiGetClassDevs",
"(",
"byref",
"(",
"self",
".",
"guid",
")",
",",
"None",
",",
"None",
",",
"(",
"DIGCF",
".",
"PRESENT",
"|",
"DIGCF",
".",
"DEVICEINTERFACE",
")",
")",
"return... | Calls SetupDiGetClassDevs to obtain a handle to an opaque device
information set that describes the device interfaces supported by all
the USB collections currently installed in the system. The
application should specify DIGCF.PRESENT and DIGCF.INTERFACEDEVICE
in the Flags parameter ... | [
"Calls",
"SetupDiGetClassDevs",
"to",
"obtain",
"a",
"handle",
"to",
"an",
"opaque",
"device",
"information",
"set",
"that",
"describes",
"the",
"device",
"interfaces",
"supported",
"by",
"all",
"the",
"USB",
"collections",
"currently",
"installed",
"in",
"the",
... | python | train | 46 |
dcramer/peek | peek/tracer.py | https://github.com/dcramer/peek/blob/da7c086660fc870c6632c4dc5ccb2ff9bfbee52e/peek/tracer.py#L237-L248 | def start(self, origin):
"""
Start this Tracer.
Return a Python function suitable for use with sys.settrace().
"""
self.start_time = time.time()
self.pause_until = None
self.data.update(self._get_struct(origin, 'origin'))
self.data_stack.append(self.data)... | [
"def",
"start",
"(",
"self",
",",
"origin",
")",
":",
"self",
".",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"pause_until",
"=",
"None",
"self",
".",
"data",
".",
"update",
"(",
"self",
".",
"_get_struct",
"(",
"origin",
",",
"... | Start this Tracer.
Return a Python function suitable for use with sys.settrace(). | [
"Start",
"this",
"Tracer",
"."
] | python | train | 30.833333 |
rgalanakis/goless | write_benchresults.py | https://github.com/rgalanakis/goless/blob/286cd69482ae5a56c899a0c0d5d895772d96e83d/write_benchresults.py#L86-L98 | def insert_seperator_results(results):
"""Given a sequence of BenchmarkResults,
return a new sequence where a "seperator" BenchmarkResult has been placed
between differing benchmarks to provide a visual difference."""
sepbench = BenchmarkResult(*[' ' * w for w in COLUMN_WIDTHS])
last_bm = None
f... | [
"def",
"insert_seperator_results",
"(",
"results",
")",
":",
"sepbench",
"=",
"BenchmarkResult",
"(",
"*",
"[",
"' '",
"*",
"w",
"for",
"w",
"in",
"COLUMN_WIDTHS",
"]",
")",
"last_bm",
"=",
"None",
"for",
"r",
"in",
"results",
":",
"if",
"last_bm",
"is",... | Given a sequence of BenchmarkResults,
return a new sequence where a "seperator" BenchmarkResult has been placed
between differing benchmarks to provide a visual difference. | [
"Given",
"a",
"sequence",
"of",
"BenchmarkResults",
"return",
"a",
"new",
"sequence",
"where",
"a",
"seperator",
"BenchmarkResult",
"has",
"been",
"placed",
"between",
"differing",
"benchmarks",
"to",
"provide",
"a",
"visual",
"difference",
"."
] | python | train | 38.461538 |
radjkarl/imgProcessor | imgProcessor/camera/CameraCalibration.py | https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/camera/CameraCalibration.py#L590-L611 | def getCoeff(self, name, light=None, date=None):
'''
try to get calibration for right light source, but
use another if they is none existent
'''
d = self.coeffs[name]
try:
c = d[light]
except KeyError:
try:
k, i ... | [
"def",
"getCoeff",
"(",
"self",
",",
"name",
",",
"light",
"=",
"None",
",",
"date",
"=",
"None",
")",
":",
"d",
"=",
"self",
".",
"coeffs",
"[",
"name",
"]",
"try",
":",
"c",
"=",
"d",
"[",
"light",
"]",
"except",
"KeyError",
":",
"try",
":",
... | try to get calibration for right light source, but
use another if they is none existent | [
"try",
"to",
"get",
"calibration",
"for",
"right",
"light",
"source",
"but",
"use",
"another",
"if",
"they",
"is",
"none",
"existent"
] | python | train | 31.772727 |
cqparts/cqparts | src/cqparts/codec/gltf.py | https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/codec/gltf.py#L223-L245 | def read(self):
"""
Read buffer out as a single stream.
.. warning::
Avoid using this function!
**Why?** This is a *convenience* function; it doesn't encourage good
memory management.
All memory required for a mesh is duplicated, and returned a... | [
"def",
"read",
"(",
"self",
")",
":",
"buffer",
"=",
"BytesIO",
"(",
")",
"for",
"chunk",
"in",
"self",
".",
"buffer_iter",
"(",
")",
":",
"log",
".",
"debug",
"(",
"'buffer.write(%r)'",
",",
"chunk",
")",
"buffer",
".",
"write",
"(",
"chunk",
")",
... | Read buffer out as a single stream.
.. warning::
Avoid using this function!
**Why?** This is a *convenience* function; it doesn't encourage good
memory management.
All memory required for a mesh is duplicated, and returned as a
single :class:`str`.... | [
"Read",
"buffer",
"out",
"as",
"a",
"single",
"stream",
"."
] | python | train | 31.304348 |
soldag/python-pwmled | pwmled/led/__init__.py | https://github.com/soldag/python-pwmled/blob/09cde36ecc0153fa81dc2a1b9bb07d1c0e418c8c/pwmled/led/__init__.py#L78-L85 | def _update_pwm(self):
"""Update the pwm values of the driver regarding the current state."""
if self._is_on:
values = self._get_pwm_values()
else:
values = [0] * len(self._driver.pins)
self._driver.set_pwm(values) | [
"def",
"_update_pwm",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_on",
":",
"values",
"=",
"self",
".",
"_get_pwm_values",
"(",
")",
"else",
":",
"values",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"self",
".",
"_driver",
".",
"pins",
")",
"self",
... | Update the pwm values of the driver regarding the current state. | [
"Update",
"the",
"pwm",
"values",
"of",
"the",
"driver",
"regarding",
"the",
"current",
"state",
"."
] | python | train | 33 |
PMEAL/OpenPNM | openpnm/models/phases/surface_tension.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/models/phases/surface_tension.py#L58-L91 | def eotvos(target, k, temperature='pore.temperature',
critical_temperature='pore.critical_temperature',
molar_density='pore.molar_density'):
r"""
Missing description
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. ... | [
"def",
"eotvos",
"(",
"target",
",",
"k",
",",
"temperature",
"=",
"'pore.temperature'",
",",
"critical_temperature",
"=",
"'pore.critical_temperature'",
",",
"molar_density",
"=",
"'pore.molar_density'",
")",
":",
"Tc",
"=",
"target",
"[",
"critical_temperature",
"... | r"""
Missing description
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. This
controls the length of the calculated array, and also provides
access to other necessary thermofluid properties.
k : float
Constant p... | [
"r",
"Missing",
"description"
] | python | train | 29.176471 |
vaexio/vaex | packages/vaex-arrow/vaex_arrow/convert.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-arrow/vaex_arrow/convert.py#L81-L88 | def arrow_table_from_vaex_df(ds, column_names=None, selection=None, strings=True, virtual=False):
"""Implementation of Dataset.to_arrow_table"""
names = []
arrays = []
for name, array in ds.to_items(column_names=column_names, selection=selection, strings=strings, virtual=virtual):
names.append(n... | [
"def",
"arrow_table_from_vaex_df",
"(",
"ds",
",",
"column_names",
"=",
"None",
",",
"selection",
"=",
"None",
",",
"strings",
"=",
"True",
",",
"virtual",
"=",
"False",
")",
":",
"names",
"=",
"[",
"]",
"arrays",
"=",
"[",
"]",
"for",
"name",
",",
"... | Implementation of Dataset.to_arrow_table | [
"Implementation",
"of",
"Dataset",
".",
"to_arrow_table"
] | python | test | 53.5 |
sentinel-hub/eo-learn | ml_tools/eolearn/ml_tools/classifier.py | https://github.com/sentinel-hub/eo-learn/blob/b8c390b9f553c561612fe9eb64e720611633a035/ml_tools/eolearn/ml_tools/classifier.py#L418-L447 | def image_predict_proba(self, X):
"""
Predicts class probabilities for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n... | [
"def",
"image_predict_proba",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"_check_image",
"(",
"X",
")",
"probabilities",
"=",
"self",
".",
"pixel_classifier",
".",
"image_predict_proba",
"(",
"X",
")",
"patches",
",",
"_",
"=",
"self",
".",
"_to_patches... | Predicts class probabilities for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n_pixels_x, n_pixels_y, n_classes]
Target pr... | [
"Predicts",
"class",
"probabilities",
"for",
"the",
"entire",
"image",
".",
"Parameters",
":",
"-----------",
"X",
":",
"array",
"shape",
"=",
"[",
"n_samples",
"n_pixels_x",
"n_pixels_y",
"n_bands",
"]",
"Array",
"of",
"training",
"images",
"y",
":",
"array",... | python | train | 34.066667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.