repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/utils.py | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/utils.py#L147-L158 | def crypto_config_from_cache(materials_provider, attribute_actions, table_info_cache, table_name):
"""Build a crypto config from the provided values, loading the table info from the provided cache.
:returns: crypto config and updated kwargs
:rtype: tuple(CryptoConfig, dict)
"""
table_info = table_i... | [
"def",
"crypto_config_from_cache",
"(",
"materials_provider",
",",
"attribute_actions",
",",
"table_info_cache",
",",
"table_name",
")",
":",
"table_info",
"=",
"table_info_cache",
".",
"table_info",
"(",
"table_name",
")",
"attribute_actions",
"=",
"attribute_actions",
... | Build a crypto config from the provided values, loading the table info from the provided cache.
:returns: crypto config and updated kwargs
:rtype: tuple(CryptoConfig, dict) | [
"Build",
"a",
"crypto",
"config",
"from",
"the",
"provided",
"values",
"loading",
"the",
"table",
"info",
"from",
"the",
"provided",
"cache",
"."
] | python | train |
rosenbrockc/fortpy | fortpy/elements.py | https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/elements.py#L1315-L1327 | def first(self):
"""Returns the first module procedure embedded in the interface that has a valid
instance of a CodeElement.
"""
if self._first is None:
for target in self.targets:
if target is not None:
self._first = target
... | [
"def",
"first",
"(",
"self",
")",
":",
"if",
"self",
".",
"_first",
"is",
"None",
":",
"for",
"target",
"in",
"self",
".",
"targets",
":",
"if",
"target",
"is",
"not",
"None",
":",
"self",
".",
"_first",
"=",
"target",
"break",
"else",
":",
"self",... | Returns the first module procedure embedded in the interface that has a valid
instance of a CodeElement. | [
"Returns",
"the",
"first",
"module",
"procedure",
"embedded",
"in",
"the",
"interface",
"that",
"has",
"a",
"valid",
"instance",
"of",
"a",
"CodeElement",
"."
] | python | train |
miku/gluish | gluish/task.py | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/gluish/task.py#L46-L51 | def is_closest_date_parameter(task, param_name):
""" Return the parameter class of param_name on task. """
for name, obj in task.get_params():
if name == param_name:
return hasattr(obj, 'use_closest_date')
return False | [
"def",
"is_closest_date_parameter",
"(",
"task",
",",
"param_name",
")",
":",
"for",
"name",
",",
"obj",
"in",
"task",
".",
"get_params",
"(",
")",
":",
"if",
"name",
"==",
"param_name",
":",
"return",
"hasattr",
"(",
"obj",
",",
"'use_closest_date'",
")",... | Return the parameter class of param_name on task. | [
"Return",
"the",
"parameter",
"class",
"of",
"param_name",
"on",
"task",
"."
] | python | train |
i3visio/osrframework | osrframework/utils/browser.py | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/browser.py#L141-L182 | def recoverURL(self, url):
"""
Public method to recover a resource.
Args:
-----
url: The URL to be collected.
Returns:
--------
Returns a resource that has to be read, for instance, with html = self.br.read()
"""
# Configuring use... | [
"def",
"recoverURL",
"(",
"self",
",",
"url",
")",
":",
"# Configuring user agents...",
"self",
".",
"setUserAgent",
"(",
")",
"# Configuring proxies",
"if",
"\"https://\"",
"in",
"url",
":",
"self",
".",
"setProxy",
"(",
"protocol",
"=",
"\"https\"",
")",
"el... | Public method to recover a resource.
Args:
-----
url: The URL to be collected.
Returns:
--------
Returns a resource that has to be read, for instance, with html = self.br.read() | [
"Public",
"method",
"to",
"recover",
"a",
"resource",
"."
] | python | train |
maartenbreddels/ipyvolume | ipyvolume/pylab.py | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L290-L302 | def squarelim():
"""Set all axes with equal aspect ratio, such that the space is 'square'."""
fig = gcf()
xmin, xmax = fig.xlim
ymin, ymax = fig.ylim
zmin, zmax = fig.zlim
width = max([abs(xmax - xmin), abs(ymax - ymin), abs(zmax - zmin)])
xc = (xmin + xmax) / 2
yc = (ymin + ymax) / 2
... | [
"def",
"squarelim",
"(",
")",
":",
"fig",
"=",
"gcf",
"(",
")",
"xmin",
",",
"xmax",
"=",
"fig",
".",
"xlim",
"ymin",
",",
"ymax",
"=",
"fig",
".",
"ylim",
"zmin",
",",
"zmax",
"=",
"fig",
".",
"zlim",
"width",
"=",
"max",
"(",
"[",
"abs",
"(... | Set all axes with equal aspect ratio, such that the space is 'square'. | [
"Set",
"all",
"axes",
"with",
"equal",
"aspect",
"ratio",
"such",
"that",
"the",
"space",
"is",
"square",
"."
] | python | train |
etingof/pysnmp | pysnmp/smi/rfc1902.py | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L1135-L1165 | def addAsn1MibSource(self, *asn1Sources, **kwargs):
"""Adds path to a repository to search ASN.1 MIB files.
Parameters
----------
*asn1Sources :
one or more URL in form of :py:obj:`str` identifying local or
remote ASN.1 MIB repositories. Path must include the *@m... | [
"def",
"addAsn1MibSource",
"(",
"self",
",",
"*",
"asn1Sources",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_objectIdentity",
".",
"addAsn1MibSource",
"(",
"*",
"asn1Sources",
",",
"*",
"*",
"kwargs",
")",
"return",
"self"
] | Adds path to a repository to search ASN.1 MIB files.
Parameters
----------
*asn1Sources :
one or more URL in form of :py:obj:`str` identifying local or
remote ASN.1 MIB repositories. Path must include the *@mib@*
component which will be replaced with MIB modu... | [
"Adds",
"path",
"to",
"a",
"repository",
"to",
"search",
"ASN",
".",
"1",
"MIB",
"files",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py#L76-L84 | def reset_sgr(self):
""" Reset graphics attributs to their default values.
"""
self.intensity = 0
self.italic = False
self.bold = False
self.underline = False
self.foreground_color = None
self.background_color = None | [
"def",
"reset_sgr",
"(",
"self",
")",
":",
"self",
".",
"intensity",
"=",
"0",
"self",
".",
"italic",
"=",
"False",
"self",
".",
"bold",
"=",
"False",
"self",
".",
"underline",
"=",
"False",
"self",
".",
"foreground_color",
"=",
"None",
"self",
".",
... | Reset graphics attributs to their default values. | [
"Reset",
"graphics",
"attributs",
"to",
"their",
"default",
"values",
"."
] | python | test |
RetailMeNotSandbox/acky | acky/ec2.py | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L515-L519 | def attach(self, volume_id, instance_id, device_path):
"""Attach a volume to an instance, exposing it with a device name."""
return self.call("AttachVolume",
VolumeId=volume_id, InstanceId=instance_id,
Device=device_path) | [
"def",
"attach",
"(",
"self",
",",
"volume_id",
",",
"instance_id",
",",
"device_path",
")",
":",
"return",
"self",
".",
"call",
"(",
"\"AttachVolume\"",
",",
"VolumeId",
"=",
"volume_id",
",",
"InstanceId",
"=",
"instance_id",
",",
"Device",
"=",
"device_pa... | Attach a volume to an instance, exposing it with a device name. | [
"Attach",
"a",
"volume",
"to",
"an",
"instance",
"exposing",
"it",
"with",
"a",
"device",
"name",
"."
] | python | train |
wonambi-python/wonambi | wonambi/widgets/notes.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L1838-L1847 | def update_event_types(self):
"""Update event types in event type box."""
self.idx_evt_type.clear()
self.idx_evt_type.setSelectionMode(QAbstractItemView.ExtendedSelection)
event_types = sorted(self.parent.notes.annot.event_types,
key=str.lower)
for t... | [
"def",
"update_event_types",
"(",
"self",
")",
":",
"self",
".",
"idx_evt_type",
".",
"clear",
"(",
")",
"self",
".",
"idx_evt_type",
".",
"setSelectionMode",
"(",
"QAbstractItemView",
".",
"ExtendedSelection",
")",
"event_types",
"=",
"sorted",
"(",
"self",
"... | Update event types in event type box. | [
"Update",
"event",
"types",
"in",
"event",
"type",
"box",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_ras_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ras_ext.py#L12-L23 | def show_raslog_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_raslog = ET.Element("show_raslog")
config = show_raslog
input = ET.SubElement(show_raslog, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
... | [
"def",
"show_raslog_input_rbridge_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_raslog",
"=",
"ET",
".",
"Element",
"(",
"\"show_raslog\"",
")",
"config",
"=",
"show_raslog",
"input",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
opencobra/memote | memote/support/helpers.py | https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/support/helpers.py#L184-L217 | def is_transport_reaction_formulae(rxn):
"""
Return boolean if a reaction is a transport reaction (from formulae).
Parameters
----------
rxn: cobra.Reaction
The metabolic reaction under investigation.
"""
# Collecting criteria to classify transporters by.
rxn_reactants = set([m... | [
"def",
"is_transport_reaction_formulae",
"(",
"rxn",
")",
":",
"# Collecting criteria to classify transporters by.",
"rxn_reactants",
"=",
"set",
"(",
"[",
"met",
".",
"formula",
"for",
"met",
"in",
"rxn",
".",
"reactants",
"]",
")",
"rxn_products",
"=",
"set",
"(... | Return boolean if a reaction is a transport reaction (from formulae).
Parameters
----------
rxn: cobra.Reaction
The metabolic reaction under investigation. | [
"Return",
"boolean",
"if",
"a",
"reaction",
"is",
"a",
"transport",
"reaction",
"(",
"from",
"formulae",
")",
"."
] | python | train |
lsst-sqre/documenteer | documenteer/stackdocs/build.py | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/stackdocs/build.py#L249-L395 | def find_package_docs(package_dir, skippedNames=None):
"""Find documentation directories in a package using ``manifest.yaml``.
Parameters
----------
package_dir : `str`
Directory of an EUPS package.
skippedNames : `list` of `str`, optional
List of package or module names to skip whe... | [
"def",
"find_package_docs",
"(",
"package_dir",
",",
"skippedNames",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"if",
"skippedNames",
"is",
"None",
":",
"skippedNames",
"=",
"[",
"]",
"doc_dir",
"=",
"os",
".",... | Find documentation directories in a package using ``manifest.yaml``.
Parameters
----------
package_dir : `str`
Directory of an EUPS package.
skippedNames : `list` of `str`, optional
List of package or module names to skip when creating links.
Returns
-------
doc_dirs : name... | [
"Find",
"documentation",
"directories",
"in",
"a",
"package",
"using",
"manifest",
".",
"yaml",
"."
] | python | train |
101Loop/drf-addons | drfaddons/auth.py | https://github.com/101Loop/drf-addons/blob/62392c72e8bce237f4140a2b7171e89984cb15c5/drfaddons/auth.py#L27-L55 | def get_authorization(self, request):
"""
This function extracts the authorization JWT string. It first
looks for specified key in header and then looks
for the same in body part.
Parameters
----------
request: HttpRequest
This is the raw request that... | [
"def",
"get_authorization",
"(",
"self",
",",
"request",
")",
":",
"from",
"django",
".",
"utils",
".",
"six",
"import",
"text_type",
"from",
"rest_framework",
"import",
"HTTP_HEADER_ENCODING",
"auth",
"=",
"request",
".",
"data",
".",
"get",
"(",
"self",
".... | This function extracts the authorization JWT string. It first
looks for specified key in header and then looks
for the same in body part.
Parameters
----------
request: HttpRequest
This is the raw request that user has sent.
Returns
-------
a... | [
"This",
"function",
"extracts",
"the",
"authorization",
"JWT",
"string",
".",
"It",
"first",
"looks",
"for",
"specified",
"key",
"in",
"header",
"and",
"then",
"looks",
"for",
"the",
"same",
"in",
"body",
"part",
"."
] | python | train |
vertexproject/synapse | synapse/lib/cli.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/cli.py#L339-L386 | async def runCmdLoop(self):
'''
Run commands from a user in an interactive fashion until fini() or EOFError is raised.
'''
while not self.isfini:
# FIXME completion
self.cmdtask = None
try:
line = await self.prompt()
... | [
"async",
"def",
"runCmdLoop",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"isfini",
":",
"# FIXME completion",
"self",
".",
"cmdtask",
"=",
"None",
"try",
":",
"line",
"=",
"await",
"self",
".",
"prompt",
"(",
")",
"if",
"not",
"line",
":",
"... | Run commands from a user in an interactive fashion until fini() or EOFError is raised. | [
"Run",
"commands",
"from",
"a",
"user",
"in",
"an",
"interactive",
"fashion",
"until",
"fini",
"()",
"or",
"EOFError",
"is",
"raised",
"."
] | python | train |
tanghaibao/jcvi | jcvi/compara/catalog.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/catalog.py#L492-L559 | def omgprepare(args):
"""
%prog omgprepare ploidy anchorsfile blastfile
Prepare to run Sankoff's OMG algorithm to get orthologs.
"""
from jcvi.formats.blast import cscore
from jcvi.formats.base import DictFile
p = OptionParser(omgprepare.__doc__)
p.add_option("--norbh", action="store_t... | [
"def",
"omgprepare",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"blast",
"import",
"cscore",
"from",
"jcvi",
".",
"formats",
".",
"base",
"import",
"DictFile",
"p",
"=",
"OptionParser",
"(",
"omgprepare",
".",
"__doc__",
")",
"p",
".",
... | %prog omgprepare ploidy anchorsfile blastfile
Prepare to run Sankoff's OMG algorithm to get orthologs. | [
"%prog",
"omgprepare",
"ploidy",
"anchorsfile",
"blastfile"
] | python | train |
pypa/pipenv | pipenv/vendor/pexpect/pty_spawn.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L563-L574 | def sendcontrol(self, char):
'''Helper method that wraps send() with mnemonic access for sending control
character to the child (such as Ctrl-C or Ctrl-D). For example, to send
Ctrl-G (ASCII 7, bell, '\a')::
child.sendcontrol('g')
See also, sendintr() and sendeof().
... | [
"def",
"sendcontrol",
"(",
"self",
",",
"char",
")",
":",
"n",
",",
"byte",
"=",
"self",
".",
"ptyproc",
".",
"sendcontrol",
"(",
"char",
")",
"self",
".",
"_log_control",
"(",
"byte",
")",
"return",
"n"
] | Helper method that wraps send() with mnemonic access for sending control
character to the child (such as Ctrl-C or Ctrl-D). For example, to send
Ctrl-G (ASCII 7, bell, '\a')::
child.sendcontrol('g')
See also, sendintr() and sendeof(). | [
"Helper",
"method",
"that",
"wraps",
"send",
"()",
"with",
"mnemonic",
"access",
"for",
"sending",
"control",
"character",
"to",
"the",
"child",
"(",
"such",
"as",
"Ctrl",
"-",
"C",
"or",
"Ctrl",
"-",
"D",
")",
".",
"For",
"example",
"to",
"send",
"Ctr... | python | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/extract.py | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/extract.py#L440-L559 | def fatigue_eval_med_freq(data, sample_rate, time_units=True, raw_to_mv=True,
device="biosignalsplux", resolution=16, show_plot=False):
"""
-----
Brief
-----
Returns the evolution time series of EMG median frequency along the acquisition, based on a sliding window
mecha... | [
"def",
"fatigue_eval_med_freq",
"(",
"data",
",",
"sample_rate",
",",
"time_units",
"=",
"True",
",",
"raw_to_mv",
"=",
"True",
",",
"device",
"=",
"\"biosignalsplux\"",
",",
"resolution",
"=",
"16",
",",
"show_plot",
"=",
"False",
")",
":",
"# Conversion of d... | -----
Brief
-----
Returns the evolution time series of EMG median frequency along the acquisition, based on a sliding window
mechanism.
-----------
Description
-----------
The median frequency of activation events in EMG signal is particularly important in fatigue evaluation methods.
... | [
"-----",
"Brief",
"-----",
"Returns",
"the",
"evolution",
"time",
"series",
"of",
"EMG",
"median",
"frequency",
"along",
"the",
"acquisition",
"based",
"on",
"a",
"sliding",
"window",
"mechanism",
"."
] | python | train |
tensorflow/probability | tensorflow_probability/python/optimizer/linesearch/hager_zhang.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/hager_zhang.py#L420-L542 | def _line_search_after_bracketing(
value_and_gradients_function,
search_interval,
val_0,
f_lim,
max_iterations,
sufficient_decrease_param,
curvature_param,
shrinkage_param):
"""The main loop of line search after the minimum has been bracketed.
Args:
value_and_gradients_function:... | [
"def",
"_line_search_after_bracketing",
"(",
"value_and_gradients_function",
",",
"search_interval",
",",
"val_0",
",",
"f_lim",
",",
"max_iterations",
",",
"sufficient_decrease_param",
",",
"curvature_param",
",",
"shrinkage_param",
")",
":",
"def",
"_loop_cond",
"(",
... | The main loop of line search after the minimum has been bracketed.
Args:
value_and_gradients_function: A Python callable that accepts a real scalar
tensor and returns a namedtuple with the fields 'x', 'f', and 'df' that
correspond to scalar tensors of real dtype containing the point at which
th... | [
"The",
"main",
"loop",
"of",
"line",
"search",
"after",
"the",
"minimum",
"has",
"been",
"bracketed",
"."
] | python | test |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/isogeo_sdk.py | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/isogeo_sdk.py#L887-L901 | def add_tags_shares(self, tags: dict = dict()):
"""Add shares list to the tags attributes in search results.
:param dict tags: tags dictionary from a search request
"""
# check if shares_id have already been retrieved or not
if not hasattr(self, "shares_id"):
shares ... | [
"def",
"add_tags_shares",
"(",
"self",
",",
"tags",
":",
"dict",
"=",
"dict",
"(",
")",
")",
":",
"# check if shares_id have already been retrieved or not",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"shares_id\"",
")",
":",
"shares",
"=",
"self",
".",
"share... | Add shares list to the tags attributes in search results.
:param dict tags: tags dictionary from a search request | [
"Add",
"shares",
"list",
"to",
"the",
"tags",
"attributes",
"in",
"search",
"results",
"."
] | python | train |
rytilahti/python-songpal | songpal/group.py | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/group.py#L125-L133 | async def call(self, action, **kwargs):
"""Make an action call with given kwargs."""
act = self.service.action(action)
_LOGGER.info("Calling %s with %s", action, kwargs)
res = await act.async_call(**kwargs)
_LOGGER.info(" Result: %s" % res)
return res | [
"async",
"def",
"call",
"(",
"self",
",",
"action",
",",
"*",
"*",
"kwargs",
")",
":",
"act",
"=",
"self",
".",
"service",
".",
"action",
"(",
"action",
")",
"_LOGGER",
".",
"info",
"(",
"\"Calling %s with %s\"",
",",
"action",
",",
"kwargs",
")",
"r... | Make an action call with given kwargs. | [
"Make",
"an",
"action",
"call",
"with",
"given",
"kwargs",
"."
] | python | train |
20c/munge | munge/codec/__init__.py | https://github.com/20c/munge/blob/e20fef8c24e48d4b0a5c387820fbb2b7bebb0af0/munge/codec/__init__.py#L66-L80 | def load_datafile(name, search_path=('.'), codecs=get_codecs(), **kwargs):
"""
find datafile and load them from codec
TODO only does the first one
kwargs:
default = if passed will return that on failure instead of throwing
"""
mod = find_datafile(name, search_path, codecs)
if not mod:
... | [
"def",
"load_datafile",
"(",
"name",
",",
"search_path",
"=",
"(",
"'.'",
")",
",",
"codecs",
"=",
"get_codecs",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"mod",
"=",
"find_datafile",
"(",
"name",
",",
"search_path",
",",
"codecs",
")",
"if",
"not... | find datafile and load them from codec
TODO only does the first one
kwargs:
default = if passed will return that on failure instead of throwing | [
"find",
"datafile",
"and",
"load",
"them",
"from",
"codec",
"TODO",
"only",
"does",
"the",
"first",
"one",
"kwargs",
":",
"default",
"=",
"if",
"passed",
"will",
"return",
"that",
"on",
"failure",
"instead",
"of",
"throwing"
] | python | train |
ray-project/ray | python/ray/experimental/serve/mixin.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/serve/mixin.py#L50-L63 | def _dispatch(self, input_batch: List[SingleQuery]):
"""Helper method to dispatch a batch of input to self.serve_method."""
method = getattr(self, self.serve_method)
if hasattr(method, "ray_serve_batched_input"):
batch = [inp.data for inp in input_batch]
result = _execute... | [
"def",
"_dispatch",
"(",
"self",
",",
"input_batch",
":",
"List",
"[",
"SingleQuery",
"]",
")",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"self",
".",
"serve_method",
")",
"if",
"hasattr",
"(",
"method",
",",
"\"ray_serve_batched_input\"",
")",
":",... | Helper method to dispatch a batch of input to self.serve_method. | [
"Helper",
"method",
"to",
"dispatch",
"a",
"batch",
"of",
"input",
"to",
"self",
".",
"serve_method",
"."
] | python | train |
PyconUK/ConferenceScheduler | src/conference_scheduler/scheduler.py | https://github.com/PyconUK/ConferenceScheduler/blob/fb139f0ef2eab5ac8f4919aa4994d94d4e040030/src/conference_scheduler/scheduler.py#L290-L349 | def slot_schedule_difference(old_schedule, new_schedule):
"""Compute the difference between two schedules from a slot perspective
Parameters
----------
old_schedule : list or tuple
of :py:class:`resources.ScheduledItem` objects
new_schedule : list or tuple
of :py:class:`resources.Sc... | [
"def",
"slot_schedule_difference",
"(",
"old_schedule",
",",
"new_schedule",
")",
":",
"old",
"=",
"{",
"item",
".",
"slot",
":",
"item",
"for",
"item",
"in",
"old_schedule",
"}",
"new",
"=",
"{",
"item",
".",
"slot",
":",
"item",
"for",
"item",
"in",
... | Compute the difference between two schedules from a slot perspective
Parameters
----------
old_schedule : list or tuple
of :py:class:`resources.ScheduledItem` objects
new_schedule : list or tuple
of :py:class:`resources.ScheduledItem` objects
Returns
-------
list
A ... | [
"Compute",
"the",
"difference",
"between",
"two",
"schedules",
"from",
"a",
"slot",
"perspective"
] | python | train |
ahmontero/dop | dop/client.py | https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L169-L182 | def reboot_droplet(self, droplet_id):
"""
This method allows you to reboot a droplet. This is the preferred method
to use if a server is not responding.
"""
if not droplet_id:
raise DOPException('droplet_id is required to reboot a droplet!')
json = self.reques... | [
"def",
"reboot_droplet",
"(",
"self",
",",
"droplet_id",
")",
":",
"if",
"not",
"droplet_id",
":",
"raise",
"DOPException",
"(",
"'droplet_id is required to reboot a droplet!'",
")",
"json",
"=",
"self",
".",
"request",
"(",
"'/droplets/%s/reboot'",
"%",
"droplet_id... | This method allows you to reboot a droplet. This is the preferred method
to use if a server is not responding. | [
"This",
"method",
"allows",
"you",
"to",
"reboot",
"a",
"droplet",
".",
"This",
"is",
"the",
"preferred",
"method",
"to",
"use",
"if",
"a",
"server",
"is",
"not",
"responding",
"."
] | python | train |
twisted/mantissa | xmantissa/interstore.py | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/interstore.py#L662-L671 | def _messageFromSender(self, sender, messageID):
"""
Locate a previously queued message by a given sender and messageID.
"""
return self.store.findUnique(
_QueuedMessage,
AND(_QueuedMessage.senderUsername == sender.localpart,
_QueuedMessage.senderD... | [
"def",
"_messageFromSender",
"(",
"self",
",",
"sender",
",",
"messageID",
")",
":",
"return",
"self",
".",
"store",
".",
"findUnique",
"(",
"_QueuedMessage",
",",
"AND",
"(",
"_QueuedMessage",
".",
"senderUsername",
"==",
"sender",
".",
"localpart",
",",
"_... | Locate a previously queued message by a given sender and messageID. | [
"Locate",
"a",
"previously",
"queued",
"message",
"by",
"a",
"given",
"sender",
"and",
"messageID",
"."
] | python | train |
nfcpy/nfcpy | src/nfc/snep/client.py | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/snep/client.py#L156-L176 | def get_records(self, records=None, timeout=1.0):
"""Get NDEF message records from a SNEP Server.
.. versionadded:: 0.13
The :class:`ndef.Record` list given by *records* is encoded as
the request message octets input to :meth:`get_octets`. The
return value is an :class:`ndef.Re... | [
"def",
"get_records",
"(",
"self",
",",
"records",
"=",
"None",
",",
"timeout",
"=",
"1.0",
")",
":",
"octets",
"=",
"b''",
".",
"join",
"(",
"ndef",
".",
"message_encoder",
"(",
"records",
")",
")",
"if",
"records",
"else",
"None",
"octets",
"=",
"s... | Get NDEF message records from a SNEP Server.
.. versionadded:: 0.13
The :class:`ndef.Record` list given by *records* is encoded as
the request message octets input to :meth:`get_octets`. The
return value is an :class:`ndef.Record` list decoded from the
response message octets r... | [
"Get",
"NDEF",
"message",
"records",
"from",
"a",
"SNEP",
"Server",
"."
] | python | train |
pandas-dev/pandas | pandas/core/arrays/datetimelike.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L1441-L1465 | def validate_periods(periods):
"""
If a `periods` argument is passed to the Datetime/Timedelta Array/Index
constructor, cast it to an integer.
Parameters
----------
periods : None, float, int
Returns
-------
periods : None or int
Raises
------
TypeError
if peri... | [
"def",
"validate_periods",
"(",
"periods",
")",
":",
"if",
"periods",
"is",
"not",
"None",
":",
"if",
"lib",
".",
"is_float",
"(",
"periods",
")",
":",
"periods",
"=",
"int",
"(",
"periods",
")",
"elif",
"not",
"lib",
".",
"is_integer",
"(",
"periods",... | If a `periods` argument is passed to the Datetime/Timedelta Array/Index
constructor, cast it to an integer.
Parameters
----------
periods : None, float, int
Returns
-------
periods : None or int
Raises
------
TypeError
if periods is None, float, or int | [
"If",
"a",
"periods",
"argument",
"is",
"passed",
"to",
"the",
"Datetime",
"/",
"Timedelta",
"Array",
"/",
"Index",
"constructor",
"cast",
"it",
"to",
"an",
"integer",
"."
] | python | train |
tensorforce/tensorforce | tensorforce/agents/learning_agent.py | https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/agents/learning_agent.py#L144-L194 | def import_experience(self, experiences):
"""
Imports experiences.
Args:
experiences:
"""
if isinstance(experiences, dict):
if self.unique_state:
experiences['states'] = dict(state=experiences['states'])
if self.unique_action:... | [
"def",
"import_experience",
"(",
"self",
",",
"experiences",
")",
":",
"if",
"isinstance",
"(",
"experiences",
",",
"dict",
")",
":",
"if",
"self",
".",
"unique_state",
":",
"experiences",
"[",
"'states'",
"]",
"=",
"dict",
"(",
"state",
"=",
"experiences"... | Imports experiences.
Args:
experiences: | [
"Imports",
"experiences",
"."
] | python | valid |
python-diamond/Diamond | src/collectors/elb/elb.py | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/elb/elb.py#L109-L116 | def get_zones(region, auth_kwargs):
"""
:param auth_kwargs:
:param region: region to get the availability zones for
:return: list of availability zones
"""
ec2_conn = boto.ec2.connect_to_region(region, **auth_kwargs)
return [zone.name for zone in ec2_conn.get_all_zones()] | [
"def",
"get_zones",
"(",
"region",
",",
"auth_kwargs",
")",
":",
"ec2_conn",
"=",
"boto",
".",
"ec2",
".",
"connect_to_region",
"(",
"region",
",",
"*",
"*",
"auth_kwargs",
")",
"return",
"[",
"zone",
".",
"name",
"for",
"zone",
"in",
"ec2_conn",
".",
... | :param auth_kwargs:
:param region: region to get the availability zones for
:return: list of availability zones | [
":",
"param",
"auth_kwargs",
":",
":",
"param",
"region",
":",
"region",
"to",
"get",
"the",
"availability",
"zones",
"for",
":",
"return",
":",
"list",
"of",
"availability",
"zones"
] | python | train |
keon/algorithms | algorithms/tree/is_balanced.py | https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/is_balanced.py#L12-L22 | def __get_depth(root):
"""
return 0 if unbalanced else depth + 1
"""
if root is None:
return 0
left = __get_depth(root.left)
right = __get_depth(root.right)
if abs(left-right) > 1 or -1 in [left, right]:
return -1
return 1 + max(left, right) | [
"def",
"__get_depth",
"(",
"root",
")",
":",
"if",
"root",
"is",
"None",
":",
"return",
"0",
"left",
"=",
"__get_depth",
"(",
"root",
".",
"left",
")",
"right",
"=",
"__get_depth",
"(",
"root",
".",
"right",
")",
"if",
"abs",
"(",
"left",
"-",
"rig... | return 0 if unbalanced else depth + 1 | [
"return",
"0",
"if",
"unbalanced",
"else",
"depth",
"+",
"1"
] | python | train |
dnanexus/dx-toolkit | src/python/dxpy/bindings/__init__.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/bindings/__init__.py#L32-L52 | def verify_string_dxid(dxid, expected_classes):
'''
:param dxid: Value to verify as a DNAnexus ID of class *expected_class*
:param expected_classes: Single string or list of strings of allowed classes of the ID, e.g. "file" or ["project", "container"]
:type expected_classes: string or list of strings
... | [
"def",
"verify_string_dxid",
"(",
"dxid",
",",
"expected_classes",
")",
":",
"if",
"isinstance",
"(",
"expected_classes",
",",
"basestring",
")",
":",
"expected_classes",
"=",
"[",
"expected_classes",
"]",
"if",
"not",
"isinstance",
"(",
"expected_classes",
",",
... | :param dxid: Value to verify as a DNAnexus ID of class *expected_class*
:param expected_classes: Single string or list of strings of allowed classes of the ID, e.g. "file" or ["project", "container"]
:type expected_classes: string or list of strings
:raises: :exc:`~dxpy.exceptions.DXError` if *dxid* is not ... | [
":",
"param",
"dxid",
":",
"Value",
"to",
"verify",
"as",
"a",
"DNAnexus",
"ID",
"of",
"class",
"*",
"expected_class",
"*",
":",
"param",
"expected_classes",
":",
"Single",
"string",
"or",
"list",
"of",
"strings",
"of",
"allowed",
"classes",
"of",
"the",
... | python | train |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L168-L212 | def _get_remote_ontology(onto_url, time_difference=None):
"""Check if the online ontology is more recent than the local ontology.
If yes, try to download and store it in Invenio's cache directory.
Return a boolean describing the success of the operation.
:return: path to the downloaded ontology.
... | [
"def",
"_get_remote_ontology",
"(",
"onto_url",
",",
"time_difference",
"=",
"None",
")",
":",
"if",
"onto_url",
"is",
"None",
":",
"return",
"False",
"dl_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"current_app",
".",
"config",
"[",
"\"CLASSIFIER_WORKDI... | Check if the online ontology is more recent than the local ontology.
If yes, try to download and store it in Invenio's cache directory.
Return a boolean describing the success of the operation.
:return: path to the downloaded ontology. | [
"Check",
"if",
"the",
"online",
"ontology",
"is",
"more",
"recent",
"than",
"the",
"local",
"ontology",
"."
] | python | train |
koordinates/python-client | koordinates/layers.py | https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/layers.py#L96-L109 | def create_draft(self, layer_id):
"""
Creates a new draft version.
If anything in the data object has changed then an import will begin immediately.
Otherwise to force a re-import from the previous sources call :py:meth:`koordinates.layers.LayerManager.start_import`.
:rtype: La... | [
"def",
"create_draft",
"(",
"self",
",",
"layer_id",
")",
":",
"target_url",
"=",
"self",
".",
"client",
".",
"get_url",
"(",
"'VERSION'",
",",
"'POST'",
",",
"'create'",
",",
"{",
"'layer_id'",
":",
"layer_id",
"}",
")",
"r",
"=",
"self",
".",
"client... | Creates a new draft version.
If anything in the data object has changed then an import will begin immediately.
Otherwise to force a re-import from the previous sources call :py:meth:`koordinates.layers.LayerManager.start_import`.
:rtype: Layer
:return: the new version
:raises C... | [
"Creates",
"a",
"new",
"draft",
"version",
"."
] | python | train |
gtaylor/python-colormath | colormath/color_conversions.py | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L853-L863 | def CMYK_to_CMY(cobj, *args, **kwargs):
"""
Converts CMYK to CMY.
NOTE: CMYK and CMY values range from 0.0 to 1.0
"""
cmy_c = cobj.cmyk_c * (1.0 - cobj.cmyk_k) + cobj.cmyk_k
cmy_m = cobj.cmyk_m * (1.0 - cobj.cmyk_k) + cobj.cmyk_k
cmy_y = cobj.cmyk_y * (1.0 - cobj.cmyk_k) + cobj.cmyk_k
... | [
"def",
"CMYK_to_CMY",
"(",
"cobj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cmy_c",
"=",
"cobj",
".",
"cmyk_c",
"*",
"(",
"1.0",
"-",
"cobj",
".",
"cmyk_k",
")",
"+",
"cobj",
".",
"cmyk_k",
"cmy_m",
"=",
"cobj",
".",
"cmyk_m",
"*",
... | Converts CMYK to CMY.
NOTE: CMYK and CMY values range from 0.0 to 1.0 | [
"Converts",
"CMYK",
"to",
"CMY",
"."
] | python | train |
rbw/pysnow | pysnow/legacy_request.py | https://github.com/rbw/pysnow/blob/87c8ce0d3a089c2f59247f30efbd545fcdb8e985/pysnow/legacy_request.py#L62-L73 | def count(self):
""" Returns the number of records the query would yield"""
self.request_params.update({'sysparm_count': True})
response = self.session.get(self._get_stats_url(),
params=self._get_formatted_query(fields=list(),
... | [
"def",
"count",
"(",
"self",
")",
":",
"self",
".",
"request_params",
".",
"update",
"(",
"{",
"'sysparm_count'",
":",
"True",
"}",
")",
"response",
"=",
"self",
".",
"session",
".",
"get",
"(",
"self",
".",
"_get_stats_url",
"(",
")",
",",
"params",
... | Returns the number of records the query would yield | [
"Returns",
"the",
"number",
"of",
"records",
"the",
"query",
"would",
"yield"
] | python | train |
cslarsen/crianza | crianza/interpreter.py | https://github.com/cslarsen/crianza/blob/fa044f9d491f37cc06892bad14b2c80b8ac5a7cd/crianza/interpreter.py#L50-L52 | def isbinary(*args):
"""Checks if value can be part of binary/bitwise operations."""
return all(map(lambda c: isnumber(c) or isbool(c), args)) | [
"def",
"isbinary",
"(",
"*",
"args",
")",
":",
"return",
"all",
"(",
"map",
"(",
"lambda",
"c",
":",
"isnumber",
"(",
"c",
")",
"or",
"isbool",
"(",
"c",
")",
",",
"args",
")",
")"
] | Checks if value can be part of binary/bitwise operations. | [
"Checks",
"if",
"value",
"can",
"be",
"part",
"of",
"binary",
"/",
"bitwise",
"operations",
"."
] | python | train |
stevearc/dynamo3 | dynamo3/connection.py | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L90-L118 | def connect_to_region(cls, region, session=None, access_key=None,
secret_key=None, **kwargs):
"""
Connect to an AWS region.
This method has been deprecated in favor of :meth:`~.connect`
Parameters
----------
region : str
Name of an ... | [
"def",
"connect_to_region",
"(",
"cls",
",",
"region",
",",
"session",
"=",
"None",
",",
"access_key",
"=",
"None",
",",
"secret_key",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"connect_to_region is deprecated and will be ... | Connect to an AWS region.
This method has been deprecated in favor of :meth:`~.connect`
Parameters
----------
region : str
Name of an AWS region
session : :class:`~botocore.session.Session`, optional
The Session object to use for the connection
a... | [
"Connect",
"to",
"an",
"AWS",
"region",
"."
] | python | train |
scarface-4711/denonavr | denonavr/denonavr.py | https://github.com/scarface-4711/denonavr/blob/59a136e27b43cb1d1e140cf67705087b3aa377cd/denonavr/denonavr.py#L1473-L1493 | def set_sound_mode_dict(self, sound_mode_dict):
"""Set the matching dictionary used to match the raw sound mode."""
error_msg = ("Syntax of sound mode dictionary not valid, "
"use: OrderedDict([('COMMAND', ['VALUE1','VALUE2'])])")
if isinstance(sound_mode_dict, dict):
... | [
"def",
"set_sound_mode_dict",
"(",
"self",
",",
"sound_mode_dict",
")",
":",
"error_msg",
"=",
"(",
"\"Syntax of sound mode dictionary not valid, \"",
"\"use: OrderedDict([('COMMAND', ['VALUE1','VALUE2'])])\"",
")",
"if",
"isinstance",
"(",
"sound_mode_dict",
",",
"dict",
")"... | Set the matching dictionary used to match the raw sound mode. | [
"Set",
"the",
"matching",
"dictionary",
"used",
"to",
"match",
"the",
"raw",
"sound",
"mode",
"."
] | python | train |
DataDog/integrations-core | mongo/datadog_checks/mongo/mongo.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/mongo/datadog_checks/mongo/mongo.py#L653-L1045 | def check(self, instance):
"""
Returns a dictionary that looks a lot like what's sent back by
db.serverStatus()
"""
def total_seconds(td):
"""
Returns total seconds of a timedelta in a way that's safe for
Python < 2.7
"""
... | [
"def",
"check",
"(",
"self",
",",
"instance",
")",
":",
"def",
"total_seconds",
"(",
"td",
")",
":",
"\"\"\"\n Returns total seconds of a timedelta in a way that's safe for\n Python < 2.7\n \"\"\"",
"if",
"hasattr",
"(",
"td",
",",
"'total_sec... | Returns a dictionary that looks a lot like what's sent back by
db.serverStatus() | [
"Returns",
"a",
"dictionary",
"that",
"looks",
"a",
"lot",
"like",
"what",
"s",
"sent",
"back",
"by",
"db",
".",
"serverStatus",
"()"
] | python | train |
nion-software/nionswift | nion/swift/LinePlotCanvasItem.py | https://github.com/nion-software/nionswift/blob/d43693eaf057b8683b9638e575000f055fede452/nion/swift/LinePlotCanvasItem.py#L402-L538 | def prepare_display(self):
"""Prepare the display.
This method gets called by the canvas layout/draw engine after being triggered by a call to `update`.
When data or display parameters change, the internal state of the line plot gets updated. This method takes
that internal state and u... | [
"def",
"prepare_display",
"(",
"self",
")",
":",
"displayed_dimensional_calibration",
"=",
"self",
".",
"__displayed_dimensional_calibration",
"intensity_calibration",
"=",
"self",
".",
"__intensity_calibration",
"calibration_style",
"=",
"self",
".",
"__calibration_style",
... | Prepare the display.
This method gets called by the canvas layout/draw engine after being triggered by a call to `update`.
When data or display parameters change, the internal state of the line plot gets updated. This method takes
that internal state and updates the child canvas items.
... | [
"Prepare",
"the",
"display",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/backports/enum/__init__.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/enum/__init__.py#L86-L91 | def _make_class_unpicklable(cls):
"""Make the given class un-picklable."""
def _break_on_call_reduce(self, protocol=None):
raise TypeError('%r cannot be pickled' % self)
cls.__reduce_ex__ = _break_on_call_reduce
cls.__module__ = '<unknown>' | [
"def",
"_make_class_unpicklable",
"(",
"cls",
")",
":",
"def",
"_break_on_call_reduce",
"(",
"self",
",",
"protocol",
"=",
"None",
")",
":",
"raise",
"TypeError",
"(",
"'%r cannot be pickled'",
"%",
"self",
")",
"cls",
".",
"__reduce_ex__",
"=",
"_break_on_call_... | Make the given class un-picklable. | [
"Make",
"the",
"given",
"class",
"un",
"-",
"picklable",
"."
] | python | train |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/fields.py | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/fields.py#L395-L410 | def create_ad_hoc_field(cls, db_type):
'''
Give an SQL column description such as "Enum8('apple' = 1, 'banana' = 2, 'orange' = 3)"
this method returns a matching enum field.
'''
import re
try:
Enum # exists in Python 3.4+
except NameError:
... | [
"def",
"create_ad_hoc_field",
"(",
"cls",
",",
"db_type",
")",
":",
"import",
"re",
"try",
":",
"Enum",
"# exists in Python 3.4+",
"except",
"NameError",
":",
"from",
"enum",
"import",
"Enum",
"# use the enum34 library instead",
"members",
"=",
"{",
"}",
"for",
... | Give an SQL column description such as "Enum8('apple' = 1, 'banana' = 2, 'orange' = 3)"
this method returns a matching enum field. | [
"Give",
"an",
"SQL",
"column",
"description",
"such",
"as",
"Enum8",
"(",
"apple",
"=",
"1",
"banana",
"=",
"2",
"orange",
"=",
"3",
")",
"this",
"method",
"returns",
"a",
"matching",
"enum",
"field",
"."
] | python | train |
marl/jams | jams/core.py | https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L2047-L2078 | def match_query(string, query):
'''Test if a string matches a query.
Parameters
----------
string : str
The string to test
query : string, callable, or object
Either a regular expression, callable function, or object.
Returns
-------
match : bool
`True` if:
... | [
"def",
"match_query",
"(",
"string",
",",
"query",
")",
":",
"if",
"six",
".",
"callable",
"(",
"query",
")",
":",
"return",
"query",
"(",
"string",
")",
"elif",
"(",
"isinstance",
"(",
"query",
",",
"six",
".",
"string_types",
")",
"and",
"isinstance"... | Test if a string matches a query.
Parameters
----------
string : str
The string to test
query : string, callable, or object
Either a regular expression, callable function, or object.
Returns
-------
match : bool
`True` if:
- `query` is a callable and `query... | [
"Test",
"if",
"a",
"string",
"matches",
"a",
"query",
"."
] | python | valid |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_1/gallery/gallery_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_1/gallery/gallery_client.py#L1368-L1390 | def update_question(self, question, publisher_name, extension_name, question_id):
"""UpdateQuestion.
[Preview API] Updates an existing question for an extension.
:param :class:`<Question> <azure.devops.v5_1.gallery.models.Question>` question: Updated question to be set for the extension.
... | [
"def",
"update_question",
"(",
"self",
",",
"question",
",",
"publisher_name",
",",
"extension_name",
",",
"question_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"publisher_name",
"is",
"not",
"None",
":",
"route_values",
"[",
"'publisherName'",
"]",
"=... | UpdateQuestion.
[Preview API] Updates an existing question for an extension.
:param :class:`<Question> <azure.devops.v5_1.gallery.models.Question>` question: Updated question to be set for the extension.
:param str publisher_name: Name of the publisher who published the extension.
:param... | [
"UpdateQuestion",
".",
"[",
"Preview",
"API",
"]",
"Updates",
"an",
"existing",
"question",
"for",
"an",
"extension",
".",
":",
"param",
":",
"class",
":",
"<Question",
">",
"<azure",
".",
"devops",
".",
"v5_1",
".",
"gallery",
".",
"models",
".",
"Quest... | python | train |
bspaans/python-mingus | mingus/core/chords.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L1021-L1082 | def determine_extended_chord5(chord, shorthand=False, no_inversions=False,
no_polychords=False):
"""Determine the names of an extended chord."""
if len(chord) != 5:
# warning raise exeption: not an extended chord
return False
def inversion_exhauster(chord, shorthand, tries, result, ... | [
"def",
"determine_extended_chord5",
"(",
"chord",
",",
"shorthand",
"=",
"False",
",",
"no_inversions",
"=",
"False",
",",
"no_polychords",
"=",
"False",
")",
":",
"if",
"len",
"(",
"chord",
")",
"!=",
"5",
":",
"# warning raise exeption: not an extended chord",
... | Determine the names of an extended chord. | [
"Determine",
"the",
"names",
"of",
"an",
"extended",
"chord",
"."
] | python | train |
JNRowe/jnrbase | jnrbase/git.py | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/git.py#L26-L52 | def find_tag(__matcher: str = 'v[0-9]*', *, strict: bool = True,
git_dir: str = '.') -> str:
"""Find closest tag for a git repository.
Note:
This defaults to `Semantic Version`_ tag matching.
Args:
__matcher: Glob-style tag pattern to match
strict: Allow commit-ish, if... | [
"def",
"find_tag",
"(",
"__matcher",
":",
"str",
"=",
"'v[0-9]*'",
",",
"*",
",",
"strict",
":",
"bool",
"=",
"True",
",",
"git_dir",
":",
"str",
"=",
"'.'",
")",
"->",
"str",
":",
"command",
"=",
"'git describe --abbrev=12 --dirty'",
".",
"split",
"(",
... | Find closest tag for a git repository.
Note:
This defaults to `Semantic Version`_ tag matching.
Args:
__matcher: Glob-style tag pattern to match
strict: Allow commit-ish, if no tag found
git_dir: Repository to search
Returns:
Matching tag name
.. _Semantic Vers... | [
"Find",
"closest",
"tag",
"for",
"a",
"git",
"repository",
"."
] | python | train |
sosy-lab/benchexec | benchexec/containerexecutor.py | https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/containerexecutor.py#L656-L918 | def _setup_container_filesystem(self, temp_dir, output_dir, memlimit, memory_nodes):
"""Setup the filesystem layout in the container.
As first step, we create a copy of all existing mountpoints in mount_base, recursively,
and as "private" mounts (i.e., changes to existing mountpoints afterwards... | [
"def",
"_setup_container_filesystem",
"(",
"self",
",",
"temp_dir",
",",
"output_dir",
",",
"memlimit",
",",
"memory_nodes",
")",
":",
"# All strings here are bytes to avoid issues if existing mountpoints are invalid UTF-8.",
"temp_base",
"=",
"self",
".",
"_get_result_files_ba... | Setup the filesystem layout in the container.
As first step, we create a copy of all existing mountpoints in mount_base, recursively,
and as "private" mounts (i.e., changes to existing mountpoints afterwards won't propagate
to our copy).
Then we iterate over all mountpoints and change t... | [
"Setup",
"the",
"filesystem",
"layout",
"in",
"the",
"container",
".",
"As",
"first",
"step",
"we",
"create",
"a",
"copy",
"of",
"all",
"existing",
"mountpoints",
"in",
"mount_base",
"recursively",
"and",
"as",
"private",
"mounts",
"(",
"i",
".",
"e",
".",... | python | train |
square/pylink | pylink/jlink.py | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3545-L3589 | def software_breakpoint_set(self, addr, thumb=False, arm=False, flash=False, ram=False):
"""Sets a software breakpoint at the specified address.
If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if
``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a
no... | [
"def",
"software_breakpoint_set",
"(",
"self",
",",
"addr",
",",
"thumb",
"=",
"False",
",",
"arm",
"=",
"False",
",",
"flash",
"=",
"False",
",",
"ram",
"=",
"False",
")",
":",
"if",
"flash",
"and",
"not",
"ram",
":",
"flags",
"=",
"enums",
".",
"... | Sets a software breakpoint at the specified address.
If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if
``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a
normal breakpoint is set.
If ``flash`` is ``True``, the breakpoint is set in flash, otherwise... | [
"Sets",
"a",
"software",
"breakpoint",
"at",
"the",
"specified",
"address",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L1020-L1027 | def is_sqlatype_text_over_one_char(
coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type a string type that's more than one character
long?
"""
coltype = _coltype_to_typeengine(coltype)
return is_sqlatype_text_of_length_at_least(coltype, 2) | [
"def",
"is_sqlatype_text_over_one_char",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"return",
"is_sqlatype_text_of_length_at_least",
"(",
"coltype",... | Is the SQLAlchemy column type a string type that's more than one character
long? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"a",
"string",
"type",
"that",
"s",
"more",
"than",
"one",
"character",
"long?"
] | python | train |
KrishnaswamyLab/graphtools | graphtools/graphs.py | https://github.com/KrishnaswamyLab/graphtools/blob/44685352be7df2005d44722903092207967457f2/graphtools/graphs.py#L483-L513 | def set_params(self, **params):
"""Set parameters on this object
Safe setter method - attributes should not be modified directly as some
changes are not valid.
Valid parameters:
- n_landmark
- n_svd
Parameters
----------
params : key-value pairs ... | [
"def",
"set_params",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"# update parameters",
"reset_landmarks",
"=",
"False",
"if",
"'n_landmark'",
"in",
"params",
"and",
"params",
"[",
"'n_landmark'",
"]",
"!=",
"self",
".",
"n_landmark",
":",
"self",
".",
... | Set parameters on this object
Safe setter method - attributes should not be modified directly as some
changes are not valid.
Valid parameters:
- n_landmark
- n_svd
Parameters
----------
params : key-value pairs of parameter name and new values
R... | [
"Set",
"parameters",
"on",
"this",
"object"
] | python | train |
saltstack/salt | salt/roster/dir.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/dir.py#L82-L100 | def _render(roster_file, **kwargs):
"""
Render the roster file
"""
renderers = salt.loader.render(__opts__, {})
domain = __opts__.get('roster_domain', '')
try:
result = salt.template.compile_template(roster_file,
renderers,
... | [
"def",
"_render",
"(",
"roster_file",
",",
"*",
"*",
"kwargs",
")",
":",
"renderers",
"=",
"salt",
".",
"loader",
".",
"render",
"(",
"__opts__",
",",
"{",
"}",
")",
"domain",
"=",
"__opts__",
".",
"get",
"(",
"'roster_domain'",
",",
"''",
")",
"try"... | Render the roster file | [
"Render",
"the",
"roster",
"file"
] | python | train |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L885-L904 | def countExtn(fimg, extname='SCI'):
"""
Return the number of 'extname' extensions, defaulting to counting the
number of SCI extensions.
"""
closefits = False
if isinstance(fimg, string_types):
fimg = fits.open(fimg)
closefits = True
n = 0
for e in fimg:
if 'extn... | [
"def",
"countExtn",
"(",
"fimg",
",",
"extname",
"=",
"'SCI'",
")",
":",
"closefits",
"=",
"False",
"if",
"isinstance",
"(",
"fimg",
",",
"string_types",
")",
":",
"fimg",
"=",
"fits",
".",
"open",
"(",
"fimg",
")",
"closefits",
"=",
"True",
"n",
"="... | Return the number of 'extname' extensions, defaulting to counting the
number of SCI extensions. | [
"Return",
"the",
"number",
"of",
"extname",
"extensions",
"defaulting",
"to",
"counting",
"the",
"number",
"of",
"SCI",
"extensions",
"."
] | python | train |
evolbioinfo/pastml | pastml/acr.py | https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/acr.py#L612-L740 | def main():
"""
Entry point, calling :py:func:`pastml.acr.pastml_pipeline` with command-line arguments.
:return: void
"""
import argparse
parser = argparse.ArgumentParser(description="Ancestral character reconstruction and visualisation "
"for r... | [
"def",
"main",
"(",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Ancestral character reconstruction and visualisation \"",
"\"for rooted phylogenetic trees.\"",
",",
"prog",
"=",
"'pastml'",
")",
"tree_group... | Entry point, calling :py:func:`pastml.acr.pastml_pipeline` with command-line arguments.
:return: void | [
"Entry",
"point",
"calling",
":",
"py",
":",
"func",
":",
"pastml",
".",
"acr",
".",
"pastml_pipeline",
"with",
"command",
"-",
"line",
"arguments",
"."
] | python | train |
azogue/i2csense | i2csense/__init__.py | https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/__init__.py#L123-L138 | def dew_point_temperature(self):
"""Return the dew point temperature in ºC for the last measurement.
For sensors implementing temperature and humidity values.
Extracted from the HTU21D sensor spec sheet."""
if self.sample_ok:
temperature = self._get_value_opc_attr('temperatu... | [
"def",
"dew_point_temperature",
"(",
"self",
")",
":",
"if",
"self",
".",
"sample_ok",
":",
"temperature",
"=",
"self",
".",
"_get_value_opc_attr",
"(",
"'temperature'",
",",
"3",
")",
"humidity",
"=",
"self",
".",
"_get_value_opc_attr",
"(",
"'humidity'",
","... | Return the dew point temperature in ºC for the last measurement.
For sensors implementing temperature and humidity values.
Extracted from the HTU21D sensor spec sheet. | [
"Return",
"the",
"dew",
"point",
"temperature",
"in",
"ºC",
"for",
"the",
"last",
"measurement",
"."
] | python | train |
Erotemic/utool | utool/util_hash.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_hash.py#L968-L979 | def get_file_uuid(fpath, hasher=None, stride=1):
""" Creates a uuid from the hash of a file
"""
if hasher is None:
hasher = hashlib.sha1() # 20 bytes of output
#hasher = hashlib.sha256() # 32 bytes of output
# sha1 produces a 20 byte hash
hashbytes_20 = get_file_hash(fpath, hasher=... | [
"def",
"get_file_uuid",
"(",
"fpath",
",",
"hasher",
"=",
"None",
",",
"stride",
"=",
"1",
")",
":",
"if",
"hasher",
"is",
"None",
":",
"hasher",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"# 20 bytes of output",
"#hasher = hashlib.sha256() # 32 bytes of output",
... | Creates a uuid from the hash of a file | [
"Creates",
"a",
"uuid",
"from",
"the",
"hash",
"of",
"a",
"file"
] | python | train |
SpikeInterface/spikeextractors | spikeextractors/SortingExtractor.py | https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/SortingExtractor.py#L178-L203 | def set_unit_property(self, unit_id, property_name, value):
'''This function adds a unit property data set under the given property
name to the given unit.
Parameters
----------
unit_id: int
The unit id for which the property will be set
property_name: str
... | [
"def",
"set_unit_property",
"(",
"self",
",",
"unit_id",
",",
"property_name",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"unit_id",
",",
"(",
"int",
",",
"np",
".",
"integer",
")",
")",
":",
"if",
"unit_id",
"in",
"self",
".",
"get_unit_ids",
"(... | This function adds a unit property data set under the given property
name to the given unit.
Parameters
----------
unit_id: int
The unit id for which the property will be set
property_name: str
The name of the property to be stored
value
... | [
"This",
"function",
"adds",
"a",
"unit",
"property",
"data",
"set",
"under",
"the",
"given",
"property",
"name",
"to",
"the",
"given",
"unit",
"."
] | python | train |
oscarbranson/latools | latools/filtering/clustering.py | https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/filtering/clustering.py#L35-L56 | def cluster_kmeans(data, n_clusters, **kwargs):
"""
Identify clusters using K - Means algorithm.
Parameters
----------
data : array_like
array of size [n_samples, n_features].
n_clusters : int
The number of clusters expected in the data.
Returns
-------
dict
... | [
"def",
"cluster_kmeans",
"(",
"data",
",",
"n_clusters",
",",
"*",
"*",
"kwargs",
")",
":",
"km",
"=",
"cl",
".",
"KMeans",
"(",
"n_clusters",
",",
"*",
"*",
"kwargs",
")",
"kmf",
"=",
"km",
".",
"fit",
"(",
"data",
")",
"labels",
"=",
"kmf",
"."... | Identify clusters using K - Means algorithm.
Parameters
----------
data : array_like
array of size [n_samples, n_features].
n_clusters : int
The number of clusters expected in the data.
Returns
-------
dict
boolean array for each identified cluster. | [
"Identify",
"clusters",
"using",
"K",
"-",
"Means",
"algorithm",
"."
] | python | test |
MaxStrange/AudioSegment | algorithms/asa.py | https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/algorithms/asa.py#L406-L430 | def _get_consecutive_and_overlapping_fronts(onset_fronts, offset_fronts, onset_front_id, offset_front_id):
"""
Gets an onset_front and an offset_front such that they both occupy at least some of the same
frequency channels, then returns the portion of each that overlaps with the other.
"""
# Get the... | [
"def",
"_get_consecutive_and_overlapping_fronts",
"(",
"onset_fronts",
",",
"offset_fronts",
",",
"onset_front_id",
",",
"offset_front_id",
")",
":",
"# Get the onset front of interest",
"onset_front",
"=",
"_get_front_idxs_from_id",
"(",
"onset_fronts",
",",
"onset_front_id",
... | Gets an onset_front and an offset_front such that they both occupy at least some of the same
frequency channels, then returns the portion of each that overlaps with the other. | [
"Gets",
"an",
"onset_front",
"and",
"an",
"offset_front",
"such",
"that",
"they",
"both",
"occupy",
"at",
"least",
"some",
"of",
"the",
"same",
"frequency",
"channels",
"then",
"returns",
"the",
"portion",
"of",
"each",
"that",
"overlaps",
"with",
"the",
"ot... | python | test |
zabertech/python-swampyer | swampyer/__init__.py | https://github.com/zabertech/python-swampyer/blob/31b040e7570455718709a496d6d9faacfb372a00/swampyer/__init__.py#L468-L479 | def subscribe(self,topic,callback=None,options=None):
""" Subscribe to a uri for events from a publisher
"""
full_topic = self.get_full_uri(topic)
result = self.send_and_await_response(SUBSCRIBE(
options=options or {},
... | [
"def",
"subscribe",
"(",
"self",
",",
"topic",
",",
"callback",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"full_topic",
"=",
"self",
".",
"get_full_uri",
"(",
"topic",
")",
"result",
"=",
"self",
".",
"send_and_await_response",
"(",
"SUBSCRIBE",
... | Subscribe to a uri for events from a publisher | [
"Subscribe",
"to",
"a",
"uri",
"for",
"events",
"from",
"a",
"publisher"
] | python | train |
jreese/aiosqlite | aiosqlite/core.py | https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L222-L228 | async def execute_fetchall(
self, sql: str, parameters: Iterable[Any] = None
) -> Iterable[sqlite3.Row]:
"""Helper to execute a query and return all the data."""
if parameters is None:
parameters = []
return await self._execute(self._execute_fetchall, sql, parameters) | [
"async",
"def",
"execute_fetchall",
"(",
"self",
",",
"sql",
":",
"str",
",",
"parameters",
":",
"Iterable",
"[",
"Any",
"]",
"=",
"None",
")",
"->",
"Iterable",
"[",
"sqlite3",
".",
"Row",
"]",
":",
"if",
"parameters",
"is",
"None",
":",
"parameters",... | Helper to execute a query and return all the data. | [
"Helper",
"to",
"execute",
"a",
"query",
"and",
"return",
"all",
"the",
"data",
"."
] | python | train |
saltstack/salt | salt/modules/cloud.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L41-L49 | def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client | [
"def",
"_get_client",
"(",
")",
":",
"client",
"=",
"salt",
".",
"cloud",
".",
"CloudClient",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__opts__",
"[",
"'conf_file'",
"]",
")",
",",
"'cloud'",
")",
",",
"pil... | Return a cloud client | [
"Return",
"a",
"cloud",
"client"
] | python | train |
opengridcc/opengrid | opengrid/library/regression.py | https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L157-L219 | def _do_analysis_cross_validation(self):
"""
Find the best model (fit) based on cross-valiation (leave one out)
"""
assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints"
# initialization: first model is the mean, but com... | [
"def",
"_do_analysis_cross_validation",
"(",
"self",
")",
":",
"assert",
"len",
"(",
"self",
".",
"df",
")",
"<",
"15",
",",
"\"Cross-validation is not implemented if your sample contains more than 15 datapoints\"",
"# initialization: first model is the mean, but compute cv correct... | Find the best model (fit) based on cross-valiation (leave one out) | [
"Find",
"the",
"best",
"model",
"(",
"fit",
")",
"based",
"on",
"cross",
"-",
"valiation",
"(",
"leave",
"one",
"out",
")"
] | python | train |
dpa-newslab/livebridge | livebridge/base/sources.py | https://github.com/dpa-newslab/livebridge/blob/d930e887faa2f882d15b574f0f1fe4a580d7c5fa/livebridge/base/sources.py#L46-L62 | async def filter_new_posts(self, source_id, post_ids):
"""Filters ist of post_id for new ones.
:param source_id: id of the source
:type string:
:param post_ids: list of post ids
:type list:
:returns: list of unknown post ids."""
new_ids = []
try:
... | [
"async",
"def",
"filter_new_posts",
"(",
"self",
",",
"source_id",
",",
"post_ids",
")",
":",
"new_ids",
"=",
"[",
"]",
"try",
":",
"db_client",
"=",
"self",
".",
"_db",
"posts_in_db",
"=",
"await",
"db_client",
".",
"get_known_posts",
"(",
"source_id",
",... | Filters ist of post_id for new ones.
:param source_id: id of the source
:type string:
:param post_ids: list of post ids
:type list:
:returns: list of unknown post ids. | [
"Filters",
"ist",
"of",
"post_id",
"for",
"new",
"ones",
"."
] | python | train |
OpenAgInitiative/openag_python | openag/utils.py | https://github.com/OpenAgInitiative/openag_python/blob/f6202340292bbf7185e1a7d4290188c0dacbb8d0/openag/utils.py#L133-L156 | def process_params(mod_id, params, type_params):
"""
Takes as input a dictionary of parameters defined on a module and the
information about the required parameters defined on the corresponding
module type. Validatates that are required parameters were supplied and
fills any missing parameters with ... | [
"def",
"process_params",
"(",
"mod_id",
",",
"params",
",",
"type_params",
")",
":",
"res",
"=",
"{",
"}",
"for",
"param_name",
",",
"param_info",
"in",
"type_params",
".",
"items",
"(",
")",
":",
"val",
"=",
"params",
".",
"get",
"(",
"param_name",
",... | Takes as input a dictionary of parameters defined on a module and the
information about the required parameters defined on the corresponding
module type. Validatates that are required parameters were supplied and
fills any missing parameters with their default values from the module
type. Returns a nest... | [
"Takes",
"as",
"input",
"a",
"dictionary",
"of",
"parameters",
"defined",
"on",
"a",
"module",
"and",
"the",
"information",
"about",
"the",
"required",
"parameters",
"defined",
"on",
"the",
"corresponding",
"module",
"type",
".",
"Validatates",
"that",
"are",
... | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_wp.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_wp.py#L202-L210 | def get_default_frame(self):
'''default frame for waypoints'''
if self.settings.terrainalt == 'Auto':
if self.get_mav_param('TERRAIN_FOLLOW',0) == 1:
return mavutil.mavlink.MAV_FRAME_GLOBAL_TERRAIN_ALT
return mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT
i... | [
"def",
"get_default_frame",
"(",
"self",
")",
":",
"if",
"self",
".",
"settings",
".",
"terrainalt",
"==",
"'Auto'",
":",
"if",
"self",
".",
"get_mav_param",
"(",
"'TERRAIN_FOLLOW'",
",",
"0",
")",
"==",
"1",
":",
"return",
"mavutil",
".",
"mavlink",
"."... | default frame for waypoints | [
"default",
"frame",
"for",
"waypoints"
] | python | train |
ltworf/typedload | typedload/dataloader.py | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L401-L433 | def _unionload(l: Loader, value, type_) -> Any:
"""
Loads a value into a union.
Basically this iterates all the types inside the
union, until one that doesn't raise an exception
is found.
If no suitable type is found, an exception is raised.
"""
try:
args = uniontypes(type_)
... | [
"def",
"_unionload",
"(",
"l",
":",
"Loader",
",",
"value",
",",
"type_",
")",
"->",
"Any",
":",
"try",
":",
"args",
"=",
"uniontypes",
"(",
"type_",
")",
"except",
"AttributeError",
":",
"raise",
"TypedloadAttributeError",
"(",
"'The typing API for this Pytho... | Loads a value into a union.
Basically this iterates all the types inside the
union, until one that doesn't raise an exception
is found.
If no suitable type is found, an exception is raised. | [
"Loads",
"a",
"value",
"into",
"a",
"union",
"."
] | python | train |
astropy/photutils | photutils/datasets/make.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/make.py#L26-L78 | def apply_poisson_noise(data, random_state=None):
"""
Apply Poisson noise to an array, where the value of each element in
the input array represents the expected number of counts.
Each pixel in the output array is generated by drawing a random
sample from a Poisson distribution whose expectation va... | [
"def",
"apply_poisson_noise",
"(",
"data",
",",
"random_state",
"=",
"None",
")",
":",
"data",
"=",
"np",
".",
"asanyarray",
"(",
"data",
")",
"if",
"np",
".",
"any",
"(",
"data",
"<",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'data must not contain an... | Apply Poisson noise to an array, where the value of each element in
the input array represents the expected number of counts.
Each pixel in the output array is generated by drawing a random
sample from a Poisson distribution whose expectation value is given
by the pixel value in the input array.
P... | [
"Apply",
"Poisson",
"noise",
"to",
"an",
"array",
"where",
"the",
"value",
"of",
"each",
"element",
"in",
"the",
"input",
"array",
"represents",
"the",
"expected",
"number",
"of",
"counts",
"."
] | python | train |
openstack/monasca-common | monasca_common/policy/policy_engine.py | https://github.com/openstack/monasca-common/blob/61e2e00454734e2881611abec8df0d85bf7655ac/monasca_common/policy/policy_engine.py#L162-L174 | def set_rules(rules, overwrite=True, use_conf=False): # pragma: no cover
"""Set rules based on the provided dict of rules.
Note:
Used in tests only.
:param rules: New rules to use. It should be an instance of dict
:param overwrite: Whether to overwrite current rules or update them
... | [
"def",
"set_rules",
"(",
"rules",
",",
"overwrite",
"=",
"True",
",",
"use_conf",
"=",
"False",
")",
":",
"# pragma: no cover",
"init",
"(",
"use_conf",
"=",
"False",
")",
"_ENFORCER",
".",
"set_rules",
"(",
"rules",
",",
"overwrite",
",",
"use_conf",
")"
... | Set rules based on the provided dict of rules.
Note:
Used in tests only.
:param rules: New rules to use. It should be an instance of dict
:param overwrite: Whether to overwrite current rules or update them
with the new rules.
:param use_conf: Whether to reload rules from ... | [
"Set",
"rules",
"based",
"on",
"the",
"provided",
"dict",
"of",
"rules",
"."
] | python | train |
genialis/resolwe | resolwe/process/fields.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/process/fields.py#L261-L281 | def import_file(self, imported_format=None, progress_from=0.0, progress_to=None):
"""Import field source file to working directory.
:param imported_format: Import file format (extracted, compressed or both)
:param progress_from: Initial progress value
:param progress_to: Final progress ... | [
"def",
"import_file",
"(",
"self",
",",
"imported_format",
"=",
"None",
",",
"progress_from",
"=",
"0.0",
",",
"progress_to",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"resolwe_runtime_utils",
",",
"'import_file'",
")",
":",
"raise",
"RuntimeError",
... | Import field source file to working directory.
:param imported_format: Import file format (extracted, compressed or both)
:param progress_from: Initial progress value
:param progress_to: Final progress value
:return: Destination file path (if extracted and compressed, extracted path giv... | [
"Import",
"field",
"source",
"file",
"to",
"working",
"directory",
"."
] | python | train |
opendatateam/udata | udata/core/dataset/models.py | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/models.py#L602-L615 | def add_resource(self, resource):
'''Perform an atomic prepend for a new resource'''
resource.validate()
self.update(__raw__={
'$push': {
'resources': {
'$each': [resource.to_mongo()],
'$position': 0
}
... | [
"def",
"add_resource",
"(",
"self",
",",
"resource",
")",
":",
"resource",
".",
"validate",
"(",
")",
"self",
".",
"update",
"(",
"__raw__",
"=",
"{",
"'$push'",
":",
"{",
"'resources'",
":",
"{",
"'$each'",
":",
"[",
"resource",
".",
"to_mongo",
"(",
... | Perform an atomic prepend for a new resource | [
"Perform",
"an",
"atomic",
"prepend",
"for",
"a",
"new",
"resource"
] | python | train |
pytroll/satpy | satpy/composites/viirs.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/composites/viirs.py#L303-L388 | def _run_dnb_normalization(self, dnb_data, sza_data):
"""Scale the DNB data using a adaptive histogram equalization method.
Args:
dnb_data (ndarray): Day/Night Band data array
sza_data (ndarray): Solar Zenith Angle data array
"""
# convert dask arrays to DataArr... | [
"def",
"_run_dnb_normalization",
"(",
"self",
",",
"dnb_data",
",",
"sza_data",
")",
":",
"# convert dask arrays to DataArray objects",
"dnb_data",
"=",
"xr",
".",
"DataArray",
"(",
"dnb_data",
",",
"dims",
"=",
"(",
"'y'",
",",
"'x'",
")",
")",
"sza_data",
"=... | Scale the DNB data using a adaptive histogram equalization method.
Args:
dnb_data (ndarray): Day/Night Band data array
sza_data (ndarray): Solar Zenith Angle data array | [
"Scale",
"the",
"DNB",
"data",
"using",
"a",
"adaptive",
"histogram",
"equalization",
"method",
"."
] | python | train |
twisted/epsilon | epsilon/ampauth.py | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/ampauth.py#L222-L229 | def connectionLost(self, reason):
"""
If a login has happened, perform a logout.
"""
AMP.connectionLost(self, reason)
if self.logout is not None:
self.logout()
self.boxReceiver = self.logout = None | [
"def",
"connectionLost",
"(",
"self",
",",
"reason",
")",
":",
"AMP",
".",
"connectionLost",
"(",
"self",
",",
"reason",
")",
"if",
"self",
".",
"logout",
"is",
"not",
"None",
":",
"self",
".",
"logout",
"(",
")",
"self",
".",
"boxReceiver",
"=",
"se... | If a login has happened, perform a logout. | [
"If",
"a",
"login",
"has",
"happened",
"perform",
"a",
"logout",
"."
] | python | train |
cloudera/impyla | impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py | https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L4873-L4881 | def alter_function(self, dbName, funcName, newFunc):
"""
Parameters:
- dbName
- funcName
- newFunc
"""
self.send_alter_function(dbName, funcName, newFunc)
self.recv_alter_function() | [
"def",
"alter_function",
"(",
"self",
",",
"dbName",
",",
"funcName",
",",
"newFunc",
")",
":",
"self",
".",
"send_alter_function",
"(",
"dbName",
",",
"funcName",
",",
"newFunc",
")",
"self",
".",
"recv_alter_function",
"(",
")"
] | Parameters:
- dbName
- funcName
- newFunc | [
"Parameters",
":",
"-",
"dbName",
"-",
"funcName",
"-",
"newFunc"
] | python | train |
appknox/google-chartwrapper | GChartWrapper/GChart.py | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L271-L283 | def scale(self, *args):
"""
Scales the data down to the given size
args must be of the form::
<data set 1 minimum value>,
<data set 1 maximum value>,
<data set n minimum value>,
<data set n maximum value>
will only work with text encoding!
... | [
"def",
"scale",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"_scale",
"=",
"[",
"','",
".",
"join",
"(",
"map",
"(",
"smart_str",
",",
"args",
")",
")",
"]",
"return",
"self"
] | Scales the data down to the given size
args must be of the form::
<data set 1 minimum value>,
<data set 1 maximum value>,
<data set n minimum value>,
<data set n maximum value>
will only work with text encoding!
APIPARAM: chds | [
"Scales",
"the",
"data",
"down",
"to",
"the",
"given",
"size",
"args",
"must",
"be",
"of",
"the",
"form",
"::",
"<data",
"set",
"1",
"minimum",
"value",
">",
"<data",
"set",
"1",
"maximum",
"value",
">",
"<data",
"set",
"n",
"minimum",
"value",
">",
... | python | test |
cnobile2012/pololu-motors | pololu/motors/qik2s9v1.py | https://github.com/cnobile2012/pololu-motors/blob/453d2283a63cfe15cda96cad6dffa73372d52a7c/pololu/motors/qik2s9v1.py#L106-L123 | def getError(self, device=DEFAULT_DEVICE_ID, message=True):
"""
Get the error message or value stored in the Qik 2s9v1 hardware.
:Keywords:
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol. Def... | [
"def",
"getError",
"(",
"self",
",",
"device",
"=",
"DEFAULT_DEVICE_ID",
",",
"message",
"=",
"True",
")",
":",
"return",
"self",
".",
"_getError",
"(",
"device",
",",
"message",
")"
] | Get the error message or value stored in the Qik 2s9v1 hardware.
:Keywords:
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol. Defaults to the hardware's
default value.
message : `bool`
... | [
"Get",
"the",
"error",
"message",
"or",
"value",
"stored",
"in",
"the",
"Qik",
"2s9v1",
"hardware",
"."
] | python | train |
pymupdf/PyMuPDF | fitz/fitz.py | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L572-L578 | def normalize(self):
"""Replace rectangle with its finite version."""
if self.x1 < self.x0:
self.x0, self.x1 = self.x1, self.x0
if self.y1 < self.y0:
self.y0, self.y1 = self.y1, self.y0
return self | [
"def",
"normalize",
"(",
"self",
")",
":",
"if",
"self",
".",
"x1",
"<",
"self",
".",
"x0",
":",
"self",
".",
"x0",
",",
"self",
".",
"x1",
"=",
"self",
".",
"x1",
",",
"self",
".",
"x0",
"if",
"self",
".",
"y1",
"<",
"self",
".",
"y0",
":"... | Replace rectangle with its finite version. | [
"Replace",
"rectangle",
"with",
"its",
"finite",
"version",
"."
] | python | train |
wmayner/pyphi | pyphi/models/cuts.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/cuts.py#L48-L57 | def apply_cut(self, cm):
"""Return a modified connectivity matrix with all connections that are
severed by this cut removed.
Args:
cm (np.ndarray): A connectivity matrix.
"""
# Invert the cut matrix, creating a matrix of preserved connections
inverse = np.log... | [
"def",
"apply_cut",
"(",
"self",
",",
"cm",
")",
":",
"# Invert the cut matrix, creating a matrix of preserved connections",
"inverse",
"=",
"np",
".",
"logical_not",
"(",
"self",
".",
"cut_matrix",
"(",
"cm",
".",
"shape",
"[",
"0",
"]",
")",
")",
".",
"astyp... | Return a modified connectivity matrix with all connections that are
severed by this cut removed.
Args:
cm (np.ndarray): A connectivity matrix. | [
"Return",
"a",
"modified",
"connectivity",
"matrix",
"with",
"all",
"connections",
"that",
"are",
"severed",
"by",
"this",
"cut",
"removed",
"."
] | python | train |
mardix/Yass | yass/yass.py | https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/yass.py#L182-L189 | def _url_to(self, page):
""" Get the url of a page """
anchor = ""
if "#" in page:
page, anchor = page.split("#")
anchor = "#" + anchor
meta = self._get_page_meta(page)
return meta.get("url") | [
"def",
"_url_to",
"(",
"self",
",",
"page",
")",
":",
"anchor",
"=",
"\"\"",
"if",
"\"#\"",
"in",
"page",
":",
"page",
",",
"anchor",
"=",
"page",
".",
"split",
"(",
"\"#\"",
")",
"anchor",
"=",
"\"#\"",
"+",
"anchor",
"meta",
"=",
"self",
".",
"... | Get the url of a page | [
"Get",
"the",
"url",
"of",
"a",
"page"
] | python | train |
pypa/setuptools | setuptools/command/easy_install.py | https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/command/easy_install.py#L596-L608 | def install_egg_scripts(self, dist):
"""Write all the scripts for `dist`, unless scripts are excluded"""
if not self.exclude_scripts and dist.metadata_isdir('scripts'):
for script_name in dist.metadata_listdir('scripts'):
if dist.metadata_isdir('scripts/' + script_name):
... | [
"def",
"install_egg_scripts",
"(",
"self",
",",
"dist",
")",
":",
"if",
"not",
"self",
".",
"exclude_scripts",
"and",
"dist",
".",
"metadata_isdir",
"(",
"'scripts'",
")",
":",
"for",
"script_name",
"in",
"dist",
".",
"metadata_listdir",
"(",
"'scripts'",
")... | Write all the scripts for `dist`, unless scripts are excluded | [
"Write",
"all",
"the",
"scripts",
"for",
"dist",
"unless",
"scripts",
"are",
"excluded"
] | python | train |
spyder-ide/spyder | spyder/widgets/fileswitcher.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L493-L500 | def select_row(self, steps):
"""Select row in list widget based on a number of steps with direction.
Steps can be positive (next rows) or negative (previous rows).
"""
row = self.current_row() + steps
if 0 <= row < self.count():
self.set_current_row(row) | [
"def",
"select_row",
"(",
"self",
",",
"steps",
")",
":",
"row",
"=",
"self",
".",
"current_row",
"(",
")",
"+",
"steps",
"if",
"0",
"<=",
"row",
"<",
"self",
".",
"count",
"(",
")",
":",
"self",
".",
"set_current_row",
"(",
"row",
")"
] | Select row in list widget based on a number of steps with direction.
Steps can be positive (next rows) or negative (previous rows). | [
"Select",
"row",
"in",
"list",
"widget",
"based",
"on",
"a",
"number",
"of",
"steps",
"with",
"direction",
"."
] | python | train |
numenta/nupic | src/nupic/support/decorators.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/decorators.py#L69-L137 | def logEntryExit(getLoggerCallback=logging.getLogger,
entryExitLogLevel=logging.DEBUG, logArgs=False,
logTraceback=False):
""" Returns a closure suitable for use as function/method decorator for
logging entry/exit of function/method.
getLoggerCallback: user-supplied callback ... | [
"def",
"logEntryExit",
"(",
"getLoggerCallback",
"=",
"logging",
".",
"getLogger",
",",
"entryExitLogLevel",
"=",
"logging",
".",
"DEBUG",
",",
"logArgs",
"=",
"False",
",",
"logTraceback",
"=",
"False",
")",
":",
"def",
"entryExitLoggingDecorator",
"(",
"func",... | Returns a closure suitable for use as function/method decorator for
logging entry/exit of function/method.
getLoggerCallback: user-supplied callback function that takes no args and
returns the logger instance to use for logging.
entryExitLogLevel: Log level for logging entry/exit ... | [
"Returns",
"a",
"closure",
"suitable",
"for",
"use",
"as",
"function",
"/",
"method",
"decorator",
"for",
"logging",
"entry",
"/",
"exit",
"of",
"function",
"/",
"method",
"."
] | python | valid |
saltstack/salt | salt/runners/bgp.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/bgp.py#L232-L409 | def neighbors(*asns, **kwargs):
'''
Search for BGP neighbors details in the mines of the ``bgp.neighbors`` function.
Arguments:
asns
A list of AS numbers to search for.
The runner will return only the neighbors of these AS numbers.
device
Filter by device name (minion ID).... | [
"def",
"neighbors",
"(",
"*",
"asns",
",",
"*",
"*",
"kwargs",
")",
":",
"opts",
"=",
"_get_bgp_runner_opts",
"(",
")",
"title",
"=",
"kwargs",
".",
"pop",
"(",
"'title'",
",",
"None",
")",
"display",
"=",
"kwargs",
".",
"pop",
"(",
"'display'",
",",... | Search for BGP neighbors details in the mines of the ``bgp.neighbors`` function.
Arguments:
asns
A list of AS numbers to search for.
The runner will return only the neighbors of these AS numbers.
device
Filter by device name (minion ID).
ip
Search BGP neighbor using t... | [
"Search",
"for",
"BGP",
"neighbors",
"details",
"in",
"the",
"mines",
"of",
"the",
"bgp",
".",
"neighbors",
"function",
"."
] | python | train |
CamDavidsonPilon/lifelines | lifelines/generate_datasets.py | https://github.com/CamDavidsonPilon/lifelines/blob/bdf6be6f1d10eea4c46365ee0ee6a47d8c30edf8/lifelines/generate_datasets.py#L249-L289 | def generate_random_lifetimes(hazard_rates, timelines, size=1, censor=None):
"""
Based on the hazard rates, compute random variables from the survival function
hazard_rates: (n,t) array of hazard rates
timelines: (t,) the observation times
size: the number to return, per hardard rate
cen... | [
"def",
"generate_random_lifetimes",
"(",
"hazard_rates",
",",
"timelines",
",",
"size",
"=",
"1",
",",
"censor",
"=",
"None",
")",
":",
"n",
"=",
"hazard_rates",
".",
"shape",
"[",
"1",
"]",
"survival_times",
"=",
"np",
".",
"empty",
"(",
"(",
"n",
","... | Based on the hazard rates, compute random variables from the survival function
hazard_rates: (n,t) array of hazard rates
timelines: (t,) the observation times
size: the number to return, per hardard rate
censor: If True, adds uniform censoring between timelines.max() and 0
If a po... | [
"Based",
"on",
"the",
"hazard",
"rates",
"compute",
"random",
"variables",
"from",
"the",
"survival",
"function",
"hazard_rates",
":",
"(",
"n",
"t",
")",
"array",
"of",
"hazard",
"rates",
"timelines",
":",
"(",
"t",
")",
"the",
"observation",
"times",
"si... | python | train |
basecrm/basecrm-python | basecrm/services.py | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L691-L705 | def retrieve(self, id) :
"""
Retrieve a single lead
Returns a single lead available to the user, according to the unique lead ID provided
If the specified lead does not exist, this query returns an error
:calls: ``get /leads/{id}``
:param int id: Unique identifier of a ... | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"lead",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/leads/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"return",
"lead"
] | Retrieve a single lead
Returns a single lead available to the user, according to the unique lead ID provided
If the specified lead does not exist, this query returns an error
:calls: ``get /leads/{id}``
:param int id: Unique identifier of a Lead.
:return: Dictionary that suppor... | [
"Retrieve",
"a",
"single",
"lead"
] | python | train |
nitely/v8-cffi | v8cffi/context.py | https://github.com/nitely/v8-cffi/blob/e3492e7eaacb30be75999c24413aa15eeab57a5d/v8cffi/context.py#L22-L38 | def _is_utf_8(txt):
"""
Check a string is utf-8 encoded
:param bytes txt: utf-8 string
:return: Whether the string\
is utf-8 encoded or not
:rtype: bool
"""
assert isinstance(txt, six.binary_type)
try:
_ = six.text_type(txt, 'utf-8')
except (TypeError, UnicodeEncodeErro... | [
"def",
"_is_utf_8",
"(",
"txt",
")",
":",
"assert",
"isinstance",
"(",
"txt",
",",
"six",
".",
"binary_type",
")",
"try",
":",
"_",
"=",
"six",
".",
"text_type",
"(",
"txt",
",",
"'utf-8'",
")",
"except",
"(",
"TypeError",
",",
"UnicodeEncodeError",
")... | Check a string is utf-8 encoded
:param bytes txt: utf-8 string
:return: Whether the string\
is utf-8 encoded or not
:rtype: bool | [
"Check",
"a",
"string",
"is",
"utf",
"-",
"8",
"encoded"
] | python | train |
quantopian/zipline | zipline/data/continuous_future_reader.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/continuous_future_reader.py#L204-L282 | def load_raw_arrays(self, columns, start_date, end_date, assets):
"""
Parameters
----------
fields : list of str
'open', 'high', 'low', 'close', or 'volume'
start_dt: Timestamp
Beginning of the window range.
end_dt: Timestamp
End of the wi... | [
"def",
"load_raw_arrays",
"(",
"self",
",",
"columns",
",",
"start_date",
",",
"end_date",
",",
"assets",
")",
":",
"rolls_by_asset",
"=",
"{",
"}",
"tc",
"=",
"self",
".",
"trading_calendar",
"start_session",
"=",
"tc",
".",
"minute_to_session_label",
"(",
... | Parameters
----------
fields : list of str
'open', 'high', 'low', 'close', or 'volume'
start_dt: Timestamp
Beginning of the window range.
end_dt: Timestamp
End of the window range.
sids : list of int
The asset identifiers in the window.... | [
"Parameters",
"----------",
"fields",
":",
"list",
"of",
"str",
"open",
"high",
"low",
"close",
"or",
"volume",
"start_dt",
":",
"Timestamp",
"Beginning",
"of",
"the",
"window",
"range",
".",
"end_dt",
":",
"Timestamp",
"End",
"of",
"the",
"window",
"range",... | python | train |
nilp0inter/cpe | cpe/comp/cpecomp1_1.py | https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp1_1.py#L156-L183 | def _decode(self):
"""
Convert the encoded value of component to standard value (WFN value).
"""
s = self._encoded_value
elements = s.replace('~', '').split('!')
dec_elements = []
for elem in elements:
result = []
idx = 0
whil... | [
"def",
"_decode",
"(",
"self",
")",
":",
"s",
"=",
"self",
".",
"_encoded_value",
"elements",
"=",
"s",
".",
"replace",
"(",
"'~'",
",",
"''",
")",
".",
"split",
"(",
"'!'",
")",
"dec_elements",
"=",
"[",
"]",
"for",
"elem",
"in",
"elements",
":",
... | Convert the encoded value of component to standard value (WFN value). | [
"Convert",
"the",
"encoded",
"value",
"of",
"component",
"to",
"standard",
"value",
"(",
"WFN",
"value",
")",
"."
] | python | train |
basvandenbroek/gcloud_taskqueue | gcloud_taskqueue/task.py | https://github.com/basvandenbroek/gcloud_taskqueue/blob/b147b57f7c0ad9e8030ee9797d6526a448aa5007/gcloud_taskqueue/task.py#L93-L106 | def delete(self, client=None):
"""Deletes a task from Task Queue.
:type client: :class:`gcloud.taskqueue.client.Client` or ``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the task's taskqueue.
:rtype... | [
"def",
"delete",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"return",
"self",
".",
"taskqueue",
".",
"delete_task",
"(",
"self",
".",
"id",
",",
"client",
"=",
"client",
")"
] | Deletes a task from Task Queue.
:type client: :class:`gcloud.taskqueue.client.Client` or ``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the task's taskqueue.
:rtype: :class:`Task`
:returns: The task... | [
"Deletes",
"a",
"task",
"from",
"Task",
"Queue",
"."
] | python | train |
pgmpy/pgmpy | pgmpy/readwrite/XMLBeliefNetwork.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/XMLBeliefNetwork.py#L85-L95 | def get_static_properties(self):
"""
Returns a dictionary of STATICPROPERTIES
Examples
--------
>>> reader = XBNReader('xbn_test.xml')
>>> reader.get_static_properties()
{'FORMAT': 'MSR DTAS XML', 'VERSION': '0.2', 'CREATOR': 'Microsoft Research DTAS'}
""... | [
"def",
"get_static_properties",
"(",
"self",
")",
":",
"return",
"{",
"tags",
".",
"tag",
":",
"tags",
".",
"get",
"(",
"'VALUE'",
")",
"for",
"tags",
"in",
"self",
".",
"bnmodel",
".",
"find",
"(",
"'STATICPROPERTIES'",
")",
"}"
] | Returns a dictionary of STATICPROPERTIES
Examples
--------
>>> reader = XBNReader('xbn_test.xml')
>>> reader.get_static_properties()
{'FORMAT': 'MSR DTAS XML', 'VERSION': '0.2', 'CREATOR': 'Microsoft Research DTAS'} | [
"Returns",
"a",
"dictionary",
"of",
"STATICPROPERTIES"
] | python | train |
google/grr | grr/core/grr_response_core/lib/lexer.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/lexer.py#L84-L97 | def Reset(self):
"""Reset the lexer to process a new data feed."""
# The first state
self.state = "INITIAL"
self.state_stack = []
# The buffer we are parsing now
self.buffer = ""
self.error = 0
self.verbose = 0
# The index into the buffer where we are currently pointing
self.pr... | [
"def",
"Reset",
"(",
"self",
")",
":",
"# The first state",
"self",
".",
"state",
"=",
"\"INITIAL\"",
"self",
".",
"state_stack",
"=",
"[",
"]",
"# The buffer we are parsing now",
"self",
".",
"buffer",
"=",
"\"\"",
"self",
".",
"error",
"=",
"0",
"self",
... | Reset the lexer to process a new data feed. | [
"Reset",
"the",
"lexer",
"to",
"process",
"a",
"new",
"data",
"feed",
"."
] | python | train |
anentropic/django-conditional-aggregates | djconnagg/aggregates.py | https://github.com/anentropic/django-conditional-aggregates/blob/20d060c31344267b589b0cff9bdcd341a6b539ab/djconnagg/aggregates.py#L9-L26 | def transform_q(q, query):
"""
Replaces (lookup, value) children of Q with equivalent WhereNode objects.
This is a pre-prep of our Q object, ready for later rendering into SQL.
Modifies in place, no need to return.
(We could do this in render_q, but then we'd have to pass the Query object
from... | [
"def",
"transform_q",
"(",
"q",
",",
"query",
")",
":",
"for",
"i",
",",
"child",
"in",
"enumerate",
"(",
"q",
".",
"children",
")",
":",
"if",
"isinstance",
"(",
"child",
",",
"Q",
")",
":",
"transform_q",
"(",
"child",
",",
"query",
")",
"else",
... | Replaces (lookup, value) children of Q with equivalent WhereNode objects.
This is a pre-prep of our Q object, ready for later rendering into SQL.
Modifies in place, no need to return.
(We could do this in render_q, but then we'd have to pass the Query object
from ConditionalAggregate down into SQLCond... | [
"Replaces",
"(",
"lookup",
"value",
")",
"children",
"of",
"Q",
"with",
"equivalent",
"WhereNode",
"objects",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/routing_system/interface/ve/ipv6/interface_ospfv3_conf/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/routing_system/interface/ve/ipv6/interface_ospfv3_conf/__init__.py#L368-L391 | def _set_network(self, v, load=False):
"""
Setter method for network, mapped from YANG variable /routing_system/interface/ve/ipv6/interface_ospfv3_conf/network (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_network is considered as a private
method. Ba... | [
"def",
"_set_network",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",... | Setter method for network, mapped from YANG variable /routing_system/interface/ve/ipv6/interface_ospfv3_conf/network (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_network is considered as a private
method. Backends looking to populate this variable should
... | [
"Setter",
"method",
"for",
"network",
"mapped",
"from",
"YANG",
"variable",
"/",
"routing_system",
"/",
"interface",
"/",
"ve",
"/",
"ipv6",
"/",
"interface_ospfv3_conf",
"/",
"network",
"(",
"enumeration",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"... | python | train |
glormph/msstitch | src/app/readers/fasta.py | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/fasta.py#L38-L60 | def get_proteins_genes(fastafn, fastadelim=None, genefield=None):
"""This returns a tuple of (protein, gene, HGNC symbol, description) from
a passed file. If the file is FASTA from ENSEMBL or UniProt, only genes and
descriptions are given and symbol will be None. If the file is a ENSEMBL
Biomart mapping... | [
"def",
"get_proteins_genes",
"(",
"fastafn",
",",
"fastadelim",
"=",
"None",
",",
"genefield",
"=",
"None",
")",
":",
"with",
"open",
"(",
"fastafn",
")",
"as",
"fp",
":",
"firstline",
"=",
"next",
"(",
"fp",
")",
".",
"strip",
"(",
")",
"if",
"first... | This returns a tuple of (protein, gene, HGNC symbol, description) from
a passed file. If the file is FASTA from ENSEMBL or UniProt, only genes and
descriptions are given and symbol will be None. If the file is a ENSEMBL
Biomart mapping file it tries to parse that and also return the rest | [
"This",
"returns",
"a",
"tuple",
"of",
"(",
"protein",
"gene",
"HGNC",
"symbol",
"description",
")",
"from",
"a",
"passed",
"file",
".",
"If",
"the",
"file",
"is",
"FASTA",
"from",
"ENSEMBL",
"or",
"UniProt",
"only",
"genes",
"and",
"descriptions",
"are",
... | python | train |
vlukes/dicom2fem | dicom2fem/mesh.py | https://github.com/vlukes/dicom2fem/blob/3056c977ca7119e01984d3aa0c4448a1c6c2430f/dicom2fem/mesh.py#L363-L399 | def from_surface( surf_faces, mesh_in ):
"""
Create a mesh given a set of surface faces and the original mesh.
"""
aux = nm.concatenate([faces.ravel() for faces in surf_faces])
inod = nm.unique(aux)
n_nod = len( inod )
n_nod_m, dim = mesh_in.coors.shape
... | [
"def",
"from_surface",
"(",
"surf_faces",
",",
"mesh_in",
")",
":",
"aux",
"=",
"nm",
".",
"concatenate",
"(",
"[",
"faces",
".",
"ravel",
"(",
")",
"for",
"faces",
"in",
"surf_faces",
"]",
")",
"inod",
"=",
"nm",
".",
"unique",
"(",
"aux",
")",
"n... | Create a mesh given a set of surface faces and the original mesh. | [
"Create",
"a",
"mesh",
"given",
"a",
"set",
"of",
"surface",
"faces",
"and",
"the",
"original",
"mesh",
"."
] | python | train |
hozn/coilmq | coilmq/protocol/__init__.py | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/protocol/__init__.py#L240-L248 | def disconnect(self, frame):
"""
Handles the DISCONNECT command: Unbinds the connection.
Clients are supposed to send this command, but in practice it should not be
relied upon.
"""
self.engine.log.debug("Disconnect")
self.engine.unbind() | [
"def",
"disconnect",
"(",
"self",
",",
"frame",
")",
":",
"self",
".",
"engine",
".",
"log",
".",
"debug",
"(",
"\"Disconnect\"",
")",
"self",
".",
"engine",
".",
"unbind",
"(",
")"
] | Handles the DISCONNECT command: Unbinds the connection.
Clients are supposed to send this command, but in practice it should not be
relied upon. | [
"Handles",
"the",
"DISCONNECT",
"command",
":",
"Unbinds",
"the",
"connection",
"."
] | python | train |
majerteam/sqla_inspect | sqla_inspect/excel.py | https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/excel.py#L150-L165 | def _render_headers(self):
"""
Write the headers row
"""
headers = getattr(self, 'headers', ())
for index, col in enumerate(headers):
# We write the headers
cell = self.worksheet.cell(row=1, column=index + 1)
cell.value = col['label']
... | [
"def",
"_render_headers",
"(",
"self",
")",
":",
"headers",
"=",
"getattr",
"(",
"self",
",",
"'headers'",
",",
"(",
")",
")",
"for",
"index",
",",
"col",
"in",
"enumerate",
"(",
"headers",
")",
":",
"# We write the headers",
"cell",
"=",
"self",
".",
... | Write the headers row | [
"Write",
"the",
"headers",
"row"
] | python | train |
cga-harvard/Hypermap-Registry | hypermap/aggregator/solr.py | https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/solr.py#L99-L221 | def update_schema(self, catalog="hypermap"):
"""
set the mapping in solr.
:param catalog: core
:return:
"""
schema_url = "{0}/solr/{1}/schema".format(SEARCH_URL, catalog)
print schema_url
# create a special type to draw better heatmaps.
location_r... | [
"def",
"update_schema",
"(",
"self",
",",
"catalog",
"=",
"\"hypermap\"",
")",
":",
"schema_url",
"=",
"\"{0}/solr/{1}/schema\"",
".",
"format",
"(",
"SEARCH_URL",
",",
"catalog",
")",
"print",
"schema_url",
"# create a special type to draw better heatmaps.",
"location_... | set the mapping in solr.
:param catalog: core
:return: | [
"set",
"the",
"mapping",
"in",
"solr",
".",
":",
"param",
"catalog",
":",
"core",
":",
"return",
":"
] | python | train |
Calysto/calysto | calysto/ai/conx.py | https://github.com/Calysto/calysto/blob/20813c0f48096317aa775d03a5c6b20f12fafc93/calysto/ai/conx.py#L641-L667 | def changeSize(self, fromLayerSize, toLayerSize):
"""
Changes the size of the connection depending on the size
change of either source or destination layer. Should only be
called through Network.changeLayerSize().
"""
if toLayerSize <= 0 or fromLayerSize <= 0:
... | [
"def",
"changeSize",
"(",
"self",
",",
"fromLayerSize",
",",
"toLayerSize",
")",
":",
"if",
"toLayerSize",
"<=",
"0",
"or",
"fromLayerSize",
"<=",
"0",
":",
"raise",
"LayerError",
"(",
"'changeSize() called with invalid layer size.'",
",",
"(",
"fromLayerSize",
",... | Changes the size of the connection depending on the size
change of either source or destination layer. Should only be
called through Network.changeLayerSize(). | [
"Changes",
"the",
"size",
"of",
"the",
"connection",
"depending",
"on",
"the",
"size",
"change",
"of",
"either",
"source",
"or",
"destination",
"layer",
".",
"Should",
"only",
"be",
"called",
"through",
"Network",
".",
"changeLayerSize",
"()",
"."
] | python | train |
BlackEarth/bl | bl/csv.py | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/csv.py#L29-L32 | def excel_key(index):
"""create a key for index by converting index into a base-26 number, using A-Z as the characters."""
X = lambda n: ~n and X((n // 26)-1) + chr(65 + (n % 26)) or ''
return X(int(index)) | [
"def",
"excel_key",
"(",
"index",
")",
":",
"X",
"=",
"lambda",
"n",
":",
"~",
"n",
"and",
"X",
"(",
"(",
"n",
"//",
"26",
")",
"-",
"1",
")",
"+",
"chr",
"(",
"65",
"+",
"(",
"n",
"%",
"26",
")",
")",
"or",
"''",
"return",
"X",
"(",
"i... | create a key for index by converting index into a base-26 number, using A-Z as the characters. | [
"create",
"a",
"key",
"for",
"index",
"by",
"converting",
"index",
"into",
"a",
"base",
"-",
"26",
"number",
"using",
"A",
"-",
"Z",
"as",
"the",
"characters",
"."
] | python | train |
codeinn/vcs | vcs/cli.py | https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/cli.py#L496-L501 | def get_changeset(self, **options):
"""
Returns changeset for given ``options``.
"""
cid = options.get('changeset_id', None)
return self.repo.get_changeset(cid) | [
"def",
"get_changeset",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"cid",
"=",
"options",
".",
"get",
"(",
"'changeset_id'",
",",
"None",
")",
"return",
"self",
".",
"repo",
".",
"get_changeset",
"(",
"cid",
")"
] | Returns changeset for given ``options``. | [
"Returns",
"changeset",
"for",
"given",
"options",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.