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 |
|---|---|---|---|---|---|---|---|---|
rameshg87/pyremotevbox | pyremotevbox/ZSI/wstools/WSDLTools.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/wstools/WSDLTools.py#L1108-L1117 | def getAddressBinding(self):
"""A convenience method to obtain the extension element used
as the address binding for the port."""
for item in self.extensions:
if isinstance(item, SoapAddressBinding) or \
isinstance(item, HttpAddressBinding):
return i... | [
"def",
"getAddressBinding",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"extensions",
":",
"if",
"isinstance",
"(",
"item",
",",
"SoapAddressBinding",
")",
"or",
"isinstance",
"(",
"item",
",",
"HttpAddressBinding",
")",
":",
"return",
"item",
... | A convenience method to obtain the extension element used
as the address binding for the port. | [
"A",
"convenience",
"method",
"to",
"obtain",
"the",
"extension",
"element",
"used",
"as",
"the",
"address",
"binding",
"for",
"the",
"port",
"."
] | python | train |
OrkoHunter/keep | keep/cli.py | https://github.com/OrkoHunter/keep/blob/2253c60b4024c902115ae0472227059caee4a5eb/keep/cli.py#L22-L25 | def vlog(self, msg, *args):
"""Logs a message to stderr only if verbose is enabled."""
if self.verbose:
self.log(msg, *args) | [
"def",
"vlog",
"(",
"self",
",",
"msg",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"verbose",
":",
"self",
".",
"log",
"(",
"msg",
",",
"*",
"args",
")"
] | Logs a message to stderr only if verbose is enabled. | [
"Logs",
"a",
"message",
"to",
"stderr",
"only",
"if",
"verbose",
"is",
"enabled",
"."
] | python | train |
Duke-GCB/DukeDSClient | ddsc/core/projectuploader.py | https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/projectuploader.py#L371-L380 | def after_run(self, remote_file_data):
"""
Save uuid of file to our LocalFile
:param remote_file_data: dict: DukeDS file data
"""
if self.file_upload_post_processor:
self.file_upload_post_processor.run(self.settings.data_service, remote_file_data)
remote_file_... | [
"def",
"after_run",
"(",
"self",
",",
"remote_file_data",
")",
":",
"if",
"self",
".",
"file_upload_post_processor",
":",
"self",
".",
"file_upload_post_processor",
".",
"run",
"(",
"self",
".",
"settings",
".",
"data_service",
",",
"remote_file_data",
")",
"rem... | Save uuid of file to our LocalFile
:param remote_file_data: dict: DukeDS file data | [
"Save",
"uuid",
"of",
"file",
"to",
"our",
"LocalFile",
":",
"param",
"remote_file_data",
":",
"dict",
":",
"DukeDS",
"file",
"data"
] | python | train |
django-treebeard/django-treebeard | treebeard/mp_tree.py | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/mp_tree.py#L1039-L1042 | def get_root(self):
""":returns: the root node for the current node object."""
return get_result_class(self.__class__).objects.get(
path=self.path[0:self.steplen]) | [
"def",
"get_root",
"(",
"self",
")",
":",
"return",
"get_result_class",
"(",
"self",
".",
"__class__",
")",
".",
"objects",
".",
"get",
"(",
"path",
"=",
"self",
".",
"path",
"[",
"0",
":",
"self",
".",
"steplen",
"]",
")"
] | :returns: the root node for the current node object. | [
":",
"returns",
":",
"the",
"root",
"node",
"for",
"the",
"current",
"node",
"object",
"."
] | python | train |
nkmathew/yasi-sexp-indenter | yasi.py | https://github.com/nkmathew/yasi-sexp-indenter/blob/6ec2a4675e79606c555bcb67494a0ba994b05805/yasi.py#L579-L615 | def add_keywords(opts):
""" add_keywords(dialect : str) -> [str, str]
Takens a lisp dialect name and returns a list of keywords that increase
indentation by two spaces and those that can be one-armed like 'if'
"""
dialect = opts.dialect
keywords = collections.defaultdict(int)
two_spacers = ... | [
"def",
"add_keywords",
"(",
"opts",
")",
":",
"dialect",
"=",
"opts",
".",
"dialect",
"keywords",
"=",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"two_spacers",
"=",
"[",
"]",
"two_armed",
"=",
"IF_LIKE",
"local_binders",
"=",
"[",
"]",
"if",
"d... | add_keywords(dialect : str) -> [str, str]
Takens a lisp dialect name and returns a list of keywords that increase
indentation by two spaces and those that can be one-armed like 'if' | [
"add_keywords",
"(",
"dialect",
":",
"str",
")",
"-",
">",
"[",
"str",
"str",
"]"
] | python | train |
saltstack/salt | salt/utils/schema.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schema.py#L1481-L1493 | def _add_missing_schema_attributes(self):
'''
Adds any missed schema attributes to the _attributes list
The attributes can be class attributes and they won't be
included in the _attributes list automatically
'''
for attr in [attr for attr in dir(self) if not attr.startsw... | [
"def",
"_add_missing_schema_attributes",
"(",
"self",
")",
":",
"for",
"attr",
"in",
"[",
"attr",
"for",
"attr",
"in",
"dir",
"(",
"self",
")",
"if",
"not",
"attr",
".",
"startswith",
"(",
"'__'",
")",
"]",
":",
"attr_val",
"=",
"getattr",
"(",
"self",... | Adds any missed schema attributes to the _attributes list
The attributes can be class attributes and they won't be
included in the _attributes list automatically | [
"Adds",
"any",
"missed",
"schema",
"attributes",
"to",
"the",
"_attributes",
"list"
] | python | train |
aio-libs/aiohttp-debugtoolbar | aiohttp_debugtoolbar/tbtools/tbtools.py | https://github.com/aio-libs/aiohttp-debugtoolbar/blob/a1c3fb2b487bcaaf23eb71ee4c9c3cfc9cb94322/aiohttp_debugtoolbar/tbtools/tbtools.py#L148-L153 | def log(self, logfile=None):
"""Log the ASCII traceback into a file object."""
if logfile is None:
logfile = sys.stderr
tb = self.plaintext.encode('utf-8', 'replace').rstrip() + '\n'
logfile.write(tb) | [
"def",
"log",
"(",
"self",
",",
"logfile",
"=",
"None",
")",
":",
"if",
"logfile",
"is",
"None",
":",
"logfile",
"=",
"sys",
".",
"stderr",
"tb",
"=",
"self",
".",
"plaintext",
".",
"encode",
"(",
"'utf-8'",
",",
"'replace'",
")",
".",
"rstrip",
"(... | Log the ASCII traceback into a file object. | [
"Log",
"the",
"ASCII",
"traceback",
"into",
"a",
"file",
"object",
"."
] | python | train |
twilio/twilio-python | twilio/rest/autopilot/v1/assistant/field_type/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/autopilot/v1/assistant/field_type/__init__.py#L296-L309 | def field_values(self):
"""
Access the field_values
:returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList
:rtype: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList
"""
if self._field_values is None:
self._fi... | [
"def",
"field_values",
"(",
"self",
")",
":",
"if",
"self",
".",
"_field_values",
"is",
"None",
":",
"self",
".",
"_field_values",
"=",
"FieldValueList",
"(",
"self",
".",
"_version",
",",
"assistant_sid",
"=",
"self",
".",
"_solution",
"[",
"'assistant_sid'... | Access the field_values
:returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList
:rtype: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList | [
"Access",
"the",
"field_values"
] | python | train |
Jajcus/pyxmpp2 | pyxmpp2/ext/disco.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L735-L752 | def set_identities(self,identities):
"""Set identities in the disco#info object.
Remove all existing identities from `self`.
:Parameters:
- `identities`: list of identities or identity properties
(jid,node,category,type,name).
:Types:
- `identities... | [
"def",
"set_identities",
"(",
"self",
",",
"identities",
")",
":",
"for",
"identity",
"in",
"self",
".",
"identities",
":",
"identity",
".",
"remove",
"(",
")",
"for",
"identity",
"in",
"identities",
":",
"try",
":",
"self",
".",
"add_identity",
"(",
"id... | Set identities in the disco#info object.
Remove all existing identities from `self`.
:Parameters:
- `identities`: list of identities or identity properties
(jid,node,category,type,name).
:Types:
- `identities`: sequence of `DiscoIdentity` or sequence of se... | [
"Set",
"identities",
"in",
"the",
"disco#info",
"object",
"."
] | python | valid |
tensorlayer/tensorlayer | tensorlayer/layers/convolution/deformable_conv.py | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/convolution/deformable_conv.py#L247-L296 | def _tf_batch_map_offsets(self, inputs, offsets, grid_offset):
"""Batch map offsets into input
Parameters
------------
inputs : ``tf.Tensor``
shape = (b, h, w, c)
offsets: ``tf.Tensor``
shape = (b, h, w, 2*n)
grid_offset: `tf.Tensor``
... | [
"def",
"_tf_batch_map_offsets",
"(",
"self",
",",
"inputs",
",",
"offsets",
",",
"grid_offset",
")",
":",
"input_shape",
"=",
"inputs",
".",
"get_shape",
"(",
")",
"batch_size",
"=",
"tf",
".",
"shape",
"(",
"inputs",
")",
"[",
"0",
"]",
"kernel_n",
"=",... | Batch map offsets into input
Parameters
------------
inputs : ``tf.Tensor``
shape = (b, h, w, c)
offsets: ``tf.Tensor``
shape = (b, h, w, 2*n)
grid_offset: `tf.Tensor``
Offset grids shape = (h, w, n, 2)
Returns
-------
... | [
"Batch",
"map",
"offsets",
"into",
"input"
] | python | valid |
getpelican/pelican-plugins | events/events.py | https://github.com/getpelican/pelican-plugins/blob/cfc7a3f224f1743063b034561f89a6a712d13587/events/events.py#L80-L103 | def parse_article(generator, metadata):
"""Collect articles metadata to be used for building the event calendar
:returns: None
"""
if 'event-start' not in metadata:
return
dtstart = parse_tstamp(metadata, 'event-start')
if 'event-end' in metadata:
dtend = parse_tstamp(metadata... | [
"def",
"parse_article",
"(",
"generator",
",",
"metadata",
")",
":",
"if",
"'event-start'",
"not",
"in",
"metadata",
":",
"return",
"dtstart",
"=",
"parse_tstamp",
"(",
"metadata",
",",
"'event-start'",
")",
"if",
"'event-end'",
"in",
"metadata",
":",
"dtend",... | Collect articles metadata to be used for building the event calendar
:returns: None | [
"Collect",
"articles",
"metadata",
"to",
"be",
"used",
"for",
"building",
"the",
"event",
"calendar"
] | python | train |
aws/aws-xray-sdk-python | aws_xray_sdk/core/recorder.py | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/recorder.py#L460-L473 | def _send_segment(self):
"""
Send the current segment to X-Ray daemon if it is present and
sampled, then clean up context storage.
The emitter will handle failures.
"""
segment = self.current_segment()
if not segment:
return
if segment.sample... | [
"def",
"_send_segment",
"(",
"self",
")",
":",
"segment",
"=",
"self",
".",
"current_segment",
"(",
")",
"if",
"not",
"segment",
":",
"return",
"if",
"segment",
".",
"sampled",
":",
"self",
".",
"emitter",
".",
"send_entity",
"(",
"segment",
")",
"self",... | Send the current segment to X-Ray daemon if it is present and
sampled, then clean up context storage.
The emitter will handle failures. | [
"Send",
"the",
"current",
"segment",
"to",
"X",
"-",
"Ray",
"daemon",
"if",
"it",
"is",
"present",
"and",
"sampled",
"then",
"clean",
"up",
"context",
"storage",
".",
"The",
"emitter",
"will",
"handle",
"failures",
"."
] | python | train |
hyperledger/sawtooth-core | cli/sawtooth_cli/admin_command/keygen.py | https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/cli/sawtooth_cli/admin_command/keygen.py#L65-L133 | def do_keygen(args):
"""Executes the key generation operation, given the parsed arguments.
Args:
args (:obj:`Namespace`): The parsed args.
"""
if args.key_name is not None:
key_name = args.key_name
else:
key_name = 'validator'
key_dir = get_key_dir()
if not os.path... | [
"def",
"do_keygen",
"(",
"args",
")",
":",
"if",
"args",
".",
"key_name",
"is",
"not",
"None",
":",
"key_name",
"=",
"args",
".",
"key_name",
"else",
":",
"key_name",
"=",
"'validator'",
"key_dir",
"=",
"get_key_dir",
"(",
")",
"if",
"not",
"os",
".",
... | Executes the key generation operation, given the parsed arguments.
Args:
args (:obj:`Namespace`): The parsed args. | [
"Executes",
"the",
"key",
"generation",
"operation",
"given",
"the",
"parsed",
"arguments",
"."
] | python | train |
NuGrid/NuGridPy | nugridpy/data_plot.py | https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/data_plot.py#L1937-L2625 | def abu_flux_chart(self, cycle, ilabel=True, imlabel=True,
imagic=False, boxstable=True, lbound=(-12,0),
plotaxis=[0,0,0,0], which_flux=None, prange=None,
profile='charged', show=True):
'''
Plots an abundance and flux chart
Pa... | [
"def",
"abu_flux_chart",
"(",
"self",
",",
"cycle",
",",
"ilabel",
"=",
"True",
",",
"imlabel",
"=",
"True",
",",
"imagic",
"=",
"False",
",",
"boxstable",
"=",
"True",
",",
"lbound",
"=",
"(",
"-",
"12",
",",
"0",
")",
",",
"plotaxis",
"=",
"[",
... | Plots an abundance and flux chart
Parameters
----------
cycle : string, integer or list
The cycle we are looking in. If it is a list of cycles,
this method will then do a plot for each of these cycles
and save them all to a file.
ilabel : boolean, opt... | [
"Plots",
"an",
"abundance",
"and",
"flux",
"chart"
] | python | train |
apache/airflow | airflow/hooks/druid_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/druid_hook.py#L127-L139 | def get_conn(self):
"""
Establish a connection to druid broker.
"""
conn = self.get_connection(self.druid_broker_conn_id)
druid_broker_conn = connect(
host=conn.host,
port=conn.port,
path=conn.extra_dejson.get('endpoint', '/druid/v2/sql'),
... | [
"def",
"get_conn",
"(",
"self",
")",
":",
"conn",
"=",
"self",
".",
"get_connection",
"(",
"self",
".",
"druid_broker_conn_id",
")",
"druid_broker_conn",
"=",
"connect",
"(",
"host",
"=",
"conn",
".",
"host",
",",
"port",
"=",
"conn",
".",
"port",
",",
... | Establish a connection to druid broker. | [
"Establish",
"a",
"connection",
"to",
"druid",
"broker",
"."
] | python | test |
beathan/django-akamai | django_akamai/purge.py | https://github.com/beathan/django-akamai/blob/00cab2dd5fab3745742721185e75a55a5c26fe7e/django_akamai/purge.py#L149-L167 | def add(self, urls):
"""
Add the provided urls to this purge request
The urls argument can be a single string, a list of strings, a queryset
or model instance. Models must implement `get_absolute_url()`.
"""
if isinstance(urls, (list, tuple)):
self.urls.exte... | [
"def",
"add",
"(",
"self",
",",
"urls",
")",
":",
"if",
"isinstance",
"(",
"urls",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"self",
".",
"urls",
".",
"extend",
"(",
"urls",
")",
"elif",
"isinstance",
"(",
"urls",
",",
"basestring",
")",
":"... | Add the provided urls to this purge request
The urls argument can be a single string, a list of strings, a queryset
or model instance. Models must implement `get_absolute_url()`. | [
"Add",
"the",
"provided",
"urls",
"to",
"this",
"purge",
"request"
] | python | train |
numenta/nupic | src/nupic/encoders/logarithm.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/logarithm.py#L261-L289 | def closenessScores(self, expValues, actValues, fractional=True):
"""
See the function description in base.py
"""
# Compute the percent error in log space
if expValues[0] > 0:
expValue = math.log10(expValues[0])
else:
expValue = self.minScaledValue
if actValues [0] > 0:
... | [
"def",
"closenessScores",
"(",
"self",
",",
"expValues",
",",
"actValues",
",",
"fractional",
"=",
"True",
")",
":",
"# Compute the percent error in log space",
"if",
"expValues",
"[",
"0",
"]",
">",
"0",
":",
"expValue",
"=",
"math",
".",
"log10",
"(",
"exp... | See the function description in base.py | [
"See",
"the",
"function",
"description",
"in",
"base",
".",
"py"
] | python | valid |
xolox/python-update-dotdee | update_dotdee/__init__.py | https://github.com/xolox/python-update-dotdee/blob/04d5836f0d217e32778745b533beeb8159d80c32/update_dotdee/__init__.py#L478-L492 | def inject_documentation(**options):
"""
Generate configuration documentation in reStructuredText_ syntax.
:param options: Any keyword arguments are passed on to the
:class:`ConfigLoader` initializer.
This methods injects the generated documentation into the output generated
by... | [
"def",
"inject_documentation",
"(",
"*",
"*",
"options",
")",
":",
"import",
"cog",
"loader",
"=",
"ConfigLoader",
"(",
"*",
"*",
"options",
")",
"cog",
".",
"out",
"(",
"\"\\n\"",
"+",
"loader",
".",
"documentation",
"+",
"\"\\n\\n\"",
")"
] | Generate configuration documentation in reStructuredText_ syntax.
:param options: Any keyword arguments are passed on to the
:class:`ConfigLoader` initializer.
This methods injects the generated documentation into the output generated
by cog_.
.. _cog: https://pypi.python.org/pypi... | [
"Generate",
"configuration",
"documentation",
"in",
"reStructuredText_",
"syntax",
"."
] | python | train |
tensorflow/datasets | tensorflow_datasets/core/utils/tqdm_utils.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/tqdm_utils.py#L120-L124 | def update(self, n=1):
"""Increment current value."""
with self._lock:
self._pbar.update(n)
self.refresh() | [
"def",
"update",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_pbar",
".",
"update",
"(",
"n",
")",
"self",
".",
"refresh",
"(",
")"
] | Increment current value. | [
"Increment",
"current",
"value",
"."
] | python | train |
bykof/billomapy | billomapy/billomapy.py | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L2046-L2055 | def get_offers_per_page(self, per_page=1000, page=1, params=None):
"""
Get offers per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return... | [
"def",
"get_offers_per_page",
"(",
"self",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"OFFERS",
",",
"per_page",
"=",
"per_page",
",",
... | Get offers per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list | [
"Get",
"offers",
"per",
"page"
] | python | train |
maweigert/gputools | gputools/fft/fftshift.py | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/fft/fftshift.py#L27-L80 | def fftshift(arr_obj, axes = None, res_g = None, return_buffer = False):
"""
gpu version of fftshift for numpy arrays or OCLArrays
Parameters
----------
arr_obj: numpy array or OCLArray (float32/complex64)
the array to be fftshifted
axes: list or None
the axes over which to shif... | [
"def",
"fftshift",
"(",
"arr_obj",
",",
"axes",
"=",
"None",
",",
"res_g",
"=",
"None",
",",
"return_buffer",
"=",
"False",
")",
":",
"if",
"axes",
"is",
"None",
":",
"axes",
"=",
"list",
"(",
"range",
"(",
"arr_obj",
".",
"ndim",
")",
")",
"if",
... | gpu version of fftshift for numpy arrays or OCLArrays
Parameters
----------
arr_obj: numpy array or OCLArray (float32/complex64)
the array to be fftshifted
axes: list or None
the axes over which to shift (like np.fft.fftshift)
if None, all axes are taken
res_g:
if gi... | [
"gpu",
"version",
"of",
"fftshift",
"for",
"numpy",
"arrays",
"or",
"OCLArrays"
] | python | train |
gwastro/pycbc | pycbc/strain/recalibrate.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/recalibrate.py#L411-L428 | def tf_from_file(cls, path, delimiter=" "):
"""Convert the contents of a file with the columns
[freq, real(h), imag(h)] to a numpy.array with columns
[freq, real(h)+j*imag(h)].
Parameters
----------
path : string
delimiter : {" ", string}
Return
... | [
"def",
"tf_from_file",
"(",
"cls",
",",
"path",
",",
"delimiter",
"=",
"\" \"",
")",
":",
"data",
"=",
"np",
".",
"loadtxt",
"(",
"path",
",",
"delimiter",
"=",
"delimiter",
")",
"freq",
"=",
"data",
"[",
":",
",",
"0",
"]",
"h",
"=",
"data",
"["... | Convert the contents of a file with the columns
[freq, real(h), imag(h)] to a numpy.array with columns
[freq, real(h)+j*imag(h)].
Parameters
----------
path : string
delimiter : {" ", string}
Return
------
numpy.array | [
"Convert",
"the",
"contents",
"of",
"a",
"file",
"with",
"the",
"columns",
"[",
"freq",
"real",
"(",
"h",
")",
"imag",
"(",
"h",
")",
"]",
"to",
"a",
"numpy",
".",
"array",
"with",
"columns",
"[",
"freq",
"real",
"(",
"h",
")",
"+",
"j",
"*",
"... | python | train |
caseyjlaw/activegit | activegit/activegit.py | https://github.com/caseyjlaw/activegit/blob/2b4a0ee0fecf13345b5257130ba98b48f46e1098/activegit/activegit.py#L105-L122 | def set_version(self, version, force=True):
""" Sets the version name for the current state of repo """
if version in self.versions:
self._version = version
if 'working' in self.repo.branch().stdout:
if force:
logger.info('Found working branch... | [
"def",
"set_version",
"(",
"self",
",",
"version",
",",
"force",
"=",
"True",
")",
":",
"if",
"version",
"in",
"self",
".",
"versions",
":",
"self",
".",
"_version",
"=",
"version",
"if",
"'working'",
"in",
"self",
".",
"repo",
".",
"branch",
"(",
")... | Sets the version name for the current state of repo | [
"Sets",
"the",
"version",
"name",
"for",
"the",
"current",
"state",
"of",
"repo"
] | python | train |
square/pylink | pylink/jlink.py | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4267-L4282 | def trace_set_buffer_capacity(self, size):
"""Sets the capacity for the trace buffer.
Args:
self (JLink): the ``JLink`` instance.
size (int): the new capacity for the trace buffer.
Returns:
``None``
"""
cmd = enums.JLinkTraceCommand.SET_CAPACITY
... | [
"def",
"trace_set_buffer_capacity",
"(",
"self",
",",
"size",
")",
":",
"cmd",
"=",
"enums",
".",
"JLinkTraceCommand",
".",
"SET_CAPACITY",
"data",
"=",
"ctypes",
".",
"c_uint32",
"(",
"size",
")",
"res",
"=",
"self",
".",
"_dll",
".",
"JLINKARM_TRACE_Contro... | Sets the capacity for the trace buffer.
Args:
self (JLink): the ``JLink`` instance.
size (int): the new capacity for the trace buffer.
Returns:
``None`` | [
"Sets",
"the",
"capacity",
"for",
"the",
"trace",
"buffer",
"."
] | python | train |
fitodic/centerline | centerline/utils.py | https://github.com/fitodic/centerline/blob/f27e7b1ecb77bd4da40093ab44754cbd3ec9f58b/centerline/utils.py#L34-L63 | def get_ogr_driver(filepath):
"""
Get the OGR driver from the provided file extension.
Args:
file_extension (str): file extension
Returns:
osgeo.ogr.Driver
Raises:
ValueError: no driver is found
"""
filename, file_extension = os.path.splitext(filepath)
EXTENSI... | [
"def",
"get_ogr_driver",
"(",
"filepath",
")",
":",
"filename",
",",
"file_extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filepath",
")",
"EXTENSION",
"=",
"file_extension",
"[",
"1",
":",
"]",
"ogr_driver_count",
"=",
"ogr",
".",
"GetDriverCount... | Get the OGR driver from the provided file extension.
Args:
file_extension (str): file extension
Returns:
osgeo.ogr.Driver
Raises:
ValueError: no driver is found | [
"Get",
"the",
"OGR",
"driver",
"from",
"the",
"provided",
"file",
"extension",
"."
] | python | train |
pybel/pybel | src/pybel/dsl/namespaces.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/dsl/namespaces.py#L13-L15 | def chebi(name=None, identifier=None) -> Abundance:
"""Build a ChEBI abundance node."""
return Abundance(namespace='CHEBI', name=name, identifier=identifier) | [
"def",
"chebi",
"(",
"name",
"=",
"None",
",",
"identifier",
"=",
"None",
")",
"->",
"Abundance",
":",
"return",
"Abundance",
"(",
"namespace",
"=",
"'CHEBI'",
",",
"name",
"=",
"name",
",",
"identifier",
"=",
"identifier",
")"
] | Build a ChEBI abundance node. | [
"Build",
"a",
"ChEBI",
"abundance",
"node",
"."
] | python | train |
brandon-rhodes/python-jplephem | jplephem/ephem.py | https://github.com/brandon-rhodes/python-jplephem/blob/48c99ce40c627e24c95479d8845e312ea168f567/jplephem/ephem.py#L179-L196 | def velocity_from_bundle(self, bundle):
"""[DEPRECATED] Return velocity, given the `coefficient_bundle()` return value."""
coefficients, days_per_set, T, twot1 = bundle
coefficient_count = coefficients.shape[2]
# Chebyshev derivative:
dT = np.empty_like(T)
dT[0] = 0.0
... | [
"def",
"velocity_from_bundle",
"(",
"self",
",",
"bundle",
")",
":",
"coefficients",
",",
"days_per_set",
",",
"T",
",",
"twot1",
"=",
"bundle",
"coefficient_count",
"=",
"coefficients",
".",
"shape",
"[",
"2",
"]",
"# Chebyshev derivative:",
"dT",
"=",
"np",
... | [DEPRECATED] Return velocity, given the `coefficient_bundle()` return value. | [
"[",
"DEPRECATED",
"]",
"Return",
"velocity",
"given",
"the",
"coefficient_bundle",
"()",
"return",
"value",
"."
] | python | test |
johnnoone/json-spec | src/jsonspec/operations/__init__.py | https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/operations/__init__.py#L49-L64 | def replace(doc, pointer, value):
"""Replace element from sequence, member from mapping.
:param doc: the document base
:param pointer: the path to search in
:param value: the new value
:return: the new object
.. note::
This operation is functionally identical to a "remove" operation f... | [
"def",
"replace",
"(",
"doc",
",",
"pointer",
",",
"value",
")",
":",
"return",
"Target",
"(",
"doc",
")",
".",
"replace",
"(",
"pointer",
",",
"value",
")",
".",
"document"
] | Replace element from sequence, member from mapping.
:param doc: the document base
:param pointer: the path to search in
:param value: the new value
:return: the new object
.. note::
This operation is functionally identical to a "remove" operation for
a value, followed immediately ... | [
"Replace",
"element",
"from",
"sequence",
"member",
"from",
"mapping",
"."
] | python | train |
readbeyond/aeneas | aeneas/tools/convert_syncmap.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/convert_syncmap.py#L81-L161 | def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
if len(self.actual_arguments) < 2:
return self.print_help()
input_file_path = self.actual_arguments[0]
output_file_path = self.actual_arguments[1]
... | [
"def",
"perform_command",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"actual_arguments",
")",
"<",
"2",
":",
"return",
"self",
".",
"print_help",
"(",
")",
"input_file_path",
"=",
"self",
".",
"actual_arguments",
"[",
"0",
"]",
"output_file_path... | Perform command and return the appropriate exit code.
:rtype: int | [
"Perform",
"command",
"and",
"return",
"the",
"appropriate",
"exit",
"code",
"."
] | python | train |
MillionIntegrals/vel | vel/optimizers/rmsprop_tf.py | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/optimizers/rmsprop_tf.py#L50-L110 | def step(self, closure=None):
"""Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
"""
loss = None
if closure is not None:
loss = closure()
for... | [
"def",
"step",
"(",
"self",
",",
"closure",
"=",
"None",
")",
":",
"loss",
"=",
"None",
"if",
"closure",
"is",
"not",
"None",
":",
"loss",
"=",
"closure",
"(",
")",
"for",
"group",
"in",
"self",
".",
"param_groups",
":",
"for",
"p",
"in",
"group",
... | Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss. | [
"Performs",
"a",
"single",
"optimization",
"step",
"."
] | python | train |
HIPS/autograd | autograd/differential_operators.py | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L48-L61 | def jacobian(fun, x):
"""
Returns a function which computes the Jacobian of `fun` with respect to
positional argument number `argnum`, which must be a scalar or array. Unlike
`grad` it is not restricted to scalar-output functions, but also it cannot
take derivatives with respect to some argument typ... | [
"def",
"jacobian",
"(",
"fun",
",",
"x",
")",
":",
"vjp",
",",
"ans",
"=",
"_make_vjp",
"(",
"fun",
",",
"x",
")",
"ans_vspace",
"=",
"vspace",
"(",
"ans",
")",
"jacobian_shape",
"=",
"ans_vspace",
".",
"shape",
"+",
"vspace",
"(",
"x",
")",
".",
... | Returns a function which computes the Jacobian of `fun` with respect to
positional argument number `argnum`, which must be a scalar or array. Unlike
`grad` it is not restricted to scalar-output functions, but also it cannot
take derivatives with respect to some argument types (like lists or dicts).
If t... | [
"Returns",
"a",
"function",
"which",
"computes",
"the",
"Jacobian",
"of",
"fun",
"with",
"respect",
"to",
"positional",
"argument",
"number",
"argnum",
"which",
"must",
"be",
"a",
"scalar",
"or",
"array",
".",
"Unlike",
"grad",
"it",
"is",
"not",
"restricted... | python | train |
openstax/cnx-archive | cnxarchive/search.py | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/search.py#L388-L396 | def _upper(val_list):
"""
:param val_list: a list of strings
:return: a list of upper-cased strings
"""
res = []
for ele in val_list:
res.append(ele.upper())
return res | [
"def",
"_upper",
"(",
"val_list",
")",
":",
"res",
"=",
"[",
"]",
"for",
"ele",
"in",
"val_list",
":",
"res",
".",
"append",
"(",
"ele",
".",
"upper",
"(",
")",
")",
"return",
"res"
] | :param val_list: a list of strings
:return: a list of upper-cased strings | [
":",
"param",
"val_list",
":",
"a",
"list",
"of",
"strings",
":",
"return",
":",
"a",
"list",
"of",
"upper",
"-",
"cased",
"strings"
] | python | train |
jason-weirather/py-seq-tools | seqtools/structure/__init__.py | https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/structure/__init__.py#L239-L249 | def get_sequence(self,ref):
"""get a sequence given a reference"""
strand = '+'
if not self._options.direction:
sys.stderr.write("WARNING: no strand information for the transcript\n")
if self._options.direction: strand = self._options.direction
seq = ''
for e in [x.range for x in self.exon... | [
"def",
"get_sequence",
"(",
"self",
",",
"ref",
")",
":",
"strand",
"=",
"'+'",
"if",
"not",
"self",
".",
"_options",
".",
"direction",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"WARNING: no strand information for the transcript\\n\"",
")",
"if",
"self",... | get a sequence given a reference | [
"get",
"a",
"sequence",
"given",
"a",
"reference"
] | python | train |
saltstack/salt | salt/cloud/clouds/azurearm.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/azurearm.py#L392-L467 | def avail_images(call=None):
'''
Return a dict of all available images on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
compconn = get_co... | [
"def",
"avail_images",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_images function must be called with '",
"'-f or --function, or with the --list-images option'",
")",
"compconn",
"=",
"get_conn",... | Return a dict of all available images on the provider | [
"Return",
"a",
"dict",
"of",
"all",
"available",
"images",
"on",
"the",
"provider"
] | python | train |
codelv/enaml-native | src/enamlnative/android/android_location.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_location.py#L61-L105 | def start(cls, callback, provider='gps', min_time=1000, min_distance=0):
""" Convenience method that checks and requests permission if necessary
and if successful calls the callback with a populated `Location`
instance on updates.
Note you must have the permissions in your manifest or ... | [
"def",
"start",
"(",
"cls",
",",
"callback",
",",
"provider",
"=",
"'gps'",
",",
"min_time",
"=",
"1000",
",",
"min_distance",
"=",
"0",
")",
":",
"app",
"=",
"AndroidApplication",
".",
"instance",
"(",
")",
"f",
"=",
"app",
".",
"create_future",
"(",
... | Convenience method that checks and requests permission if necessary
and if successful calls the callback with a populated `Location`
instance on updates.
Note you must have the permissions in your manifest or requests
will be denied immediately. | [
"Convenience",
"method",
"that",
"checks",
"and",
"requests",
"permission",
"if",
"necessary",
"and",
"if",
"successful",
"calls",
"the",
"callback",
"with",
"a",
"populated",
"Location",
"instance",
"on",
"updates",
"."
] | python | train |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/flask/app.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/flask/app.py#L1441-L1461 | def dispatch_request(self):
"""Does the request dispatching. Matches the URL and returns the
return value of the view or error handler. This does not have to
be a response object. In order to convert the return value to a
proper response object, call :func:`make_response`.
..... | [
"def",
"dispatch_request",
"(",
"self",
")",
":",
"req",
"=",
"_request_ctx_stack",
".",
"top",
".",
"request",
"if",
"req",
".",
"routing_exception",
"is",
"not",
"None",
":",
"self",
".",
"raise_routing_exception",
"(",
"req",
")",
"rule",
"=",
"req",
".... | Does the request dispatching. Matches the URL and returns the
return value of the view or error handler. This does not have to
be a response object. In order to convert the return value to a
proper response object, call :func:`make_response`.
.. versionchanged:: 0.7
This n... | [
"Does",
"the",
"request",
"dispatching",
".",
"Matches",
"the",
"URL",
"and",
"returns",
"the",
"return",
"value",
"of",
"the",
"view",
"or",
"error",
"handler",
".",
"This",
"does",
"not",
"have",
"to",
"be",
"a",
"response",
"object",
".",
"In",
"order... | python | test |
ga4gh/ga4gh-server | ga4gh/server/gff3.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/gff3.py#L200-L205 | def _recSortKey(r):
"""
Sort order for Features, by genomic coordinate,
disambiguated by feature type (alphabetically).
"""
return r.seqname, r.start, -r.end, r.type | [
"def",
"_recSortKey",
"(",
"r",
")",
":",
"return",
"r",
".",
"seqname",
",",
"r",
".",
"start",
",",
"-",
"r",
".",
"end",
",",
"r",
".",
"type"
] | Sort order for Features, by genomic coordinate,
disambiguated by feature type (alphabetically). | [
"Sort",
"order",
"for",
"Features",
"by",
"genomic",
"coordinate",
"disambiguated",
"by",
"feature",
"type",
"(",
"alphabetically",
")",
"."
] | python | train |
jepegit/cellpy | cellpy/readers/cellreader.py | https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/cellreader.py#L391-L428 | def check_file_ids(self, rawfiles, cellpyfile):
"""Check the stats for the files (raw-data and cellpy hdf5).
This function checks if the hdf5 file and the res-files have the same
timestamps etc to find out if we need to bother to load .res -files.
Args:
cellpyfile (str): fi... | [
"def",
"check_file_ids",
"(",
"self",
",",
"rawfiles",
",",
"cellpyfile",
")",
":",
"txt",
"=",
"\"checking file ids - using '%s'\"",
"%",
"self",
".",
"filestatuschecker",
"self",
".",
"logger",
".",
"info",
"(",
"txt",
")",
"ids_cellpy_file",
"=",
"self",
".... | Check the stats for the files (raw-data and cellpy hdf5).
This function checks if the hdf5 file and the res-files have the same
timestamps etc to find out if we need to bother to load .res -files.
Args:
cellpyfile (str): filename of the cellpy hdf5-file.
rawfiles (list ... | [
"Check",
"the",
"stats",
"for",
"the",
"files",
"(",
"raw",
"-",
"data",
"and",
"cellpy",
"hdf5",
")",
"."
] | python | train |
pyQode/pyqode.core | pyqode/core/widgets/splittable_tab_widget.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L201-L213 | def close_right(self):
"""
Closes every editors tabs on the left of the current one.
"""
current_widget = self.widget(self.tab_under_menu())
index = self.indexOf(current_widget)
if self._try_close_dirty_tabs(tab_range=range(index + 1, self.count())):
while Tru... | [
"def",
"close_right",
"(",
"self",
")",
":",
"current_widget",
"=",
"self",
".",
"widget",
"(",
"self",
".",
"tab_under_menu",
"(",
")",
")",
"index",
"=",
"self",
".",
"indexOf",
"(",
"current_widget",
")",
"if",
"self",
".",
"_try_close_dirty_tabs",
"(",... | Closes every editors tabs on the left of the current one. | [
"Closes",
"every",
"editors",
"tabs",
"on",
"the",
"left",
"of",
"the",
"current",
"one",
"."
] | python | train |
SBRG/ssbio | ssbio/utils.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/utils.py#L752-L785 | def input_list_parser(infile_list):
"""Always return a list of files with varying input.
>>> input_list_parser(['/path/to/folder/'])
['/path/to/folder/file1.txt', '/path/to/folder/file2.txt', '/path/to/folder/file3.txt']
>>> input_list_parser(['/path/to/file.txt'])
['/path/to/file.txt']
>>> i... | [
"def",
"input_list_parser",
"(",
"infile_list",
")",
":",
"final_list_of_files",
"=",
"[",
"]",
"for",
"x",
"in",
"infile_list",
":",
"# If the input is a folder",
"if",
"op",
".",
"isdir",
"(",
"x",
")",
":",
"os",
".",
"chdir",
"(",
"x",
")",
"final_list... | Always return a list of files with varying input.
>>> input_list_parser(['/path/to/folder/'])
['/path/to/folder/file1.txt', '/path/to/folder/file2.txt', '/path/to/folder/file3.txt']
>>> input_list_parser(['/path/to/file.txt'])
['/path/to/file.txt']
>>> input_list_parser(['file1.txt'])
['file1... | [
"Always",
"return",
"a",
"list",
"of",
"files",
"with",
"varying",
"input",
"."
] | python | train |
inveniosoftware/invenio-github | invenio_github/handlers.py | https://github.com/inveniosoftware/invenio-github/blob/ec42fd6a06079310dcbe2c46d9fd79d5197bbe26/invenio_github/handlers.py#L62-L103 | def disconnect(remote):
"""Disconnect callback handler for GitHub."""
# User must be authenticated
if not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
external_method = 'github'
external_ids = [i.id for i in current_user.external_identifiers
... | [
"def",
"disconnect",
"(",
"remote",
")",
":",
"# User must be authenticated",
"if",
"not",
"current_user",
".",
"is_authenticated",
":",
"return",
"current_app",
".",
"login_manager",
".",
"unauthorized",
"(",
")",
"external_method",
"=",
"'github'",
"external_ids",
... | Disconnect callback handler for GitHub. | [
"Disconnect",
"callback",
"handler",
"for",
"GitHub",
"."
] | python | train |
mitsei/dlkit | dlkit/records/assessment/basic/simple_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/basic/simple_records.py#L482-L494 | def set_max_string_length(self, length=None):
"""stub"""
if self.get_max_string_length_metadata().is_read_only():
raise NoAccess()
if not self.my_osid_object_form._is_valid_cardinal(
length,
self.get_max_string_length_metadata()):
raise Inv... | [
"def",
"set_max_string_length",
"(",
"self",
",",
"length",
"=",
"None",
")",
":",
"if",
"self",
".",
"get_max_string_length_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
":",
"raise",
"NoAccess",
"(",
")",
"if",
"not",
"self",
".",
"my_osid_object_for... | stub | [
"stub"
] | python | train |
nickmckay/LiPD-utilities | Python/lipd/excel.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1377-L1389 | def compile_authors(cell):
"""
Split the string of author names into the BibJSON format.
:param str cell: Data from author cell
:return: (list of dicts) Author names
"""
logger_excel.info("enter compile_authors")
author_lst = []
s = cell.split(';')
for w in s:
author_lst.appe... | [
"def",
"compile_authors",
"(",
"cell",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter compile_authors\"",
")",
"author_lst",
"=",
"[",
"]",
"s",
"=",
"cell",
".",
"split",
"(",
"';'",
")",
"for",
"w",
"in",
"s",
":",
"author_lst",
".",
"append",
... | Split the string of author names into the BibJSON format.
:param str cell: Data from author cell
:return: (list of dicts) Author names | [
"Split",
"the",
"string",
"of",
"author",
"names",
"into",
"the",
"BibJSON",
"format",
".",
":",
"param",
"str",
"cell",
":",
"Data",
"from",
"author",
"cell",
":",
"return",
":",
"(",
"list",
"of",
"dicts",
")",
"Author",
"names"
] | python | train |
mrjoes/sockjs-tornado | sockjs/tornado/session.py | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/session.py#L255-L292 | def set_handler(self, handler, start_heartbeat=True):
"""Set active handler for the session
`handler`
Associate active Tornado handler with the session
`start_heartbeat`
Should session start heartbeat immediately
"""
# Check if session already has associa... | [
"def",
"set_handler",
"(",
"self",
",",
"handler",
",",
"start_heartbeat",
"=",
"True",
")",
":",
"# Check if session already has associated handler",
"if",
"self",
".",
"handler",
"is",
"not",
"None",
":",
"handler",
".",
"send_pack",
"(",
"proto",
".",
"discon... | Set active handler for the session
`handler`
Associate active Tornado handler with the session
`start_heartbeat`
Should session start heartbeat immediately | [
"Set",
"active",
"handler",
"for",
"the",
"session"
] | python | train |
pylast/pylast | src/pylast/__init__.py | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1395-L1412 | def get_top_tags(self, limit=None):
"""Returns a list of the most frequently used Tags on this object."""
doc = self._request(self.ws_prefix + ".getTopTags", True)
elements = doc.getElementsByTagName("tag")
seq = []
for element in elements:
tag_name = _extract(elem... | [
"def",
"get_top_tags",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getTopTags\"",
",",
"True",
")",
"elements",
"=",
"doc",
".",
"getElementsByTagName",
"(",
"\"tag\"",
")... | Returns a list of the most frequently used Tags on this object. | [
"Returns",
"a",
"list",
"of",
"the",
"most",
"frequently",
"used",
"Tags",
"on",
"this",
"object",
"."
] | python | train |
photo/openphoto-python | trovebox/objects/photo.py | https://github.com/photo/openphoto-python/blob/209a1da27c8d8c88dbcf4ea6c6f57031ea1bc44b/trovebox/objects/photo.py#L10-L20 | def delete(self, **kwds):
"""
Endpoint: /photo/<id>/delete.json
Deletes this photo.
Returns True if successful.
Raises a TroveboxError if not.
"""
result = self._client.photo.delete(self, **kwds)
self._delete_fields()
return result | [
"def",
"delete",
"(",
"self",
",",
"*",
"*",
"kwds",
")",
":",
"result",
"=",
"self",
".",
"_client",
".",
"photo",
".",
"delete",
"(",
"self",
",",
"*",
"*",
"kwds",
")",
"self",
".",
"_delete_fields",
"(",
")",
"return",
"result"
] | Endpoint: /photo/<id>/delete.json
Deletes this photo.
Returns True if successful.
Raises a TroveboxError if not. | [
"Endpoint",
":",
"/",
"photo",
"/",
"<id",
">",
"/",
"delete",
".",
"json"
] | python | train |
suds-community/suds | suds/umx/core.py | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/umx/core.py#L130-L153 | def append_children(self, content):
"""
Append child nodes into L{Content.data}
@param content: The current content being unmarshalled.
@type content: L{Content}
"""
for child in content.node:
cont = Content(child)
cval = self.append(cont)
... | [
"def",
"append_children",
"(",
"self",
",",
"content",
")",
":",
"for",
"child",
"in",
"content",
".",
"node",
":",
"cont",
"=",
"Content",
"(",
"child",
")",
"cval",
"=",
"self",
".",
"append",
"(",
"cont",
")",
"key",
"=",
"reserved",
".",
"get",
... | Append child nodes into L{Content.data}
@param content: The current content being unmarshalled.
@type content: L{Content} | [
"Append",
"child",
"nodes",
"into",
"L",
"{",
"Content",
".",
"data",
"}"
] | python | train |
Tanganelli/CoAPthon3 | coapthon/resources/resource.py | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L330-L342 | def resource_type(self):
"""
Get the CoRE Link Format rt attribute of the resource.
:return: the CoRE Link Format rt attribute
"""
value = "rt="
lst = self._attributes.get("rt")
if lst is None:
value = ""
else:
value += "\"" + str(... | [
"def",
"resource_type",
"(",
"self",
")",
":",
"value",
"=",
"\"rt=\"",
"lst",
"=",
"self",
".",
"_attributes",
".",
"get",
"(",
"\"rt\"",
")",
"if",
"lst",
"is",
"None",
":",
"value",
"=",
"\"\"",
"else",
":",
"value",
"+=",
"\"\\\"\"",
"+",
"str",
... | Get the CoRE Link Format rt attribute of the resource.
:return: the CoRE Link Format rt attribute | [
"Get",
"the",
"CoRE",
"Link",
"Format",
"rt",
"attribute",
"of",
"the",
"resource",
"."
] | python | train |
gem/oq-engine | openquake/hazardlib/gsim/si_midorikawa_1999.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/si_midorikawa_1999.py#L96-L109 | def _get_min_distance_to_volcanic_front(lons, lats):
"""
Compute and return minimum distance between volcanic front and points
specified by 'lon' and 'lat'.
Distance is negative if point is located east of the volcanic front,
positive otherwise.
The method uses the same approach as :meth:`_get... | [
"def",
"_get_min_distance_to_volcanic_front",
"(",
"lons",
",",
"lats",
")",
":",
"vf",
"=",
"_construct_surface",
"(",
"VOLCANIC_FRONT_LONS",
",",
"VOLCANIC_FRONT_LATS",
",",
"0.",
",",
"10.",
")",
"sites",
"=",
"Mesh",
"(",
"lons",
",",
"lats",
",",
"None",
... | Compute and return minimum distance between volcanic front and points
specified by 'lon' and 'lat'.
Distance is negative if point is located east of the volcanic front,
positive otherwise.
The method uses the same approach as :meth:`_get_min_distance_to_sub_trench`
but final distance is returned w... | [
"Compute",
"and",
"return",
"minimum",
"distance",
"between",
"volcanic",
"front",
"and",
"points",
"specified",
"by",
"lon",
"and",
"lat",
"."
] | python | train |
pantsbuild/pants | src/python/pants/base/mustache.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/mustache.py#L88-L98 | def _get_template_text_from_package(self, template_name):
"""Load the named template embedded in our package."""
if self._package_name is None:
raise self.MustacheError('No package specified for template loading.')
path = os.path.join('templates', template_name + '.mustache')
template_text = pkgu... | [
"def",
"_get_template_text_from_package",
"(",
"self",
",",
"template_name",
")",
":",
"if",
"self",
".",
"_package_name",
"is",
"None",
":",
"raise",
"self",
".",
"MustacheError",
"(",
"'No package specified for template loading.'",
")",
"path",
"=",
"os",
".",
"... | Load the named template embedded in our package. | [
"Load",
"the",
"named",
"template",
"embedded",
"in",
"our",
"package",
"."
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/runsnakerun/squaremap/squaremap.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/runsnakerun/squaremap/squaremap.py#L460-L462 | def children_sum( self, children,node ):
"""Calculate children's total sum"""
return sum( [self.value(value,node) for value in children] ) | [
"def",
"children_sum",
"(",
"self",
",",
"children",
",",
"node",
")",
":",
"return",
"sum",
"(",
"[",
"self",
".",
"value",
"(",
"value",
",",
"node",
")",
"for",
"value",
"in",
"children",
"]",
")"
] | Calculate children's total sum | [
"Calculate",
"children",
"s",
"total",
"sum"
] | python | train |
lappis-unb/salic-ml | src/salicml/metrics/finance/common_items_ratio.py | https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/common_items_ratio.py#L110-L118 | def get_project_items(pronac):
"""
Returns all items from a project.
"""
df = data.all_items
return (
df[df['PRONAC'] == pronac]
.drop(columns=['PRONAC', 'idSegmento'])
) | [
"def",
"get_project_items",
"(",
"pronac",
")",
":",
"df",
"=",
"data",
".",
"all_items",
"return",
"(",
"df",
"[",
"df",
"[",
"'PRONAC'",
"]",
"==",
"pronac",
"]",
".",
"drop",
"(",
"columns",
"=",
"[",
"'PRONAC'",
",",
"'idSegmento'",
"]",
")",
")"... | Returns all items from a project. | [
"Returns",
"all",
"items",
"from",
"a",
"project",
"."
] | python | train |
SamLau95/nbinteract | nbinteract/exporters.py | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/exporters.py#L236-L249 | def _wait_for_save(nb_name, timeout=5):
"""Waits for nb_name to update, waiting up to TIMEOUT seconds.
Returns True if a save was detected, and False otherwise.
"""
modification_time = os.path.getmtime(nb_name)
start_time = time.time()
while time.time() < start_time + timeout:
if (
... | [
"def",
"_wait_for_save",
"(",
"nb_name",
",",
"timeout",
"=",
"5",
")",
":",
"modification_time",
"=",
"os",
".",
"path",
".",
"getmtime",
"(",
"nb_name",
")",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"while",
"time",
".",
"time",
"(",
")",
... | Waits for nb_name to update, waiting up to TIMEOUT seconds.
Returns True if a save was detected, and False otherwise. | [
"Waits",
"for",
"nb_name",
"to",
"update",
"waiting",
"up",
"to",
"TIMEOUT",
"seconds",
".",
"Returns",
"True",
"if",
"a",
"save",
"was",
"detected",
"and",
"False",
"otherwise",
"."
] | python | train |
horazont/aioxmpp | aioxmpp/stream.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1195-L1211 | def flush_incoming(self):
"""
Flush all incoming queues to the respective processing methods. The
handlers are called as usual, thus it may require at least one
iteration through the asyncio event loop before effects can be seen.
The incoming queues are empty after a call to thi... | [
"def",
"flush_incoming",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"stanza_obj",
"=",
"self",
".",
"_incoming_queue",
".",
"get_nowait",
"(",
")",
"except",
"asyncio",
".",
"QueueEmpty",
":",
"break",
"self",
".",
"_process_incoming",
"(",
"... | Flush all incoming queues to the respective processing methods. The
handlers are called as usual, thus it may require at least one
iteration through the asyncio event loop before effects can be seen.
The incoming queues are empty after a call to this method.
It is legal (but pretty use... | [
"Flush",
"all",
"incoming",
"queues",
"to",
"the",
"respective",
"processing",
"methods",
".",
"The",
"handlers",
"are",
"called",
"as",
"usual",
"thus",
"it",
"may",
"require",
"at",
"least",
"one",
"iteration",
"through",
"the",
"asyncio",
"event",
"loop",
... | python | train |
titusjan/argos | argos/utils/cls.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L350-L370 | def array_has_real_numbers(array):
""" Uses the dtype kind of the numpy array to determine if it represents real numbers.
That is, the array kind should be one of: i u f
Possible dtype.kind values.
b boolean
i signed integer
u unsigned integer
f ... | [
"def",
"array_has_real_numbers",
"(",
"array",
")",
":",
"kind",
"=",
"array",
".",
"dtype",
".",
"kind",
"assert",
"kind",
"in",
"'biufcmMOSUV'",
",",
"\"Unexpected array kind: {}\"",
".",
"format",
"(",
"kind",
")",
"return",
"kind",
"in",
"'iuf'"
] | Uses the dtype kind of the numpy array to determine if it represents real numbers.
That is, the array kind should be one of: i u f
Possible dtype.kind values.
b boolean
i signed integer
u unsigned integer
f floating-point
c complex float... | [
"Uses",
"the",
"dtype",
"kind",
"of",
"the",
"numpy",
"array",
"to",
"determine",
"if",
"it",
"represents",
"real",
"numbers",
"."
] | python | train |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/segments.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/segments.py#L112-L121 | def sort(self, *args):
"""
Sort the internal segment lists. The optional args are
passed to the .sort() method of the segment lists. This
can be used to control the sort order by providing an
alternate comparison function. The default is to sort by
start time with ties broken by end time.
"""
self.va... | [
"def",
"sort",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"valid",
".",
"sort",
"(",
"*",
"args",
")",
"self",
".",
"active",
".",
"sort",
"(",
"*",
"args",
")"
] | Sort the internal segment lists. The optional args are
passed to the .sort() method of the segment lists. This
can be used to control the sort order by providing an
alternate comparison function. The default is to sort by
start time with ties broken by end time. | [
"Sort",
"the",
"internal",
"segment",
"lists",
".",
"The",
"optional",
"args",
"are",
"passed",
"to",
"the",
".",
"sort",
"()",
"method",
"of",
"the",
"segment",
"lists",
".",
"This",
"can",
"be",
"used",
"to",
"control",
"the",
"sort",
"order",
"by",
... | python | train |
boundlessgeo/lib-qgis-commons | qgiscommons2/layers.py | https://github.com/boundlessgeo/lib-qgis-commons/blob/d25d13803db08c18632b55d12036e332f006d9ac/qgiscommons2/layers.py#L246-L261 | def loadLayerNoCrsDialog(filename, name=None, provider=None):
'''
Tries to load a layer from the given file
Same as the loadLayer method, but it does not ask for CRS, regardless of current
configuration in QGIS settings
'''
settings = QSettings()
prjSetting = settings.value('/Projections/def... | [
"def",
"loadLayerNoCrsDialog",
"(",
"filename",
",",
"name",
"=",
"None",
",",
"provider",
"=",
"None",
")",
":",
"settings",
"=",
"QSettings",
"(",
")",
"prjSetting",
"=",
"settings",
".",
"value",
"(",
"'/Projections/defaultBehaviour'",
")",
"settings",
".",... | Tries to load a layer from the given file
Same as the loadLayer method, but it does not ask for CRS, regardless of current
configuration in QGIS settings | [
"Tries",
"to",
"load",
"a",
"layer",
"from",
"the",
"given",
"file",
"Same",
"as",
"the",
"loadLayer",
"method",
"but",
"it",
"does",
"not",
"ask",
"for",
"CRS",
"regardless",
"of",
"current",
"configuration",
"in",
"QGIS",
"settings"
] | python | train |
pypa/pipenv | pipenv/vendor/distlib/database.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L617-L630 | def read_exports(self):
"""
Read exports data from a file in .ini format.
:return: A dictionary of exports, mapping an export category to a list
of :class:`ExportEntry` instances describing the individual
export entries.
"""
result = {}
... | [
"def",
"read_exports",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"r",
"=",
"self",
".",
"get_distinfo_resource",
"(",
"EXPORTS_FILENAME",
")",
"if",
"r",
":",
"with",
"contextlib",
".",
"closing",
"(",
"r",
".",
"as_stream",
"(",
")",
")",
"as",
... | Read exports data from a file in .ini format.
:return: A dictionary of exports, mapping an export category to a list
of :class:`ExportEntry` instances describing the individual
export entries. | [
"Read",
"exports",
"data",
"from",
"a",
"file",
"in",
".",
"ini",
"format",
"."
] | python | train |
luiscberrocal/pyjavaprops | pyjavaprops/javaproperties.py | https://github.com/luiscberrocal/pyjavaprops/blob/7d0327b1758b3d907af657e0df3b0618776ac46d/pyjavaprops/javaproperties.py#L285-L291 | def list(self, out=sys.stdout):
""" Prints a listing of the properties to the
stream 'out' which defaults to the standard output """
out.write('-- listing properties --\n')
for key,value in self._properties.items():
out.write(''.join((key,'=',value,'\n'))) | [
"def",
"list",
"(",
"self",
",",
"out",
"=",
"sys",
".",
"stdout",
")",
":",
"out",
".",
"write",
"(",
"'-- listing properties --\\n'",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"_properties",
".",
"items",
"(",
")",
":",
"out",
".",
"write... | Prints a listing of the properties to the
stream 'out' which defaults to the standard output | [
"Prints",
"a",
"listing",
"of",
"the",
"properties",
"to",
"the",
"stream",
"out",
"which",
"defaults",
"to",
"the",
"standard",
"output"
] | python | train |
applegrew/django-select2 | django_select2/forms.py | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/forms.py#L350-L368 | def set_to_cache(self):
"""
Add widget's attributes to Django's cache.
Split the QuerySet, to not pickle the result set.
"""
queryset = self.get_queryset()
cache.set(self._get_cache_key(), {
'queryset':
[
queryset.none(),
... | [
"def",
"set_to_cache",
"(",
"self",
")",
":",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"cache",
".",
"set",
"(",
"self",
".",
"_get_cache_key",
"(",
")",
",",
"{",
"'queryset'",
":",
"[",
"queryset",
".",
"none",
"(",
")",
",",
"querys... | Add widget's attributes to Django's cache.
Split the QuerySet, to not pickle the result set. | [
"Add",
"widget",
"s",
"attributes",
"to",
"Django",
"s",
"cache",
"."
] | python | train |
UCL-INGI/INGInious | inginious/frontend/pages/api/courses.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/courses.py#L16-L67 | def API_GET(self, courseid=None): # pylint: disable=arguments-differ
"""
List courses available to the connected client. Returns a dict in the form
::
{
"courseid1":
{
"name": "Name of the course", #th... | [
"def",
"API_GET",
"(",
"self",
",",
"courseid",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"output",
"=",
"[",
"]",
"if",
"courseid",
"is",
"None",
":",
"courses",
"=",
"self",
".",
"course_factory",
".",
"get_all_courses",
"(",
")",
"else"... | List courses available to the connected client. Returns a dict in the form
::
{
"courseid1":
{
"name": "Name of the course", #the name of the course
"require_password": False, #indicates if t... | [
"List",
"courses",
"available",
"to",
"the",
"connected",
"client",
".",
"Returns",
"a",
"dict",
"in",
"the",
"form"
] | python | train |
bcbio/bcbio-nextgen | bcbio/variation/joint.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/joint.py#L196-L207 | def _fix_orig_vcf_refs(data):
"""Supply references to initial variantcalls if run in addition to batching.
"""
variantcaller = tz.get_in(("config", "algorithm", "variantcaller"), data)
if variantcaller:
data["vrn_file_orig"] = data["vrn_file"]
for i, sub in enumerate(data.get("group_orig", [... | [
"def",
"_fix_orig_vcf_refs",
"(",
"data",
")",
":",
"variantcaller",
"=",
"tz",
".",
"get_in",
"(",
"(",
"\"config\"",
",",
"\"algorithm\"",
",",
"\"variantcaller\"",
")",
",",
"data",
")",
"if",
"variantcaller",
":",
"data",
"[",
"\"vrn_file_orig\"",
"]",
"... | Supply references to initial variantcalls if run in addition to batching. | [
"Supply",
"references",
"to",
"initial",
"variantcalls",
"if",
"run",
"in",
"addition",
"to",
"batching",
"."
] | python | train |
openstax/cnx-epub | cnxepub/epub.py | https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/epub.py#L379-L413 | def to_file(package, directory):
"""Write the package to the given ``directory``.
Returns the OPF filename.
"""
opf_filepath = os.path.join(directory, package.name)
# Create the directory structure
for name in ('contents', 'resources',):
path = os.path.join(d... | [
"def",
"to_file",
"(",
"package",
",",
"directory",
")",
":",
"opf_filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"package",
".",
"name",
")",
"# Create the directory structure",
"for",
"name",
"in",
"(",
"'contents'",
",",
"'resource... | Write the package to the given ``directory``.
Returns the OPF filename. | [
"Write",
"the",
"package",
"to",
"the",
"given",
"directory",
".",
"Returns",
"the",
"OPF",
"filename",
"."
] | python | train |
Rockhopper-Technologies/enlighten | enlighten/_win_terminal.py | https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_win_terminal.py#L163-L172 | def color(self, code):
"""
When color is given as a number, apply that color to the content
While this is designed to support 256 color terminals, Windows will approximate
this with 16 colors
"""
def func(content=''):
return self._apply_color(u'38;5;%d' % cod... | [
"def",
"color",
"(",
"self",
",",
"code",
")",
":",
"def",
"func",
"(",
"content",
"=",
"''",
")",
":",
"return",
"self",
".",
"_apply_color",
"(",
"u'38;5;%d'",
"%",
"code",
",",
"content",
")",
"return",
"func"
] | When color is given as a number, apply that color to the content
While this is designed to support 256 color terminals, Windows will approximate
this with 16 colors | [
"When",
"color",
"is",
"given",
"as",
"a",
"number",
"apply",
"that",
"color",
"to",
"the",
"content",
"While",
"this",
"is",
"designed",
"to",
"support",
"256",
"color",
"terminals",
"Windows",
"will",
"approximate",
"this",
"with",
"16",
"colors"
] | python | train |
materialsproject/pymatgen | pymatgen/symmetry/analyzer.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/symmetry/analyzer.py#L1471-L1508 | def cluster_sites(mol, tol, give_only_index=False):
"""
Cluster sites based on distance and species type.
Args:
mol (Molecule): Molecule **with origin at center of mass**.
tol (float): Tolerance to use.
Returns:
(origin_site, clustered_sites): origin_site is a site at the cente... | [
"def",
"cluster_sites",
"(",
"mol",
",",
"tol",
",",
"give_only_index",
"=",
"False",
")",
":",
"# Cluster works for dim > 2 data. We just add a dummy 0 for second",
"# coordinate.",
"dists",
"=",
"[",
"[",
"np",
".",
"linalg",
".",
"norm",
"(",
"site",
".",
"coor... | Cluster sites based on distance and species type.
Args:
mol (Molecule): Molecule **with origin at center of mass**.
tol (float): Tolerance to use.
Returns:
(origin_site, clustered_sites): origin_site is a site at the center
of mass (None if there are no origin atoms). clustered... | [
"Cluster",
"sites",
"based",
"on",
"distance",
"and",
"species",
"type",
"."
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/pympler/summary.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/summary.py#L283-L293 | def _subtract(summary, o):
"""Remove object o from the summary by subtracting it's size."""
found = False
row = [_repr(o), 1, _getsizeof(o)]
for r in summary:
if r[0] == row[0]:
(r[1], r[2]) = (r[1] - row[1], r[2] - row[2])
found = True
if not found:
summary.a... | [
"def",
"_subtract",
"(",
"summary",
",",
"o",
")",
":",
"found",
"=",
"False",
"row",
"=",
"[",
"_repr",
"(",
"o",
")",
",",
"1",
",",
"_getsizeof",
"(",
"o",
")",
"]",
"for",
"r",
"in",
"summary",
":",
"if",
"r",
"[",
"0",
"]",
"==",
"row",
... | Remove object o from the summary by subtracting it's size. | [
"Remove",
"object",
"o",
"from",
"the",
"summary",
"by",
"subtracting",
"it",
"s",
"size",
"."
] | python | train |
Scoppio/RagnarokEngine3 | RagnarokEngine3/RE3.py | https://github.com/Scoppio/RagnarokEngine3/blob/4395d419ccd64fe9327c41f200b72ee0176ad896/RagnarokEngine3/RE3.py#L3227-L3231 | def update(self, milliseconds):
"""Updates all of the objects in our world."""
self.__sort_up()
for obj in self.__up_objects:
obj.update(milliseconds) | [
"def",
"update",
"(",
"self",
",",
"milliseconds",
")",
":",
"self",
".",
"__sort_up",
"(",
")",
"for",
"obj",
"in",
"self",
".",
"__up_objects",
":",
"obj",
".",
"update",
"(",
"milliseconds",
")"
] | Updates all of the objects in our world. | [
"Updates",
"all",
"of",
"the",
"objects",
"in",
"our",
"world",
"."
] | python | train |
quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/minute_bars.py#L1098-L1149 | def get_value(self, sid, dt, field):
"""
Retrieve the pricing info for the given sid, dt, and field.
Parameters
----------
sid : int
Asset identifier.
dt : datetime-like
The datetime at which the trade occurred.
field : string
... | [
"def",
"get_value",
"(",
"self",
",",
"sid",
",",
"dt",
",",
"field",
")",
":",
"if",
"self",
".",
"_last_get_value_dt_value",
"==",
"dt",
".",
"value",
":",
"minute_pos",
"=",
"self",
".",
"_last_get_value_dt_position",
"else",
":",
"try",
":",
"minute_po... | Retrieve the pricing info for the given sid, dt, and field.
Parameters
----------
sid : int
Asset identifier.
dt : datetime-like
The datetime at which the trade occurred.
field : string
The type of pricing data to retrieve.
('open'... | [
"Retrieve",
"the",
"pricing",
"info",
"for",
"the",
"given",
"sid",
"dt",
"and",
"field",
"."
] | python | train |
digidotcom/python-streamexpect | streamexpect.py | https://github.com/digidotcom/python-streamexpect/blob/9ab894506ffd679b37230e935158ff3b0aa170ab/streamexpect.py#L193-L209 | def search(self, buf):
"""Search the provided buffer for matching text.
Search the provided buffer for matching text. If the *match* is found,
returns a :class:`SequenceMatch` object, otherwise returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`Sequenc... | [
"def",
"search",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"_check_type",
"(",
"buf",
")",
"normalized",
"=",
"unicodedata",
".",
"normalize",
"(",
"self",
".",
"FORM",
",",
"buf",
")",
"idx",
"=",
"normalized",
".",
"find",
"(",
"self",
".",
... | Search the provided buffer for matching text.
Search the provided buffer for matching text. If the *match* is found,
returns a :class:`SequenceMatch` object, otherwise returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`SequenceMatch` if matched, None if no mat... | [
"Search",
"the",
"provided",
"buffer",
"for",
"matching",
"text",
"."
] | python | train |
blockstack/virtualchain | virtualchain/lib/indexer.py | https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/indexer.py#L1681-L1745 | def sqlite3_backup(src_path, dest_path):
"""
Back up a sqlite3 database, while ensuring
that no ongoing queries are being executed.
Return True on success
Return False on error.
"""
# find sqlite3
sqlite3_path = sqlite3_find_tool()
if sqlite3_path is None:
log.error("Failed... | [
"def",
"sqlite3_backup",
"(",
"src_path",
",",
"dest_path",
")",
":",
"# find sqlite3",
"sqlite3_path",
"=",
"sqlite3_find_tool",
"(",
")",
"if",
"sqlite3_path",
"is",
"None",
":",
"log",
".",
"error",
"(",
"\"Failed to find sqlite3 tool\"",
")",
"return",
"False"... | Back up a sqlite3 database, while ensuring
that no ongoing queries are being executed.
Return True on success
Return False on error. | [
"Back",
"up",
"a",
"sqlite3",
"database",
"while",
"ensuring",
"that",
"no",
"ongoing",
"queries",
"are",
"being",
"executed",
"."
] | python | train |
pandas-dev/pandas | pandas/core/dtypes/common.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/common.py#L1980-L2002 | def _validate_date_like_dtype(dtype):
"""
Check whether the dtype is a date-like dtype. Raises an error if invalid.
Parameters
----------
dtype : dtype, type
The dtype to check.
Raises
------
TypeError : The dtype could not be casted to a date-like dtype.
ValueError : The d... | [
"def",
"_validate_date_like_dtype",
"(",
"dtype",
")",
":",
"try",
":",
"typ",
"=",
"np",
".",
"datetime_data",
"(",
"dtype",
")",
"[",
"0",
"]",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"TypeError",
"(",
"'{error}'",
".",
"format",
"(",
"error",... | Check whether the dtype is a date-like dtype. Raises an error if invalid.
Parameters
----------
dtype : dtype, type
The dtype to check.
Raises
------
TypeError : The dtype could not be casted to a date-like dtype.
ValueError : The dtype is an illegal date-like dtype (e.g. the
... | [
"Check",
"whether",
"the",
"dtype",
"is",
"a",
"date",
"-",
"like",
"dtype",
".",
"Raises",
"an",
"error",
"if",
"invalid",
"."
] | python | train |
nmdp-bioinformatics/SeqAnn | seqann/blast_cmd.py | https://github.com/nmdp-bioinformatics/SeqAnn/blob/5ce91559b0a4fbe4fb7758e034eb258202632463/seqann/blast_cmd.py#L40-L184 | def blastn(sequences, locus, nseqs, kir=False,
verbose=False, refdata=None, evalue=10):
"""
Gets the a list of alleles that are the most similar to the input sequence
:param sequences: The input sequence record.
:type sequences: SeqRecord
:param locus: The gene locus associated with the ... | [
"def",
"blastn",
"(",
"sequences",
",",
"locus",
",",
"nseqs",
",",
"kir",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"refdata",
"=",
"None",
",",
"evalue",
"=",
"10",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"Logger.\"",
"+... | Gets the a list of alleles that are the most similar to the input sequence
:param sequences: The input sequence record.
:type sequences: SeqRecord
:param locus: The gene locus associated with the sequence.
:type locus: ``str``
:param nseqs: The incomplete annotation from a previous iteration.
:... | [
"Gets",
"the",
"a",
"list",
"of",
"alleles",
"that",
"are",
"the",
"most",
"similar",
"to",
"the",
"input",
"sequence"
] | python | train |
FutunnOpen/futuquant | futuquant/common/open_context_base.py | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/common/open_context_base.py#L242-L286 | def get_global_state(self):
"""
获取全局状态
:return: (ret, data)
ret == RET_OK data为包含全局状态的字典,含义如下
ret != RET_OK data为错误描述字符串
===================== =========== ==============================================================
key ... | [
"def",
"get_global_state",
"(",
"self",
")",
":",
"query_processor",
"=",
"self",
".",
"_get_sync_query_processor",
"(",
"GlobalStateQuery",
".",
"pack_req",
",",
"GlobalStateQuery",
".",
"unpack_rsp",
")",
"kargs",
"=",
"{",
"'user_id'",
":",
"self",
".",
"get_... | 获取全局状态
:return: (ret, data)
ret == RET_OK data为包含全局状态的字典,含义如下
ret != RET_OK data为错误描述字符串
===================== =========== ==============================================================
key value类型 ... | [
"获取全局状态"
] | python | train |
hawkular/hawkular-client-python | hawkular/metrics.py | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/metrics.py#L176-L212 | def query_metric_stats(self, metric_type, metric_id=None, start=None, end=None, bucketDuration=None, **query_options):
"""
Query for metric aggregates from the server. This is called buckets in the Hawkular-Metrics documentation.
:param metric_type: MetricType to be matched (required)
:... | [
"def",
"query_metric_stats",
"(",
"self",
",",
"metric_type",
",",
"metric_id",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"bucketDuration",
"=",
"None",
",",
"*",
"*",
"query_options",
")",
":",
"if",
"start",
"is",
"not",
"... | Query for metric aggregates from the server. This is called buckets in the Hawkular-Metrics documentation.
:param metric_type: MetricType to be matched (required)
:param metric_id: Exact string matching metric id or None for tags matching only
:param start: Milliseconds since epoch or datetime ... | [
"Query",
"for",
"metric",
"aggregates",
"from",
"the",
"server",
".",
"This",
"is",
"called",
"buckets",
"in",
"the",
"Hawkular",
"-",
"Metrics",
"documentation",
"."
] | python | train |
ingolemo/python-lenses | examples/naughts_and_crosses.py | https://github.com/ingolemo/python-lenses/blob/a3a6ed0a31f6674451e542e7380a8aa16e6f8edf/examples/naughts_and_crosses.py#L55-L64 | def winner(self):
'The winner of this board if one exists.'
for potential_win in self._potential_wins():
if potential_win == tuple('XXX'):
return Outcome.win_for_crosses
elif potential_win == tuple('OOO'):
return Outcome.win_for_naughts
if ... | [
"def",
"winner",
"(",
"self",
")",
":",
"for",
"potential_win",
"in",
"self",
".",
"_potential_wins",
"(",
")",
":",
"if",
"potential_win",
"==",
"tuple",
"(",
"'XXX'",
")",
":",
"return",
"Outcome",
".",
"win_for_crosses",
"elif",
"potential_win",
"==",
"... | The winner of this board if one exists. | [
"The",
"winner",
"of",
"this",
"board",
"if",
"one",
"exists",
"."
] | python | test |
spyder-ide/spyder | spyder/widgets/arraybuilder.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/arraybuilder.py#L271-L285 | def keyPressEvent(self, event):
"""
Qt override.
"""
QToolTip.hideText()
ctrl = event.modifiers() & Qt.ControlModifier
if event.key() in [Qt.Key_Enter, Qt.Key_Return]:
if ctrl:
self.process_text(array=False)
else:
... | [
"def",
"keyPressEvent",
"(",
"self",
",",
"event",
")",
":",
"QToolTip",
".",
"hideText",
"(",
")",
"ctrl",
"=",
"event",
".",
"modifiers",
"(",
")",
"&",
"Qt",
".",
"ControlModifier",
"if",
"event",
".",
"key",
"(",
")",
"in",
"[",
"Qt",
".",
"Key... | Qt override. | [
"Qt",
"override",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/click/termui.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/termui.py#L580-L606 | def pause(info='Press any key to continue ...', err=False):
"""This command stops execution and waits for the user to press any
key to continue. This is similar to the Windows batch "pause"
command. If the program is not run through a terminal, this command
will instead do nothing.
.. versionadde... | [
"def",
"pause",
"(",
"info",
"=",
"'Press any key to continue ...'",
",",
"err",
"=",
"False",
")",
":",
"if",
"not",
"isatty",
"(",
"sys",
".",
"stdin",
")",
"or",
"not",
"isatty",
"(",
"sys",
".",
"stdout",
")",
":",
"return",
"try",
":",
"if",
"in... | This command stops execution and waits for the user to press any
key to continue. This is similar to the Windows batch "pause"
command. If the program is not run through a terminal, this command
will instead do nothing.
.. versionadded:: 2.0
.. versionadded:: 4.0
Added the `err` parameter... | [
"This",
"command",
"stops",
"execution",
"and",
"waits",
"for",
"the",
"user",
"to",
"press",
"any",
"key",
"to",
"continue",
".",
"This",
"is",
"similar",
"to",
"the",
"Windows",
"batch",
"pause",
"command",
".",
"If",
"the",
"program",
"is",
"not",
"ru... | python | train |
bitesofcode/projexui | projexui/widgets/xscintillaedit/xscintillaedit.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xscintillaedit/xscintillaedit.py#L311-L361 | def initOptions(self, options):
"""
Initializes the edit with the inputed options data set.
:param options | <XScintillaEditOptions>
"""
self.setAutoIndent( options.value('autoIndent'))
self.setIndentationsUseTabs( options.value('indentationsU... | [
"def",
"initOptions",
"(",
"self",
",",
"options",
")",
":",
"self",
".",
"setAutoIndent",
"(",
"options",
".",
"value",
"(",
"'autoIndent'",
")",
")",
"self",
".",
"setIndentationsUseTabs",
"(",
"options",
".",
"value",
"(",
"'indentationsUseTabs'",
")",
")... | Initializes the edit with the inputed options data set.
:param options | <XScintillaEditOptions> | [
"Initializes",
"the",
"edit",
"with",
"the",
"inputed",
"options",
"data",
"set",
".",
":",
"param",
"options",
"|",
"<XScintillaEditOptions",
">"
] | python | train |
vingd/encrypted-pickle-python | encryptedpickle/encryptedpickle.py | https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L362-L383 | def _decode(self, data, algorithm, key=None):
'''Decode data with specific algorithm'''
if algorithm['type'] == 'hmac':
verify_signature = data[-algorithm['hash_size']:]
data = data[:-algorithm['hash_size']]
signature = self._hmac_generate(data, algorithm, key)
... | [
"def",
"_decode",
"(",
"self",
",",
"data",
",",
"algorithm",
",",
"key",
"=",
"None",
")",
":",
"if",
"algorithm",
"[",
"'type'",
"]",
"==",
"'hmac'",
":",
"verify_signature",
"=",
"data",
"[",
"-",
"algorithm",
"[",
"'hash_size'",
"]",
":",
"]",
"d... | Decode data with specific algorithm | [
"Decode",
"data",
"with",
"specific",
"algorithm"
] | python | valid |
puiterwijk/flask-oidc | flask_oidc/__init__.py | https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L692-L744 | def _process_callback(self, statefield):
"""
Exchange the auth code for actual credentials,
then redirect to the originally requested page.
"""
# retrieve session and callback variables
try:
session_csrf_token = session.get('oidc_csrf_token')
stat... | [
"def",
"_process_callback",
"(",
"self",
",",
"statefield",
")",
":",
"# retrieve session and callback variables",
"try",
":",
"session_csrf_token",
"=",
"session",
".",
"get",
"(",
"'oidc_csrf_token'",
")",
"state",
"=",
"_json_loads",
"(",
"urlsafe_b64decode",
"(",
... | Exchange the auth code for actual credentials,
then redirect to the originally requested page. | [
"Exchange",
"the",
"auth",
"code",
"for",
"actual",
"credentials",
"then",
"redirect",
"to",
"the",
"originally",
"requested",
"page",
"."
] | python | train |
SheffieldML/GPy | GPy/kern/src/independent_outputs.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/kern/src/independent_outputs.py#L9-L35 | def index_to_slices(index):
"""
take a numpy array of integers (index) and return a nested list of slices such that the slices describe the start, stop points for each integer in the index.
e.g.
>>> index = np.asarray([0,0,0,1,1,1,2,2,2])
returns
>>> [[slice(0,3,None)],[slice(3,6,None)],[slice... | [
"def",
"index_to_slices",
"(",
"index",
")",
":",
"if",
"len",
"(",
"index",
")",
"==",
"0",
":",
"return",
"[",
"]",
"#contruct the return structure",
"ind",
"=",
"np",
".",
"asarray",
"(",
"index",
",",
"dtype",
"=",
"np",
".",
"int",
")",
"ret",
"... | take a numpy array of integers (index) and return a nested list of slices such that the slices describe the start, stop points for each integer in the index.
e.g.
>>> index = np.asarray([0,0,0,1,1,1,2,2,2])
returns
>>> [[slice(0,3,None)],[slice(3,6,None)],[slice(6,9,None)]]
or, a more complicated... | [
"take",
"a",
"numpy",
"array",
"of",
"integers",
"(",
"index",
")",
"and",
"return",
"a",
"nested",
"list",
"of",
"slices",
"such",
"that",
"the",
"slices",
"describe",
"the",
"start",
"stop",
"points",
"for",
"each",
"integer",
"in",
"the",
"index",
"."... | python | train |
gwpy/gwpy | gwpy/timeseries/core.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/timeseries/core.py#L382-L498 | def fetch_open_data(cls, ifo, start, end, sample_rate=4096,
tag=None, version=None,
format='hdf5', host=GWOSC_DEFAULT_HOST,
verbose=False, cache=None, **kwargs):
"""Fetch open-access data from the LIGO Open Science Center
Parameter... | [
"def",
"fetch_open_data",
"(",
"cls",
",",
"ifo",
",",
"start",
",",
"end",
",",
"sample_rate",
"=",
"4096",
",",
"tag",
"=",
"None",
",",
"version",
"=",
"None",
",",
"format",
"=",
"'hdf5'",
",",
"host",
"=",
"GWOSC_DEFAULT_HOST",
",",
"verbose",
"="... | Fetch open-access data from the LIGO Open Science Center
Parameters
----------
ifo : `str`
the two-character prefix of the IFO in which you are interested,
e.g. `'L1'`
start : `~gwpy.time.LIGOTimeGPS`, `float`, `str`, optional
GPS start time of requi... | [
"Fetch",
"open",
"-",
"access",
"data",
"from",
"the",
"LIGO",
"Open",
"Science",
"Center"
] | python | train |
singularityhub/singularity-cli | spython/main/parse/docker.py | https://github.com/singularityhub/singularity-cli/blob/cb36b4504812ca87e29c6a40b222a545d1865799/spython/main/parse/docker.py#L315-L325 | def _workdir(self, line):
'''A Docker WORKDIR command simply implies to cd to that location
Parameters
==========
line: the line from the recipe file to parse for WORKDIR
'''
workdir = self._setup('WORKDIR', line)
line = "cd %s" %(''.join(workdir))
... | [
"def",
"_workdir",
"(",
"self",
",",
"line",
")",
":",
"workdir",
"=",
"self",
".",
"_setup",
"(",
"'WORKDIR'",
",",
"line",
")",
"line",
"=",
"\"cd %s\"",
"%",
"(",
"''",
".",
"join",
"(",
"workdir",
")",
")",
"self",
".",
"install",
".",
"append"... | A Docker WORKDIR command simply implies to cd to that location
Parameters
==========
line: the line from the recipe file to parse for WORKDIR | [
"A",
"Docker",
"WORKDIR",
"command",
"simply",
"implies",
"to",
"cd",
"to",
"that",
"location"
] | python | train |
apache/incubator-mxnet | example/gluon/lipnet/utils/preprocess_data.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/preprocess_data.py#L118-L124 | def process_frames_mouth(self, frames):
"""
Preprocess from frames using mouth detector
"""
self.face = np.array(frames)
self.mouth = np.array(frames)
self.set_data(frames) | [
"def",
"process_frames_mouth",
"(",
"self",
",",
"frames",
")",
":",
"self",
".",
"face",
"=",
"np",
".",
"array",
"(",
"frames",
")",
"self",
".",
"mouth",
"=",
"np",
".",
"array",
"(",
"frames",
")",
"self",
".",
"set_data",
"(",
"frames",
")"
] | Preprocess from frames using mouth detector | [
"Preprocess",
"from",
"frames",
"using",
"mouth",
"detector"
] | python | train |
ssato/python-anyconfig | src/anyconfig/processors.py | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L321-L334 | def findall(self, obj, forced_type=None,
cls=anyconfig.models.processor.Processor):
"""
:param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param forced_type: Forced processor type to f... | [
"def",
"findall",
"(",
"self",
",",
"obj",
",",
"forced_type",
"=",
"None",
",",
"cls",
"=",
"anyconfig",
".",
"models",
".",
"processor",
".",
"Processor",
")",
":",
"return",
"[",
"p",
"(",
")",
"for",
"p",
"in",
"findall",
"(",
"obj",
",",
"self... | :param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param forced_type: Forced processor type to find
:param cls: A class object to compare with 'ptype'
:return: A list of instances of processor classe... | [
":",
"param",
"obj",
":",
"a",
"file",
"path",
"file",
"file",
"-",
"like",
"object",
"pathlib",
".",
"Path",
"object",
"or",
"an",
"anyconfig",
".",
"globals",
".",
"IOInfo",
"(",
"namedtuple",
")",
"object",
":",
"param",
"forced_type",
":",
"Forced",
... | python | train |
monarch-initiative/dipper | dipper/sources/UCSCBands.py | https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/UCSCBands.py#L208-L460 | def _get_chrbands(self, limit, taxon):
"""
:param limit:
:return:
"""
if limit is None:
limit = sys.maxsize # practical limit anyway
model = Model(self.graph)
line_counter = 0
myfile = '/'.join((self.rawdir, self.files[taxon]['file']))
... | [
"def",
"_get_chrbands",
"(",
"self",
",",
"limit",
",",
"taxon",
")",
":",
"if",
"limit",
"is",
"None",
":",
"limit",
"=",
"sys",
".",
"maxsize",
"# practical limit anyway",
"model",
"=",
"Model",
"(",
"self",
".",
"graph",
")",
"line_counter",
"=",
"0",... | :param limit:
:return: | [
":",
"param",
"limit",
":",
":",
"return",
":"
] | python | train |
openstax/cnx-archive | cnxarchive/views/xpath.py | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/xpath.py#L116-L120 | def xpath_page(request, uuid, version):
"""Given a page UUID (and optional version), returns a JSON object of
results, as in xpath_book()"""
xpath_string = request.params.get('q')
return execute_xpath(xpath_string, 'xpath-module', uuid, version) | [
"def",
"xpath_page",
"(",
"request",
",",
"uuid",
",",
"version",
")",
":",
"xpath_string",
"=",
"request",
".",
"params",
".",
"get",
"(",
"'q'",
")",
"return",
"execute_xpath",
"(",
"xpath_string",
",",
"'xpath-module'",
",",
"uuid",
",",
"version",
")"
... | Given a page UUID (and optional version), returns a JSON object of
results, as in xpath_book() | [
"Given",
"a",
"page",
"UUID",
"(",
"and",
"optional",
"version",
")",
"returns",
"a",
"JSON",
"object",
"of",
"results",
"as",
"in",
"xpath_book",
"()"
] | python | train |
eshandas/simple_django_logger | django_project/simple_django_logger/tasks/__init__.py | https://github.com/eshandas/simple_django_logger/blob/a6d15ca1c1ded414ed8fe5cc0c4ca0c20a846582/django_project/simple_django_logger/tasks/__init__.py#L27-L34 | def purge_old_event_logs(delete_before_days=7):
"""
Purges old event logs from the database table
"""
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = EventLog.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | [
"def",
"purge_old_event_logs",
"(",
"delete_before_days",
"=",
"7",
")",
":",
"delete_before_date",
"=",
"timezone",
".",
"now",
"(",
")",
"-",
"timedelta",
"(",
"days",
"=",
"delete_before_days",
")",
"logs_deleted",
"=",
"EventLog",
".",
"objects",
".",
"fil... | Purges old event logs from the database table | [
"Purges",
"old",
"event",
"logs",
"from",
"the",
"database",
"table"
] | python | train |
brandon-rhodes/python-jplephem | jplephem/spk.py | https://github.com/brandon-rhodes/python-jplephem/blob/48c99ce40c627e24c95479d8845e312ea168f567/jplephem/spk.py#L46-L53 | def close(self):
"""Close this SPK file."""
self.daf.file.close()
for segment in self.segments:
if hasattr(segment, '_data'):
del segment._data
self.daf._array = None
self.daf._map = None | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"daf",
".",
"file",
".",
"close",
"(",
")",
"for",
"segment",
"in",
"self",
".",
"segments",
":",
"if",
"hasattr",
"(",
"segment",
",",
"'_data'",
")",
":",
"del",
"segment",
".",
"_data",
"self",... | Close this SPK file. | [
"Close",
"this",
"SPK",
"file",
"."
] | python | test |
theolind/pymysensors | mysensors/gateway_serial.py | https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/gateway_serial.py#L79-L96 | def _connect(self):
"""Connect to the serial port."""
try:
while True:
_LOGGER.info('Trying to connect to %s', self.port)
try:
yield from serial_asyncio.create_serial_connection(
self.loop, lambda: self.protocol, sel... | [
"def",
"_connect",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"_LOGGER",
".",
"info",
"(",
"'Trying to connect to %s'",
",",
"self",
".",
"port",
")",
"try",
":",
"yield",
"from",
"serial_asyncio",
".",
"create_serial_connection",
"(",
"self",
... | Connect to the serial port. | [
"Connect",
"to",
"the",
"serial",
"port",
"."
] | python | train |
inspirehep/harvesting-kit | harvestingkit/aps_package.py | https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/aps_package.py#L143-L211 | def _add_references(self, rec):
""" Adds the reference to the record """
for ref in self.document.getElementsByTagName('ref'):
for ref_type, doi, authors, collaboration, journal, volume, page, year,\
label, arxiv, publisher, institution, unstructured_text,\
... | [
"def",
"_add_references",
"(",
"self",
",",
"rec",
")",
":",
"for",
"ref",
"in",
"self",
".",
"document",
".",
"getElementsByTagName",
"(",
"'ref'",
")",
":",
"for",
"ref_type",
",",
"doi",
",",
"authors",
",",
"collaboration",
",",
"journal",
",",
"volu... | Adds the reference to the record | [
"Adds",
"the",
"reference",
"to",
"the",
"record"
] | python | valid |
pdkit/pdkit | pdkit/utils.py | https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/utils.py#L514-L544 | def crossings_nonzero_pos2neg(data):
"""
Find `indices of zero crossings from positive to negative values <http://stackoverflow.com/questions/3843017/efficiently-detect-sign-changes-in-python>`_.
:param data: numpy array of floats
:type data: numpy array of floats
:return crossings:... | [
"def",
"crossings_nonzero_pos2neg",
"(",
"data",
")",
":",
"import",
"numpy",
"as",
"np",
"if",
"isinstance",
"(",
"data",
",",
"np",
".",
"ndarray",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"data",
"=",
"np",
".",
... | Find `indices of zero crossings from positive to negative values <http://stackoverflow.com/questions/3843017/efficiently-detect-sign-changes-in-python>`_.
:param data: numpy array of floats
:type data: numpy array of floats
:return crossings: crossing indices to data
:rtype crossings: n... | [
"Find",
"indices",
"of",
"zero",
"crossings",
"from",
"positive",
"to",
"negative",
"values",
"<http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"3843017",
"/",
"efficiently",
"-",
"detect",
"-",
"sign",
"-",
"changes",
"-",
"in",
"-",... | python | train |
google/importlab | importlab/output.py | https://github.com/google/importlab/blob/92090a0b4421137d1369c2ed952eda6bb4c7a155/importlab/output.py#L20-L33 | def format_file_node(import_graph, node, indent):
"""Prettyprint nodes based on their provenance."""
f = import_graph.provenance[node]
if isinstance(f, resolve.Direct):
out = '+ ' + f.short_path
elif isinstance(f, resolve.Local):
out = ' ' + f.short_path
elif isinstance(f, resolve.S... | [
"def",
"format_file_node",
"(",
"import_graph",
",",
"node",
",",
"indent",
")",
":",
"f",
"=",
"import_graph",
".",
"provenance",
"[",
"node",
"]",
"if",
"isinstance",
"(",
"f",
",",
"resolve",
".",
"Direct",
")",
":",
"out",
"=",
"'+ '",
"+",
"f",
... | Prettyprint nodes based on their provenance. | [
"Prettyprint",
"nodes",
"based",
"on",
"their",
"provenance",
"."
] | python | train |
markomanninen/abnum | abnum/search.py | https://github.com/markomanninen/abnum/blob/9bfc8f06f34d9a51aab038638f87e2bb5f9f4c99/abnum/search.py#L5-L22 | def find_cumulative_indices(list_of_numbers, search_sum):
"""
find_cumulative_indices([70, 58, 81, 909, 70, 215, 70, 1022, 580, 930, 898], 285) ->
[[4, 5],[5, 6]]
"""
u = 0
y = 0
result = []
for idx, val in enumerate(list_of_numbers):
y += list_of_numbers[idx]
while y >=... | [
"def",
"find_cumulative_indices",
"(",
"list_of_numbers",
",",
"search_sum",
")",
":",
"u",
"=",
"0",
"y",
"=",
"0",
"result",
"=",
"[",
"]",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"list_of_numbers",
")",
":",
"y",
"+=",
"list_of_numbers",
"["... | find_cumulative_indices([70, 58, 81, 909, 70, 215, 70, 1022, 580, 930, 898], 285) ->
[[4, 5],[5, 6]] | [
"find_cumulative_indices",
"(",
"[",
"70",
"58",
"81",
"909",
"70",
"215",
"70",
"1022",
"580",
"930",
"898",
"]",
"285",
")",
"-",
">",
"[[",
"4",
"5",
"]",
"[",
"5",
"6",
"]]"
] | python | train |
cuihantao/andes | andes/models/line.py | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L131-L152 | def build_y(self):
"""Build transmission line admittance matrix into self.Y"""
if not self.n:
return
self.y1 = mul(self.u, self.g1 + self.b1 * 1j)
self.y2 = mul(self.u, self.g2 + self.b2 * 1j)
self.y12 = div(self.u, self.r + self.x * 1j)
self.m = polar(self.ta... | [
"def",
"build_y",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"n",
":",
"return",
"self",
".",
"y1",
"=",
"mul",
"(",
"self",
".",
"u",
",",
"self",
".",
"g1",
"+",
"self",
".",
"b1",
"*",
"1j",
")",
"self",
".",
"y2",
"=",
"mul",
"(",... | Build transmission line admittance matrix into self.Y | [
"Build",
"transmission",
"line",
"admittance",
"matrix",
"into",
"self",
".",
"Y"
] | python | train |
Nixiware/viper | nx/viper/application.py | https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L62-L98 | def _getInterfaces(self):
"""
Load application communication interfaces.
:return: <dict>
"""
interfaces = {}
interfacesPath = os.path.join("application", "interface")
interfaceList = os.listdir(interfacesPath)
for file in interfaceList:
inte... | [
"def",
"_getInterfaces",
"(",
"self",
")",
":",
"interfaces",
"=",
"{",
"}",
"interfacesPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"application\"",
",",
"\"interface\"",
")",
"interfaceList",
"=",
"os",
".",
"listdir",
"(",
"interfacesPath",
")",
"... | Load application communication interfaces.
:return: <dict> | [
"Load",
"application",
"communication",
"interfaces",
"."
] | python | train |
enkore/i3pystatus | i3pystatus/sabnzbd.py | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/sabnzbd.py#L52-L91 | def run(self):
"""Connect to SABnzbd and get the data."""
try:
answer = urlopen(self.url + "&mode=queue").read().decode()
except (HTTPError, URLError) as error:
self.output = {
"full_text": str(error.reason),
"color": "#FF0000"
... | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"answer",
"=",
"urlopen",
"(",
"self",
".",
"url",
"+",
"\"&mode=queue\"",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
")",
"except",
"(",
"HTTPError",
",",
"URLError",
")",
"as",
"error",
":",
... | Connect to SABnzbd and get the data. | [
"Connect",
"to",
"SABnzbd",
"and",
"get",
"the",
"data",
"."
] | python | train |
ask/carrot | carrot/messaging.py | https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/messaging.py#L821-L823 | def send(self, message_data, delivery_mode=None):
"""See :meth:`Publisher.send`"""
self.publisher.send(message_data, delivery_mode=delivery_mode) | [
"def",
"send",
"(",
"self",
",",
"message_data",
",",
"delivery_mode",
"=",
"None",
")",
":",
"self",
".",
"publisher",
".",
"send",
"(",
"message_data",
",",
"delivery_mode",
"=",
"delivery_mode",
")"
] | See :meth:`Publisher.send` | [
"See",
":",
"meth",
":",
"Publisher",
".",
"send"
] | python | train |
dj-stripe/dj-stripe | djstripe/models/base.py | https://github.com/dj-stripe/dj-stripe/blob/a5308a3808cd6e2baba49482f7a699f3a8992518/djstripe/models/base.py#L539-L560 | def _stripe_object_to_refunds(cls, target_cls, data, charge):
"""
Retrieves Refunds for a charge
:param target_cls: The target class to instantiate per invoice item.
:type target_cls: ``Refund``
:param data: The data dictionary received from the Stripe API.
:type data: dict
:param charge: The charge objec... | [
"def",
"_stripe_object_to_refunds",
"(",
"cls",
",",
"target_cls",
",",
"data",
",",
"charge",
")",
":",
"refunds",
"=",
"data",
".",
"get",
"(",
"\"refunds\"",
")",
"if",
"not",
"refunds",
":",
"return",
"[",
"]",
"refund_objs",
"=",
"[",
"]",
"for",
... | Retrieves Refunds for a charge
:param target_cls: The target class to instantiate per invoice item.
:type target_cls: ``Refund``
:param data: The data dictionary received from the Stripe API.
:type data: dict
:param charge: The charge object that refunds are for.
:type invoice: ``djstripe.models.Refund``
... | [
"Retrieves",
"Refunds",
"for",
"a",
"charge",
":",
"param",
"target_cls",
":",
"The",
"target",
"class",
"to",
"instantiate",
"per",
"invoice",
"item",
".",
":",
"type",
"target_cls",
":",
"Refund",
":",
"param",
"data",
":",
"The",
"data",
"dictionary",
"... | python | train |
rockyzhengwu/FoolNLTK | train/data_utils.py | https://github.com/rockyzhengwu/FoolNLTK/blob/f9929edc7b2f1b154b5f9bbd2c0c95203a5bddb3/train/data_utils.py#L80-L94 | def get_char_type(ch):
"""
0, 汉字
1, 英文字母
2. 数字
3. 其他
"""
if re.match(en_p, ch):
return 1
elif re.match("\d+", ch):
return 2
elif re.match(re_han, ch):
return 3
else:
return 4 | [
"def",
"get_char_type",
"(",
"ch",
")",
":",
"if",
"re",
".",
"match",
"(",
"en_p",
",",
"ch",
")",
":",
"return",
"1",
"elif",
"re",
".",
"match",
"(",
"\"\\d+\"",
",",
"ch",
")",
":",
"return",
"2",
"elif",
"re",
".",
"match",
"(",
"re_han",
... | 0, 汉字
1, 英文字母
2. 数字
3. 其他 | [
"0",
"汉字",
"1",
"英文字母",
"2",
".",
"数字",
"3",
".",
"其他"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.