repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
boundlessgeo/lib-qgis-commons | qgiscommons2/settings.py | https://github.com/boundlessgeo/lib-qgis-commons/blob/d25d13803db08c18632b55d12036e332f006d9ac/qgiscommons2/settings.py#L35-L47 | def setPluginSetting(name, value, namespace = None):
'''
Sets the value of a plugin setting.
:param name: the name of the setting. It is not the full path, but just the last name of it
:param value: the value to set for the plugin setting
:param namespace: The namespace. If not passed or None, the ... | [
"def",
"setPluginSetting",
"(",
"name",
",",
"value",
",",
"namespace",
"=",
"None",
")",
":",
"namespace",
"=",
"namespace",
"or",
"_callerName",
"(",
")",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"settings",
".",
"setValue",
"(",
"namespace",
... | Sets the value of a plugin setting.
:param name: the name of the setting. It is not the full path, but just the last name of it
:param value: the value to set for the plugin setting
:param namespace: The namespace. If not passed or None, the namespace will be inferred from
the caller method. Normally, ... | [
"Sets",
"the",
"value",
"of",
"a",
"plugin",
"setting",
"."
] | python | train | 52.307692 |
Qiskit/qiskit-terra | qiskit/extensions/standard/ubase.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/ubase.py#L50-L52 | def u_base(self, theta, phi, lam, q):
"""Apply U to q."""
return self.append(UBase(theta, phi, lam), [q], []) | [
"def",
"u_base",
"(",
"self",
",",
"theta",
",",
"phi",
",",
"lam",
",",
"q",
")",
":",
"return",
"self",
".",
"append",
"(",
"UBase",
"(",
"theta",
",",
"phi",
",",
"lam",
")",
",",
"[",
"q",
"]",
",",
"[",
"]",
")"
] | Apply U to q. | [
"Apply",
"U",
"to",
"q",
"."
] | python | test | 38.333333 |
chrislit/abydos | abydos/stemmer/_porter.py | https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_porter.py#L76-L94 | def _has_vowel(self, term):
"""Return Porter helper function _has_vowel value.
Parameters
----------
term : str
The word to scan for vowels
Returns
-------
bool
True iff a vowel exists in the term (as defined in the Porter
ste... | [
"def",
"_has_vowel",
"(",
"self",
",",
"term",
")",
":",
"for",
"letter",
"in",
"term",
":",
"if",
"letter",
"in",
"self",
".",
"_vowels",
":",
"return",
"True",
"return",
"False"
] | Return Porter helper function _has_vowel value.
Parameters
----------
term : str
The word to scan for vowels
Returns
-------
bool
True iff a vowel exists in the term (as defined in the Porter
stemmer definition) | [
"Return",
"Porter",
"helper",
"function",
"_has_vowel",
"value",
"."
] | python | valid | 23.526316 |
rhgrant10/Groupy | groupy/api/messages.py | https://github.com/rhgrant10/Groupy/blob/ffd8cac57586fa1c218e3b4bfaa531142c3be766/groupy/api/messages.py#L157-L169 | def list(self, before_id=None, since_id=None, **kwargs):
"""Return a page of direct messages.
The messages come in reversed order (newest first). Note you can only
provide _one_ of ``before_id``, ``since_id``.
:param str before_id: message ID for paging backwards
:param str sin... | [
"def",
"list",
"(",
"self",
",",
"before_id",
"=",
"None",
",",
"since_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"pagers",
".",
"MessageList",
"(",
"self",
",",
"self",
".",
"_raw_list",
",",
"before_id",
"=",
"before_id",
",",
"... | Return a page of direct messages.
The messages come in reversed order (newest first). Note you can only
provide _one_ of ``before_id``, ``since_id``.
:param str before_id: message ID for paging backwards
:param str since_id: message ID for most recent messages since
:return: di... | [
"Return",
"a",
"page",
"of",
"direct",
"messages",
"."
] | python | train | 45.615385 |
MeirKriheli/python-bidi | bidi/algorithm.py | https://github.com/MeirKriheli/python-bidi/blob/a0e265bb465c1b7ad628487991e33b5ebe364641/bidi/algorithm.py#L62-L104 | def debug_storage(storage, base_info=False, chars=True, runs=False):
"Display debug information for the storage"
import codecs
import locale
import sys
if six.PY2:
stderr = codecs.getwriter(locale.getpreferredencoding())(sys.stderr)
else:
stderr = sys.stderr
caller = inspe... | [
"def",
"debug_storage",
"(",
"storage",
",",
"base_info",
"=",
"False",
",",
"chars",
"=",
"True",
",",
"runs",
"=",
"False",
")",
":",
"import",
"codecs",
"import",
"locale",
"import",
"sys",
"if",
"six",
".",
"PY2",
":",
"stderr",
"=",
"codecs",
".",... | Display debug information for the storage | [
"Display",
"debug",
"information",
"for",
"the",
"storage"
] | python | test | 29.418605 |
iotile/coretools | iotilecore/iotile/core/utilities/schema_verify/bytes_verify.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/schema_verify/bytes_verify.py#L58-L66 | def format(self, indent_level, indent_size=4):
"""Format this verifier
Returns:
string: A formatted string
"""
name = self.format_name('Bytes', indent_size)
return self.wrap_lines(name, indent_level, indent_size) | [
"def",
"format",
"(",
"self",
",",
"indent_level",
",",
"indent_size",
"=",
"4",
")",
":",
"name",
"=",
"self",
".",
"format_name",
"(",
"'Bytes'",
",",
"indent_size",
")",
"return",
"self",
".",
"wrap_lines",
"(",
"name",
",",
"indent_level",
",",
"inde... | Format this verifier
Returns:
string: A formatted string | [
"Format",
"this",
"verifier"
] | python | train | 28.666667 |
juju/python-libjuju | juju/client/_client5.py | https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/_client5.py#L5003-L5016 | async def StorageAttachmentLife(self, ids):
'''
ids : typing.Sequence[~StorageAttachmentId]
Returns -> typing.Sequence[~LifeResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Uniter',
request='StorageAttachmentLife',
... | [
"async",
"def",
"StorageAttachmentLife",
"(",
"self",
",",
"ids",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'Uniter'",
",",
"request",
"=",
"'StorageAttachmentLife'",
",",
"version",
"=",... | ids : typing.Sequence[~StorageAttachmentId]
Returns -> typing.Sequence[~LifeResult] | [
"ids",
":",
"typing",
".",
"Sequence",
"[",
"~StorageAttachmentId",
"]",
"Returns",
"-",
">",
"typing",
".",
"Sequence",
"[",
"~LifeResult",
"]"
] | python | train | 32.357143 |
iotile/coretools | iotilecore/iotile/core/hw/transport/virtualadapter.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/virtualadapter.py#L369-L380 | async def _send_scan_event(self, device):
"""Send a scan event from a device."""
conn_string = str(device.iotile_id)
info = {
'connection_string': conn_string,
'uuid': device.iotile_id,
'signal_strength': 100,
'validity_period': self.ExpirationTim... | [
"async",
"def",
"_send_scan_event",
"(",
"self",
",",
"device",
")",
":",
"conn_string",
"=",
"str",
"(",
"device",
".",
"iotile_id",
")",
"info",
"=",
"{",
"'connection_string'",
":",
"conn_string",
",",
"'uuid'",
":",
"device",
".",
"iotile_id",
",",
"'s... | Send a scan event from a device. | [
"Send",
"a",
"scan",
"event",
"from",
"a",
"device",
"."
] | python | train | 32.25 |
SmokinCaterpillar/pypet | pypet/utils/mpwrappers.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/mpwrappers.py#L678-L685 | def _put_on_queue(self, to_put):
"""Puts data on queue"""
old = self.pickle_queue
self.pickle_queue = False
try:
self.queue.put(to_put, block=True)
finally:
self.pickle_queue = old | [
"def",
"_put_on_queue",
"(",
"self",
",",
"to_put",
")",
":",
"old",
"=",
"self",
".",
"pickle_queue",
"self",
".",
"pickle_queue",
"=",
"False",
"try",
":",
"self",
".",
"queue",
".",
"put",
"(",
"to_put",
",",
"block",
"=",
"True",
")",
"finally",
... | Puts data on queue | [
"Puts",
"data",
"on",
"queue"
] | python | test | 29.625 |
projectshift/shift-schema | shiftschema/result.py | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/result.py#L352-L359 | def format_error(self, error, args=None):
""" Format error with positional or named arguments (if any) """
if type(args) is dict:
return error.format(**args)
if type(args) is list or type(args) is tuple:
return error.format(*args)
return error | [
"def",
"format_error",
"(",
"self",
",",
"error",
",",
"args",
"=",
"None",
")",
":",
"if",
"type",
"(",
"args",
")",
"is",
"dict",
":",
"return",
"error",
".",
"format",
"(",
"*",
"*",
"args",
")",
"if",
"type",
"(",
"args",
")",
"is",
"list",
... | Format error with positional or named arguments (if any) | [
"Format",
"error",
"with",
"positional",
"or",
"named",
"arguments",
"(",
"if",
"any",
")"
] | python | train | 36.625 |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L24556-L24607 | def put_mouse_event(self, dx, dy, dz, dw, button_state):
"""Initiates a mouse event using relative pointer movements
along x and y axis.
in dx of type int
Amount of pixels the mouse should move to the right.
Negative values move the mouse to the left.
in dy of t... | [
"def",
"put_mouse_event",
"(",
"self",
",",
"dx",
",",
"dy",
",",
"dz",
",",
"dw",
",",
"button_state",
")",
":",
"if",
"not",
"isinstance",
"(",
"dx",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"dx can only be an instance of type baseinteger\"... | Initiates a mouse event using relative pointer movements
along x and y axis.
in dx of type int
Amount of pixels the mouse should move to the right.
Negative values move the mouse to the left.
in dy of type int
Amount of pixels the mouse should move downwards... | [
"Initiates",
"a",
"mouse",
"event",
"using",
"relative",
"pointer",
"movements",
"along",
"x",
"and",
"y",
"axis",
"."
] | python | train | 40.980769 |
cmbruns/pyopenvr | src/openvr/__init__.py | https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L5360-L5365 | def loadIntoTextureD3D11_Async(self, textureId, pDstTexture):
"""Helper function to copy the bits into an existing texture."""
fn = self.function_table.loadIntoTextureD3D11_Async
result = fn(textureId, pDstTexture)
return result | [
"def",
"loadIntoTextureD3D11_Async",
"(",
"self",
",",
"textureId",
",",
"pDstTexture",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"loadIntoTextureD3D11_Async",
"result",
"=",
"fn",
"(",
"textureId",
",",
"pDstTexture",
")",
"return",
"result"
] | Helper function to copy the bits into an existing texture. | [
"Helper",
"function",
"to",
"copy",
"the",
"bits",
"into",
"an",
"existing",
"texture",
"."
] | python | train | 42.666667 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_qos.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_qos.py#L299-L312 | def qos_map_cos_traffic_class_cos0(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
map = ET.SubElement(qos, "map")
cos_traffic_class = ET.SubElement(map, "cos-traffic-cl... | [
"def",
"qos_map_cos_traffic_class_cos0",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"qos",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"qos\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 42.928571 |
gmr/infoblox | infoblox/cli.py | https://github.com/gmr/infoblox/blob/163dd9cff5f77c08751936c56aa8428acfd2d208/infoblox/cli.py#L41-L49 | def delete_old_host(self, hostname):
"""Remove all records for the host.
:param str hostname: Hostname to remove
:rtype: bool
"""
host = Host(self.session, name=hostname)
return host.delete() | [
"def",
"delete_old_host",
"(",
"self",
",",
"hostname",
")",
":",
"host",
"=",
"Host",
"(",
"self",
".",
"session",
",",
"name",
"=",
"hostname",
")",
"return",
"host",
".",
"delete",
"(",
")"
] | Remove all records for the host.
:param str hostname: Hostname to remove
:rtype: bool | [
"Remove",
"all",
"records",
"for",
"the",
"host",
"."
] | python | train | 25.888889 |
cthorey/pdsimage | pdsimage/PDS_Extractor.py | https://github.com/cthorey/pdsimage/blob/f71de6dfddd3d538d76da229b4b9605c40f3fbac/pdsimage/PDS_Extractor.py#L314-L321 | def _control_sample(self, sample):
''' Control the asked sample is ok '''
if sample > float(self.SAMPLE_LAST_PIXEL):
return int(self.SAMPLE_LAST_PIXEL)
elif sample < float(self.SAMPLE_FIRST_PIXEL):
return int(self.SAMPLE_FIRST_PIXEL)
else:
return sampl... | [
"def",
"_control_sample",
"(",
"self",
",",
"sample",
")",
":",
"if",
"sample",
">",
"float",
"(",
"self",
".",
"SAMPLE_LAST_PIXEL",
")",
":",
"return",
"int",
"(",
"self",
".",
"SAMPLE_LAST_PIXEL",
")",
"elif",
"sample",
"<",
"float",
"(",
"self",
".",
... | Control the asked sample is ok | [
"Control",
"the",
"asked",
"sample",
"is",
"ok"
] | python | train | 39.25 |
Erotemic/utool | utool/util_hash.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_hash.py#L1028-L1087 | def combine_uuids(uuids, ordered=True, salt=''):
"""
Creates a uuid that specifies a group of UUIDS
Args:
uuids (list): list of uuid objects
ordered (bool): if False uuid order changes the resulting combined uuid
otherwise the uuids are considered an orderless set
salt (... | [
"def",
"combine_uuids",
"(",
"uuids",
",",
"ordered",
"=",
"True",
",",
"salt",
"=",
"''",
")",
":",
"if",
"len",
"(",
"uuids",
")",
"==",
"0",
":",
"return",
"get_zero_uuid",
"(",
")",
"elif",
"len",
"(",
"uuids",
")",
"==",
"1",
":",
"return",
... | Creates a uuid that specifies a group of UUIDS
Args:
uuids (list): list of uuid objects
ordered (bool): if False uuid order changes the resulting combined uuid
otherwise the uuids are considered an orderless set
salt (str): salts the resulting hash
Returns:
uuid.UUI... | [
"Creates",
"a",
"uuid",
"that",
"specifies",
"a",
"group",
"of",
"UUIDS"
] | python | train | 38.216667 |
pycontribs/pyrax | pyrax/clouddatabases.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/clouddatabases.py#L301-L313 | def revoke_user_access(self, user, db_names, strict=True):
"""
Revokes access to the databases listed in `db_names` for the user.
If any of the databases do not exist, a NoSuchDatabase exception will
be raised, unless you specify `strict=False` in the call.
"""
user = ut... | [
"def",
"revoke_user_access",
"(",
"self",
",",
"user",
",",
"db_names",
",",
"strict",
"=",
"True",
")",
":",
"user",
"=",
"utils",
".",
"get_name",
"(",
"user",
")",
"db_names",
"=",
"self",
".",
"_get_db_names",
"(",
"db_names",
",",
"strict",
"=",
"... | Revokes access to the databases listed in `db_names` for the user.
If any of the databases do not exist, a NoSuchDatabase exception will
be raised, unless you specify `strict=False` in the call. | [
"Revokes",
"access",
"to",
"the",
"databases",
"listed",
"in",
"db_names",
"for",
"the",
"user",
"."
] | python | train | 44.307692 |
hydpy-dev/hydpy | hydpy/models/arma/arma_control.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/arma/arma_control.py#L308-L311 | def thresholds(self):
"""Threshold values of the response functions."""
return numpy.array(
sorted(self._key2float(key) for key in self._coefs), dtype=float) | [
"def",
"thresholds",
"(",
"self",
")",
":",
"return",
"numpy",
".",
"array",
"(",
"sorted",
"(",
"self",
".",
"_key2float",
"(",
"key",
")",
"for",
"key",
"in",
"self",
".",
"_coefs",
")",
",",
"dtype",
"=",
"float",
")"
] | Threshold values of the response functions. | [
"Threshold",
"values",
"of",
"the",
"response",
"functions",
"."
] | python | train | 45.5 |
Microsoft/vsts-cd-manager | continuous_delivery/continuous_delivery.py | https://github.com/Microsoft/vsts-cd-manager/blob/2649d236be94d119b13e0ac607964c94a9e51fde/continuous_delivery/continuous_delivery.py#L128-L180 | def get_provisioning_configuration(
self, provisioning_configuration_id, custom_headers=None, raw=False, **operation_config):
"""GetContinuousDeploymentOperation.
:param provisioning_configuration_id:
:type provisioning_configuration_id: str
:param dict custom_headers: heade... | [
"def",
"get_provisioning_configuration",
"(",
"self",
",",
"provisioning_configuration_id",
",",
"custom_headers",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"*",
"*",
"operation_config",
")",
":",
"# Construct URL",
"url",
"=",
"'/_apis/continuousdelivery/provisioning... | GetContinuousDeploymentOperation.
:param provisioning_configuration_id:
:type provisioning_configuration_id: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param... | [
"GetContinuousDeploymentOperation",
"."
] | python | train | 42.641509 |
scanny/python-pptx | pptx/shapes/shapetree.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/shapes/shapetree.py#L736-L755 | def BaseShapeFactory(shape_elm, parent):
"""
Return an instance of the appropriate shape proxy class for *shape_elm*.
"""
tag = shape_elm.tag
if tag == qn('p:pic'):
videoFiles = shape_elm.xpath('./p:nvPicPr/p:nvPr/a:videoFile')
if videoFiles:
return Movie(shape_elm, pare... | [
"def",
"BaseShapeFactory",
"(",
"shape_elm",
",",
"parent",
")",
":",
"tag",
"=",
"shape_elm",
".",
"tag",
"if",
"tag",
"==",
"qn",
"(",
"'p:pic'",
")",
":",
"videoFiles",
"=",
"shape_elm",
".",
"xpath",
"(",
"'./p:nvPicPr/p:nvPr/a:videoFile'",
")",
"if",
... | Return an instance of the appropriate shape proxy class for *shape_elm*. | [
"Return",
"an",
"instance",
"of",
"the",
"appropriate",
"shape",
"proxy",
"class",
"for",
"*",
"shape_elm",
"*",
"."
] | python | train | 29.8 |
sludgedesk/metoffer | metoffer.py | https://github.com/sludgedesk/metoffer/blob/449748d31f913d961d6f0406542bb784e931a95b/metoffer.py#L276-L286 | def text_uk_extremes(self, request):
"""
Return textual data of UK extremes.
request:
metoffer.CAPABILITIES Returns available extreme date
and issue time
metoffer.LATEST Returns data of late... | [
"def",
"text_uk_extremes",
"(",
"self",
",",
"request",
")",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"_query",
"(",
"TEXT",
",",
"OBSERVATIONS",
",",
"UK_EXTREMES",
",",
"request",
",",
"\"\"",
")",
".",
"decode",
"(",
"errors",
"=",
"\"... | Return textual data of UK extremes.
request:
metoffer.CAPABILITIES Returns available extreme date
and issue time
metoffer.LATEST Returns data of latest extremes
... | [
"Return",
"textual",
"data",
"of",
"UK",
"extremes",
".",
"request",
":",
"metoffer",
".",
"CAPABILITIES",
"Returns",
"available",
"extreme",
"date",
"and",
"issue",
"time",
"metoffer",
".",
"LATEST",
"Returns",
"data",
"of",
"latest",
"extremes",
"for",
"all"... | python | train | 45.818182 |
annoviko/pyclustering | pyclustering/nnet/syncpr.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/nnet/syncpr.py#L452-L469 | def memory_order(self, pattern):
"""!
@brief Calculates function of the memorized pattern.
@details Throws exception if length of pattern is not equal to size of the network or if it consists feature with value that are not equal to [-1; 1].
@param[in] pattern (list): Pattern fo... | [
"def",
"memory_order",
"(",
"self",
",",
"pattern",
")",
":",
"self",
".",
"__validate_pattern",
"(",
"pattern",
")",
"if",
"(",
"self",
".",
"_ccore_network_pointer",
"is",
"not",
"None",
")",
":",
"return",
"wrapper",
".",
"syncpr_memory_order",
"(",
"self... | !
@brief Calculates function of the memorized pattern.
@details Throws exception if length of pattern is not equal to size of the network or if it consists feature with value that are not equal to [-1; 1].
@param[in] pattern (list): Pattern for recognition represented by list of feature... | [
"!"
] | python | valid | 41.944444 |
tensorflow/probability | tensorflow_probability/python/bijectors/masked_autoregressive.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/masked_autoregressive.py#L337-L407 | def masked_dense(inputs,
units,
num_blocks=None,
exclusive=False,
kernel_initializer=None,
reuse=None,
name=None,
*args, # pylint: disable=keyword-arg-before-vararg
**kwargs):
"""A ... | [
"def",
"masked_dense",
"(",
"inputs",
",",
"units",
",",
"num_blocks",
"=",
"None",
",",
"exclusive",
"=",
"False",
",",
"kernel_initializer",
"=",
"None",
",",
"reuse",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"args",
",",
"# pylint: disable=keywo... | A autoregressively masked dense layer. Analogous to `tf.layers.dense`.
See [Germain et al. (2015)][1] for detailed explanation.
Arguments:
inputs: Tensor input.
units: Python `int` scalar representing the dimensionality of the output
space.
num_blocks: Python `int` scalar representing the number... | [
"A",
"autoregressively",
"masked",
"dense",
"layer",
".",
"Analogous",
"to",
"tf",
".",
"layers",
".",
"dense",
"."
] | python | test | 37.408451 |
Esri/ArcREST | src/arcrest/ags/_imageservice.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/_imageservice.py#L604-L684 | def query(self,
where="1=1",
out_fields="*",
timeFilter=None,
geometryFilter=None,
returnGeometry=True,
returnIDsOnly=False,
returnCountOnly=False,
pixelSize=None,
orderByFields=None,
... | [
"def",
"query",
"(",
"self",
",",
"where",
"=",
"\"1=1\"",
",",
"out_fields",
"=",
"\"*\"",
",",
"timeFilter",
"=",
"None",
",",
"geometryFilter",
"=",
"None",
",",
"returnGeometry",
"=",
"True",
",",
"returnIDsOnly",
"=",
"False",
",",
"returnCountOnly",
... | queries a feature service based on a sql statement
Inputs:
where - the selection sql statement
out_fields - the attribute fields to return
timeFilter - a TimeFilter object where either the start time
or start and end time are defined t... | [
"queries",
"a",
"feature",
"service",
"based",
"on",
"a",
"sql",
"statement",
"Inputs",
":",
"where",
"-",
"the",
"selection",
"sql",
"statement",
"out_fields",
"-",
"the",
"attribute",
"fields",
"to",
"return",
"timeFilter",
"-",
"a",
"TimeFilter",
"object",
... | python | train | 50.888889 |
adafruit/Adafruit_Python_BluefruitLE | Adafruit_BluefruitLE/bluez_dbus/provider.py | https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/bluez_dbus/provider.py#L109-L130 | def _user_thread_main(self, target):
"""Main entry point for the thread that will run user's code."""
try:
# Wait for GLib main loop to start running before starting user code.
while True:
if self._gobject_mainloop is not None and self._gobject_mainloop.is_running... | [
"def",
"_user_thread_main",
"(",
"self",
",",
"target",
")",
":",
"try",
":",
"# Wait for GLib main loop to start running before starting user code.",
"while",
"True",
":",
"if",
"self",
".",
"_gobject_mainloop",
"is",
"not",
"None",
"and",
"self",
".",
"_gobject_main... | Main entry point for the thread that will run user's code. | [
"Main",
"entry",
"point",
"for",
"the",
"thread",
"that",
"will",
"run",
"user",
"s",
"code",
"."
] | python | valid | 47.863636 |
linode/linode_api4-python | linode_api4/objects/linode.py | https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L275-L308 | def available_backups(self):
"""
The backups response contains what backups are available to be restored.
"""
if not hasattr(self, '_avail_backups'):
result = self._client.get("{}/backups".format(Instance.api_endpoint), model=self)
if not 'automatic' in result:
... | [
"def",
"available_backups",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_avail_backups'",
")",
":",
"result",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"{}/backups\"",
".",
"format",
"(",
"Instance",
".",
"api_endpoint",
")",
... | The backups response contains what backups are available to be restored. | [
"The",
"backups",
"response",
"contains",
"what",
"backups",
"are",
"available",
"to",
"be",
"restored",
"."
] | python | train | 37.911765 |
secdev/scapy | scapy/arch/windows/__init__.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/arch/windows/__init__.py#L391-L399 | def _npcap_set(self, key, val):
"""Internal function. Set a [key] parameter to [value]"""
res, code = _exec_cmd(_encapsulate_admin(
" ".join([_WlanHelper, self.guid[1:-1], key, val])
))
_windows_title() # Reset title of the window
if code != 0:
raise OSEr... | [
"def",
"_npcap_set",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"res",
",",
"code",
"=",
"_exec_cmd",
"(",
"_encapsulate_admin",
"(",
"\" \"",
".",
"join",
"(",
"[",
"_WlanHelper",
",",
"self",
".",
"guid",
"[",
"1",
":",
"-",
"1",
"]",
",",
... | Internal function. Set a [key] parameter to [value] | [
"Internal",
"function",
".",
"Set",
"a",
"[",
"key",
"]",
"parameter",
"to",
"[",
"value",
"]"
] | python | train | 42.111111 |
Yelp/kafka-utils | kafka_utils/util/zookeeper.py | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/zookeeper.py#L549-L557 | def get_pending_plan(self):
"""Read the currently running plan on reassign_partitions node."""
reassignment_path = '{admin}/{reassignment_node}'\
.format(admin=ADMIN_PATH, reassignment_node=REASSIGNMENT_NODE)
try:
result = self.get(reassignment_path)
return lo... | [
"def",
"get_pending_plan",
"(",
"self",
")",
":",
"reassignment_path",
"=",
"'{admin}/{reassignment_node}'",
".",
"format",
"(",
"admin",
"=",
"ADMIN_PATH",
",",
"reassignment_node",
"=",
"REASSIGNMENT_NODE",
")",
"try",
":",
"result",
"=",
"self",
".",
"get",
"... | Read the currently running plan on reassign_partitions node. | [
"Read",
"the",
"currently",
"running",
"plan",
"on",
"reassign_partitions",
"node",
"."
] | python | train | 42.222222 |
Dentosal/python-sc2 | sc2/unit.py | https://github.com/Dentosal/python-sc2/blob/608bd25f04e89d39cef68b40101d8e9a8a7f1634/sc2/unit.py#L418-L429 | def target_in_range(self, target: "Unit", bonus_distance: Union[int, float] = 0) -> bool:
""" Includes the target's radius when calculating distance to target """
if self.can_attack_ground and not target.is_flying:
unit_attack_range = self.ground_range
elif self.can_attack_air and (t... | [
"def",
"target_in_range",
"(",
"self",
",",
"target",
":",
"\"Unit\"",
",",
"bonus_distance",
":",
"Union",
"[",
"int",
",",
"float",
"]",
"=",
"0",
")",
"->",
"bool",
":",
"if",
"self",
".",
"can_attack_ground",
"and",
"not",
"target",
".",
"is_flying",... | Includes the target's radius when calculating distance to target | [
"Includes",
"the",
"target",
"s",
"radius",
"when",
"calculating",
"distance",
"to",
"target"
] | python | train | 53.166667 |
markovmodel/PyEMMA | pyemma/util/types.py | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/types.py#L268-L287 | def ensure_float_vector_or_None(F, require_order = False):
"""Ensures that F is either None, or a numpy array of floats
If F is already either None or a numpy array of floats, F is returned (no copied!)
Otherwise, checks if the argument can be converted to an array of floats and does that.
Parameters
... | [
"def",
"ensure_float_vector_or_None",
"(",
"F",
",",
"require_order",
"=",
"False",
")",
":",
"if",
"F",
"is",
"None",
":",
"return",
"F",
"else",
":",
"return",
"ensure_float_vector",
"(",
"F",
",",
"require_order",
"=",
"require_order",
")"
] | Ensures that F is either None, or a numpy array of floats
If F is already either None or a numpy array of floats, F is returned (no copied!)
Otherwise, checks if the argument can be converted to an array of floats and does that.
Parameters
----------
F: float, list of float or 1D-ndarray of float
... | [
"Ensures",
"that",
"F",
"is",
"either",
"None",
"or",
"a",
"numpy",
"array",
"of",
"floats"
] | python | train | 29.85 |
DataBiosphere/toil | src/toil/fileStore.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/fileStore.py#L1931-L1941 | def write(self, data):
"""
Write the given data to the file.
"""
# Do the write
self.backingStream.write(data)
for listener in self.writeListeners:
# Send out notifications
listener(len(data)) | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"# Do the write",
"self",
".",
"backingStream",
".",
"write",
"(",
"data",
")",
"for",
"listener",
"in",
"self",
".",
"writeListeners",
":",
"# Send out notifications",
"listener",
"(",
"len",
"(",
"data",
... | Write the given data to the file. | [
"Write",
"the",
"given",
"data",
"to",
"the",
"file",
"."
] | python | train | 24.727273 |
google/grr | grr/client/grr_response_client/client_actions/tempfiles.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/client_actions/tempfiles.py#L185-L209 | def CreateGRRTempFileVFS(filename=None, lifetime=0, mode="w+b", suffix=""):
"""Creates a GRR VFS temp file.
This function is analogous to CreateGRRTempFile but returns an open VFS handle
to the newly created file. Arguments are the same as for CreateGRRTempFile:
Args:
filename: The name of the file to use... | [
"def",
"CreateGRRTempFileVFS",
"(",
"filename",
"=",
"None",
",",
"lifetime",
"=",
"0",
",",
"mode",
"=",
"\"w+b\"",
",",
"suffix",
"=",
"\"\"",
")",
":",
"fd",
"=",
"CreateGRRTempFile",
"(",
"filename",
"=",
"filename",
",",
"lifetime",
"=",
"lifetime",
... | Creates a GRR VFS temp file.
This function is analogous to CreateGRRTempFile but returns an open VFS handle
to the newly created file. Arguments are the same as for CreateGRRTempFile:
Args:
filename: The name of the file to use. Note that setting both filename and
directory name is not allowed.
... | [
"Creates",
"a",
"GRR",
"VFS",
"temp",
"file",
"."
] | python | train | 33.64 |
Clivern/PyLogging | pylogging/mailer.py | https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/mailer.py#L25-L43 | def send(self, me, to, subject, msg):
""" Send Message """
msg = MIMEText(msg)
msg['Subject'] = subject
msg['From'] = me
msg['To'] = to
server = smtplib.SMTP(self.host, self.port)
server.starttls()
# Check if user and password defined
if self._usr ... | [
"def",
"send",
"(",
"self",
",",
"me",
",",
"to",
",",
"subject",
",",
"msg",
")",
":",
"msg",
"=",
"MIMEText",
"(",
"msg",
")",
"msg",
"[",
"'Subject'",
"]",
"=",
"subject",
"msg",
"[",
"'From'",
"]",
"=",
"me",
"msg",
"[",
"'To'",
"]",
"=",
... | Send Message | [
"Send",
"Message"
] | python | train | 33.052632 |
tornadoweb/tornado | tornado/locale.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L462-L471 | def friendly_number(self, value: int) -> str:
"""Returns a comma-separated number for the given integer."""
if self.code not in ("en", "en_US"):
return str(value)
s = str(value)
parts = []
while s:
parts.append(s[-3:])
s = s[:-3]
return... | [
"def",
"friendly_number",
"(",
"self",
",",
"value",
":",
"int",
")",
"->",
"str",
":",
"if",
"self",
".",
"code",
"not",
"in",
"(",
"\"en\"",
",",
"\"en_US\"",
")",
":",
"return",
"str",
"(",
"value",
")",
"s",
"=",
"str",
"(",
"value",
")",
"pa... | Returns a comma-separated number for the given integer. | [
"Returns",
"a",
"comma",
"-",
"separated",
"number",
"for",
"the",
"given",
"integer",
"."
] | python | train | 33.7 |
adaptive-learning/proso-apps | proso/dict.py | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/dict.py#L6-L32 | def group_keys_by_values(d):
"""
Take a dict (A -> B( and return another one (B -> [A]). It groups keys
from the original dict by their values.
.. testsetup::
from proso.dict import group_keys_by_values
from pprint import pprint
.. doctest::
>>> pprint(group_keys_by_value... | [
"def",
"group_keys_by_values",
"(",
"d",
")",
":",
"result",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"saved",
"=",
"result",
".",
"get",
"(",
"v",
",",
"[",
"]",
")",
"saved",
".",
"append",
"(",
"k",
")",... | Take a dict (A -> B( and return another one (B -> [A]). It groups keys
from the original dict by their values.
.. testsetup::
from proso.dict import group_keys_by_values
from pprint import pprint
.. doctest::
>>> pprint(group_keys_by_values({1: True, 2: False, 3: True, 4: True}))... | [
"Take",
"a",
"dict",
"(",
"A",
"-",
">",
"B",
"(",
"and",
"return",
"another",
"one",
"(",
"B",
"-",
">",
"[",
"A",
"]",
")",
".",
"It",
"groups",
"keys",
"from",
"the",
"original",
"dict",
"by",
"their",
"values",
"."
] | python | train | 28.666667 |
apache/spark | python/pyspark/rdd.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2159-L2184 | def zipWithIndex(self):
"""
Zips this RDD with its element indices.
The ordering is first based on the partition index and then the
ordering of items within each partition. So the first item in
the first partition gets index 0, and the last item in the last
partition rec... | [
"def",
"zipWithIndex",
"(",
"self",
")",
":",
"starts",
"=",
"[",
"0",
"]",
"if",
"self",
".",
"getNumPartitions",
"(",
")",
">",
"1",
":",
"nums",
"=",
"self",
".",
"mapPartitions",
"(",
"lambda",
"it",
":",
"[",
"sum",
"(",
"1",
"for",
"i",
"in... | Zips this RDD with its element indices.
The ordering is first based on the partition index and then the
ordering of items within each partition. So the first item in
the first partition gets index 0, and the last item in the last
partition receives the largest index.
This metho... | [
"Zips",
"this",
"RDD",
"with",
"its",
"element",
"indices",
"."
] | python | train | 36.730769 |
bspaans/python-mingus | mingus/midi/pyfluidsynth.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L242-L256 | def cc(self, chan, ctrl, val):
"""Send control change value.
The controls that are recognized are dependent on the
SoundFont. Values are always 0 to 127. Typical controls
include:
1: vibrato
7: volume
10: pan (left to right)
11: expression (soft... | [
"def",
"cc",
"(",
"self",
",",
"chan",
",",
"ctrl",
",",
"val",
")",
":",
"return",
"fluid_synth_cc",
"(",
"self",
".",
"synth",
",",
"chan",
",",
"ctrl",
",",
"val",
")"
] | Send control change value.
The controls that are recognized are dependent on the
SoundFont. Values are always 0 to 127. Typical controls
include:
1: vibrato
7: volume
10: pan (left to right)
11: expression (soft to loud)
64: sustain
... | [
"Send",
"control",
"change",
"value",
"."
] | python | train | 30 |
tmacwill/stellata | stellata/database.py | https://github.com/tmacwill/stellata/blob/9519c170397740eb6faf5d8a96b9a77f0d909b92/stellata/database.py#L57-L67 | def initialize(name='', pool_size=10, host='localhost', password='', port=5432, user=''):
"""Initialize a new database connection and return the pool object.
Saves a reference to that instance in a module-level variable, so applications with only one database
can just call this function and not worry about... | [
"def",
"initialize",
"(",
"name",
"=",
"''",
",",
"pool_size",
"=",
"10",
",",
"host",
"=",
"'localhost'",
",",
"password",
"=",
"''",
",",
"port",
"=",
"5432",
",",
"user",
"=",
"''",
")",
":",
"global",
"pool",
"instance",
"=",
"Pool",
"(",
"name... | Initialize a new database connection and return the pool object.
Saves a reference to that instance in a module-level variable, so applications with only one database
can just call this function and not worry about pool objects. | [
"Initialize",
"a",
"new",
"database",
"connection",
"and",
"return",
"the",
"pool",
"object",
"."
] | python | train | 44.818182 |
saltstack/salt | salt/minion.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/minion.py#L272-L320 | def get_proc_dir(cachedir, **kwargs):
'''
Given the cache directory, return the directory that process data is
stored in, creating it if it doesn't exist.
The following optional Keyword Arguments are handled:
mode: which is anything os.makedir would accept as mode.
uid: the uid to set, if not ... | [
"def",
"get_proc_dir",
"(",
"cachedir",
",",
"*",
"*",
"kwargs",
")",
":",
"fn_",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cachedir",
",",
"'proc'",
")",
"mode",
"=",
"kwargs",
".",
"pop",
"(",
"'mode'",
",",
"None",
")",
"if",
"mode",
"is",
"N... | Given the cache directory, return the directory that process data is
stored in, creating it if it doesn't exist.
The following optional Keyword Arguments are handled:
mode: which is anything os.makedir would accept as mode.
uid: the uid to set, if not set, or it is None or -1 no changes are
m... | [
"Given",
"the",
"cache",
"directory",
"return",
"the",
"directory",
"that",
"process",
"data",
"is",
"stored",
"in",
"creating",
"it",
"if",
"it",
"doesn",
"t",
"exist",
".",
"The",
"following",
"optional",
"Keyword",
"Arguments",
"are",
"handled",
":"
] | python | train | 33.816327 |
uralbash/sqlalchemy_mptt | sqlalchemy_mptt/mixins.py | https://github.com/uralbash/sqlalchemy_mptt/blob/2971c9fa49bbeaa3e2fb96229d933ceae450b319/sqlalchemy_mptt/mixins.py#L124-L139 | def is_ancestor_of(self, other, inclusive=False):
""" class or instance level method which returns True if self is
ancestor (closer to root) of other else False. Optional flag
`inclusive` on whether or not to treat self as ancestor of self.
For example see:
* :mod:`sqlalchemy_m... | [
"def",
"is_ancestor_of",
"(",
"self",
",",
"other",
",",
"inclusive",
"=",
"False",
")",
":",
"if",
"inclusive",
":",
"return",
"(",
"self",
".",
"tree_id",
"==",
"other",
".",
"tree_id",
")",
"&",
"(",
"self",
".",
"left",
"<=",
"other",
".",
"left"... | class or instance level method which returns True if self is
ancestor (closer to root) of other else False. Optional flag
`inclusive` on whether or not to treat self as ancestor of self.
For example see:
* :mod:`sqlalchemy_mptt.tests.cases.integrity.test_hierarchy_structure` | [
"class",
"or",
"instance",
"level",
"method",
"which",
"returns",
"True",
"if",
"self",
"is",
"ancestor",
"(",
"closer",
"to",
"root",
")",
"of",
"other",
"else",
"False",
".",
"Optional",
"flag",
"inclusive",
"on",
"whether",
"or",
"not",
"to",
"treat",
... | python | train | 41.625 |
archman/beamline | beamline/element.py | https://github.com/archman/beamline/blob/417bc5dc13e754bc89d246427984590fced64d07/beamline/element.py#L109-L129 | def rot(inputArray, theta=0, pc=(0, 0)):
""" rotate input array with angle of theta
:param inputArray: input array or list,
e.g. np.array([[0,0],[0,1],[0,2]]) or [[0,0],[0,1],[0,2]]
:param theta: rotation angle in degree
:param pc: central point coords (x,y) r... | [
"def",
"rot",
"(",
"inputArray",
",",
"theta",
"=",
"0",
",",
"pc",
"=",
"(",
"0",
",",
"0",
")",
")",
":",
"if",
"not",
"isinstance",
"(",
"inputArray",
",",
"np",
".",
"ndarray",
")",
":",
"inputArray",
"=",
"np",
".",
"array",
"(",
"inputArray... | rotate input array with angle of theta
:param inputArray: input array or list,
e.g. np.array([[0,0],[0,1],[0,2]]) or [[0,0],[0,1],[0,2]]
:param theta: rotation angle in degree
:param pc: central point coords (x,y) regarding to rotation
:return: rotated numpy a... | [
"rotate",
"input",
"array",
"with",
"angle",
"of",
"theta"
] | python | train | 38.380952 |
mitsei/dlkit | dlkit/json_/resource/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/resource/managers.py#L1238-L1261 | def get_resource_agent_session_for_bin(self, bin_id, proxy):
"""Gets a resource agent session for the given bin.
arg: bin_id (osid.id.Id): the ``Id`` of the bin
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.resource.ResourceAgentSession) - a
``ResourceAgentS... | [
"def",
"get_resource_agent_session_for_bin",
"(",
"self",
",",
"bin_id",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_resource_agent",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"##",
"# Also include check to see if the catalog ... | Gets a resource agent session for the given bin.
arg: bin_id (osid.id.Id): the ``Id`` of the bin
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.resource.ResourceAgentSession) - a
``ResourceAgentSession``
raise: NotFound - ``bin_id`` not found
raise: ... | [
"Gets",
"a",
"resource",
"agent",
"session",
"for",
"the",
"given",
"bin",
"."
] | python | train | 46.041667 |
gem/oq-engine | openquake/baselib/zeromq.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/zeromq.py#L139-L150 | def send(self, obj):
"""
Send an object to the remote server; block and return the reply
if the socket type is REQ.
:param obj:
the Python object to send
"""
self.zsocket.send_pyobj(obj)
self.num_sent += 1
if self.socket_type == zmq.REQ:
... | [
"def",
"send",
"(",
"self",
",",
"obj",
")",
":",
"self",
".",
"zsocket",
".",
"send_pyobj",
"(",
"obj",
")",
"self",
".",
"num_sent",
"+=",
"1",
"if",
"self",
".",
"socket_type",
"==",
"zmq",
".",
"REQ",
":",
"return",
"self",
".",
"zsocket",
".",... | Send an object to the remote server; block and return the reply
if the socket type is REQ.
:param obj:
the Python object to send | [
"Send",
"an",
"object",
"to",
"the",
"remote",
"server",
";",
"block",
"and",
"return",
"the",
"reply",
"if",
"the",
"socket",
"type",
"is",
"REQ",
"."
] | python | train | 29 |
frnsys/broca | broca/vectorize/dcs.py | https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/vectorize/dcs.py#L104-L130 | def _disambiguate_doc(self, tagged_tokens):
"""
Takes a list of tagged tokens, representing a document,
in the form:
[(token, tag), ...]
And returns a mapping of terms to their disambiguated concepts (synsets).
"""
# Group tokens by PoS
pos_groups =... | [
"def",
"_disambiguate_doc",
"(",
"self",
",",
"tagged_tokens",
")",
":",
"# Group tokens by PoS",
"pos_groups",
"=",
"{",
"pos",
":",
"[",
"]",
"for",
"pos",
"in",
"[",
"wn",
".",
"NOUN",
",",
"wn",
".",
"VERB",
",",
"wn",
".",
"ADJ",
",",
"wn",
".",... | Takes a list of tagged tokens, representing a document,
in the form:
[(token, tag), ...]
And returns a mapping of terms to their disambiguated concepts (synsets). | [
"Takes",
"a",
"list",
"of",
"tagged",
"tokens",
"representing",
"a",
"document",
"in",
"the",
"form",
":"
] | python | train | 30.148148 |
DocNow/twarc | utils/media2warc.py | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/utils/media2warc.py#L141-L173 | def parse_extended_entities(extended_entities_dict):
"""Parse media file URL:s form tweet data
:extended_entities_dict:
:returns: list of media file urls
"""
urls = []
if "media" in extended_entities_dict.keys():
for item in extended_entities_dict["media"]:
# add static i... | [
"def",
"parse_extended_entities",
"(",
"extended_entities_dict",
")",
":",
"urls",
"=",
"[",
"]",
"if",
"\"media\"",
"in",
"extended_entities_dict",
".",
"keys",
"(",
")",
":",
"for",
"item",
"in",
"extended_entities_dict",
"[",
"\"media\"",
"]",
":",
"# add sta... | Parse media file URL:s form tweet data
:extended_entities_dict:
:returns: list of media file urls | [
"Parse",
"media",
"file",
"URL",
":",
"s",
"form",
"tweet",
"data"
] | python | train | 35.242424 |
Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L96-L109 | def lovasz_hinge(logits, labels, per_image=True, ignore=None):
"""
Binary Lovasz hinge loss
logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
per_image: compute the loss per image instead of per batch
... | [
"def",
"lovasz_hinge",
"(",
"logits",
",",
"labels",
",",
"per_image",
"=",
"True",
",",
"ignore",
"=",
"None",
")",
":",
"if",
"per_image",
":",
"loss",
"=",
"mean",
"(",
"lovasz_hinge_flat",
"(",
"*",
"flatten_binary_scores",
"(",
"log",
".",
"unsqueeze"... | Binary Lovasz hinge loss
logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
per_image: compute the loss per image instead of per batch
ignore: void class id | [
"Binary",
"Lovasz",
"hinge",
"loss",
"logits",
":",
"[",
"B",
"H",
"W",
"]",
"Variable",
"logits",
"at",
"each",
"pixel",
"(",
"between",
"-",
"\\",
"infty",
"and",
"+",
"\\",
"infty",
")",
"labels",
":",
"[",
"B",
"H",
"W",
"]",
"Tensor",
"binary"... | python | train | 45.214286 |
materialsproject/pymatgen | pymatgen/io/abinit/abiobjects.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/abiobjects.py#L227-L245 | def contract(s):
"""
>>> assert contract("1 1 1 2 2 3") == "3*1 2*2 1*3"
>>> assert contract("1 1 3 2 3") == "2*1 1*3 1*2 1*3"
"""
if not s: return s
tokens = s.split()
old = tokens[0]
count = [[1, old]]
for t in tokens[1:]:
if t == old:
count[-1][0] += 1
... | [
"def",
"contract",
"(",
"s",
")",
":",
"if",
"not",
"s",
":",
"return",
"s",
"tokens",
"=",
"s",
".",
"split",
"(",
")",
"old",
"=",
"tokens",
"[",
"0",
"]",
"count",
"=",
"[",
"[",
"1",
",",
"old",
"]",
"]",
"for",
"t",
"in",
"tokens",
"["... | >>> assert contract("1 1 1 2 2 3") == "3*1 2*2 1*3"
>>> assert contract("1 1 3 2 3") == "2*1 1*3 1*2 1*3" | [
">>>",
"assert",
"contract",
"(",
"1",
"1",
"1",
"2",
"2",
"3",
")",
"==",
"3",
"*",
"1",
"2",
"*",
"2",
"1",
"*",
"3",
">>>",
"assert",
"contract",
"(",
"1",
"1",
"3",
"2",
"3",
")",
"==",
"2",
"*",
"1",
"1",
"*",
"3",
"1",
"*",
"2",
... | python | train | 22.052632 |
oscarbranson/latools | Supplement/comparison_tools/stats.py | https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/Supplement/comparison_tools/stats.py#L14-L81 | def pairwise_reproducibility(df, plot=False):
"""
Calculate the reproducibility of LA-ICPMS based on unique pairs of repeat analyses.
Pairwise differences are fit with a half-Cauchy distribution, and the median and
95% confidence limits are returned for each analyte.
Parameters
------... | [
"def",
"pairwise_reproducibility",
"(",
"df",
",",
"plot",
"=",
"False",
")",
":",
"ans",
"=",
"df",
".",
"columns",
".",
"values",
"pdifs",
"=",
"[",
"]",
"# calculate differences between unique pairs",
"for",
"ind",
",",
"d",
"in",
"df",
".",
"groupby",
... | Calculate the reproducibility of LA-ICPMS based on unique pairs of repeat analyses.
Pairwise differences are fit with a half-Cauchy distribution, and the median and
95% confidence limits are returned for each analyte.
Parameters
----------
df : pandas.DataFrame
A dataset
... | [
"Calculate",
"the",
"reproducibility",
"of",
"LA",
"-",
"ICPMS",
"based",
"on",
"unique",
"pairs",
"of",
"repeat",
"analyses",
".",
"Pairwise",
"differences",
"are",
"fit",
"with",
"a",
"half",
"-",
"Cauchy",
"distribution",
"and",
"the",
"median",
"and",
"9... | python | test | 28.955882 |
lvieirajr/mongorest | mongorest/decorators.py | https://github.com/lvieirajr/mongorest/blob/00f4487ded33254434bc51ff09d48c7a936bd465/mongorest/decorators.py#L47-L67 | def serializable(wrapped):
"""
If a keyword argument 'serialize' with a True value is passed to the
Wrapped function, the return of the wrapped function will be serialized.
Nothing happens if the argument is not passed or the value is not True
"""
@wraps(wrapped)
def wrapper(*args, **kwargs... | [
"def",
"serializable",
"(",
"wrapped",
")",
":",
"@",
"wraps",
"(",
"wrapped",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"should_serialize",
"=",
"kwargs",
".",
"pop",
"(",
"'serialize'",
",",
"False",
")",
"result",
... | If a keyword argument 'serialize' with a True value is passed to the
Wrapped function, the return of the wrapped function will be serialized.
Nothing happens if the argument is not passed or the value is not True | [
"If",
"a",
"keyword",
"argument",
"serialize",
"with",
"a",
"True",
"value",
"is",
"passed",
"to",
"the",
"Wrapped",
"function",
"the",
"return",
"of",
"the",
"wrapped",
"function",
"will",
"be",
"serialized",
".",
"Nothing",
"happens",
"if",
"the",
"argumen... | python | train | 32.47619 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py#L241-L256 | def overlay_gateway_map_vlan_vni_mapping_vni(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
... | [
"def",
"overlay_gateway_map_vlan_vni_mapping_vni",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"overlay_gateway",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"overlay-gateway\"",
",",
"xm... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 46.125 |
rwl/godot | godot/component/text.py | https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/component/text.py#L93-L120 | def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):
""" Draws the component """
gc.save_state()
try:
# Specify the font
font = str_to_font(str(self.pen.font))
gc.set_font(font)
gc.set_fill_color(self.pen.color_)
x = self... | [
"def",
"_draw_mainlayer",
"(",
"self",
",",
"gc",
",",
"view_bounds",
"=",
"None",
",",
"mode",
"=",
"\"default\"",
")",
":",
"gc",
".",
"save_state",
"(",
")",
"try",
":",
"# Specify the font",
"font",
"=",
"str_to_font",
"(",
"str",
"(",
"self",
".",
... | Draws the component | [
"Draws",
"the",
"component"
] | python | test | 35.714286 |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/mox.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/mox.py#L164-L177 | def CreateMock(self, class_to_mock):
"""Create a new mock object.
Args:
# class_to_mock: the class to be mocked
class_to_mock: class
Returns:
MockObject that can be used as the class_to_mock would be.
"""
new_mock = MockObject(class_to_mock)
self._mock_objects.append(new_moc... | [
"def",
"CreateMock",
"(",
"self",
",",
"class_to_mock",
")",
":",
"new_mock",
"=",
"MockObject",
"(",
"class_to_mock",
")",
"self",
".",
"_mock_objects",
".",
"append",
"(",
"new_mock",
")",
"return",
"new_mock"
] | Create a new mock object.
Args:
# class_to_mock: the class to be mocked
class_to_mock: class
Returns:
MockObject that can be used as the class_to_mock would be. | [
"Create",
"a",
"new",
"mock",
"object",
"."
] | python | train | 23.5 |
portfors-lab/sparkle | sparkle/stim/stimulus_model.py | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/stim/stimulus_model.py#L557-L566 | def duration(self):
"""The duration of this stimulus
:returns: float -- duration in seconds
"""
durs = []
for track in self._segments:
durs.append(sum([comp.duration() for comp in track]))
return max(durs) | [
"def",
"duration",
"(",
"self",
")",
":",
"durs",
"=",
"[",
"]",
"for",
"track",
"in",
"self",
".",
"_segments",
":",
"durs",
".",
"append",
"(",
"sum",
"(",
"[",
"comp",
".",
"duration",
"(",
")",
"for",
"comp",
"in",
"track",
"]",
")",
")",
"... | The duration of this stimulus
:returns: float -- duration in seconds | [
"The",
"duration",
"of",
"this",
"stimulus"
] | python | train | 27 |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAFetch/QAQuery_Advance.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery_Advance.py#L185-L200 | def QA_fetch_stock_day_full_adv(date):
'''
'返回全市场某一天的数据'
:param date:
:return: QA_DataStruct_Stock_day类 型数据
'''
# 🛠 todo 检查日期data参数
res = QA_fetch_stock_full(date, 'pd')
if res is None:
print("QA Error QA_fetch_stock_day_full_adv parameter date=%s call QA_fetch_stock_full return... | [
"def",
"QA_fetch_stock_day_full_adv",
"(",
"date",
")",
":",
"# 🛠 todo 检查日期data参数",
"res",
"=",
"QA_fetch_stock_full",
"(",
"date",
",",
"'pd'",
")",
"if",
"res",
"is",
"None",
":",
"print",
"(",
"\"QA Error QA_fetch_stock_day_full_adv parameter date=%s call QA_fetch_sto... | '返回全市场某一天的数据'
:param date:
:return: QA_DataStruct_Stock_day类 型数据 | [
"返回全市场某一天的数据",
":",
"param",
"date",
":",
":",
"return",
":",
"QA_DataStruct_Stock_day类",
"型数据"
] | python | train | 36.6875 |
havardgulldahl/jottalib | src/jottalib/JFS.py | https://github.com/havardgulldahl/jottalib/blob/4d015e4309b1d9055e561ec757363fb2632b4eb7/src/jottalib/JFS.py#L693-L695 | def modified(self):
'return datetime.datetime'
return dateutil.parser.parse(str(self.f.currentRevision.modified)) | [
"def",
"modified",
"(",
"self",
")",
":",
"return",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"str",
"(",
"self",
".",
"f",
".",
"currentRevision",
".",
"modified",
")",
")"
] | return datetime.datetime | [
"return",
"datetime",
".",
"datetime"
] | python | train | 42.333333 |
numenta/nupic | src/nupic/frameworks/opf/opf_basic_environment.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_basic_environment.py#L346-L457 | def __openDatafile(self, modelResult):
"""Open the data file and write the header row"""
# Write reset bit
resetFieldMeta = FieldMetaInfo(
name="reset",
type=FieldMetaType.integer,
special = FieldMetaSpecial.reset)
self.__outputFieldsMeta.append(resetFieldMeta)
# --------------... | [
"def",
"__openDatafile",
"(",
"self",
",",
"modelResult",
")",
":",
"# Write reset bit",
"resetFieldMeta",
"=",
"FieldMetaInfo",
"(",
"name",
"=",
"\"reset\"",
",",
"type",
"=",
"FieldMetaType",
".",
"integer",
",",
"special",
"=",
"FieldMetaSpecial",
".",
"rese... | Open the data file and write the header row | [
"Open",
"the",
"data",
"file",
"and",
"write",
"the",
"header",
"row"
] | python | valid | 35.776786 |
chinuno-usami/CuteR | CuteR/CuteR.py | https://github.com/chinuno-usami/CuteR/blob/ba4e017d3460bda9c1ccaf90723ddbfd4cc5426c/CuteR/CuteR.py#L28-L51 | def produce(txt,img,ver=5,err_crt = qrcode.constants.ERROR_CORRECT_H,bri = 1.0, cont = 1.0,\
colourful = False, rgba = (0,0,0,255),pixelate = False):
"""Produce QR code
:txt: QR text
:img: Image path / Image object
:ver: QR version
:err_crt: QR error correct
:bri: Brightness enhance
... | [
"def",
"produce",
"(",
"txt",
",",
"img",
",",
"ver",
"=",
"5",
",",
"err_crt",
"=",
"qrcode",
".",
"constants",
".",
"ERROR_CORRECT_H",
",",
"bri",
"=",
"1.0",
",",
"cont",
"=",
"1.0",
",",
"colourful",
"=",
"False",
",",
"rgba",
"=",
"(",
"0",
... | Produce QR code
:txt: QR text
:img: Image path / Image object
:ver: QR version
:err_crt: QR error correct
:bri: Brightness enhance
:cont: Contrast enhance
:colourful: If colourful mode
:rgba: color to replace black
:pixelate: pixelate
:returns: list of produced image | [
"Produce",
"QR",
"code"
] | python | train | 30.833333 |
thanethomson/statik | statik/models.py | https://github.com/thanethomson/statik/blob/56b1b5a2cb05a97afa81f428bfcefc833e935b8d/statik/models.py#L73-L96 | def find_additional_rels(self, all_models):
"""Attempts to scan for additional relationship fields for this model based on all of the other models'
structures and relationships.
"""
for model_name, model in iteritems(all_models):
if model_name != self.name:
fo... | [
"def",
"find_additional_rels",
"(",
"self",
",",
"all_models",
")",
":",
"for",
"model_name",
",",
"model",
"in",
"iteritems",
"(",
"all_models",
")",
":",
"if",
"model_name",
"!=",
"self",
".",
"name",
":",
"for",
"field_name",
"in",
"model",
".",
"field_... | Attempts to scan for additional relationship fields for this model based on all of the other models'
structures and relationships. | [
"Attempts",
"to",
"scan",
"for",
"additional",
"relationship",
"fields",
"for",
"this",
"model",
"based",
"on",
"all",
"of",
"the",
"other",
"models",
"structures",
"and",
"relationships",
"."
] | python | train | 56.958333 |
CentOS/python-cicoclient | cicoclient/wrapper.py | https://github.com/CentOS/python-cicoclient/blob/ffee34f446ceb25348b13a500d5c545df202c182/cicoclient/wrapper.py#L135-L181 | def node_get(self, arch=None, ver=None, flavor=None, count=1,
retry_count=1, retry_interval=10):
"""
Requests specified number of nodes with the provided parameters.
:param arch: Server architecture (ex: x86_64)
:param ver: CentOS version (ex: 7)
:param count: N... | [
"def",
"node_get",
"(",
"self",
",",
"arch",
"=",
"None",
",",
"ver",
"=",
"None",
",",
"flavor",
"=",
"None",
",",
"count",
"=",
"1",
",",
"retry_count",
"=",
"1",
",",
"retry_interval",
"=",
"10",
")",
":",
"if",
"self",
".",
"api_key",
"is",
"... | Requests specified number of nodes with the provided parameters.
:param arch: Server architecture (ex: x86_64)
:param ver: CentOS version (ex: 7)
:param count: Number of servers (ex: 2)
:parma flavor: The flavor of machine to use (multi-arch only)
:param retry_count: Number of t... | [
"Requests",
"specified",
"number",
"of",
"nodes",
"with",
"the",
"provided",
"parameters",
"."
] | python | train | 38.744681 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/sql_io.py | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/sql_io.py#L16-L52 | def smart_insert(df, table, engine, minimal_size=5):
"""An optimized Insert strategy.
**中文文档**
一种优化的将大型DataFrame中的数据, 在有IntegrityError的情况下将所有
好数据存入数据库的方法。
"""
from sqlalchemy.exc import IntegrityError
try:
table_name = table.name
except:
table_name = table
# 首先进行尝... | [
"def",
"smart_insert",
"(",
"df",
",",
"table",
",",
"engine",
",",
"minimal_size",
"=",
"5",
")",
":",
"from",
"sqlalchemy",
".",
"exc",
"import",
"IntegrityError",
"try",
":",
"table_name",
"=",
"table",
".",
"name",
"except",
":",
"table_name",
"=",
"... | An optimized Insert strategy.
**中文文档**
一种优化的将大型DataFrame中的数据, 在有IntegrityError的情况下将所有
好数据存入数据库的方法。 | [
"An",
"optimized",
"Insert",
"strategy",
"."
] | python | train | 27 |
CEA-COSMIC/ModOpt | modopt/opt/proximity.py | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L154-L171 | def _cost_method(self, *args, **kwargs):
"""Calculate sparsity component of the cost
This method returns the l1 norm error of the weighted wavelet
coefficients
Returns
-------
float sparsity cost component
"""
cost_val = np.sum(np.abs(self.weights * se... | [
"def",
"_cost_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cost_val",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"abs",
"(",
"self",
".",
"weights",
"*",
"self",
".",
"_linear",
".",
"op",
"(",
"args",
"[",
"0",
"]",
... | Calculate sparsity component of the cost
This method returns the l1 norm error of the weighted wavelet
coefficients
Returns
-------
float sparsity cost component | [
"Calculate",
"sparsity",
"component",
"of",
"the",
"cost"
] | python | train | 25.222222 |
spotify/luigi | luigi/contrib/hdfs/target.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/target.py#L134-L138 | def move(self, path, raise_if_exists=False):
"""
Alias for ``rename()``
"""
self.rename(path, raise_if_exists=raise_if_exists) | [
"def",
"move",
"(",
"self",
",",
"path",
",",
"raise_if_exists",
"=",
"False",
")",
":",
"self",
".",
"rename",
"(",
"path",
",",
"raise_if_exists",
"=",
"raise_if_exists",
")"
] | Alias for ``rename()`` | [
"Alias",
"for",
"rename",
"()"
] | python | train | 30.8 |
andrewda/frc-livescore | livescore/simpleocr_utils/processor.py | https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/processor.py#L25-L37 | def create_broadcast(src_atr_name, dest_processors, dest_atr_name=None, transform_function=lambda x: x):
"""
This method creates a function, intended to be called as a
Processor posthook, that copies some of the processor's attributes
to other processors
"""
from functools import partial
if ... | [
"def",
"create_broadcast",
"(",
"src_atr_name",
",",
"dest_processors",
",",
"dest_atr_name",
"=",
"None",
",",
"transform_function",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"from",
"functools",
"import",
"partial",
"if",
"dest_atr_name",
"==",
"None",
":",
"d... | This method creates a function, intended to be called as a
Processor posthook, that copies some of the processor's attributes
to other processors | [
"This",
"method",
"creates",
"a",
"function",
"intended",
"to",
"be",
"called",
"as",
"a",
"Processor",
"posthook",
"that",
"copies",
"some",
"of",
"the",
"processor",
"s",
"attributes",
"to",
"other",
"processors"
] | python | train | 52.153846 |
blockadeio/analyst_toolbench | blockade/cli/aws_serverless.py | https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L701-L717 | def generate_api_gateway():
"""Create the Blockade API Gateway REST service."""
logger.debug("[#] Setting up the API Gateway")
client = boto3.client('apigateway', region_name=PRIMARY_REGION)
matches = [x for x in client.get_rest_apis().get('items', list())
if x['name'] == API_GATEWAY]
... | [
"def",
"generate_api_gateway",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\"[#] Setting up the API Gateway\"",
")",
"client",
"=",
"boto3",
".",
"client",
"(",
"'apigateway'",
",",
"region_name",
"=",
"PRIMARY_REGION",
")",
"matches",
"=",
"[",
"x",
"for",
"... | Create the Blockade API Gateway REST service. | [
"Create",
"the",
"Blockade",
"API",
"Gateway",
"REST",
"service",
"."
] | python | train | 36.470588 |
teepark/greenhouse | greenhouse/util.py | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L655-L664 | def cancel(self):
"""attempt to prevent the timer from ever running its function
:returns:
``True`` if it was successful, ``False`` if the timer had already
run or been cancelled
"""
done = self.finished.is_set()
self.finished.set()
return not don... | [
"def",
"cancel",
"(",
"self",
")",
":",
"done",
"=",
"self",
".",
"finished",
".",
"is_set",
"(",
")",
"self",
".",
"finished",
".",
"set",
"(",
")",
"return",
"not",
"done"
] | attempt to prevent the timer from ever running its function
:returns:
``True`` if it was successful, ``False`` if the timer had already
run or been cancelled | [
"attempt",
"to",
"prevent",
"the",
"timer",
"from",
"ever",
"running",
"its",
"function"
] | python | train | 31.2 |
pantsbuild/pants | src/python/pants/scm/git.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/scm/git.py#L40-L60 | def detect_worktree(cls, binary='git', subdir=None):
"""Detect the git working tree above cwd and return it; else, return None.
:param string binary: The path to the git binary to use, 'git' by default.
:param string subdir: The path to start searching for a git repo.
:returns: path to the directory wh... | [
"def",
"detect_worktree",
"(",
"cls",
",",
"binary",
"=",
"'git'",
",",
"subdir",
"=",
"None",
")",
":",
"# TODO(John Sirois): This is only used as a factory for a Git instance in",
"# pants.base.build_environment.get_scm, encapsulate in a true factory method.",
"cmd",
"=",
"[",
... | Detect the git working tree above cwd and return it; else, return None.
:param string binary: The path to the git binary to use, 'git' by default.
:param string subdir: The path to start searching for a git repo.
:returns: path to the directory where the git working tree is rooted.
:rtype: string | [
"Detect",
"the",
"git",
"working",
"tree",
"above",
"cwd",
"and",
"return",
"it",
";",
"else",
"return",
"None",
"."
] | python | train | 41.666667 |
instacart/jardin | jardin/model.py | https://github.com/instacart/jardin/blob/007e283b9ccd621b60b86679148cacd9eab7c4e3/jardin/model.py#L259-L282 | def query(self, sql=None, filename=None, **kwargs):
""" run raw sql from sql or file against.
:param sql: Raw SQL query to pass directly to the connection.
:type sql: string
:param filename: Path to a file containing a SQL query. The path should be relative to CWD.
:type filenam... | [
"def",
"query",
"(",
"self",
",",
"sql",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"query",
"(",
"sql",
"=",
"sql",
",",
"filename",
"=",
"filename",
",",
"db",
"=",
"self",
".",
"db_names",
"["... | run raw sql from sql or file against.
:param sql: Raw SQL query to pass directly to the connection.
:type sql: string
:param filename: Path to a file containing a SQL query. The path should be relative to CWD.
:type filename: string
:param db: `optional` Database name from your ... | [
"run",
"raw",
"sql",
"from",
"sql",
"or",
"file",
"against",
"."
] | python | train | 40.541667 |
fermiPy/fermipy | fermipy/gtanalysis.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/gtanalysis.py#L5677-L5686 | def get_model_path(self, name):
"""Infer the path to the XML model name."""
name, ext = os.path.splitext(name)
ext = '.xml'
xmlfile = name + self.config['file_suffix'] + ext
xmlfile = utils.resolve_path(xmlfile,
workdir=self.config['fileio'][... | [
"def",
"get_model_path",
"(",
"self",
",",
"name",
")",
":",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
"ext",
"=",
"'.xml'",
"xmlfile",
"=",
"name",
"+",
"self",
".",
"config",
"[",
"'file_suffix'",
"]",
"+",
"e... | Infer the path to the XML model name. | [
"Infer",
"the",
"path",
"to",
"the",
"XML",
"model",
"name",
"."
] | python | train | 34.6 |
roclark/sportsreference | sportsreference/nfl/roster.py | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/roster.py#L271-L320 | def _combine_season_stats(self, table_rows, career_stats, all_stats_dict):
"""
Combine all stats for each season.
Since all of the stats are spread across multiple tables, they should
be combined into a single field which can be used to easily query stats
at once.
Param... | [
"def",
"_combine_season_stats",
"(",
"self",
",",
"table_rows",
",",
"career_stats",
",",
"all_stats_dict",
")",
":",
"most_recent_season",
"=",
"self",
".",
"_most_recent_season",
"if",
"not",
"table_rows",
":",
"table_rows",
"=",
"[",
"]",
"for",
"row",
"in",
... | Combine all stats for each season.
Since all of the stats are spread across multiple tables, they should
be combined into a single field which can be used to easily query stats
at once.
Parameters
----------
table_rows : generator
A generator where each elem... | [
"Combine",
"all",
"stats",
"for",
"each",
"season",
"."
] | python | train | 39.86 |
kragniz/python-etcd3 | etcd3/client.py | https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L856-L877 | def add_member(self, urls):
"""
Add a member into the cluster.
:returns: new member
:rtype: :class:`.Member`
"""
member_add_request = etcdrpc.MemberAddRequest(peerURLs=urls)
member_add_response = self.clusterstub.MemberAdd(
member_add_request,
... | [
"def",
"add_member",
"(",
"self",
",",
"urls",
")",
":",
"member_add_request",
"=",
"etcdrpc",
".",
"MemberAddRequest",
"(",
"peerURLs",
"=",
"urls",
")",
"member_add_response",
"=",
"self",
".",
"clusterstub",
".",
"MemberAdd",
"(",
"member_add_request",
",",
... | Add a member into the cluster.
:returns: new member
:rtype: :class:`.Member` | [
"Add",
"a",
"member",
"into",
"the",
"cluster",
"."
] | python | train | 32.409091 |
deep-compute/logagg | logagg/formatters.py | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/formatters.py#L374-L391 | def elasticsearch_ispartial_log(line):
'''
>>> line1 = ' [2018-04-03T00:22:38,048][DEBUG][o.e.c.u.c.QueueResizingEsThreadPoolExecutor] [search17/search]: there were [2000] tasks in [809ms], avg task time [28.4micros], EWMA task execution [790nanos], [35165.36 tasks/s], optimal queue is [35165], current capacit... | [
"def",
"elasticsearch_ispartial_log",
"(",
"line",
")",
":",
"match_result",
"=",
"[",
"]",
"for",
"p",
"in",
"LOG_BEGIN_PATTERN",
":",
"if",
"re",
".",
"match",
"(",
"p",
",",
"line",
")",
"!=",
"None",
":",
"return",
"False",
"return",
"True"
] | >>> line1 = ' [2018-04-03T00:22:38,048][DEBUG][o.e.c.u.c.QueueResizingEsThreadPoolExecutor] [search17/search]: there were [2000] tasks in [809ms], avg task time [28.4micros], EWMA task execution [790nanos], [35165.36 tasks/s], optimal queue is [35165], current capacity [1000]'
>>> line2 = ' org.elasticsearch.Reso... | [
">>>",
"line1",
"=",
"[",
"2018",
"-",
"04",
"-",
"03T00",
":",
"22",
":",
"38",
"048",
"]",
"[",
"DEBUG",
"]",
"[",
"o",
".",
"e",
".",
"c",
".",
"u",
".",
"c",
".",
"QueueResizingEsThreadPoolExecutor",
"]",
"[",
"search17",
"/",
"search",
"]",
... | python | train | 51.222222 |
jrfonseca/gprof2dot | gprof2dot.py | https://github.com/jrfonseca/gprof2dot/blob/0500e89f001e555f5eaa32e70793b4875f2f70db/gprof2dot.py#L315-L333 | def find_cycles(self):
"""Find cycles using Tarjan's strongly connected components algorithm."""
# Apply the Tarjan's algorithm successively until all functions are visited
stack = []
data = {}
order = 0
for function in compat_itervalues(self.functions):
orde... | [
"def",
"find_cycles",
"(",
"self",
")",
":",
"# Apply the Tarjan's algorithm successively until all functions are visited",
"stack",
"=",
"[",
"]",
"data",
"=",
"{",
"}",
"order",
"=",
"0",
"for",
"function",
"in",
"compat_itervalues",
"(",
"self",
".",
"functions",... | Find cycles using Tarjan's strongly connected components algorithm. | [
"Find",
"cycles",
"using",
"Tarjan",
"s",
"strongly",
"connected",
"components",
"algorithm",
"."
] | python | train | 41.421053 |
Galarzaa90/tibia.py | tibiapy/guild.py | https://github.com/Galarzaa90/tibia.py/blob/02ba1a8f1e18177ef5c7dcd44affc8d761d59e12/tibiapy/guild.py#L275-L286 | def _parse_guild_homepage(self, info_container):
"""
Parses the guild's homepage info.
Parameters
----------
info_container: :class:`bs4.Tag`
The parsed content of the information container.
"""
m = homepage_regex.search(info_container.text)
i... | [
"def",
"_parse_guild_homepage",
"(",
"self",
",",
"info_container",
")",
":",
"m",
"=",
"homepage_regex",
".",
"search",
"(",
"info_container",
".",
"text",
")",
"if",
"m",
":",
"self",
".",
"homepage",
"=",
"m",
".",
"group",
"(",
"1",
")"
] | Parses the guild's homepage info.
Parameters
----------
info_container: :class:`bs4.Tag`
The parsed content of the information container. | [
"Parses",
"the",
"guild",
"s",
"homepage",
"info",
"."
] | python | train | 29.333333 |
fermiPy/fermipy | fermipy/gtanalysis.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/gtanalysis.py#L511-L549 | def create(cls, infile, config=None, params=None, mask=None):
"""Create a new instance of GTAnalysis from an analysis output file
generated with `~fermipy.GTAnalysis.write_roi`. By default
the new instance will inherit the configuration of the saved
analysis instance. The configuration... | [
"def",
"create",
"(",
"cls",
",",
"infile",
",",
"config",
"=",
"None",
",",
"params",
"=",
"None",
",",
"mask",
"=",
"None",
")",
":",
"infile",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"infile",
")",
"roi_file",
",",
"roi_data",
"=",
"utils",... | Create a new instance of GTAnalysis from an analysis output file
generated with `~fermipy.GTAnalysis.write_roi`. By default
the new instance will inherit the configuration of the saved
analysis instance. The configuration may be overriden by
passing a configuration file path with the `... | [
"Create",
"a",
"new",
"instance",
"of",
"GTAnalysis",
"from",
"an",
"analysis",
"output",
"file",
"generated",
"with",
"~fermipy",
".",
"GTAnalysis",
".",
"write_roi",
".",
"By",
"default",
"the",
"new",
"instance",
"will",
"inherit",
"the",
"configuration",
"... | python | train | 30.615385 |
sergei-maertens/django-systemjs | systemjs/base.py | https://github.com/sergei-maertens/django-systemjs/blob/efd4a3862a39d9771609a25a5556f36023cf6e5c/systemjs/base.py#L130-L138 | def needs_ext(self):
"""
Check whether `self.app` is missing the '.js' extension and if it needs it.
"""
if settings.SYSTEMJS_DEFAULT_JS_EXTENSIONS:
name, ext = posixpath.splitext(self.app)
if not ext:
return True
return False | [
"def",
"needs_ext",
"(",
"self",
")",
":",
"if",
"settings",
".",
"SYSTEMJS_DEFAULT_JS_EXTENSIONS",
":",
"name",
",",
"ext",
"=",
"posixpath",
".",
"splitext",
"(",
"self",
".",
"app",
")",
"if",
"not",
"ext",
":",
"return",
"True",
"return",
"False"
] | Check whether `self.app` is missing the '.js' extension and if it needs it. | [
"Check",
"whether",
"self",
".",
"app",
"is",
"missing",
"the",
".",
"js",
"extension",
"and",
"if",
"it",
"needs",
"it",
"."
] | python | test | 33.111111 |
jmgilman/Neolib | neolib/pyamf/amf3.py | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/amf3.py#L713-L721 | def addProxyObject(self, obj, proxied):
"""
Stores a reference to the unproxied and proxied versions of C{obj} for
later retrieval.
@since: 0.6
"""
self.proxied_objects[id(obj)] = proxied
self.proxied_objects[id(proxied)] = obj | [
"def",
"addProxyObject",
"(",
"self",
",",
"obj",
",",
"proxied",
")",
":",
"self",
".",
"proxied_objects",
"[",
"id",
"(",
"obj",
")",
"]",
"=",
"proxied",
"self",
".",
"proxied_objects",
"[",
"id",
"(",
"proxied",
")",
"]",
"=",
"obj"
] | Stores a reference to the unproxied and proxied versions of C{obj} for
later retrieval.
@since: 0.6 | [
"Stores",
"a",
"reference",
"to",
"the",
"unproxied",
"and",
"proxied",
"versions",
"of",
"C",
"{",
"obj",
"}",
"for",
"later",
"retrieval",
"."
] | python | train | 30.666667 |
openstack/proliantutils | proliantutils/redfish/resources/account_service/account.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/account_service/account.py#L43-L52 | def get_member_details(self, username):
"""Returns the HPEAccount object
:param username: username of account
:returns: HPEAccount object if criterion matches, None otherwise
"""
members = self.get_members()
for member in members:
if member.username == userna... | [
"def",
"get_member_details",
"(",
"self",
",",
"username",
")",
":",
"members",
"=",
"self",
".",
"get_members",
"(",
")",
"for",
"member",
"in",
"members",
":",
"if",
"member",
".",
"username",
"==",
"username",
":",
"return",
"member"
] | Returns the HPEAccount object
:param username: username of account
:returns: HPEAccount object if criterion matches, None otherwise | [
"Returns",
"the",
"HPEAccount",
"object"
] | python | train | 34.4 |
ejeschke/ginga | ginga/rv/plugins/TVMark.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMark.py#L413-L430 | def clear_marking(self):
"""Clear marking from image.
This does not clear loaded coordinates from memory."""
if self.marktag:
try:
self.canvas.delete_object_by_tag(self.marktag, redraw=False)
except Exception:
pass
if self.markhlta... | [
"def",
"clear_marking",
"(",
"self",
")",
":",
"if",
"self",
".",
"marktag",
":",
"try",
":",
"self",
".",
"canvas",
".",
"delete_object_by_tag",
"(",
"self",
".",
"marktag",
",",
"redraw",
"=",
"False",
")",
"except",
"Exception",
":",
"pass",
"if",
"... | Clear marking from image.
This does not clear loaded coordinates from memory. | [
"Clear",
"marking",
"from",
"image",
".",
"This",
"does",
"not",
"clear",
"loaded",
"coordinates",
"from",
"memory",
"."
] | python | train | 31.666667 |
tensorflow/tensor2tensor | tensor2tensor/models/video/epva.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L584-L595 | def mean_squared_error(true, pred):
"""L2 distance between tensors true and pred.
Args:
true: the ground truth image.
pred: the predicted image.
Returns:
mean squared error between ground truth and predicted image.
"""
result = tf.reduce_sum(
tf.squared_difference(true, pred)) / tf.to_float... | [
"def",
"mean_squared_error",
"(",
"true",
",",
"pred",
")",
":",
"result",
"=",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"squared_difference",
"(",
"true",
",",
"pred",
")",
")",
"/",
"tf",
".",
"to_float",
"(",
"tf",
".",
"size",
"(",
"pred",
")",
... | L2 distance between tensors true and pred.
Args:
true: the ground truth image.
pred: the predicted image.
Returns:
mean squared error between ground truth and predicted image. | [
"L2",
"distance",
"between",
"tensors",
"true",
"and",
"pred",
"."
] | python | train | 28.333333 |
seleniumbase/SeleniumBase | seleniumbase/fixtures/page_actions.py | https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/fixtures/page_actions.py#L495-L518 | def wait_for_and_switch_to_alert(driver, timeout=settings.LARGE_TIMEOUT):
"""
Wait for a browser alert to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.alert when the alert box
may not exist yet.
@Params
driver - the webdriver object (required)
... | [
"def",
"wait_for_and_switch_to_alert",
"(",
"driver",
",",
"timeout",
"=",
"settings",
".",
"LARGE_TIMEOUT",
")",
":",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"timeout",
"*",
"1000.0",
")",
"for"... | Wait for a browser alert to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.alert when the alert box
may not exist yet.
@Params
driver - the webdriver object (required)
timeout - the time to wait for the alert in seconds | [
"Wait",
"for",
"a",
"browser",
"alert",
"to",
"appear",
"and",
"switch",
"to",
"it",
".",
"This",
"should",
"be",
"usable",
"as",
"a",
"drop",
"-",
"in",
"replacement",
"for",
"driver",
".",
"switch_to",
".",
"alert",
"when",
"the",
"alert",
"box",
"ma... | python | train | 37.333333 |
Neurita/boyle | boyle/files/search.py | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/search.py#L253-L274 | def recursive_glob(base_directory, regex=''):
"""
Uses glob to find all files or folders that match the regex
starting from the base_directory.
Parameters
----------
base_directory: str
regex: str
Returns
-------
files: list
"""
files = glob(op.join(base_directory, re... | [
"def",
"recursive_glob",
"(",
"base_directory",
",",
"regex",
"=",
"''",
")",
":",
"files",
"=",
"glob",
"(",
"op",
".",
"join",
"(",
"base_directory",
",",
"regex",
")",
")",
"for",
"path",
",",
"dirlist",
",",
"filelist",
"in",
"os",
".",
"walk",
"... | Uses glob to find all files or folders that match the regex
starting from the base_directory.
Parameters
----------
base_directory: str
regex: str
Returns
-------
files: list | [
"Uses",
"glob",
"to",
"find",
"all",
"files",
"or",
"folders",
"that",
"match",
"the",
"regex",
"starting",
"from",
"the",
"base_directory",
"."
] | python | valid | 21.727273 |
saltstack/salt | salt/modules/debian_ip.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L315-L323 | def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer') | [
"def",
"__int",
"(",
"value",
")",
":",
"valid",
",",
"_value",
"=",
"False",
",",
"value",
"try",
":",
"_value",
"=",
"int",
"(",
"value",
")",
"valid",
"=",
"True",
"except",
"ValueError",
":",
"pass",
"return",
"(",
"valid",
",",
"_value",
",",
... | validate an integer | [
"validate",
"an",
"integer"
] | python | train | 22.666667 |
quantmind/pulsar | pulsar/utils/httpurl.py | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/httpurl.py#L451-L472 | def patch_vary_headers(response, newheaders):
"""Adds (or updates) the "Vary" header in the given HttpResponse object.
newheaders is a list of header names that should be in "Vary". Existing
headers in "Vary" aren't removed.
For information on the Vary header, see:
http://www.w3.org/Protocols... | [
"def",
"patch_vary_headers",
"(",
"response",
",",
"newheaders",
")",
":",
"# Note that we need to keep the original order intact, because cache",
"# implementations may rely on the order of the Vary contents in, say,",
"# computing an MD5 hash.",
"if",
"'Vary'",
"in",
"response",
":",... | Adds (or updates) the "Vary" header in the given HttpResponse object.
newheaders is a list of header names that should be in "Vary". Existing
headers in "Vary" aren't removed.
For information on the Vary header, see:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44 | [
"Adds",
"(",
"or",
"updates",
")",
"the",
"Vary",
"header",
"in",
"the",
"given",
"HttpResponse",
"object",
"."
] | python | train | 44.636364 |
openstack/networking-cisco | networking_cisco/neutronclient/hostingdevicescheduler.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/neutronclient/hostingdevicescheduler.py#L70-L75 | def associate_hosting_device_with_config_agent(
self, client, config_agent_id, body):
"""Associates a hosting_device with a config agent."""
return client.post((ConfigAgentHandlingHostingDevice.resource_path +
CFG_AGENT_HOSTING_DEVICES) % config_agent_id,
... | [
"def",
"associate_hosting_device_with_config_agent",
"(",
"self",
",",
"client",
",",
"config_agent_id",
",",
"body",
")",
":",
"return",
"client",
".",
"post",
"(",
"(",
"ConfigAgentHandlingHostingDevice",
".",
"resource_path",
"+",
"CFG_AGENT_HOSTING_DEVICES",
")",
... | Associates a hosting_device with a config agent. | [
"Associates",
"a",
"hosting_device",
"with",
"a",
"config",
"agent",
"."
] | python | train | 57.333333 |
dpgaspar/Flask-AppBuilder | flask_appbuilder/console.py | https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/console.py#L218-L224 | def security_cleanup(app, appbuilder):
"""
Cleanup unused permissions from views and roles.
"""
_appbuilder = import_application(app, appbuilder)
_appbuilder.security_cleanup()
click.echo(click.style("Finished security cleanup", fg="green")) | [
"def",
"security_cleanup",
"(",
"app",
",",
"appbuilder",
")",
":",
"_appbuilder",
"=",
"import_application",
"(",
"app",
",",
"appbuilder",
")",
"_appbuilder",
".",
"security_cleanup",
"(",
")",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"\"Fini... | Cleanup unused permissions from views and roles. | [
"Cleanup",
"unused",
"permissions",
"from",
"views",
"and",
"roles",
"."
] | python | train | 37.571429 |
ansible/tower-cli | tower_cli/cli/action.py | https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/action.py#L48-L85 | def format_options(self, ctx, formatter):
"""Monkey-patch click's format_options method to support option categorization.
"""
field_opts = []
global_opts = []
local_opts = []
other_opts = []
for param in self.params:
if param.name in SETTINGS_PARMS:
... | [
"def",
"format_options",
"(",
"self",
",",
"ctx",
",",
"formatter",
")",
":",
"field_opts",
"=",
"[",
"]",
"global_opts",
"=",
"[",
"]",
"local_opts",
"=",
"[",
"]",
"other_opts",
"=",
"[",
"]",
"for",
"param",
"in",
"self",
".",
"params",
":",
"if",... | Monkey-patch click's format_options method to support option categorization. | [
"Monkey",
"-",
"patch",
"click",
"s",
"format_options",
"method",
"to",
"support",
"option",
"categorization",
"."
] | python | valid | 36.947368 |
Tanganelli/CoAPthon3 | coapthon/messages/message.py | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L419-L429 | def del_option_by_number(self, number):
"""
Delete an option from the message by number
:type number: Integer
:param number: option naumber
"""
for o in list(self._options):
assert isinstance(o, Option)
if o.number == number:
self.... | [
"def",
"del_option_by_number",
"(",
"self",
",",
"number",
")",
":",
"for",
"o",
"in",
"list",
"(",
"self",
".",
"_options",
")",
":",
"assert",
"isinstance",
"(",
"o",
",",
"Option",
")",
"if",
"o",
".",
"number",
"==",
"number",
":",
"self",
".",
... | Delete an option from the message by number
:type number: Integer
:param number: option naumber | [
"Delete",
"an",
"option",
"from",
"the",
"message",
"by",
"number"
] | python | train | 29.818182 |
d11wtq/dockerpty | dockerpty/io.py | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/io.py#L380-L388 | def is_done(self):
"""
Returns True if the read stream is done (either it's returned EOF or
the pump doesn't have wait_for_output set), and the write
side does not have pending bytes to send.
"""
return (not self.wait_for_output or self.eof) and \
not (ha... | [
"def",
"is_done",
"(",
"self",
")",
":",
"return",
"(",
"not",
"self",
".",
"wait_for_output",
"or",
"self",
".",
"eof",
")",
"and",
"not",
"(",
"hasattr",
"(",
"self",
".",
"to_stream",
",",
"'needs_write'",
")",
"and",
"self",
".",
"to_stream",
".",
... | Returns True if the read stream is done (either it's returned EOF or
the pump doesn't have wait_for_output set), and the write
side does not have pending bytes to send. | [
"Returns",
"True",
"if",
"the",
"read",
"stream",
"is",
"done",
"(",
"either",
"it",
"s",
"returned",
"EOF",
"or",
"the",
"pump",
"doesn",
"t",
"have",
"wait_for_output",
"set",
")",
"and",
"the",
"write",
"side",
"does",
"not",
"have",
"pending",
"bytes... | python | train | 42.444444 |
robertmartin8/PyPortfolioOpt | pypfopt/base_optimizer.py | https://github.com/robertmartin8/PyPortfolioOpt/blob/dfad1256cb6995c7fbd7a025eedb54b1ca04b2fc/pypfopt/base_optimizer.py#L37-L56 | def clean_weights(self, cutoff=1e-4, rounding=5):
"""
Helper method to clean the raw weights, setting any weights whose absolute
values are below the cutoff to zero, and rounding the rest.
:param cutoff: the lower bound, defaults to 1e-4
:type cutoff: float, optional
:pa... | [
"def",
"clean_weights",
"(",
"self",
",",
"cutoff",
"=",
"1e-4",
",",
"rounding",
"=",
"5",
")",
":",
"if",
"not",
"isinstance",
"(",
"rounding",
",",
"int",
")",
"or",
"rounding",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"rounding must be a positive i... | Helper method to clean the raw weights, setting any weights whose absolute
values are below the cutoff to zero, and rounding the rest.
:param cutoff: the lower bound, defaults to 1e-4
:type cutoff: float, optional
:param rounding: number of decimal places to round the weights, defaults ... | [
"Helper",
"method",
"to",
"clean",
"the",
"raw",
"weights",
"setting",
"any",
"weights",
"whose",
"absolute",
"values",
"are",
"below",
"the",
"cutoff",
"to",
"zero",
"and",
"rounding",
"the",
"rest",
"."
] | python | train | 46 |
pyGrowler/Growler | growler/http/responder.py | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/responder.py#L103-L154 | def on_data(self, data):
"""
This is the function called by the handler object upon
receipt of incoming client data.
The data is passed to the responder's parser class (via the
:method:`consume` method), which digests and stores the HTTP
data.
Upon completion of ... | [
"def",
"on_data",
"(",
"self",
",",
"data",
")",
":",
"# Headers have not been read in yet",
"if",
"len",
"(",
"self",
".",
"headers",
")",
"==",
"0",
":",
"# forward data to the parser",
"data",
"=",
"self",
".",
"parser",
".",
"consume",
"(",
"data",
")",
... | This is the function called by the handler object upon
receipt of incoming client data.
The data is passed to the responder's parser class (via the
:method:`consume` method), which digests and stores the HTTP
data.
Upon completion of parsing the HTTP headers, the responder
... | [
"This",
"is",
"the",
"function",
"called",
"by",
"the",
"handler",
"object",
"upon",
"receipt",
"of",
"incoming",
"client",
"data",
".",
"The",
"data",
"is",
"passed",
"to",
"the",
"responder",
"s",
"parser",
"class",
"(",
"via",
"the",
":",
"method",
":... | python | train | 40.038462 |
spacetelescope/stsci.tools | lib/stsci/tools/teal.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/teal.py#L781-L792 | def _setTaskParsObj(self, theTask):
""" Overridden version for ConfigObj. theTask can be either
a .cfg file name or a ConfigObjPars object. """
# Create the ConfigObjPars obj
self._taskParsObj = cfgpars.getObjectFromTaskArg(theTask,
self._strict, F... | [
"def",
"_setTaskParsObj",
"(",
"self",
",",
"theTask",
")",
":",
"# Create the ConfigObjPars obj",
"self",
".",
"_taskParsObj",
"=",
"cfgpars",
".",
"getObjectFromTaskArg",
"(",
"theTask",
",",
"self",
".",
"_strict",
",",
"False",
")",
"# Tell it that we can be use... | Overridden version for ConfigObj. theTask can be either
a .cfg file name or a ConfigObjPars object. | [
"Overridden",
"version",
"for",
"ConfigObj",
".",
"theTask",
"can",
"be",
"either",
"a",
".",
"cfg",
"file",
"name",
"or",
"a",
"ConfigObjPars",
"object",
"."
] | python | train | 51.583333 |
pyopenapi/pyswagger | pyswagger/primitives/render.py | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/primitives/render.py#L266-L285 | def render(self, obj, opt=None):
""" render a Schema/Parameter
:param obj Schema/Parameter: the swagger spec object
:param opt dict: render option
:return: values that can be passed to Operation.__call__
:rtype: depends on type of 'obj'
"""
opt = self.default() i... | [
"def",
"render",
"(",
"self",
",",
"obj",
",",
"opt",
"=",
"None",
")",
":",
"opt",
"=",
"self",
".",
"default",
"(",
")",
"if",
"opt",
"==",
"None",
"else",
"opt",
"if",
"not",
"isinstance",
"(",
"opt",
",",
"dict",
")",
":",
"raise",
"ValueErro... | render a Schema/Parameter
:param obj Schema/Parameter: the swagger spec object
:param opt dict: render option
:return: values that can be passed to Operation.__call__
:rtype: depends on type of 'obj' | [
"render",
"a",
"Schema",
"/",
"Parameter"
] | python | train | 39.15 |
apple/turicreate | src/external/xgboost/subtree/rabit/wrapper/rabit.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/subtree/rabit/wrapper/rabit.py#L105-L118 | def tracker_print(msg):
"""Print message to the tracker.
This function can be used to communicate the information of
the progress to the tracker
Parameters
----------
msg : str
The message to be printed to tracker.
"""
if not isinstance(msg, str):
msg = str(msg)
_LI... | [
"def",
"tracker_print",
"(",
"msg",
")",
":",
"if",
"not",
"isinstance",
"(",
"msg",
",",
"str",
")",
":",
"msg",
"=",
"str",
"(",
"msg",
")",
"_LIB",
".",
"RabitTrackerPrint",
"(",
"ctypes",
".",
"c_char_p",
"(",
"msg",
")",
".",
"encode",
"(",
"'... | Print message to the tracker.
This function can be used to communicate the information of
the progress to the tracker
Parameters
----------
msg : str
The message to be printed to tracker. | [
"Print",
"message",
"to",
"the",
"tracker",
"."
] | python | train | 26 |
titusjan/argos | argos/config/qtctis.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L145-L149 | def createEditor(self, delegate, parent, option):
""" Creates a ColorCtiEditor.
For the parameters see the AbstractCti constructor documentation.
"""
return ColorCtiEditor(self, delegate, parent=parent) | [
"def",
"createEditor",
"(",
"self",
",",
"delegate",
",",
"parent",
",",
"option",
")",
":",
"return",
"ColorCtiEditor",
"(",
"self",
",",
"delegate",
",",
"parent",
"=",
"parent",
")"
] | Creates a ColorCtiEditor.
For the parameters see the AbstractCti constructor documentation. | [
"Creates",
"a",
"ColorCtiEditor",
".",
"For",
"the",
"parameters",
"see",
"the",
"AbstractCti",
"constructor",
"documentation",
"."
] | python | train | 46.8 |
cggh/scikit-allel | allel/stats/mendel.py | https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/stats/mendel.py#L326-L405 | def phase_progeny_by_transmission(g):
"""Phase progeny genotypes from a trio or cross using Mendelian
transmission.
Parameters
----------
g : array_like, int, shape (n_variants, n_samples, 2)
Genotype array, with parents as first two columns and progeny as
remaining columns.
Re... | [
"def",
"phase_progeny_by_transmission",
"(",
"g",
")",
":",
"# setup",
"g",
"=",
"GenotypeArray",
"(",
"g",
",",
"dtype",
"=",
"'i1'",
",",
"copy",
"=",
"True",
")",
"check_ploidy",
"(",
"g",
".",
"ploidy",
",",
"2",
")",
"check_min_samples",
"(",
"g",
... | Phase progeny genotypes from a trio or cross using Mendelian
transmission.
Parameters
----------
g : array_like, int, shape (n_variants, n_samples, 2)
Genotype array, with parents as first two columns and progeny as
remaining columns.
Returns
-------
g : ndarray, int8, shap... | [
"Phase",
"progeny",
"genotypes",
"from",
"a",
"trio",
"or",
"cross",
"using",
"Mendelian",
"transmission",
"."
] | python | train | 27.575 |
Kortemme-Lab/klab | klab/benchmarking/analysis/ddg_monomeric_stability_analysis.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/benchmarking/analysis/ddg_monomeric_stability_analysis.py#L624-L776 | def get_dataframe_row(self, dataset_cases, predicted_data, pdb_data, record_id, additional_prediction_data_columns):
'''Create a dataframe row for a prediction.'''
# Ignore derived mutations if appropriate
record = dataset_cases[record_id]
if self.is_this_record_a_derived_mutation(recor... | [
"def",
"get_dataframe_row",
"(",
"self",
",",
"dataset_cases",
",",
"predicted_data",
",",
"pdb_data",
",",
"record_id",
",",
"additional_prediction_data_columns",
")",
":",
"# Ignore derived mutations if appropriate",
"record",
"=",
"dataset_cases",
"[",
"record_id",
"]"... | Create a dataframe row for a prediction. | [
"Create",
"a",
"dataframe",
"row",
"for",
"a",
"prediction",
"."
] | python | train | 47.993464 |
fermiPy/fermipy | fermipy/version.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/version.py#L62-L74 | def render_pep440(vcs):
"""Convert git release tag into a form that is PEP440 compliant."""
if vcs is None:
return None
tags = vcs.split('-')
# Bare version number
if len(tags) == 1:
return tags[0]
else:
return tags[0] + '+' + '.'.join(tags[1:]) | [
"def",
"render_pep440",
"(",
"vcs",
")",
":",
"if",
"vcs",
"is",
"None",
":",
"return",
"None",
"tags",
"=",
"vcs",
".",
"split",
"(",
"'-'",
")",
"# Bare version number",
"if",
"len",
"(",
"tags",
")",
"==",
"1",
":",
"return",
"tags",
"[",
"0",
"... | Convert git release tag into a form that is PEP440 compliant. | [
"Convert",
"git",
"release",
"tag",
"into",
"a",
"form",
"that",
"is",
"PEP440",
"compliant",
"."
] | python | train | 21.846154 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L395-L404 | def delete_fw(self, tenant_id, data):
"""Top level routine called when a FW is deleted. """
try:
ret = self._delete_fw(tenant_id, data)
return ret
except Exception as exc:
LOG.error("Failed to delete FW for device native, tenant "
"%(tena... | [
"def",
"delete_fw",
"(",
"self",
",",
"tenant_id",
",",
"data",
")",
":",
"try",
":",
"ret",
"=",
"self",
".",
"_delete_fw",
"(",
"tenant_id",
",",
"data",
")",
"return",
"ret",
"except",
"Exception",
"as",
"exc",
":",
"LOG",
".",
"error",
"(",
"\"Fa... | Top level routine called when a FW is deleted. | [
"Top",
"level",
"routine",
"called",
"when",
"a",
"FW",
"is",
"deleted",
"."
] | python | train | 43.9 |
marrabld/planarradpy | gui/gui_mainLayout.py | https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/gui/gui_mainLayout.py#L645-L674 | def run(self):
"""
This function executes planarRad using the batch file.
"""
"""
Error when planarRad start : /bin/sh: 1: ../planarrad.py: not found
"""
print('Executing planarrad')
# If we are not in the reverse_mode :
if self.ui.tabWidget.curre... | [
"def",
"run",
"(",
"self",
")",
":",
"\"\"\"\n Error when planarRad start : /bin/sh: 1: ../planarrad.py: not found\n \"\"\"",
"print",
"(",
"'Executing planarrad'",
")",
"# If we are not in the reverse_mode :",
"if",
"self",
".",
"ui",
".",
"tabWidget",
".",
"curr... | This function executes planarRad using the batch file. | [
"This",
"function",
"executes",
"planarRad",
"using",
"the",
"batch",
"file",
"."
] | python | test | 41.366667 |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QASetting/crontab.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASetting/crontab.py#L51-L62 | def next_time(self, asc=False):
"""Get the local time of the next schedule time this job will run.
:param bool asc: Format the result with ``time.asctime()``
:returns: The epoch time or string representation of the epoch time that
the job should be run next
"""
_time ... | [
"def",
"next_time",
"(",
"self",
",",
"asc",
"=",
"False",
")",
":",
"_time",
"=",
"time",
".",
"localtime",
"(",
"time",
".",
"time",
"(",
")",
"+",
"self",
".",
"next",
"(",
")",
")",
"if",
"asc",
":",
"return",
"time",
".",
"asctime",
"(",
"... | Get the local time of the next schedule time this job will run.
:param bool asc: Format the result with ``time.asctime()``
:returns: The epoch time or string representation of the epoch time that
the job should be run next | [
"Get",
"the",
"local",
"time",
"of",
"the",
"next",
"schedule",
"time",
"this",
"job",
"will",
"run",
".",
":",
"param",
"bool",
"asc",
":",
"Format",
"the",
"result",
"with",
"time",
".",
"asctime",
"()",
":",
"returns",
":",
"The",
"epoch",
"time",
... | python | train | 36.916667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.