repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
blue-yonder/tsfresh | tsfresh/utilities/dataframe_functions.py | https://github.com/blue-yonder/tsfresh/blob/c72c9c574371cf7dd7d54e00a466792792e5d202/tsfresh/utilities/dataframe_functions.py#L237-L351 | def _normalize_input_to_internal_representation(timeseries_container, column_id, column_sort, column_kind, column_value):
"""
Try to transform any given input to the internal representation of time series, which is a flat DataFrame
(the first format from see :ref:`data-formats-label`).
This function ca... | [
"def",
"_normalize_input_to_internal_representation",
"(",
"timeseries_container",
",",
"column_id",
",",
"column_sort",
",",
"column_kind",
",",
"column_value",
")",
":",
"# Also make it possible to have a dict as an input",
"if",
"isinstance",
"(",
"timeseries_container",
","... | Try to transform any given input to the internal representation of time series, which is a flat DataFrame
(the first format from see :ref:`data-formats-label`).
This function can transform pandas DataFrames in different formats or dictionaries into the internal format
that we use. It should not be called b... | [
"Try",
"to",
"transform",
"any",
"given",
"input",
"to",
"the",
"internal",
"representation",
"of",
"time",
"series",
"which",
"is",
"a",
"flat",
"DataFrame",
"(",
"the",
"first",
"format",
"from",
"see",
":",
"ref",
":",
"data",
"-",
"formats",
"-",
"la... | python | train |
OpenTreeOfLife/peyotl | peyotl/collections_store/collections_umbrella.py | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/collections_store/collections_umbrella.py#L238-L244 | def _slugify_internal_collection_name(self, json_repr):
"""Parse the JSON, find its name, return a slug of its name"""
collection = self._coerce_json_to_collection(json_repr)
if collection is None:
return None
internal_name = collection['name']
return slugify(internal... | [
"def",
"_slugify_internal_collection_name",
"(",
"self",
",",
"json_repr",
")",
":",
"collection",
"=",
"self",
".",
"_coerce_json_to_collection",
"(",
"json_repr",
")",
"if",
"collection",
"is",
"None",
":",
"return",
"None",
"internal_name",
"=",
"collection",
"... | Parse the JSON, find its name, return a slug of its name | [
"Parse",
"the",
"JSON",
"find",
"its",
"name",
"return",
"a",
"slug",
"of",
"its",
"name"
] | python | train |
apache/incubator-mxnet | python/mxnet/model.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L394-L421 | def save_checkpoint(prefix, epoch, symbol, arg_params, aux_params):
"""Checkpoint the model data into file.
Parameters
----------
prefix : str
Prefix of model name.
epoch : int
The epoch number of the model.
symbol : Symbol
The input Symbol.
arg_params : dict of str ... | [
"def",
"save_checkpoint",
"(",
"prefix",
",",
"epoch",
",",
"symbol",
",",
"arg_params",
",",
"aux_params",
")",
":",
"if",
"symbol",
"is",
"not",
"None",
":",
"symbol",
".",
"save",
"(",
"'%s-symbol.json'",
"%",
"prefix",
")",
"save_dict",
"=",
"{",
"("... | Checkpoint the model data into file.
Parameters
----------
prefix : str
Prefix of model name.
epoch : int
The epoch number of the model.
symbol : Symbol
The input Symbol.
arg_params : dict of str to NDArray
Model parameter, dict of name to NDArray of net's weight... | [
"Checkpoint",
"the",
"model",
"data",
"into",
"file",
"."
] | python | train |
zikzakmedia/python-mediawiki | mediawiki/wikimarkup/__init__.py | https://github.com/zikzakmedia/python-mediawiki/blob/7c26732efa520e16c35350815ce98cd7610a0bcb/mediawiki/wikimarkup/__init__.py#L2042-L2075 | def to_unicode(text, charset=None):
"""Convert a `str` object to an `unicode` object.
If `charset` is given, we simply assume that encoding for the text,
but we'll use the "replace" mode so that the decoding will always
succeed.
If `charset` is ''not'' specified, we'll make some guesses, first
trying the UTF-8 e... | [
"def",
"to_unicode",
"(",
"text",
",",
"charset",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"Exception",
")",
":",
"# two possibilities for storing unicode strings in exception data... | Convert a `str` object to an `unicode` object.
If `charset` is given, we simply assume that encoding for the text,
but we'll use the "replace" mode so that the decoding will always
succeed.
If `charset` is ''not'' specified, we'll make some guesses, first
trying the UTF-8 encoding, then trying the locale preferre... | [
"Convert",
"a",
"str",
"object",
"to",
"an",
"unicode",
"object",
"."
] | python | train |
jantman/versionfinder | versionfinder/versionfinder.py | https://github.com/jantman/versionfinder/blob/773dd9c0a99fa02e515347111c352471a7a3e30c/versionfinder/versionfinder.py#L196-L211 | def _git_repo_path(self):
"""
Attempt to determine whether this package is installed via git or not;
if so, return the path to the git repository.
:rtype: str
:returns: path to git repo, or None
"""
logger.debug('Checking for git directory in: %s', self._package_... | [
"def",
"_git_repo_path",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Checking for git directory in: %s'",
",",
"self",
".",
"_package_top_dir",
")",
"for",
"p",
"in",
"self",
".",
"_package_top_dir",
":",
"gitdir",
"=",
"os",
".",
"path",
".",
"joi... | Attempt to determine whether this package is installed via git or not;
if so, return the path to the git repository.
:rtype: str
:returns: path to git repo, or None | [
"Attempt",
"to",
"determine",
"whether",
"this",
"package",
"is",
"installed",
"via",
"git",
"or",
"not",
";",
"if",
"so",
"return",
"the",
"path",
"to",
"the",
"git",
"repository",
"."
] | python | train |
vpelletier/python-ioctl-opt | ioctl_opt/__init__.py | https://github.com/vpelletier/python-ioctl-opt/blob/29ec5029af4a7de8709c449090529c4cc63d62b0/ioctl_opt/__init__.py#L79-L86 | def IOR(type, nr, size):
"""
An ioctl with read parameters.
size (ctype type or instance)
Type/structure of the argument passed to ioctl's "arg" argument.
"""
return IOC(IOC_READ, type, nr, IOC_TYPECHECK(size)) | [
"def",
"IOR",
"(",
"type",
",",
"nr",
",",
"size",
")",
":",
"return",
"IOC",
"(",
"IOC_READ",
",",
"type",
",",
"nr",
",",
"IOC_TYPECHECK",
"(",
"size",
")",
")"
] | An ioctl with read parameters.
size (ctype type or instance)
Type/structure of the argument passed to ioctl's "arg" argument. | [
"An",
"ioctl",
"with",
"read",
"parameters",
"."
] | python | train |
bitesofcode/projex | projex/makotext.py | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/makotext.py#L104-L186 | def render(text,
options=None,
templatePaths=None,
default=None,
silent=False,
raiseErrors=False):
"""
Renders a template text to a resolved text value using the mako template
system.
Provides a much more robust template option to the projex.te... | [
"def",
"render",
"(",
"text",
",",
"options",
"=",
"None",
",",
"templatePaths",
"=",
"None",
",",
"default",
"=",
"None",
",",
"silent",
"=",
"False",
",",
"raiseErrors",
"=",
"False",
")",
":",
"if",
"not",
"mako",
":",
"logger",
".",
"debug",
"(",... | Renders a template text to a resolved text value using the mako template
system.
Provides a much more robust template option to the projex.text system.
While the projex.text method can handle many simple cases with no
dependencies, the makotext module makes use of the powerful mako template
l... | [
"Renders",
"a",
"template",
"text",
"to",
"a",
"resolved",
"text",
"value",
"using",
"the",
"mako",
"template",
"system",
".",
"Provides",
"a",
"much",
"more",
"robust",
"template",
"option",
"to",
"the",
"projex",
".",
"text",
"system",
".",
"While",
"the... | python | train |
kakwa/ldapcherry | ldapcherry/backend/backendDemo.py | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendDemo.py#L121-L131 | def set_attrs(self, username, attrs):
""" set a list of attributes for a given user
:param username: 'key' attribute of the user
:type username: string
:param attrs: attributes of the user
:type attrs: dict ({<attr>: <value>})
"""
self._check_fix_users(username)
... | [
"def",
"set_attrs",
"(",
"self",
",",
"username",
",",
"attrs",
")",
":",
"self",
".",
"_check_fix_users",
"(",
"username",
")",
"for",
"attr",
"in",
"attrs",
":",
"self",
".",
"users",
"[",
"username",
"]",
"[",
"attr",
"]",
"=",
"attrs",
"[",
"attr... | set a list of attributes for a given user
:param username: 'key' attribute of the user
:type username: string
:param attrs: attributes of the user
:type attrs: dict ({<attr>: <value>}) | [
"set",
"a",
"list",
"of",
"attributes",
"for",
"a",
"given",
"user"
] | python | train |
gopalkoduri/pypeaks | pypeaks/slope.py | https://github.com/gopalkoduri/pypeaks/blob/59b1e4153e80c6a4c523dda241cc1713fd66161e/pypeaks/slope.py#L142-L154 | def peaks(x, y, lookahead=20, delta=0.00003):
"""
A wrapper around peakdetect to pack the return values in a nicer format
"""
_max, _min = peakdetect(y, x, lookahead, delta)
x_peaks = [p[0] for p in _max]
y_peaks = [p[1] for p in _max]
x_valleys = [p[0] for p in _min]
y_valleys = [p[1] f... | [
"def",
"peaks",
"(",
"x",
",",
"y",
",",
"lookahead",
"=",
"20",
",",
"delta",
"=",
"0.00003",
")",
":",
"_max",
",",
"_min",
"=",
"peakdetect",
"(",
"y",
",",
"x",
",",
"lookahead",
",",
"delta",
")",
"x_peaks",
"=",
"[",
"p",
"[",
"0",
"]",
... | A wrapper around peakdetect to pack the return values in a nicer format | [
"A",
"wrapper",
"around",
"peakdetect",
"to",
"pack",
"the",
"return",
"values",
"in",
"a",
"nicer",
"format"
] | python | train |
jmoiron/micromongo | micromongo/spec.py | https://github.com/jmoiron/micromongo/blob/0d7dd1396e2f25ece6648619ccff32345bc306a1/micromongo/spec.py#L100-L123 | def validate(document, spec):
"""Validate that a document meets a specification. Returns True if
validation was successful, but otherwise raises a ValueError."""
if not spec:
return True
missing = []
for key, field in spec.iteritems():
if field.required and key not in document:
... | [
"def",
"validate",
"(",
"document",
",",
"spec",
")",
":",
"if",
"not",
"spec",
":",
"return",
"True",
"missing",
"=",
"[",
"]",
"for",
"key",
",",
"field",
"in",
"spec",
".",
"iteritems",
"(",
")",
":",
"if",
"field",
".",
"required",
"and",
"key"... | Validate that a document meets a specification. Returns True if
validation was successful, but otherwise raises a ValueError. | [
"Validate",
"that",
"a",
"document",
"meets",
"a",
"specification",
".",
"Returns",
"True",
"if",
"validation",
"was",
"successful",
"but",
"otherwise",
"raises",
"a",
"ValueError",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/repository/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/objects.py#L1967-L1986 | def set_children(self, child_ids):
"""Sets the children.
arg: child_ids (osid.id.Id[]): the children``Ids``
raise: InvalidArgument - ``child_ids`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
... | [
"def",
"set_children",
"(",
"self",
",",
"child_ids",
")",
":",
"if",
"not",
"isinstance",
"(",
"child_ids",
",",
"list",
")",
":",
"raise",
"errors",
".",
"InvalidArgument",
"(",
")",
"if",
"self",
".",
"get_children_metadata",
"(",
")",
".",
"is_read_onl... | Sets the children.
arg: child_ids (osid.id.Id[]): the children``Ids``
raise: InvalidArgument - ``child_ids`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* | [
"Sets",
"the",
"children",
"."
] | python | train |
summanlp/textrank | summa/preprocessing/porter.py | https://github.com/summanlp/textrank/blob/6844bbe8c4b2b468020ae0dfd6574a743f9ad442/summa/preprocessing/porter.py#L211-L216 | def _vowelinstem(self, stem):
"""vowelinstem(stem) is TRUE <=> stem contains a vowel"""
for i in range(len(stem)):
if not self._cons(stem, i):
return True
return False | [
"def",
"_vowelinstem",
"(",
"self",
",",
"stem",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"stem",
")",
")",
":",
"if",
"not",
"self",
".",
"_cons",
"(",
"stem",
",",
"i",
")",
":",
"return",
"True",
"return",
"False"
] | vowelinstem(stem) is TRUE <=> stem contains a vowel | [
"vowelinstem",
"(",
"stem",
")",
"is",
"TRUE",
"<",
"=",
">",
"stem",
"contains",
"a",
"vowel"
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L170-L205 | def _read_waypoints_v110(self, file):
'''read a version 110 waypoint'''
comment = ''
for line in file:
if line.startswith('#'):
comment = line[1:].lstrip()
continue
line = line.strip()
if not line:
continue
... | [
"def",
"_read_waypoints_v110",
"(",
"self",
",",
"file",
")",
":",
"comment",
"=",
"''",
"for",
"line",
"in",
"file",
":",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"comment",
"=",
"line",
"[",
"1",
":",
"]",
".",
"lstrip",
"(",
")",
... | read a version 110 waypoint | [
"read",
"a",
"version",
"110",
"waypoint"
] | python | train |
CiscoDevNet/webexteamssdk | webexteamssdk/restsession.py | https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/restsession.py#L421-L440 | def delete(self, url, **kwargs):
"""Sends a DELETE request.
Args:
url(basestring): The URL of the API endpoint.
**kwargs:
erc(int): The expected (success) response code for the request.
others: Passed on to the requests package.
Raises:
... | [
"def",
"delete",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"check_type",
"(",
"url",
",",
"basestring",
",",
"may_be_none",
"=",
"False",
")",
"# Expected response code",
"erc",
"=",
"kwargs",
".",
"pop",
"(",
"'erc'",
",",
"EXPECTED_RE... | Sends a DELETE request.
Args:
url(basestring): The URL of the API endpoint.
**kwargs:
erc(int): The expected (success) response code for the request.
others: Passed on to the requests package.
Raises:
ApiError: If anything other than ... | [
"Sends",
"a",
"DELETE",
"request",
"."
] | python | test |
intelsdi-x/snap-plugin-lib-py | snap_plugin/v1/config_map.py | https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L195-L207 | def pop(self, key, default=None):
"""Remove specified key and return the corresponding value.
If key is not found, default is returned if given, otherwise
KeyError is raised.
"""
if key not in self:
if default is not None:
return default
... | [
"def",
"pop",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"key",
"not",
"in",
"self",
":",
"if",
"default",
"is",
"not",
"None",
":",
"return",
"default",
"raise",
"KeyError",
"(",
"key",
")",
"for",
"map",
"in",
"[",
"s... | Remove specified key and return the corresponding value.
If key is not found, default is returned if given, otherwise
KeyError is raised. | [
"Remove",
"specified",
"key",
"and",
"return",
"the",
"corresponding",
"value",
".",
"If",
"key",
"is",
"not",
"found",
"default",
"is",
"returned",
"if",
"given",
"otherwise",
"KeyError",
"is",
"raised",
"."
] | python | train |
CI-WATER/gsshapy | gsshapy/lib/db_tools.py | https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/lib/db_tools.py#L177-L231 | def init_mysql_db(username, host, database, port='', password='', initTime=False):
"""
Initialize MySQL Database
.. note:: mysql-python or similar driver required
Args:
username(str): Database username.
host(str): Database host URL.
database(str): Database name.
... | [
"def",
"init_mysql_db",
"(",
"username",
",",
"host",
",",
"database",
",",
"port",
"=",
"''",
",",
"password",
"=",
"''",
",",
"initTime",
"=",
"False",
")",
":",
"mysql_base_url",
"=",
"'mysql://'",
"if",
"password",
"!=",
"''",
":",
"password",
"=",
... | Initialize MySQL Database
.. note:: mysql-python or similar driver required
Args:
username(str): Database username.
host(str): Database host URL.
database(str): Database name.
port(Optional[int,str]): Database port.
password(Optional[str]): Database password.
... | [
"Initialize",
"MySQL",
"Database",
"..",
"note",
"::",
"mysql",
"-",
"python",
"or",
"similar",
"driver",
"required",
"Args",
":",
"username",
"(",
"str",
")",
":",
"Database",
"username",
".",
"host",
"(",
"str",
")",
":",
"Database",
"host",
"URL",
"."... | python | train |
jreese/tasky | tasky/config.py | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/config.py#L72-L94 | async def init(self) -> None:
'''Load configuration in JSON format from either a file or
a raw data string.'''
if self.data:
return
if self.json_data:
try:
self.data = json.loads(self.json_data)
except Exception:
Log.... | [
"async",
"def",
"init",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"data",
":",
"return",
"if",
"self",
".",
"json_data",
":",
"try",
":",
"self",
".",
"data",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"json_data",
")",
"except",
... | Load configuration in JSON format from either a file or
a raw data string. | [
"Load",
"configuration",
"in",
"JSON",
"format",
"from",
"either",
"a",
"file",
"or",
"a",
"raw",
"data",
"string",
"."
] | python | train |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/view.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/view.py#L237-L243 | def unselect_item(self, item):
""" Unselect an item. """
self.queue_draw_item(item)
if item.model in self._selection:
with self._suppress_selection_events():
self._selection.remove(item.model)
self.emit('selection-changed', self._get_selected_items()) | [
"def",
"unselect_item",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"queue_draw_item",
"(",
"item",
")",
"if",
"item",
".",
"model",
"in",
"self",
".",
"_selection",
":",
"with",
"self",
".",
"_suppress_selection_events",
"(",
")",
":",
"self",
".",... | Unselect an item. | [
"Unselect",
"an",
"item",
"."
] | python | train |
nerdvegas/rez | src/rez/vendor/pygraph/algorithms/heuristics/chow.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/heuristics/chow.py#L51-L61 | def optimize(self, graph):
"""
Build a dictionary mapping each pair of nodes to a number (the distance between them).
@type graph: graph
@param graph: Graph.
"""
for center in self.centers:
shortest_routes = shortest_path(graph, center)[1]
... | [
"def",
"optimize",
"(",
"self",
",",
"graph",
")",
":",
"for",
"center",
"in",
"self",
".",
"centers",
":",
"shortest_routes",
"=",
"shortest_path",
"(",
"graph",
",",
"center",
")",
"[",
"1",
"]",
"for",
"node",
",",
"weight",
"in",
"list",
"(",
"sh... | Build a dictionary mapping each pair of nodes to a number (the distance between them).
@type graph: graph
@param graph: Graph. | [
"Build",
"a",
"dictionary",
"mapping",
"each",
"pair",
"of",
"nodes",
"to",
"a",
"number",
"(",
"the",
"distance",
"between",
"them",
")",
"."
] | python | train |
vsoch/helpme | helpme/main/base/settings.py | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/settings.py#L107-L111 | def remove_user_setting(self, section, name, save=False):
'''remove a setting from the user config
'''
configfile = get_configfile_user()
return _remove_setting(section, name, configfile, save) | [
"def",
"remove_user_setting",
"(",
"self",
",",
"section",
",",
"name",
",",
"save",
"=",
"False",
")",
":",
"configfile",
"=",
"get_configfile_user",
"(",
")",
"return",
"_remove_setting",
"(",
"section",
",",
"name",
",",
"configfile",
",",
"save",
")"
] | remove a setting from the user config | [
"remove",
"a",
"setting",
"from",
"the",
"user",
"config"
] | python | train |
saltstack/salt | salt/states/tomcat.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/tomcat.py#L73-L222 | def war_deployed(name,
war,
force=False,
url='http://localhost:8080/manager',
timeout=180,
temp_war_location=None,
version=True):
'''
Enforce that the WAR will be deployed and started in the context path,
w... | [
"def",
"war_deployed",
"(",
"name",
",",
"war",
",",
"force",
"=",
"False",
",",
"url",
"=",
"'http://localhost:8080/manager'",
",",
"timeout",
"=",
"180",
",",
"temp_war_location",
"=",
"None",
",",
"version",
"=",
"True",
")",
":",
"# Prepare",
"ret",
"=... | Enforce that the WAR will be deployed and started in the context path,
while making use of WAR versions in the filename.
.. note::
For more info about Tomcats file paths and context naming, please see
http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Naming
name
The cont... | [
"Enforce",
"that",
"the",
"WAR",
"will",
"be",
"deployed",
"and",
"started",
"in",
"the",
"context",
"path",
"while",
"making",
"use",
"of",
"WAR",
"versions",
"in",
"the",
"filename",
"."
] | python | train |
infobloxopen/infoblox-client | infoblox_client/connector.py | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/connector.py#L212-L220 | def _parse_reply(request):
"""Tries to parse reply from NIOS.
Raises exception with content if reply is not in json format
"""
try:
return jsonutils.loads(request.content)
except ValueError:
raise ib_ex.InfobloxConnectionError(reason=request.content) | [
"def",
"_parse_reply",
"(",
"request",
")",
":",
"try",
":",
"return",
"jsonutils",
".",
"loads",
"(",
"request",
".",
"content",
")",
"except",
"ValueError",
":",
"raise",
"ib_ex",
".",
"InfobloxConnectionError",
"(",
"reason",
"=",
"request",
".",
"content... | Tries to parse reply from NIOS.
Raises exception with content if reply is not in json format | [
"Tries",
"to",
"parse",
"reply",
"from",
"NIOS",
"."
] | python | train |
quantopian/pyfolio | pyfolio/plotting.py | https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L235-L283 | def plot_monthly_returns_dist(returns, ax=None, **kwargs):
"""
Plots a distribution of monthly returns.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
ax : matplotlib.Axes, optional... | [
"def",
"plot_monthly_returns_dist",
"(",
"returns",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"x_axis_formatter",
"=",
"FuncFormatter",
"(",
"utils",
".",
"percenta... | Plots a distribution of monthly returns.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
ax : matplotlib.Axes, optional
Axes upon which to plot.
**kwargs, optional
Passed... | [
"Plots",
"a",
"distribution",
"of",
"monthly",
"returns",
"."
] | python | valid |
angr/angr | angr/analyses/cfg/cfg_fast.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/cfg/cfg_fast.py#L3163-L3333 | def _generate_cfgnode(self, cfg_job, current_function_addr):
"""
Generate a CFGNode that starts at `cfg_job.addr`.
Since lifting machine code to IRSBs is slow, self._nodes is used as a cache of CFGNodes.
If the current architecture is ARM, this method will try to lift the block in the ... | [
"def",
"_generate_cfgnode",
"(",
"self",
",",
"cfg_job",
",",
"current_function_addr",
")",
":",
"addr",
"=",
"cfg_job",
".",
"addr",
"try",
":",
"if",
"addr",
"in",
"self",
".",
"_nodes",
":",
"cfg_node",
"=",
"self",
".",
"_nodes",
"[",
"addr",
"]",
... | Generate a CFGNode that starts at `cfg_job.addr`.
Since lifting machine code to IRSBs is slow, self._nodes is used as a cache of CFGNodes.
If the current architecture is ARM, this method will try to lift the block in the mode specified by the address
(determined by the parity of the address: e... | [
"Generate",
"a",
"CFGNode",
"that",
"starts",
"at",
"cfg_job",
".",
"addr",
"."
] | python | train |
robotools/fontParts | Lib/fontParts/base/glyph.py | https://github.com/robotools/fontParts/blob/d2ff106fe95f9d566161d936a645157626568712/Lib/fontParts/base/glyph.py#L1222-L1238 | def removeAnchor(self, anchor):
"""
Remove ``anchor`` from the glyph.
>>> glyph.removeAnchor(anchor)
``anchor`` may be an :ref:`BaseAnchor` or an
:ref:`type-int` representing an anchor index.
"""
if isinstance(anchor, int):
index = anchor
... | [
"def",
"removeAnchor",
"(",
"self",
",",
"anchor",
")",
":",
"if",
"isinstance",
"(",
"anchor",
",",
"int",
")",
":",
"index",
"=",
"anchor",
"else",
":",
"index",
"=",
"self",
".",
"_getAnchorIndex",
"(",
"anchor",
")",
"index",
"=",
"normalizers",
".... | Remove ``anchor`` from the glyph.
>>> glyph.removeAnchor(anchor)
``anchor`` may be an :ref:`BaseAnchor` or an
:ref:`type-int` representing an anchor index. | [
"Remove",
"anchor",
"from",
"the",
"glyph",
"."
] | python | train |
pyviz/holoviews | holoviews/plotting/plot.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/plot.py#L886-L900 | def _execute_hooks(self, element):
"""
Executes finalize hooks
"""
if self.hooks and self.finalize_hooks:
self.param.warning(
"Supply either hooks or finalize_hooks not both, "
"using hooks and ignoring finalize_hooks.")
hooks = self.ho... | [
"def",
"_execute_hooks",
"(",
"self",
",",
"element",
")",
":",
"if",
"self",
".",
"hooks",
"and",
"self",
".",
"finalize_hooks",
":",
"self",
".",
"param",
".",
"warning",
"(",
"\"Supply either hooks or finalize_hooks not both, \"",
"\"using hooks and ignoring finali... | Executes finalize hooks | [
"Executes",
"finalize",
"hooks"
] | python | train |
Kortemme-Lab/klab | klab/bio/basics.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/basics.py#L270-L274 | def translate_codons(sequence):
'''Return the translated protein from 'sequence' assuming +1 reading frame
Source - http://adamcoster.com/2011/01/13/python-clean-up-and-translate-nucleotide-sequences/
'''
return ''.join([gencode.get(sequence[3*i:3*i+3],'X') for i in range(len(sequence)//3)]) | [
"def",
"translate_codons",
"(",
"sequence",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"gencode",
".",
"get",
"(",
"sequence",
"[",
"3",
"*",
"i",
":",
"3",
"*",
"i",
"+",
"3",
"]",
",",
"'X'",
")",
"for",
"i",
"in",
"range",
"(",
"len",
... | Return the translated protein from 'sequence' assuming +1 reading frame
Source - http://adamcoster.com/2011/01/13/python-clean-up-and-translate-nucleotide-sequences/ | [
"Return",
"the",
"translated",
"protein",
"from",
"sequence",
"assuming",
"+",
"1",
"reading",
"frame",
"Source",
"-",
"http",
":",
"//",
"adamcoster",
".",
"com",
"/",
"2011",
"/",
"01",
"/",
"13",
"/",
"python",
"-",
"clean",
"-",
"up",
"-",
"and",
... | python | train |
proteanhq/protean | src/protean/core/transport/request.py | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/transport/request.py#L40-L117 | def construct(cls, name: str, declared_fields: typing.List[tuple]):
"""
Utility method packaged along with the factory to be able to construct Request Object
classes on the fly.
Example:
.. code-block:: python
UserShowRequestObject = Factory.create_request_object(
... | [
"def",
"construct",
"(",
"cls",
",",
"name",
":",
"str",
",",
"declared_fields",
":",
"typing",
".",
"List",
"[",
"tuple",
"]",
")",
":",
"# FIXME Refactor this method to make it simpler",
"@",
"classmethod",
"def",
"from_dict",
"(",
"cls",
",",
"adict",
")",
... | Utility method packaged along with the factory to be able to construct Request Object
classes on the fly.
Example:
.. code-block:: python
UserShowRequestObject = Factory.create_request_object(
'CreateRequestObject',
[('identifier', int, {'required':... | [
"Utility",
"method",
"packaged",
"along",
"with",
"the",
"factory",
"to",
"be",
"able",
"to",
"construct",
"Request",
"Object",
"classes",
"on",
"the",
"fly",
"."
] | python | train |
riga/scinum | scinum.py | https://github.com/riga/scinum/blob/55eb6d8aa77beacee5a07443392954b8a0aad8cb/scinum.py#L1389-L1422 | def split_value(val):
"""
Splits a value *val* into its significand and decimal exponent (magnitude) and returns them in a
2-tuple. *val* might also be a numpy array. Example:
.. code-block:: python
split_value(1) # -> (1.0, 0)
split_value(0.123) # -> (1.23, -1)
split_value... | [
"def",
"split_value",
"(",
"val",
")",
":",
"val",
"=",
"ensure_nominal",
"(",
"val",
")",
"if",
"not",
"is_numpy",
"(",
"val",
")",
":",
"# handle 0 separately",
"if",
"val",
"==",
"0",
":",
"return",
"(",
"0.",
",",
"0",
")",
"mag",
"=",
"int",
"... | Splits a value *val* into its significand and decimal exponent (magnitude) and returns them in a
2-tuple. *val* might also be a numpy array. Example:
.. code-block:: python
split_value(1) # -> (1.0, 0)
split_value(0.123) # -> (1.23, -1)
split_value(-42.5) # -> (-4.25, 1)
a... | [
"Splits",
"a",
"value",
"*",
"val",
"*",
"into",
"its",
"significand",
"and",
"decimal",
"exponent",
"(",
"magnitude",
")",
"and",
"returns",
"them",
"in",
"a",
"2",
"-",
"tuple",
".",
"*",
"val",
"*",
"might",
"also",
"be",
"a",
"numpy",
"array",
".... | python | train |
GNS3/gns3-server | gns3server/controller/import_project.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/import_project.py#L157-L172 | def _move_node_file(path, old_id, new_id):
"""
Move the files from a node when changing his id
:param path: Path of the project
:param old_id: ID before change
:param new_id: New node UUID
"""
root = os.path.join(path, "project-files")
if os.path.exists(root):
for dirname in os.... | [
"def",
"_move_node_file",
"(",
"path",
",",
"old_id",
",",
"new_id",
")",
":",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"project-files\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"root",
")",
":",
"for",
"dirname",
... | Move the files from a node when changing his id
:param path: Path of the project
:param old_id: ID before change
:param new_id: New node UUID | [
"Move",
"the",
"files",
"from",
"a",
"node",
"when",
"changing",
"his",
"id"
] | python | train |
Gandi/gandi.cli | gandi/cli/core/utils/__init__.py | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/utils/__init__.py#L480-L484 | def output_sub_generic(gandi, data, output_keys, justify=10):
""" Generic helper to output info from a data dict."""
for key in output_keys:
if key in data:
output_sub_line(gandi, key, data[key], justify) | [
"def",
"output_sub_generic",
"(",
"gandi",
",",
"data",
",",
"output_keys",
",",
"justify",
"=",
"10",
")",
":",
"for",
"key",
"in",
"output_keys",
":",
"if",
"key",
"in",
"data",
":",
"output_sub_line",
"(",
"gandi",
",",
"key",
",",
"data",
"[",
"key... | Generic helper to output info from a data dict. | [
"Generic",
"helper",
"to",
"output",
"info",
"from",
"a",
"data",
"dict",
"."
] | python | train |
jasonlaska/spherecluster | spherecluster/von_mises_fisher_mixture.py | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/von_mises_fisher_mixture.py#L814-L850 | def fit(self, X, y=None):
"""Compute mixture of von Mises Fisher clustering.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
"""
if self.normalize:
X = normalize(X)
self._check_force_weights()
random_state... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"if",
"self",
".",
"normalize",
":",
"X",
"=",
"normalize",
"(",
"X",
")",
"self",
".",
"_check_force_weights",
"(",
")",
"random_state",
"=",
"check_random_state",
"(",
"self",
".... | Compute mixture of von Mises Fisher clustering.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features) | [
"Compute",
"mixture",
"of",
"von",
"Mises",
"Fisher",
"clustering",
"."
] | python | train |
aparsons/threadfix_api | threadfix_api/threadfix.py | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L211-L221 | def create_waf(self, name, waf_type):
"""
Creates a WAF with the given type.
:param name: Name of the WAF.
:param waf_type: WAF type. ('mod_security', 'Snort', 'Imperva SecureSphere', 'F5 BigIP ASM', 'DenyAll rWeb')
"""
params = {
'name': name,
'ty... | [
"def",
"create_waf",
"(",
"self",
",",
"name",
",",
"waf_type",
")",
":",
"params",
"=",
"{",
"'name'",
":",
"name",
",",
"'type'",
":",
"waf_type",
"}",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'rest/wafs/new'",
",",
"params",
")"
] | Creates a WAF with the given type.
:param name: Name of the WAF.
:param waf_type: WAF type. ('mod_security', 'Snort', 'Imperva SecureSphere', 'F5 BigIP ASM', 'DenyAll rWeb') | [
"Creates",
"a",
"WAF",
"with",
"the",
"given",
"type",
".",
":",
"param",
"name",
":",
"Name",
"of",
"the",
"WAF",
".",
":",
"param",
"waf_type",
":",
"WAF",
"type",
".",
"(",
"mod_security",
"Snort",
"Imperva",
"SecureSphere",
"F5",
"BigIP",
"ASM",
"D... | python | train |
tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L1160-L1176 | def video_l1_top(body_output, targets, model_hparams, vocab_size):
"""Top transformation for video."""
del targets, vocab_size # unused arg
num_channels = model_hparams.problem.num_channels
num_frames = model_hparams.video_num_target_frames
with tf.variable_scope("rgb"):
body_output_shape = common_layers... | [
"def",
"video_l1_top",
"(",
"body_output",
",",
"targets",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"del",
"targets",
",",
"vocab_size",
"# unused arg",
"num_channels",
"=",
"model_hparams",
".",
"problem",
".",
"num_channels",
"num_frames",
"=",
"model_... | Top transformation for video. | [
"Top",
"transformation",
"for",
"video",
"."
] | python | train |
iskandr/serializable | serializable/helpers.py | https://github.com/iskandr/serializable/blob/6807dfd582567b3bda609910806b7429d8d53b44/serializable/helpers.py#L120-L133 | def function_to_serializable_representation(fn):
"""
Converts a Python function into a serializable representation. Does not
currently work for methods or functions with closure data.
"""
if type(fn) not in (FunctionType, BuiltinFunctionType):
raise ValueError(
"Can't serialize %... | [
"def",
"function_to_serializable_representation",
"(",
"fn",
")",
":",
"if",
"type",
"(",
"fn",
")",
"not",
"in",
"(",
"FunctionType",
",",
"BuiltinFunctionType",
")",
":",
"raise",
"ValueError",
"(",
"\"Can't serialize %s : %s, must be globally defined function\"",
"%"... | Converts a Python function into a serializable representation. Does not
currently work for methods or functions with closure data. | [
"Converts",
"a",
"Python",
"function",
"into",
"a",
"serializable",
"representation",
".",
"Does",
"not",
"currently",
"work",
"for",
"methods",
"or",
"functions",
"with",
"closure",
"data",
"."
] | python | train |
molmod/molmod | molmod/io/number_state.py | https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/io/number_state.py#L120-L137 | def dump(self, f, name):
"""Write the attribute to a file-like object"""
array = self.get()
# print the header line
print("% 40s kind=%s shape=(%s)" % (
name,
array.dtype.kind,
",".join([str(int(size_axis)) for size_axis in array.shape]),
), ... | [
"def",
"dump",
"(",
"self",
",",
"f",
",",
"name",
")",
":",
"array",
"=",
"self",
".",
"get",
"(",
")",
"# print the header line",
"print",
"(",
"\"% 40s kind=%s shape=(%s)\"",
"%",
"(",
"name",
",",
"array",
".",
"dtype",
".",
"kind",
",",
"\",\"",
... | Write the attribute to a file-like object | [
"Write",
"the",
"attribute",
"to",
"a",
"file",
"-",
"like",
"object"
] | python | train |
pandas-dev/pandas | pandas/core/indexes/datetimelike.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L34-L52 | def ea_passthrough(array_method):
"""
Make an alias for a method of the underlying ExtensionArray.
Parameters
----------
array_method : method on an Array class
Returns
-------
method
"""
def method(self, *args, **kwargs):
return array_method(self._data, *args, **kwarg... | [
"def",
"ea_passthrough",
"(",
"array_method",
")",
":",
"def",
"method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"array_method",
"(",
"self",
".",
"_data",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"method",
... | Make an alias for a method of the underlying ExtensionArray.
Parameters
----------
array_method : method on an Array class
Returns
-------
method | [
"Make",
"an",
"alias",
"for",
"a",
"method",
"of",
"the",
"underlying",
"ExtensionArray",
"."
] | python | train |
uber/tchannel-python | tchannel/tracing.py | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tracing.py#L137-L180 | def start_span(self, request, headers, peer_host, peer_port):
"""
Start a new server-side span. If the span has already been started
by `start_basic_span`, this method only adds baggage from the headers.
:param request: inbound tchannel.tornado.request.Request
:param headers: di... | [
"def",
"start_span",
"(",
"self",
",",
"request",
",",
"headers",
",",
"peer_host",
",",
"peer_port",
")",
":",
"parent_context",
"=",
"None",
"# noinspection PyBroadException",
"try",
":",
"if",
"headers",
"and",
"hasattr",
"(",
"headers",
",",
"'iteritems'",
... | Start a new server-side span. If the span has already been started
by `start_basic_span`, this method only adds baggage from the headers.
:param request: inbound tchannel.tornado.request.Request
:param headers: dictionary containing parsed application headers
:return: | [
"Start",
"a",
"new",
"server",
"-",
"side",
"span",
".",
"If",
"the",
"span",
"has",
"already",
"been",
"started",
"by",
"start_basic_span",
"this",
"method",
"only",
"adds",
"baggage",
"from",
"the",
"headers",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/psutil/__init__.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L470-L520 | def get_cpu_percent(self, interval=0.1):
"""Return a float representing the current process CPU
utilization as a percentage.
When interval is > 0.0 compares process times to system CPU
times elapsed before and after the interval (blocking).
When interval is 0.0 or None compares... | [
"def",
"get_cpu_percent",
"(",
"self",
",",
"interval",
"=",
"0.1",
")",
":",
"blocking",
"=",
"interval",
"is",
"not",
"None",
"and",
"interval",
">",
"0.0",
"if",
"blocking",
":",
"st1",
"=",
"sum",
"(",
"cpu_times",
"(",
")",
")",
"pt1",
"=",
"sel... | Return a float representing the current process CPU
utilization as a percentage.
When interval is > 0.0 compares process times to system CPU
times elapsed before and after the interval (blocking).
When interval is 0.0 or None compares process times to system CPU
times elapsed s... | [
"Return",
"a",
"float",
"representing",
"the",
"current",
"process",
"CPU",
"utilization",
"as",
"a",
"percentage",
"."
] | python | test |
kytos/python-openflow | pyof/v0x04/common/action.py | https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/action.py#L390-L396 | def _update_length(self):
"""Update the length field of the struct."""
action_length = 4 + len(self.field.pack())
overflow = action_length % 8
self.length = action_length
if overflow:
self.length = action_length + 8 - overflow | [
"def",
"_update_length",
"(",
"self",
")",
":",
"action_length",
"=",
"4",
"+",
"len",
"(",
"self",
".",
"field",
".",
"pack",
"(",
")",
")",
"overflow",
"=",
"action_length",
"%",
"8",
"self",
".",
"length",
"=",
"action_length",
"if",
"overflow",
":"... | Update the length field of the struct. | [
"Update",
"the",
"length",
"field",
"of",
"the",
"struct",
"."
] | python | train |
log2timeline/plaso | plaso/cli/psteal_tool.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/psteal_tool.py#L425-L497 | def ParseOptions(self, options):
"""Parses tool specific options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
# The extraction options are dependent on the data location.
helpers_manager.ArgumentHelperManager.... | [
"def",
"ParseOptions",
"(",
"self",
",",
"options",
")",
":",
"# The extraction options are dependent on the data location.",
"helpers_manager",
".",
"ArgumentHelperManager",
".",
"ParseOptions",
"(",
"options",
",",
"self",
",",
"names",
"=",
"[",
"'data_location'",
"]... | Parses tool specific options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid. | [
"Parses",
"tool",
"specific",
"options",
"."
] | python | train |
Nachtfeuer/pipeline | spline/tools/event.py | https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/tools/event.py#L46-L55 | def configure(**kwargs):
"""Global configuration for event handling."""
for key in kwargs:
if key == 'is_logging_enabled':
Event.is_logging_enabled = kwargs[key]
elif key == 'collector_queue':
Event.collector_queue = kwargs[key]
else:
... | [
"def",
"configure",
"(",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
"in",
"kwargs",
":",
"if",
"key",
"==",
"'is_logging_enabled'",
":",
"Event",
".",
"is_logging_enabled",
"=",
"kwargs",
"[",
"key",
"]",
"elif",
"key",
"==",
"'collector_queue'",
":",
"... | Global configuration for event handling. | [
"Global",
"configuration",
"for",
"event",
"handling",
"."
] | python | train |
jleinonen/pytmatrix | pytmatrix/tmatrix.py | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/tmatrix.py#L315-L333 | def get_SZ(self):
"""Get the S and Z matrices using the current parameters.
"""
if self.psd_integrator is None:
(self._S, self._Z) = self.get_SZ_orient()
else:
scatter_outdated = self._scatter_signature != (self.thet0,
self.thet, self.phi0, self.p... | [
"def",
"get_SZ",
"(",
"self",
")",
":",
"if",
"self",
".",
"psd_integrator",
"is",
"None",
":",
"(",
"self",
".",
"_S",
",",
"self",
".",
"_Z",
")",
"=",
"self",
".",
"get_SZ_orient",
"(",
")",
"else",
":",
"scatter_outdated",
"=",
"self",
".",
"_s... | Get the S and Z matrices using the current parameters. | [
"Get",
"the",
"S",
"and",
"Z",
"matrices",
"using",
"the",
"current",
"parameters",
"."
] | python | train |
quantmind/pulsar | pulsar/utils/html.py | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/html.py#L73-L80 | def capfirst(x):
'''Capitalise the first letter of ``x``.
'''
x = to_string(x).strip()
if x:
return x[0].upper() + x[1:].lower()
else:
return x | [
"def",
"capfirst",
"(",
"x",
")",
":",
"x",
"=",
"to_string",
"(",
"x",
")",
".",
"strip",
"(",
")",
"if",
"x",
":",
"return",
"x",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"x",
"[",
"1",
":",
"]",
".",
"lower",
"(",
")",
"else",
":",
... | Capitalise the first letter of ``x``. | [
"Capitalise",
"the",
"first",
"letter",
"of",
"x",
"."
] | python | train |
Duke-GCB/DukeDSClient | ddsc/sdk/client.py | https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/sdk/client.py#L490-L496 | def get_child(self):
"""
Find file or folder at the remote_path
:return: File|Folder
"""
path_parts = self.remote_path.split(os.sep)
return self._get_child_recurse(path_parts, self.node) | [
"def",
"get_child",
"(",
"self",
")",
":",
"path_parts",
"=",
"self",
".",
"remote_path",
".",
"split",
"(",
"os",
".",
"sep",
")",
"return",
"self",
".",
"_get_child_recurse",
"(",
"path_parts",
",",
"self",
".",
"node",
")"
] | Find file or folder at the remote_path
:return: File|Folder | [
"Find",
"file",
"or",
"folder",
"at",
"the",
"remote_path",
":",
"return",
":",
"File|Folder"
] | python | train |
python-tap/tappy | tap/parser.py | https://github.com/python-tap/tappy/blob/79a749313c61ea94ee49d67ba6a1534974bc03aa/tap/parser.py#L118-L143 | def parse_line(self, text, fh=None):
"""Parse a line into whatever TAP category it belongs."""
match = self.ok.match(text)
if match:
return self._parse_result(True, match, fh)
match = self.not_ok.match(text)
if match:
return self._parse_result(False, matc... | [
"def",
"parse_line",
"(",
"self",
",",
"text",
",",
"fh",
"=",
"None",
")",
":",
"match",
"=",
"self",
".",
"ok",
".",
"match",
"(",
"text",
")",
"if",
"match",
":",
"return",
"self",
".",
"_parse_result",
"(",
"True",
",",
"match",
",",
"fh",
")... | Parse a line into whatever TAP category it belongs. | [
"Parse",
"a",
"line",
"into",
"whatever",
"TAP",
"category",
"it",
"belongs",
"."
] | python | train |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/_backends/update_service/apis/default_api.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/update_service/apis/default_api.py#L2474-L2498 | def upload_job_list(self, **kwargs): # noqa: E501
"""Get all upload jobs # noqa: E501
Get all upload jobs # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.upload_job_list... | [
"def",
"upload_job_list",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
".",
"upload_job_list_with_htt... | Get all upload jobs # noqa: E501
Get all upload jobs # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.upload_job_list(asynchronous=True)
>>> result = thread.get()
... | [
"Get",
"all",
"upload",
"jobs",
"#",
"noqa",
":",
"E501"
] | python | train |
impact27/registrator | registrator/channel.py | https://github.com/impact27/registrator/blob/04c099d83e0466207dc5b2e40d9b03db020d4dad/registrator/channel.py#L35-L143 | def channel_width(im, chanangle=None, *, chanapproxangle=None,
isccsedge=False):
"""Get an estimation of the channel width.
Parameters:
-----------
im: 2d array
The channel image
chanangle: number, optional
The angle of the channel (None if unknown)
chanapproxa... | [
"def",
"channel_width",
"(",
"im",
",",
"chanangle",
"=",
"None",
",",
"*",
",",
"chanapproxangle",
"=",
"None",
",",
"isccsedge",
"=",
"False",
")",
":",
"# check input is numpy array",
"im",
"=",
"np",
".",
"asarray",
"(",
"im",
")",
"# Compute the dft if ... | Get an estimation of the channel width.
Parameters:
-----------
im: 2d array
The channel image
chanangle: number, optional
The angle of the channel (None if unknown)
chanapproxangle: number, optional
If chanangle is None, the approximate channel angle
isccsedge: boolean,... | [
"Get",
"an",
"estimation",
"of",
"the",
"channel",
"width",
"."
] | python | train |
mjirik/imcut | imcut/pycut.py | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/pycut.py#L153-L169 | def load(self, filename, fv_extern=None):
"""
Read model stored in the file.
:param filename: Path to file with model
:param fv_extern: external feature vector function is passed here
:return:
"""
self.modelparams["mdl_stored_file"] = filename
if fv_exter... | [
"def",
"load",
"(",
"self",
",",
"filename",
",",
"fv_extern",
"=",
"None",
")",
":",
"self",
".",
"modelparams",
"[",
"\"mdl_stored_file\"",
"]",
"=",
"filename",
"if",
"fv_extern",
"is",
"not",
"None",
":",
"self",
".",
"modelparams",
"[",
"\"fv_extern\"... | Read model stored in the file.
:param filename: Path to file with model
:param fv_extern: external feature vector function is passed here
:return: | [
"Read",
"model",
"stored",
"in",
"the",
"file",
"."
] | python | train |
PMEAL/OpenPNM | openpnm/materials/VoronoiFibers.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/materials/VoronoiFibers.py#L543-L572 | def _bresenham(self, faces, dx):
r'''
A Bresenham line function to generate points to fill in for the fibers
'''
line_points = []
for face in faces:
# Get in hull order
fx = face[:, 0]
fy = face[:, 1]
fz = face[:, 2]
# F... | [
"def",
"_bresenham",
"(",
"self",
",",
"faces",
",",
"dx",
")",
":",
"line_points",
"=",
"[",
"]",
"for",
"face",
"in",
"faces",
":",
"# Get in hull order",
"fx",
"=",
"face",
"[",
":",
",",
"0",
"]",
"fy",
"=",
"face",
"[",
":",
",",
"1",
"]",
... | r'''
A Bresenham line function to generate points to fill in for the fibers | [
"r",
"A",
"Bresenham",
"line",
"function",
"to",
"generate",
"points",
"to",
"fill",
"in",
"for",
"the",
"fibers"
] | python | train |
carta/ldap_tools | src/ldap_tools/user.py | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L204-L209 | def delete(config, username, type):
"""Delete an LDAP user."""
client = Client()
client.prepare_connection()
user_api = API(client)
user_api.delete(username, type) | [
"def",
"delete",
"(",
"config",
",",
"username",
",",
"type",
")",
":",
"client",
"=",
"Client",
"(",
")",
"client",
".",
"prepare_connection",
"(",
")",
"user_api",
"=",
"API",
"(",
"client",
")",
"user_api",
".",
"delete",
"(",
"username",
",",
"type... | Delete an LDAP user. | [
"Delete",
"an",
"LDAP",
"user",
"."
] | python | train |
PyCQA/astroid | astroid/brain/brain_builtin_inference.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_builtin_inference.py#L512-L536 | def infer_slice(node, context=None):
"""Understand `slice` calls."""
args = node.args
if not 0 < len(args) <= 3:
raise UseInferenceDefault
infer_func = partial(helpers.safe_infer, context=context)
args = [infer_func(arg) for arg in args]
for arg in args:
if not arg or arg is uti... | [
"def",
"infer_slice",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"args",
"=",
"node",
".",
"args",
"if",
"not",
"0",
"<",
"len",
"(",
"args",
")",
"<=",
"3",
":",
"raise",
"UseInferenceDefault",
"infer_func",
"=",
"partial",
"(",
"helpers",
... | Understand `slice` calls. | [
"Understand",
"slice",
"calls",
"."
] | python | train |
wal-e/wal-e | wal_e/pipeline.py | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pipeline.py#L17-L30 | def get_upload_pipeline(in_fd, out_fd, rate_limit=None,
gpg_key=None, lzop=True):
""" Create a UNIX pipeline to process a file for uploading.
(Compress, and optionally encrypt) """
commands = []
if rate_limit is not None:
commands.append(PipeViewerRateLimitFilter(rate... | [
"def",
"get_upload_pipeline",
"(",
"in_fd",
",",
"out_fd",
",",
"rate_limit",
"=",
"None",
",",
"gpg_key",
"=",
"None",
",",
"lzop",
"=",
"True",
")",
":",
"commands",
"=",
"[",
"]",
"if",
"rate_limit",
"is",
"not",
"None",
":",
"commands",
".",
"appen... | Create a UNIX pipeline to process a file for uploading.
(Compress, and optionally encrypt) | [
"Create",
"a",
"UNIX",
"pipeline",
"to",
"process",
"a",
"file",
"for",
"uploading",
".",
"(",
"Compress",
"and",
"optionally",
"encrypt",
")"
] | python | train |
mikedh/trimesh | trimesh/viewer/windowed.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/viewer/windowed.py#L487-L492 | def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
"""
Pan or rotate the view.
"""
self.view['ball'].drag(np.array([x, y]))
self.scene.camera.transform = self.view['ball'].pose | [
"def",
"on_mouse_drag",
"(",
"self",
",",
"x",
",",
"y",
",",
"dx",
",",
"dy",
",",
"buttons",
",",
"modifiers",
")",
":",
"self",
".",
"view",
"[",
"'ball'",
"]",
".",
"drag",
"(",
"np",
".",
"array",
"(",
"[",
"x",
",",
"y",
"]",
")",
")",
... | Pan or rotate the view. | [
"Pan",
"or",
"rotate",
"the",
"view",
"."
] | python | train |
GoogleCloudPlatform/cloud-debug-python | src/googleclouddebugger/yaml_data_visibility_config_reader.py | https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/yaml_data_visibility_config_reader.py#L72-L91 | def OpenAndRead(relative_path='debugger-blacklist.yaml'):
"""Attempts to find the yaml configuration file, then read it.
Args:
relative_path: Optional relative path override.
Returns:
A Config object if the open and read were successful, None if the file
does not exist (which is not considered an er... | [
"def",
"OpenAndRead",
"(",
"relative_path",
"=",
"'debugger-blacklist.yaml'",
")",
":",
"# Note: This logic follows the convention established by source-context.json",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sys",
".",
"path",
"[",
"0",
... | Attempts to find the yaml configuration file, then read it.
Args:
relative_path: Optional relative path override.
Returns:
A Config object if the open and read were successful, None if the file
does not exist (which is not considered an error).
Raises:
Error (some subclass): As thrown by the ca... | [
"Attempts",
"to",
"find",
"the",
"yaml",
"configuration",
"file",
"then",
"read",
"it",
"."
] | python | train |
splunk/splunk-sdk-python | splunklib/client.py | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2771-L2812 | def preview(self, **query_params):
"""Returns a streaming handle to this job's preview search results.
Unlike :class:`splunklib.results.ResultsReader`, which requires a job to
be finished to
return any results, the ``preview`` method returns any results that have
been generated ... | [
"def",
"preview",
"(",
"self",
",",
"*",
"*",
"query_params",
")",
":",
"query_params",
"[",
"'segmentation'",
"]",
"=",
"query_params",
".",
"get",
"(",
"'segmentation'",
",",
"'none'",
")",
"return",
"self",
".",
"get",
"(",
"\"results_preview\"",
",",
"... | Returns a streaming handle to this job's preview search results.
Unlike :class:`splunklib.results.ResultsReader`, which requires a job to
be finished to
return any results, the ``preview`` method returns any results that have
been generated so far, whether the job is running or not. The... | [
"Returns",
"a",
"streaming",
"handle",
"to",
"this",
"job",
"s",
"preview",
"search",
"results",
"."
] | python | train |
saltstack/salt | salt/fileserver/__init__.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L231-L246 | def diff_mtime_map(map1, map2):
'''
Is there a change to the mtime map? return a boolean
'''
# check if the mtimes are the same
if sorted(map1) != sorted(map2):
return True
# map1 and map2 are guaranteed to have same keys,
# so compare mtimes
for filename, mtime in six.iteritems... | [
"def",
"diff_mtime_map",
"(",
"map1",
",",
"map2",
")",
":",
"# check if the mtimes are the same",
"if",
"sorted",
"(",
"map1",
")",
"!=",
"sorted",
"(",
"map2",
")",
":",
"return",
"True",
"# map1 and map2 are guaranteed to have same keys,",
"# so compare mtimes",
"f... | Is there a change to the mtime map? return a boolean | [
"Is",
"there",
"a",
"change",
"to",
"the",
"mtime",
"map?",
"return",
"a",
"boolean"
] | python | train |
mitsei/dlkit | dlkit/handcar/relationship/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/relationship/sessions.py#L912-L942 | def get_relationship_form_for_create(self, source_id=None, destination_id=None, relationship_record_types=None):
"""Gets the relationship form for creating new relationships.
A new form should be requested for each create transaction.
arg: source_id (osid.id.Id): ``Id`` of a peer
ar... | [
"def",
"get_relationship_form_for_create",
"(",
"self",
",",
"source_id",
"=",
"None",
",",
"destination_id",
"=",
"None",
",",
"relationship_record_types",
"=",
"None",
")",
":",
"if",
"source_id",
"is",
"None",
"or",
"destination_id",
"is",
"None",
":",
"raise... | Gets the relationship form for creating new relationships.
A new form should be requested for each create transaction.
arg: source_id (osid.id.Id): ``Id`` of a peer
arg: destination_id (osid.id.Id): ``Id`` of the related peer
arg: relationship_record_types (osid.type.Type[]): ... | [
"Gets",
"the",
"relationship",
"form",
"for",
"creating",
"new",
"relationships",
"."
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L12304-L12317 | def altitude_send(self, time_usec, altitude_monotonic, altitude_amsl, altitude_local, altitude_relative, altitude_terrain, bottom_clearance, force_mavlink1=False):
'''
The current system altitude.
time_usec : Timestamp (micros since boot or Unix epoch) (u... | [
"def",
"altitude_send",
"(",
"self",
",",
"time_usec",
",",
"altitude_monotonic",
",",
"altitude_amsl",
",",
"altitude_local",
",",
"altitude_relative",
",",
"altitude_terrain",
",",
"bottom_clearance",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self"... | The current system altitude.
time_usec : Timestamp (micros since boot or Unix epoch) (uint64_t)
altitude_monotonic : This altitude measure is initialized on system boot and monotonic (it is never reset, but represents the local altitude change). The only guarantee... | [
"The",
"current",
"system",
"altitude",
"."
] | python | train |
Murali-group/halp | halp/directed_hypergraph.py | https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L846-L857 | def get_backward_star(self, node):
"""Given a node, get a copy of that node's backward star.
:param node: node to retrieve the backward-star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's backward star.
:raises: ValueError -- No such node exis... | [
"def",
"get_backward_star",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"not",
"in",
"self",
".",
"_node_attributes",
":",
"raise",
"ValueError",
"(",
"\"No such node exists.\"",
")",
"return",
"self",
".",
"_backward_star",
"[",
"node",
"]",
".",
"cop... | Given a node, get a copy of that node's backward star.
:param node: node to retrieve the backward-star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's backward star.
:raises: ValueError -- No such node exists. | [
"Given",
"a",
"node",
"get",
"a",
"copy",
"of",
"that",
"node",
"s",
"backward",
"star",
"."
] | python | train |
JIC-CSB/jicbioimage.segment | jicbioimage/segment/__init__.py | https://github.com/JIC-CSB/jicbioimage.segment/blob/289e5ab834913326a097e57bea458ea0737efb0c/jicbioimage/segment/__init__.py#L287-L299 | def watershed_with_seeds(image, seeds, mask=None):
"""Return :class:`jicbioimage.core.image.SegmentedImage`.
:param image: input :class:`jicbioimage.core.image.Image`
:param seeds: numpy.ndarray of same shape as image,
each seed needs to be a unique integer
:param mask: bool numpy.nda... | [
"def",
"watershed_with_seeds",
"(",
"image",
",",
"seeds",
",",
"mask",
"=",
"None",
")",
":",
"ar",
"=",
"skimage",
".",
"morphology",
".",
"watershed",
"(",
"-",
"image",
",",
"seeds",
",",
"mask",
"=",
"mask",
")",
"segmentation",
"=",
"SegmentedImage... | Return :class:`jicbioimage.core.image.SegmentedImage`.
:param image: input :class:`jicbioimage.core.image.Image`
:param seeds: numpy.ndarray of same shape as image,
each seed needs to be a unique integer
:param mask: bool numpy.ndarray of same shape as image,
only regions... | [
"Return",
":",
"class",
":",
"jicbioimage",
".",
"core",
".",
"image",
".",
"SegmentedImage",
"."
] | python | train |
ga4gh/ga4gh-client | ga4gh/client/client.py | https://github.com/ga4gh/ga4gh-client/blob/d23b00b89112ef0930d45ee75aa3c6de3db615c5/ga4gh/client/client.py#L828-L846 | def search_expression_levels(
self, rna_quantification_id="", names=[], threshold=0.0):
"""
Returns an iterator over the ExpressionLevel objects from the server
:param str feature_ids: The IDs of the
:class:`ga4gh.protocol.Feature` of interest.
:param str rna_qua... | [
"def",
"search_expression_levels",
"(",
"self",
",",
"rna_quantification_id",
"=",
"\"\"",
",",
"names",
"=",
"[",
"]",
",",
"threshold",
"=",
"0.0",
")",
":",
"request",
"=",
"protocol",
".",
"SearchExpressionLevelsRequest",
"(",
")",
"request",
".",
"rna_qua... | Returns an iterator over the ExpressionLevel objects from the server
:param str feature_ids: The IDs of the
:class:`ga4gh.protocol.Feature` of interest.
:param str rna_quantification_id: The ID of the
:class:`ga4gh.protocol.RnaQuantification` of interest.
:param float th... | [
"Returns",
"an",
"iterator",
"over",
"the",
"ExpressionLevel",
"objects",
"from",
"the",
"server"
] | python | train |
jeffh/pyconstraints | pyconstraints/solvers.py | https://github.com/jeffh/pyconstraints/blob/923abce2f9ba484d1964165616a253bbccd1a630/pyconstraints/solvers.py#L224-L243 | def set_conditions(self, variables, constraints):
"""Problem provided data.
variables = {variable-name: list-of-domain-values}
constraints = [(constraint_function, variable-names, variable-default-values)]
"""
self._vars, self._constraints = variables, []
self._constrain... | [
"def",
"set_conditions",
"(",
"self",
",",
"variables",
",",
"constraints",
")",
":",
"self",
".",
"_vars",
",",
"self",
".",
"_constraints",
"=",
"variables",
",",
"[",
"]",
"self",
".",
"_constraints_for_var",
"=",
"{",
"}",
"vars_constraint_count",
"=",
... | Problem provided data.
variables = {variable-name: list-of-domain-values}
constraints = [(constraint_function, variable-names, variable-default-values)] | [
"Problem",
"provided",
"data",
"."
] | python | train |
cyface/django-termsandconditions | termsandconditions/middleware.py | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/middleware.py#L27-L46 | def process_request(self, request):
"""Process each request to app to ensure terms have been accepted"""
LOGGER.debug('termsandconditions.middleware')
current_path = request.META['PATH_INFO']
if DJANGO_VERSION <= (2, 0, 0):
user_authenticated = request.user.is_authenticate... | [
"def",
"process_request",
"(",
"self",
",",
"request",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'termsandconditions.middleware'",
")",
"current_path",
"=",
"request",
".",
"META",
"[",
"'PATH_INFO'",
"]",
"if",
"DJANGO_VERSION",
"<=",
"(",
"2",
",",
"0",
",",... | Process each request to app to ensure terms have been accepted | [
"Process",
"each",
"request",
"to",
"app",
"to",
"ensure",
"terms",
"have",
"been",
"accepted"
] | python | train |
muckamuck/stackility | stackility/CloudStackUtility.py | https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L563-L603 | def _archive_elements(self):
"""
Cloud Formation likes to take the template from S3 so here we put the
template into S3. We also store the parameters file that was used in
this run. Note: you can pass anything as the version string but you
should at least consider a version contr... | [
"def",
"_archive_elements",
"(",
"self",
")",
":",
"try",
":",
"stackfile_key",
",",
"propertyfile_key",
"=",
"self",
".",
"_craft_s3_keys",
"(",
")",
"template_file",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"'environment'",
",",
"{",
"}",
")",
".",
... | Cloud Formation likes to take the template from S3 so here we put the
template into S3. We also store the parameters file that was used in
this run. Note: you can pass anything as the version string but you
should at least consider a version control tag or git commit hash as
the version.... | [
"Cloud",
"Formation",
"likes",
"to",
"take",
"the",
"template",
"from",
"S3",
"so",
"here",
"we",
"put",
"the",
"template",
"into",
"S3",
".",
"We",
"also",
"store",
"the",
"parameters",
"file",
"that",
"was",
"used",
"in",
"this",
"run",
".",
"Note",
... | python | train |
brocade/pynos | pynos/versions/base/yang/brocade_sflow.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/yang/brocade_sflow.py#L12-L20 | def sflow_enable(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
sflow = ET.SubElement(config, "sflow", xmlns="urn:brocade.com:mgmt:brocade-sflow")
enable = ET.SubElement(sflow, "enable")
callback = kwargs.pop('callback', self._callback)
... | [
"def",
"sflow_enable",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"sflow",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"sflow\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:mgmt:brocade-s... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
econ-ark/HARK | HARK/interpolation.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/interpolation.py#L676-L688 | def _der(self,*args):
'''
Evaluate the derivative of the function. The first input must exist and should be an array.
Returns an array of identical shape to args[0] (if it exists). This is an array of zeros.
'''
if len(args) > 0:
if _isscalar(args[0]):
... | [
"def",
"_der",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"0",
":",
"if",
"_isscalar",
"(",
"args",
"[",
"0",
"]",
")",
":",
"return",
"0.0",
"else",
":",
"shape",
"=",
"args",
"[",
"0",
"]",
".",
"shape",
... | Evaluate the derivative of the function. The first input must exist and should be an array.
Returns an array of identical shape to args[0] (if it exists). This is an array of zeros. | [
"Evaluate",
"the",
"derivative",
"of",
"the",
"function",
".",
"The",
"first",
"input",
"must",
"exist",
"and",
"should",
"be",
"an",
"array",
".",
"Returns",
"an",
"array",
"of",
"identical",
"shape",
"to",
"args",
"[",
"0",
"]",
"(",
"if",
"it",
"exi... | python | train |
googleapis/google-cloud-python | storage/google/cloud/storage/batch.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/batch.py#L248-L266 | def finish(self):
"""Submit a single `multipart/mixed` request with deferred requests.
:rtype: list of tuples
:returns: one ``(headers, payload)`` tuple per deferred request.
"""
headers, body = self._prepare_batch_request()
url = "%s/batch/storage/v1" % self.API_BASE_U... | [
"def",
"finish",
"(",
"self",
")",
":",
"headers",
",",
"body",
"=",
"self",
".",
"_prepare_batch_request",
"(",
")",
"url",
"=",
"\"%s/batch/storage/v1\"",
"%",
"self",
".",
"API_BASE_URL",
"# Use the private ``_base_connection`` rather than the property",
"# ``_connec... | Submit a single `multipart/mixed` request with deferred requests.
:rtype: list of tuples
:returns: one ``(headers, payload)`` tuple per deferred request. | [
"Submit",
"a",
"single",
"multipart",
"/",
"mixed",
"request",
"with",
"deferred",
"requests",
"."
] | python | train |
Rackspace-DOT/flask_keystone | flask_keystone/user.py | https://github.com/Rackspace-DOT/flask_keystone/blob/6f6d630e9e66a3beca6607b0b786510ec2a79747/flask_keystone/user.py#L106-L141 | def generate_has_role_function(cls, roles):
"""
Generate a `class.has_role('role_name')` method for a class.
:param class cls: The python class to be modified.
:param dict roles: The roles to use for generation.
This method is intended to be used by an inheriting class to
... | [
"def",
"generate_has_role_function",
"(",
"cls",
",",
"roles",
")",
":",
"def",
"has_role_func",
"(",
"self",
",",
"role",
")",
":",
"\"\"\"\n Determine if an instance of this class has the configured role.\n\n :param str role: The role identifier from `oslo.con... | Generate a `class.has_role('role_name')` method for a class.
:param class cls: The python class to be modified.
:param dict roles: The roles to use for generation.
This method is intended to be used by an inheriting class to
generate the has_role method based on the roles provided.
... | [
"Generate",
"a",
"class",
".",
"has_role",
"(",
"role_name",
")",
"method",
"for",
"a",
"class",
"."
] | python | train |
zlobspb/txtarantool | txtarantool.py | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L233-L253 | def pack_field(self, value):
"""
Pack single field (string or integer value)
<field> ::= <int32_varint><data>
:param value: value to be packed
:type value: bytes, str, int or long
:return: packed value
:rtype: bytes
"""
if isinstance(value, str):... | [
"def",
"pack_field",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"self",
".",
"pack_str",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"unicode",
")",
":",
"return",
"self",
".... | Pack single field (string or integer value)
<field> ::= <int32_varint><data>
:param value: value to be packed
:type value: bytes, str, int or long
:return: packed value
:rtype: bytes | [
"Pack",
"single",
"field",
"(",
"string",
"or",
"integer",
"value",
")",
"<field",
">",
"::",
"=",
"<int32_varint",
">",
"<data",
">"
] | python | train |
census-instrumentation/opencensus-python | contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L193-L252 | def _convert_point(self, metric, ts, point, sd_point):
"""Convert an OC metric point to a SD point."""
if (metric.descriptor.type == metric_descriptor.MetricDescriptorType
.CUMULATIVE_DISTRIBUTION):
sd_dist_val = sd_point.value.distribution_value
sd_dist_val.coun... | [
"def",
"_convert_point",
"(",
"self",
",",
"metric",
",",
"ts",
",",
"point",
",",
"sd_point",
")",
":",
"if",
"(",
"metric",
".",
"descriptor",
".",
"type",
"==",
"metric_descriptor",
".",
"MetricDescriptorType",
".",
"CUMULATIVE_DISTRIBUTION",
")",
":",
"s... | Convert an OC metric point to a SD point. | [
"Convert",
"an",
"OC",
"metric",
"point",
"to",
"a",
"SD",
"point",
"."
] | python | train |
tanghaibao/jcvi | jcvi/variation/tassel.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/tassel.py#L33-L107 | def prepare(args):
"""
%prog prepare barcode_key.csv reference.fasta
Prepare TASSEL pipeline.
"""
valid_enzymes = "ApeKI|ApoI|BamHI|EcoT22I|HinP1I|HpaII|MseI|MspI|" \
"NdeI|PasI|PstI|Sau3AI|SbfI|AsiSI-MspI|BssHII-MspI|" \
"FseI-MspI|PaeR7I-HhaI|PstI-ApeKI|Pst... | [
"def",
"prepare",
"(",
"args",
")",
":",
"valid_enzymes",
"=",
"\"ApeKI|ApoI|BamHI|EcoT22I|HinP1I|HpaII|MseI|MspI|\"",
"\"NdeI|PasI|PstI|Sau3AI|SbfI|AsiSI-MspI|BssHII-MspI|\"",
"\"FseI-MspI|PaeR7I-HhaI|PstI-ApeKI|PstI-EcoT22I|PstI-MspI\"",
"\"PstI-TaqI|SalI-MspI|SbfI-MspI\"",
".",
"split",... | %prog prepare barcode_key.csv reference.fasta
Prepare TASSEL pipeline. | [
"%prog",
"prepare",
"barcode_key",
".",
"csv",
"reference",
".",
"fasta"
] | python | train |
saltstack/salt | salt/states/ansiblegate.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ansiblegate.py#L114-L130 | def _changes(plays):
'''
Find changes in ansible return data
'''
changes = {}
for play in plays['plays']:
task_changes = {}
for task in play['tasks']:
host_changes = {}
for host, data in six.iteritems(task['hosts']):
if data['changed'] is True:... | [
"def",
"_changes",
"(",
"plays",
")",
":",
"changes",
"=",
"{",
"}",
"for",
"play",
"in",
"plays",
"[",
"'plays'",
"]",
":",
"task_changes",
"=",
"{",
"}",
"for",
"task",
"in",
"play",
"[",
"'tasks'",
"]",
":",
"host_changes",
"=",
"{",
"}",
"for",... | Find changes in ansible return data | [
"Find",
"changes",
"in",
"ansible",
"return",
"data"
] | python | train |
SheffieldML/GPy | GPy/util/mocap.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/util/mocap.py#L430-L475 | def read_channels(self, fid):
"""Read channels from an acclaim file."""
bones = [[] for i in self.vertices]
num_channels = 0
for vertex in self.vertices:
num_channels = num_channels + len(vertex.meta['channels'])
lin = self.read_line(fid)
while lin != ':DEGRE... | [
"def",
"read_channels",
"(",
"self",
",",
"fid",
")",
":",
"bones",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"self",
".",
"vertices",
"]",
"num_channels",
"=",
"0",
"for",
"vertex",
"in",
"self",
".",
"vertices",
":",
"num_channels",
"=",
"num_channels",
... | Read channels from an acclaim file. | [
"Read",
"channels",
"from",
"an",
"acclaim",
"file",
"."
] | python | train |
bloomreach/s4cmd | s4cmd.py | https://github.com/bloomreach/s4cmd/blob/bb51075bf43703e7cd95aa39288cf7732ec13a6d/s4cmd.py#L1635-L1641 | def mb_handler(self, args):
'''Handler for mb command'''
if len(args) == 1:
raise InvalidArgument('No s3 bucketname provided')
self.validate('cmd|s3', args)
self.s3handler().create_bucket(args[1]) | [
"def",
"mb_handler",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"raise",
"InvalidArgument",
"(",
"'No s3 bucketname provided'",
")",
"self",
".",
"validate",
"(",
"'cmd|s3'",
",",
"args",
")",
"self",
".",
"s3handl... | Handler for mb command | [
"Handler",
"for",
"mb",
"command"
] | python | test |
bram85/topydo | topydo/ui/CLIApplicationBase.py | https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/CLIApplicationBase.py#L130-L135 | def version():
""" Print the current version and exit. """
from topydo.lib.Version import VERSION, LICENSE
print("topydo {}\n".format(VERSION))
print(LICENSE)
sys.exit(0) | [
"def",
"version",
"(",
")",
":",
"from",
"topydo",
".",
"lib",
".",
"Version",
"import",
"VERSION",
",",
"LICENSE",
"print",
"(",
"\"topydo {}\\n\"",
".",
"format",
"(",
"VERSION",
")",
")",
"print",
"(",
"LICENSE",
")",
"sys",
".",
"exit",
"(",
"0",
... | Print the current version and exit. | [
"Print",
"the",
"current",
"version",
"and",
"exit",
"."
] | python | train |
orbingol/NURBS-Python | geomdl/utilities.py | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/utilities.py#L20-L37 | def color_generator(seed=None):
""" Generates random colors for control and evaluated curve/surface points plots.
The ``seed`` argument is used to set the random seed by directly passing the value to ``random.seed()`` function.
Please see the Python documentation for more details on the ``random`` module .... | [
"def",
"color_generator",
"(",
"seed",
"=",
"None",
")",
":",
"def",
"r_int",
"(",
")",
":",
"return",
"random",
".",
"randint",
"(",
"0",
",",
"255",
")",
"if",
"seed",
"is",
"not",
"None",
":",
"random",
".",
"seed",
"(",
"seed",
")",
"color_stri... | Generates random colors for control and evaluated curve/surface points plots.
The ``seed`` argument is used to set the random seed by directly passing the value to ``random.seed()`` function.
Please see the Python documentation for more details on the ``random`` module .
Inspired from https://stackoverflo... | [
"Generates",
"random",
"colors",
"for",
"control",
"and",
"evaluated",
"curve",
"/",
"surface",
"points",
"plots",
"."
] | python | train |
dshean/pygeotools | pygeotools/lib/filtlib.py | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/filtlib.py#L43-L58 | def sigma_fltr(dem, n=3):
"""sigma * factor filter
Useful for outlier removal
These are min/max percentile ranges for different sigma values:
1: 15.865, 84.135
2: 2.275, 97.725
3: 0.135, 99.865
"""
std = dem.std()
u = dem.mean()
print('Excluding values outside of range: {1:... | [
"def",
"sigma_fltr",
"(",
"dem",
",",
"n",
"=",
"3",
")",
":",
"std",
"=",
"dem",
".",
"std",
"(",
")",
"u",
"=",
"dem",
".",
"mean",
"(",
")",
"print",
"(",
"'Excluding values outside of range: {1:0.2f} +/- {0}*{2:0.2f}'",
".",
"format",
"(",
"n",
",",
... | sigma * factor filter
Useful for outlier removal
These are min/max percentile ranges for different sigma values:
1: 15.865, 84.135
2: 2.275, 97.725
3: 0.135, 99.865 | [
"sigma",
"*",
"factor",
"filter",
"Useful",
"for",
"outlier",
"removal"
] | python | train |
quantumlib/Cirq | cirq/google/line/placement/chip.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/line/placement/chip.py#L75-L96 | def chip_as_adjacency_list(device: 'cirq.google.XmonDevice',
) -> Dict[GridQubit, List[GridQubit]]:
"""Gives adjacency list representation of a chip.
The adjacency list is constructed in order of above, left_of, below and
right_of consecutively.
Args:
device: Chip to... | [
"def",
"chip_as_adjacency_list",
"(",
"device",
":",
"'cirq.google.XmonDevice'",
",",
")",
"->",
"Dict",
"[",
"GridQubit",
",",
"List",
"[",
"GridQubit",
"]",
"]",
":",
"c_set",
"=",
"set",
"(",
"device",
".",
"qubits",
")",
"c_adj",
"=",
"{",
"}",
"# ty... | Gives adjacency list representation of a chip.
The adjacency list is constructed in order of above, left_of, below and
right_of consecutively.
Args:
device: Chip to be converted.
Returns:
Map from nodes to list of qubits which represent all the neighbours of
given qubit. | [
"Gives",
"adjacency",
"list",
"representation",
"of",
"a",
"chip",
"."
] | python | train |
theonion/django-bulbs | bulbs/api/views.py | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L186-L201 | def trash(self, request, **kwargs):
"""Psuedo-deletes a `Content` instance and removes it from the ElasticSearch index
Content is not actually deleted, merely hidden by deleted from ES index.import
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
... | [
"def",
"trash",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"content",
"=",
"self",
".",
"get_object",
"(",
")",
"content",
".",
"indexed",
"=",
"False",
"content",
".",
"save",
"(",
")",
"LogEntry",
".",
"objects",
".",
"log",
... | Psuedo-deletes a `Content` instance and removes it from the ElasticSearch index
Content is not actually deleted, merely hidden by deleted from ES index.import
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response` | [
"Psuedo",
"-",
"deletes",
"a",
"Content",
"instance",
"and",
"removes",
"it",
"from",
"the",
"ElasticSearch",
"index"
] | python | train |
OSSOS/MOP | src/ossos/core/ossos/pipeline.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/pipeline.py#L21-L149 | def align(expnums, ccd, version='s', dry_run=False):
"""Create a 'shifts' file that transforms the space/flux/time scale of all images to the first image.
This function relies on the .fwhm, .trans.jmp, .phot and .zeropoint.used files for inputs.
The scaling we are computing here is for use in planting sour... | [
"def",
"align",
"(",
"expnums",
",",
"ccd",
",",
"version",
"=",
"'s'",
",",
"dry_run",
"=",
"False",
")",
":",
"# Get the images and supporting files that we need from the VOSpace area",
"# get_image and get_file check if the image/file is already on disk.",
"# re-computed fluxe... | Create a 'shifts' file that transforms the space/flux/time scale of all images to the first image.
This function relies on the .fwhm, .trans.jmp, .phot and .zeropoint.used files for inputs.
The scaling we are computing here is for use in planting sources into the image at the same sky/flux locations
while ... | [
"Create",
"a",
"shifts",
"file",
"that",
"transforms",
"the",
"space",
"/",
"flux",
"/",
"time",
"scale",
"of",
"all",
"images",
"to",
"the",
"first",
"image",
"."
] | python | train |
jamieleshaw/lurklib | lurklib/channel.py | https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/channel.py#L24-L40 | def is_in_channel(self, channel, should_be=True):
"""
Find out if you are in a channel.
Required arguments:
* channel - Channel to check whether you are in it or not.
* should_be - If True, raise an exception if you aren't in the channel;
If False, raise an ex... | [
"def",
"is_in_channel",
"(",
"self",
",",
"channel",
",",
"should_be",
"=",
"True",
")",
":",
"with",
"self",
".",
"lock",
":",
"for",
"channel_",
"in",
"self",
".",
"channels",
":",
"if",
"self",
".",
"compare",
"(",
"channel_",
",",
"channel",
")",
... | Find out if you are in a channel.
Required arguments:
* channel - Channel to check whether you are in it or not.
* should_be - If True, raise an exception if you aren't in the channel;
If False, raise an exception if you are in the channel. | [
"Find",
"out",
"if",
"you",
"are",
"in",
"a",
"channel",
".",
"Required",
"arguments",
":",
"*",
"channel",
"-",
"Channel",
"to",
"check",
"whether",
"you",
"are",
"in",
"it",
"or",
"not",
".",
"*",
"should_be",
"-",
"If",
"True",
"raise",
"an",
"exc... | python | train |
svinota/mdns | mdns/zeroconf.py | https://github.com/svinota/mdns/blob/295f6407132616a0ff7401124b9057d89555f91d/mdns/zeroconf.py#L342-L355 | def to_string(self, hdr, other):
"""String representation with additional information"""
result = "%s[%s,%s" % (
hdr, self.get_type(self.type), self.get_clazz(self.clazz))
if self.unique:
result += "-unique,"
else:
result += ","
result += s... | [
"def",
"to_string",
"(",
"self",
",",
"hdr",
",",
"other",
")",
":",
"result",
"=",
"\"%s[%s,%s\"",
"%",
"(",
"hdr",
",",
"self",
".",
"get_type",
"(",
"self",
".",
"type",
")",
",",
"self",
".",
"get_clazz",
"(",
"self",
".",
"clazz",
")",
")",
... | String representation with additional information | [
"String",
"representation",
"with",
"additional",
"information"
] | python | train |
dossier/dossier.fc | python/dossier/fc/feature_collection.py | https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L256-L283 | def to_dict(self):
'''Dump a feature collection's features to a dictionary.
This does not include additional data, such as whether
or not the collection is read-only. The returned dictionary
is suitable for serialization into JSON, CBOR, or similar
data formats.
'''
... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"def",
"is_non_native_sc",
"(",
"ty",
",",
"encoded",
")",
":",
"return",
"(",
"ty",
"==",
"'StringCounter'",
"and",
"not",
"is_native_string_counter",
"(",
"encoded",
")",
")",
"fc",
"=",
"{",
"}",
"native",
"=",... | Dump a feature collection's features to a dictionary.
This does not include additional data, such as whether
or not the collection is read-only. The returned dictionary
is suitable for serialization into JSON, CBOR, or similar
data formats. | [
"Dump",
"a",
"feature",
"collection",
"s",
"features",
"to",
"a",
"dictionary",
"."
] | python | train |
postlund/pyatv | pyatv/interface.py | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/interface.py#L28-L39 | def retrieve_commands(obj):
"""Retrieve all commands and help texts from an API object."""
commands = {} # Name and help
for func in obj.__dict__:
if not inspect.isfunction(obj.__dict__[func]) and \
not isinstance(obj.__dict__[func], property):
continue
if func.starts... | [
"def",
"retrieve_commands",
"(",
"obj",
")",
":",
"commands",
"=",
"{",
"}",
"# Name and help",
"for",
"func",
"in",
"obj",
".",
"__dict__",
":",
"if",
"not",
"inspect",
".",
"isfunction",
"(",
"obj",
".",
"__dict__",
"[",
"func",
"]",
")",
"and",
"not... | Retrieve all commands and help texts from an API object. | [
"Retrieve",
"all",
"commands",
"and",
"help",
"texts",
"from",
"an",
"API",
"object",
"."
] | python | train |
woolfson-group/isambard | isambard/ampal/interactions.py | https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/interactions.py#L206-L242 | def find_covalent_bonds(ampal, max_range=2.2, threshold=1.1, tag=True):
"""Finds all covalent bonds in the AMPAL object.
Parameters
----------
ampal : AMPAL Object
Any AMPAL object with a `get_atoms` method.
max_range : float, optional
Used to define the sector size, so interactions... | [
"def",
"find_covalent_bonds",
"(",
"ampal",
",",
"max_range",
"=",
"2.2",
",",
"threshold",
"=",
"1.1",
",",
"tag",
"=",
"True",
")",
":",
"sectors",
"=",
"gen_sectors",
"(",
"ampal",
".",
"get_atoms",
"(",
")",
",",
"max_range",
"*",
"1.1",
")",
"bond... | Finds all covalent bonds in the AMPAL object.
Parameters
----------
ampal : AMPAL Object
Any AMPAL object with a `get_atoms` method.
max_range : float, optional
Used to define the sector size, so interactions at longer ranges
will not be found.
threshold : float, optional
... | [
"Finds",
"all",
"covalent",
"bonds",
"in",
"the",
"AMPAL",
"object",
"."
] | python | train |
UCL-INGI/INGInious | inginious/frontend/accessible_time.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/accessible_time.py#L102-L104 | def is_never_accessible(self):
""" Returns true if the course/task is never accessible """
return self._val[0] == datetime.max and self._val[1] == datetime.max | [
"def",
"is_never_accessible",
"(",
"self",
")",
":",
"return",
"self",
".",
"_val",
"[",
"0",
"]",
"==",
"datetime",
".",
"max",
"and",
"self",
".",
"_val",
"[",
"1",
"]",
"==",
"datetime",
".",
"max"
] | Returns true if the course/task is never accessible | [
"Returns",
"true",
"if",
"the",
"course",
"/",
"task",
"is",
"never",
"accessible"
] | python | train |
Spinmob/spinmob | egg/example_other_widgets.py | https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/egg/example_other_widgets.py#L90-L101 | def acquire_fake_data(number_of_points=1000):
"""
This function generates some fake data and returns two channels of data
in the form
time_array, [channel1, channel2]
"""
# time array
t = _n.linspace(0,10,number_of_points)
return(t, [_n.cos(t)*(1.0+0.2*_n.random.random(number_of_points... | [
"def",
"acquire_fake_data",
"(",
"number_of_points",
"=",
"1000",
")",
":",
"# time array",
"t",
"=",
"_n",
".",
"linspace",
"(",
"0",
",",
"10",
",",
"number_of_points",
")",
"return",
"(",
"t",
",",
"[",
"_n",
".",
"cos",
"(",
"t",
")",
"*",
"(",
... | This function generates some fake data and returns two channels of data
in the form
time_array, [channel1, channel2] | [
"This",
"function",
"generates",
"some",
"fake",
"data",
"and",
"returns",
"two",
"channels",
"of",
"data",
"in",
"the",
"form"
] | python | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py#L531-L541 | def pspawn_wrapper(self, sh, escape, cmd, args, env):
"""Wrapper function for handling piped spawns.
This looks to the calling interface (in Action.py) like a "normal"
spawn, but associates the call with the PSPAWN variable from
the construction environment and with the streams to which... | [
"def",
"pspawn_wrapper",
"(",
"self",
",",
"sh",
",",
"escape",
",",
"cmd",
",",
"args",
",",
"env",
")",
":",
"return",
"self",
".",
"pspawn",
"(",
"sh",
",",
"escape",
",",
"cmd",
",",
"args",
",",
"env",
",",
"self",
".",
"logstream",
",",
"se... | Wrapper function for handling piped spawns.
This looks to the calling interface (in Action.py) like a "normal"
spawn, but associates the call with the PSPAWN variable from
the construction environment and with the streams to which we
want the output logged. This gets slid into the cons... | [
"Wrapper",
"function",
"for",
"handling",
"piped",
"spawns",
"."
] | python | train |
GNS3/gns3-server | gns3server/controller/udp_link.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L41-L96 | def create(self):
"""
Create the link on the nodes
"""
node1 = self._nodes[0]["node"]
adapter_number1 = self._nodes[0]["adapter_number"]
port_number1 = self._nodes[0]["port_number"]
node2 = self._nodes[1]["node"]
adapter_number2 = self._nodes[1]["adapter_... | [
"def",
"create",
"(",
"self",
")",
":",
"node1",
"=",
"self",
".",
"_nodes",
"[",
"0",
"]",
"[",
"\"node\"",
"]",
"adapter_number1",
"=",
"self",
".",
"_nodes",
"[",
"0",
"]",
"[",
"\"adapter_number\"",
"]",
"port_number1",
"=",
"self",
".",
"_nodes",
... | Create the link on the nodes | [
"Create",
"the",
"link",
"on",
"the",
"nodes"
] | python | train |
readbeyond/aeneas | aeneas/validator.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L348-L378 | def check_config_txt(self, contents, is_config_string=False):
"""
Check whether the given TXT config file contents
(if ``is_config_string`` is ``False``) or
TXT config string (if ``is_config_string`` is ``True``)
is well-formed and it has all the required parameters.
:pa... | [
"def",
"check_config_txt",
"(",
"self",
",",
"contents",
",",
"is_config_string",
"=",
"False",
")",
":",
"self",
".",
"log",
"(",
"u\"Checking contents TXT config file\"",
")",
"self",
".",
"result",
"=",
"ValidatorResult",
"(",
")",
"if",
"self",
".",
"_are_... | Check whether the given TXT config file contents
(if ``is_config_string`` is ``False``) or
TXT config string (if ``is_config_string`` is ``True``)
is well-formed and it has all the required parameters.
:param string contents: the TXT config file contents or TXT config string
:pa... | [
"Check",
"whether",
"the",
"given",
"TXT",
"config",
"file",
"contents",
"(",
"if",
"is_config_string",
"is",
"False",
")",
"or",
"TXT",
"config",
"string",
"(",
"if",
"is_config_string",
"is",
"True",
")",
"is",
"well",
"-",
"formed",
"and",
"it",
"has",
... | python | train |
tensorflow/probability | tensorflow_probability/python/optimizer/differential_evolution.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/differential_evolution.py#L554-L602 | def _get_starting_population(initial_population,
initial_position,
population_size,
population_stddev,
seed):
"""Constructs the initial population.
If an initial population is not already provided, t... | [
"def",
"_get_starting_population",
"(",
"initial_population",
",",
"initial_position",
",",
"population_size",
",",
"population_stddev",
",",
"seed",
")",
":",
"if",
"initial_population",
"is",
"not",
"None",
":",
"return",
"[",
"tf",
".",
"convert_to_tensor",
"(",
... | Constructs the initial population.
If an initial population is not already provided, this function constructs
a population by adding random normal noise to the initial position.
Args:
initial_population: None or a list of `Tensor`s. The initial population.
initial_position: None or a list of `Tensor`s. ... | [
"Constructs",
"the",
"initial",
"population",
"."
] | python | test |
rr-/docstring_parser | docstring_parser/parser/__init__.py | https://github.com/rr-/docstring_parser/blob/389773f6790a84d33b10160589ce8591122e12bb/docstring_parser/parser/__init__.py#L18-L37 | def parse(text: str, style: Style = Style.auto) -> Docstring:
"""
Parse the docstring into its components.
:param text: docstring text to parse
:param style: docstring style
:returns: parsed docstring representation
"""
if style != Style.auto:
return _styles[style](text)
rets =... | [
"def",
"parse",
"(",
"text",
":",
"str",
",",
"style",
":",
"Style",
"=",
"Style",
".",
"auto",
")",
"->",
"Docstring",
":",
"if",
"style",
"!=",
"Style",
".",
"auto",
":",
"return",
"_styles",
"[",
"style",
"]",
"(",
"text",
")",
"rets",
"=",
"[... | Parse the docstring into its components.
:param text: docstring text to parse
:param style: docstring style
:returns: parsed docstring representation | [
"Parse",
"the",
"docstring",
"into",
"its",
"components",
"."
] | python | train |
apache/incubator-mxnet | example/bayesian-methods/data_loader.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/data_loader.py#L24-L44 | def load_mnist(training_num=50000):
"""Load mnist dataset"""
data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz')
if not os.path.isfile(data_path):
from six.moves import urllib
origin = (
'https://github.com/sxjscience/mxnet/raw/master/example/baye... | [
"def",
"load_mnist",
"(",
"training_num",
"=",
"50000",
")",
":",
"data_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"'__file__'",
")",
")",
",",
"'mnist.npz'",
")",... | Load mnist dataset | [
"Load",
"mnist",
"dataset"
] | python | train |
senaite/senaite.core | bika/lims/api/analysis.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/api/analysis.py#L31-L119 | def is_out_of_range(brain_or_object, result=_marker):
"""Checks if the result for the analysis passed in is out of range and/or
out of shoulders range.
min max
warn min max warn
·········|----... | [
"def",
"is_out_of_range",
"(",
"brain_or_object",
",",
"result",
"=",
"_marker",
")",
":",
"analysis",
"=",
"api",
".",
"get_object",
"(",
"brain_or_object",
")",
"if",
"not",
"IAnalysis",
".",
"providedBy",
"(",
"analysis",
")",
"and",
"not",
"IReferenceAnaly... | Checks if the result for the analysis passed in is out of range and/or
out of shoulders range.
min max
warn min max warn
·········|---------------|=====================|---------------|·········
... | [
"Checks",
"if",
"the",
"result",
"for",
"the",
"analysis",
"passed",
"in",
"is",
"out",
"of",
"range",
"and",
"/",
"or",
"out",
"of",
"shoulders",
"range",
"."
] | python | train |
kytos/python-openflow | pyof/v0x04/controller2switch/multipart_reply.py | https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/controller2switch/multipart_reply.py#L87-L113 | def pack(self, value=None):
"""Pack a StatsReply using the object's attributes.
This method will pack the attribute body and multipart_type before pack
the StatsReply object, then will return this struct as a binary data.
Returns:
stats_reply_packed (bytes): Binary data wit... | [
"def",
"pack",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"buff",
"=",
"self",
".",
"body",
"if",
"not",
"value",
":",
"value",
"=",
"self",
".",
"body",
"if",
"value",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"FixedTy... | Pack a StatsReply using the object's attributes.
This method will pack the attribute body and multipart_type before pack
the StatsReply object, then will return this struct as a binary data.
Returns:
stats_reply_packed (bytes): Binary data with StatsReply packed. | [
"Pack",
"a",
"StatsReply",
"using",
"the",
"object",
"s",
"attributes",
"."
] | python | train |
fabiobatalha/crossrefapi | crossref/restful.py | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L535-L589 | def order(self, order='asc'):
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
This method can be used compounded with query, filter,
sort and facet methods.
kwar... | [
"def",
"order",
"(",
"self",
",",
"order",
"=",
"'asc'",
")",
":",
"context",
"=",
"str",
"(",
"self",
".",
"context",
")",
"request_url",
"=",
"build_url_endpoint",
"(",
"self",
".",
"ENDPOINT",
",",
"context",
")",
"request_params",
"=",
"dict",
"(",
... | This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
This method can be used compounded with query, filter,
sort and facet methods.
kwargs: valid SORT_VALUES arguments.
return: ... | [
"This",
"method",
"retrieve",
"an",
"iterable",
"object",
"that",
"implements",
"the",
"method",
"__iter__",
".",
"The",
"arguments",
"given",
"will",
"compose",
"the",
"parameters",
"in",
"the",
"request",
"url",
"."
] | python | train |
MacHu-GWU/macro-project | macro/bot.py | https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L394-L403 | def delete(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Pres delete key n times.
**中文文档**
按 delete 键n次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.delete_key, n, interval)
self.delay(post_dl) | [
"def",
"delete",
"(",
"self",
",",
"n",
"=",
"1",
",",
"interval",
"=",
"0",
",",
"pre_dl",
"=",
"None",
",",
"post_dl",
"=",
"None",
")",
":",
"self",
".",
"delay",
"(",
"pre_dl",
")",
"self",
".",
"k",
".",
"tap_key",
"(",
"self",
".",
"k",
... | Pres delete key n times.
**中文文档**
按 delete 键n次。 | [
"Pres",
"delete",
"key",
"n",
"times",
"."
] | python | train |
TeamHG-Memex/html-text | html_text/html_text.py | https://github.com/TeamHG-Memex/html-text/blob/871d4dbe9f4f99e5f041110c60458adcaae6fab4/html_text/html_text.py#L67-L137 | def etree_to_text(tree,
guess_punct_space=True,
guess_layout=True,
newline_tags=NEWLINE_TAGS,
double_newline_tags=DOUBLE_NEWLINE_TAGS):
"""
Convert a html tree to text. Tree should be cleaned with
``html_text.html_text.cleaner.clean_htm... | [
"def",
"etree_to_text",
"(",
"tree",
",",
"guess_punct_space",
"=",
"True",
",",
"guess_layout",
"=",
"True",
",",
"newline_tags",
"=",
"NEWLINE_TAGS",
",",
"double_newline_tags",
"=",
"DOUBLE_NEWLINE_TAGS",
")",
":",
"chunks",
"=",
"[",
"]",
"_NEWLINE",
"=",
... | Convert a html tree to text. Tree should be cleaned with
``html_text.html_text.cleaner.clean_html`` before passing to this
function.
See html_text.extract_text docstring for description of the
approach and options. | [
"Convert",
"a",
"html",
"tree",
"to",
"text",
".",
"Tree",
"should",
"be",
"cleaned",
"with",
"html_text",
".",
"html_text",
".",
"cleaner",
".",
"clean_html",
"before",
"passing",
"to",
"this",
"function",
"."
] | python | train |
nickmckay/LiPD-utilities | Python/lipd/versions.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/versions.py#L132-L169 | def update_lipd_v1_1(d):
"""
Update LiPD v1.0 to v1.1
- chronData entry is a list that allows multiple tables
- paleoData entry is a list that allows multiple tables
- chronData now allows measurement, model, summary, modelTable, ensemble, calibratedAges tables
- Added 'lipdVersion' key
:pa... | [
"def",
"update_lipd_v1_1",
"(",
"d",
")",
":",
"logger_versions",
".",
"info",
"(",
"\"enter update_lipd_v1_1\"",
")",
"tmp_all",
"=",
"[",
"]",
"try",
":",
"# ChronData is the only structure update",
"if",
"\"chronData\"",
"in",
"d",
":",
"# As of v1.1, ChronData sho... | Update LiPD v1.0 to v1.1
- chronData entry is a list that allows multiple tables
- paleoData entry is a list that allows multiple tables
- chronData now allows measurement, model, summary, modelTable, ensemble, calibratedAges tables
- Added 'lipdVersion' key
:param dict d: Metadata v1.0
:return... | [
"Update",
"LiPD",
"v1",
".",
"0",
"to",
"v1",
".",
"1",
"-",
"chronData",
"entry",
"is",
"a",
"list",
"that",
"allows",
"multiple",
"tables",
"-",
"paleoData",
"entry",
"is",
"a",
"list",
"that",
"allows",
"multiple",
"tables",
"-",
"chronData",
"now",
... | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.