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 |
|---|---|---|---|---|---|---|---|---|
minttu/tmc.py | tmc/__main__.py | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L403-L459 | def update(course=False):
"""
Update the data of courses and or exercises from server.
"""
if course:
with Spinner.context(msg="Updated course metadata.",
waitmsg="Updating course metadata."):
for course in api.get_courses():
old = None
... | [
"def",
"update",
"(",
"course",
"=",
"False",
")",
":",
"if",
"course",
":",
"with",
"Spinner",
".",
"context",
"(",
"msg",
"=",
"\"Updated course metadata.\"",
",",
"waitmsg",
"=",
"\"Updating course metadata.\"",
")",
":",
"for",
"course",
"in",
"api",
"."... | Update the data of courses and or exercises from server. | [
"Update",
"the",
"data",
"of",
"courses",
"and",
"or",
"exercises",
"from",
"server",
"."
] | python | valid |
ampl/amplpy | amplpy/ampl.py | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L349-L381 | def readAsync(self, fileName, callback, **kwargs):
"""
Interprets the specified file asynchronously, interpreting it as a
model or a script file. As a side effect, it invalidates all entities
(as the passed file can contain any arbitrary command); the lists of
entities will be re... | [
"def",
"readAsync",
"(",
"self",
",",
"fileName",
",",
"callback",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_langext",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"fileName",
",",
"'r'",
")",
"as",
"fin",
":",
"newmodel",
"=",
"sel... | Interprets the specified file asynchronously, interpreting it as a
model or a script file. As a side effect, it invalidates all entities
(as the passed file can contain any arbitrary command); the lists of
entities will be re-populated lazily (at first access).
Args:
fileNam... | [
"Interprets",
"the",
"specified",
"file",
"asynchronously",
"interpreting",
"it",
"as",
"a",
"model",
"or",
"a",
"script",
"file",
".",
"As",
"a",
"side",
"effect",
"it",
"invalidates",
"all",
"entities",
"(",
"as",
"the",
"passed",
"file",
"can",
"contain",... | python | train |
pypa/pipenv | pipenv/vendor/delegator.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/delegator.py#L125-L135 | def out(self):
"""Std/out output (cached)"""
if self.__out is not None:
return self.__out
if self._uses_subprocess:
self.__out = self.std_out.read()
else:
self.__out = self._pexpect_out
return self.__out | [
"def",
"out",
"(",
"self",
")",
":",
"if",
"self",
".",
"__out",
"is",
"not",
"None",
":",
"return",
"self",
".",
"__out",
"if",
"self",
".",
"_uses_subprocess",
":",
"self",
".",
"__out",
"=",
"self",
".",
"std_out",
".",
"read",
"(",
")",
"else",... | Std/out output (cached) | [
"Std",
"/",
"out",
"output",
"(",
"cached",
")"
] | python | train |
python-openxml/python-docx | docx/image/png.py | https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/image/png.py#L281-L291 | def from_offset(cls, chunk_type, stream_rdr, offset):
"""
Return a _pHYsChunk instance containing the image resolution
extracted from the pHYs chunk in *stream* at *offset*.
"""
horz_px_per_unit = stream_rdr.read_long(offset)
vert_px_per_unit = stream_rdr.read_long(offset... | [
"def",
"from_offset",
"(",
"cls",
",",
"chunk_type",
",",
"stream_rdr",
",",
"offset",
")",
":",
"horz_px_per_unit",
"=",
"stream_rdr",
".",
"read_long",
"(",
"offset",
")",
"vert_px_per_unit",
"=",
"stream_rdr",
".",
"read_long",
"(",
"offset",
",",
"4",
")... | Return a _pHYsChunk instance containing the image resolution
extracted from the pHYs chunk in *stream* at *offset*. | [
"Return",
"a",
"_pHYsChunk",
"instance",
"containing",
"the",
"image",
"resolution",
"extracted",
"from",
"the",
"pHYs",
"chunk",
"in",
"*",
"stream",
"*",
"at",
"*",
"offset",
"*",
"."
] | python | train |
clalancette/pycdlib | pycdlib/udf.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/udf.py#L1336-L1375 | def parse(self, data):
# type: (bytes) -> None
'''
Parse the passed in data into a UDF Partition Header Descriptor.
Parameters:
data - The data to parse.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInter... | [
"def",
"parse",
"(",
"self",
",",
"data",
")",
":",
"# type: (bytes) -> None",
"if",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'UDF Partition Header Descriptor already initialized'",
")",
"(",
"unalloc_table_length",... | Parse the passed in data into a UDF Partition Header Descriptor.
Parameters:
data - The data to parse.
Returns:
Nothing. | [
"Parse",
"the",
"passed",
"in",
"data",
"into",
"a",
"UDF",
"Partition",
"Header",
"Descriptor",
"."
] | python | train |
PGower/PyCanvas | pycanvas/apis/base.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/base.py#L164-L170 | def _validate_iso8601_string(self, value):
"""Return the value or raise a ValueError if it is not a string in ISO8601 format."""
ISO8601_REGEX = r'(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})([+-](\d{2})\:(\d{2})|Z)'
if re.match(ISO8601_REGEX, value):
return value
e... | [
"def",
"_validate_iso8601_string",
"(",
"self",
",",
"value",
")",
":",
"ISO8601_REGEX",
"=",
"r'(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2})\\:(\\d{2})\\:(\\d{2})([+-](\\d{2})\\:(\\d{2})|Z)'",
"if",
"re",
".",
"match",
"(",
"ISO8601_REGEX",
",",
"value",
")",
":",
"return",
"valu... | Return the value or raise a ValueError if it is not a string in ISO8601 format. | [
"Return",
"the",
"value",
"or",
"raise",
"a",
"ValueError",
"if",
"it",
"is",
"not",
"a",
"string",
"in",
"ISO8601",
"format",
"."
] | python | train |
postlund/pyatv | pyatv/interface.py | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/interface.py#L213-L221 | def hash(self):
"""Create a unique hash for what is currently playing.
The hash is based on title, artist, album and total time. It should
always be the same for the same content, but it is not guaranteed.
"""
base = '{0}{1}{2}{3}'.format(
self.title, self.artist, se... | [
"def",
"hash",
"(",
"self",
")",
":",
"base",
"=",
"'{0}{1}{2}{3}'",
".",
"format",
"(",
"self",
".",
"title",
",",
"self",
".",
"artist",
",",
"self",
".",
"album",
",",
"self",
".",
"total_time",
")",
"return",
"hashlib",
".",
"sha256",
"(",
"base"... | Create a unique hash for what is currently playing.
The hash is based on title, artist, album and total time. It should
always be the same for the same content, but it is not guaranteed. | [
"Create",
"a",
"unique",
"hash",
"for",
"what",
"is",
"currently",
"playing",
"."
] | python | train |
IndicoDataSolutions/IndicoIo-python | indicoio/image/image_recognition.py | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/image/image_recognition.py#L7-L29 | def image_recognition(image, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given an input image, returns a dictionary of image classifications with associated scores
* Input can be either grayscale or rgb color and should either be a numpy array or nested list format.
* Input data... | [
"def",
"image_recognition",
"(",
"image",
",",
"cloud",
"=",
"None",
",",
"batch",
"=",
"False",
",",
"api_key",
"=",
"None",
",",
"version",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"image",
"=",
"data_preprocess",
"(",
"image",
",",
"batch",
... | Given an input image, returns a dictionary of image classifications with associated scores
* Input can be either grayscale or rgb color and should either be a numpy array or nested list format.
* Input data should be either uint8 0-255 range values or floating point between 0 and 1.
* Large images (i.e. 10... | [
"Given",
"an",
"input",
"image",
"returns",
"a",
"dictionary",
"of",
"image",
"classifications",
"with",
"associated",
"scores"
] | python | train |
Damgaard/PyImgur | pyimgur/__init__.py | https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1407-L1425 | def send_message(self, body, subject=None, reply_to=None):
"""
Send a message to this user from the logged in user.
:param body: The body of the message.
:param subject: The subject of the message. Note that if the this
message is a reply, then the subject of the first messa... | [
"def",
"send_message",
"(",
"self",
",",
"body",
",",
"subject",
"=",
"None",
",",
"reply_to",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"_imgur",
".",
"_base_url",
"+",
"\"/3/message\"",
"parent_id",
"=",
"reply_to",
".",
"id",
"if",
"isinstance",... | Send a message to this user from the logged in user.
:param body: The body of the message.
:param subject: The subject of the message. Note that if the this
message is a reply, then the subject of the first message will be
used instead.
:param reply_to: Messages can eith... | [
"Send",
"a",
"message",
"to",
"this",
"user",
"from",
"the",
"logged",
"in",
"user",
"."
] | python | train |
diux-dev/ncluster | ncluster/util.py | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L23-L28 | def now_micros(absolute=False) -> int:
"""Return current micros since epoch as integer."""
micros = int(time.time() * 1e6)
if absolute:
return micros
return micros - EPOCH_MICROS | [
"def",
"now_micros",
"(",
"absolute",
"=",
"False",
")",
"->",
"int",
":",
"micros",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1e6",
")",
"if",
"absolute",
":",
"return",
"micros",
"return",
"micros",
"-",
"EPOCH_MICROS"
] | Return current micros since epoch as integer. | [
"Return",
"current",
"micros",
"since",
"epoch",
"as",
"integer",
"."
] | python | train |
joferkington/mplstereonet | mplstereonet/stereonet_math.py | https://github.com/joferkington/mplstereonet/blob/f6d78ca49807915d4223e864e12bb24d497cc2d6/mplstereonet/stereonet_math.py#L382-L437 | def fisher_stats(lons, lats, conf=95):
"""
Returns the resultant vector from a series of longitudes and latitudes. If
a confidence is set the function additionally returns the opening angle
of the confidence small circle (Fisher, 19..) and the dispersion factor
(kappa).
Parameters
---------... | [
"def",
"fisher_stats",
"(",
"lons",
",",
"lats",
",",
"conf",
"=",
"95",
")",
":",
"xyz",
"=",
"sph2cart",
"(",
"lons",
",",
"lats",
")",
"xyz",
"=",
"np",
".",
"vstack",
"(",
"xyz",
")",
".",
"T",
"mean_vec",
"=",
"xyz",
".",
"mean",
"(",
"axi... | Returns the resultant vector from a series of longitudes and latitudes. If
a confidence is set the function additionally returns the opening angle
of the confidence small circle (Fisher, 19..) and the dispersion factor
(kappa).
Parameters
----------
lons : array-like
A sequence of longi... | [
"Returns",
"the",
"resultant",
"vector",
"from",
"a",
"series",
"of",
"longitudes",
"and",
"latitudes",
".",
"If",
"a",
"confidence",
"is",
"set",
"the",
"function",
"additionally",
"returns",
"the",
"opening",
"angle",
"of",
"the",
"confidence",
"small",
"cir... | python | train |
milesgranger/gap_statistic | gap_statistic/optimalK.py | https://github.com/milesgranger/gap_statistic/blob/146f868febfac37823114e87819df5e8bfc16ac8/gap_statistic/optimalK.py#L129-L135 | def _process_with_rust(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray):
"""
Process gap stat using pure rust
"""
from gap_statistic.rust import gapstat
for label, gap_value in gapstat.optimal_k(X, list(cluster_array)):
yield (gap_valu... | [
"def",
"_process_with_rust",
"(",
"self",
",",
"X",
":",
"Union",
"[",
"pd",
".",
"DataFrame",
",",
"np",
".",
"ndarray",
"]",
",",
"n_refs",
":",
"int",
",",
"cluster_array",
":",
"np",
".",
"ndarray",
")",
":",
"from",
"gap_statistic",
".",
"rust",
... | Process gap stat using pure rust | [
"Process",
"gap",
"stat",
"using",
"pure",
"rust"
] | python | train |
camptocamp/Studio | studio/controllers/error.py | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/error.py#L41-L49 | def document(self):
"""Render the error document"""
resp = request.environ.get('pylons.original_response')
content = literal(resp.body) or cgi.escape(request.GET.get('message'))
page = error_document_template % \
dict(prefix=request.environ.get('SCRIPT_NAME', ''),
... | [
"def",
"document",
"(",
"self",
")",
":",
"resp",
"=",
"request",
".",
"environ",
".",
"get",
"(",
"'pylons.original_response'",
")",
"content",
"=",
"literal",
"(",
"resp",
".",
"body",
")",
"or",
"cgi",
".",
"escape",
"(",
"request",
".",
"GET",
".",... | Render the error document | [
"Render",
"the",
"error",
"document"
] | python | train |
fermiPy/fermipy | fermipy/jobs/target_collect.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/target_collect.py#L344-L389 | def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
ttype = args['ttype']
(targets_yaml, sim) = NAME_FACTORY.resolve_targetfile(
args, require_sim_name=True)
if targets_yaml is None:
return job_configs
... | [
"def",
"build_job_configs",
"(",
"self",
",",
"args",
")",
":",
"job_configs",
"=",
"{",
"}",
"ttype",
"=",
"args",
"[",
"'ttype'",
"]",
"(",
"targets_yaml",
",",
"sim",
")",
"=",
"NAME_FACTORY",
".",
"resolve_targetfile",
"(",
"args",
",",
"require_sim_na... | Hook to build job configurations | [
"Hook",
"to",
"build",
"job",
"configurations"
] | python | train |
CalebBell/fluids | fluids/geometry.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L1336-L1458 | def V_from_h(h, D, L, horizontal=True, sideA=None, sideB=None, sideA_a=0,
sideB_a=0, sideA_f=None, sideA_k=None, sideB_f=None, sideB_k=None):
r'''Calculates partially full volume of a vertical or horizontal tank with
different head types according to [1]_.
Parameters
----------
h : flo... | [
"def",
"V_from_h",
"(",
"h",
",",
"D",
",",
"L",
",",
"horizontal",
"=",
"True",
",",
"sideA",
"=",
"None",
",",
"sideB",
"=",
"None",
",",
"sideA_a",
"=",
"0",
",",
"sideB_a",
"=",
"0",
",",
"sideA_f",
"=",
"None",
",",
"sideA_k",
"=",
"None",
... | r'''Calculates partially full volume of a vertical or horizontal tank with
different head types according to [1]_.
Parameters
----------
h : float
Height of the liquid in the tank, [m]
D : float
Diameter of the cylindrical section of the tank, [m]
L : float
Length of the... | [
"r",
"Calculates",
"partially",
"full",
"volume",
"of",
"a",
"vertical",
"or",
"horizontal",
"tank",
"with",
"different",
"head",
"types",
"according",
"to",
"[",
"1",
"]",
"_",
"."
] | python | train |
ktbyers/netmiko | netmiko/fortinet/fortinet_ssh.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/fortinet/fortinet_ssh.py#L27-L62 | def disable_paging(self, delay_factor=1):
"""Disable paging is only available with specific roles so it may fail."""
check_command = "get system status | grep Virtual"
output = self.send_command_timing(check_command)
self.allow_disable_global = True
self.vdoms = False
sel... | [
"def",
"disable_paging",
"(",
"self",
",",
"delay_factor",
"=",
"1",
")",
":",
"check_command",
"=",
"\"get system status | grep Virtual\"",
"output",
"=",
"self",
".",
"send_command_timing",
"(",
"check_command",
")",
"self",
".",
"allow_disable_global",
"=",
"True... | Disable paging is only available with specific roles so it may fail. | [
"Disable",
"paging",
"is",
"only",
"available",
"with",
"specific",
"roles",
"so",
"it",
"may",
"fail",
"."
] | python | train |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L428-L468 | def refreshCompositeOf(self, single_keywords, composite_keywords,
store=None, namespace=None):
"""Re-check sub-parts of this keyword.
This should be called after the whole RDF was processed, because
it is using a cache of single keywords and if that
one is inc... | [
"def",
"refreshCompositeOf",
"(",
"self",
",",
"single_keywords",
",",
"composite_keywords",
",",
"store",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"def",
"_get_ckw_components",
"(",
"new_vals",
",",
"label",
")",
":",
"if",
"label",
"in",
"sing... | Re-check sub-parts of this keyword.
This should be called after the whole RDF was processed, because
it is using a cache of single keywords and if that
one is incomplete, you will not identify all parts. | [
"Re",
"-",
"check",
"sub",
"-",
"parts",
"of",
"this",
"keyword",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/overlay/access_list/type/vxlan/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/overlay/access_list/type/vxlan/__init__.py#L127-L148 | def _set_extended(self, v, load=False):
"""
Setter method for extended, mapped from YANG variable /overlay/access_list/type/vxlan/extended (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_extended is considered as a private
method. Backends looking to populate ... | [
"def",
"_set_extended",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base"... | Setter method for extended, mapped from YANG variable /overlay/access_list/type/vxlan/extended (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_extended is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._... | [
"Setter",
"method",
"for",
"extended",
"mapped",
"from",
"YANG",
"variable",
"/",
"overlay",
"/",
"access_list",
"/",
"type",
"/",
"vxlan",
"/",
"extended",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false... | python | train |
inveniosoftware-attic/invenio-upgrader | invenio_upgrader/engine.py | https://github.com/inveniosoftware-attic/invenio-upgrader/blob/cee4bcb118515463ecf6de1421642007f79a9fcd/invenio_upgrader/engine.py#L211-L227 | def _check_errors(self, errors, prefix):
"""Check for errors and possible raise and format an error message.
:param errors: List of error messages.
:param prefix: str, Prefix message for error messages
"""
args = []
for uid, messages in errors:
error_msg = [... | [
"def",
"_check_errors",
"(",
"self",
",",
"errors",
",",
"prefix",
")",
":",
"args",
"=",
"[",
"]",
"for",
"uid",
",",
"messages",
"in",
"errors",
":",
"error_msg",
"=",
"[",
"]",
"error_msg",
".",
"append",
"(",
"prefix",
"%",
"uid",
")",
"for",
"... | Check for errors and possible raise and format an error message.
:param errors: List of error messages.
:param prefix: str, Prefix message for error messages | [
"Check",
"for",
"errors",
"and",
"possible",
"raise",
"and",
"format",
"an",
"error",
"message",
"."
] | python | train |
inveniosoftware-contrib/invenio-groups | invenio_groups/models.py | https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L562-L570 | def _filter(cls, query, state=MembershipState.ACTIVE, eager=None):
"""Filter a query result."""
query = query.filter_by(state=state)
eager = eager or []
for field in eager:
query = query.options(joinedload(field))
return query | [
"def",
"_filter",
"(",
"cls",
",",
"query",
",",
"state",
"=",
"MembershipState",
".",
"ACTIVE",
",",
"eager",
"=",
"None",
")",
":",
"query",
"=",
"query",
".",
"filter_by",
"(",
"state",
"=",
"state",
")",
"eager",
"=",
"eager",
"or",
"[",
"]",
"... | Filter a query result. | [
"Filter",
"a",
"query",
"result",
"."
] | python | valid |
django-haystack/pysolr | pysolr.py | https://github.com/django-haystack/pysolr/blob/ee28b39324fa21a99842d297e313c1759d8adbd2/pysolr.py#L700-L720 | def _is_null_value(self, value):
"""
Check if a given value is ``null``.
Criteria for this is based on values that shouldn't be included
in the Solr ``add`` request at all.
"""
if value is None:
return True
if IS_PY3:
# Python 3.X
... | [
"def",
"_is_null_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"True",
"if",
"IS_PY3",
":",
"# Python 3.X",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
"and",
"len",
"(",
"value",
")",
"==",
"0",
":",... | Check if a given value is ``null``.
Criteria for this is based on values that shouldn't be included
in the Solr ``add`` request at all. | [
"Check",
"if",
"a",
"given",
"value",
"is",
"null",
"."
] | python | train |
markfinger/assembla | assembla/api.py | https://github.com/markfinger/assembla/blob/967a77a5ba718df94f60e832b6e0cf14c72426aa/assembla/api.py#L42-L112 | def _get_json(self, model, space=None, rel_path=None, extra_params=None, get_all=None):
"""
Base level method for fetching data from the API
"""
# Only API.spaces and API.event should not provide
# the `space argument
if space is None and model not in (Space, Event):
... | [
"def",
"_get_json",
"(",
"self",
",",
"model",
",",
"space",
"=",
"None",
",",
"rel_path",
"=",
"None",
",",
"extra_params",
"=",
"None",
",",
"get_all",
"=",
"None",
")",
":",
"# Only API.spaces and API.event should not provide",
"# the `space argument",
"if",
... | Base level method for fetching data from the API | [
"Base",
"level",
"method",
"for",
"fetching",
"data",
"from",
"the",
"API"
] | python | train |
thefactory/marathon-python | marathon/client.py | https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L498-L516 | def list_tasks(self, app_id=None, **kwargs):
"""List running tasks, optionally filtered by app_id.
:param str app_id: if passed, only show tasks for this application
:param kwargs: arbitrary search filters
:returns: list of tasks
:rtype: list[:class:`marathon.models.task.Marath... | [
"def",
"list_tasks",
"(",
"self",
",",
"app_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"_do_request",
"(",
"'GET'",
",",
"'/v2/apps/%s/tasks'",
"%",
"app_id",
"if",
"app_id",
"else",
"'/v2/tasks'",
")",
"tasks",
"=... | List running tasks, optionally filtered by app_id.
:param str app_id: if passed, only show tasks for this application
:param kwargs: arbitrary search filters
:returns: list of tasks
:rtype: list[:class:`marathon.models.task.MarathonTask`] | [
"List",
"running",
"tasks",
"optionally",
"filtered",
"by",
"app_id",
"."
] | python | train |
goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L536-L553 | def images(self):
'''
List of URLs of images on the page.
'''
if not getattr(self, '_images', False):
self._images = [
page['imageinfo'][0]['url']
for page in self.__continued_query({
'generator': 'images',
'gimlimit': 'max',
'prop': 'imageinfo',
... | [
"def",
"images",
"(",
"self",
")",
":",
"if",
"not",
"getattr",
"(",
"self",
",",
"'_images'",
",",
"False",
")",
":",
"self",
".",
"_images",
"=",
"[",
"page",
"[",
"'imageinfo'",
"]",
"[",
"0",
"]",
"[",
"'url'",
"]",
"for",
"page",
"in",
"self... | List of URLs of images on the page. | [
"List",
"of",
"URLs",
"of",
"images",
"on",
"the",
"page",
"."
] | python | train |
ailionx/cloudflare-ddns | cloudflare_ddns/cloudflare.py | https://github.com/ailionx/cloudflare-ddns/blob/e4808b8314e447f69fab77b5bd3880846e59adbe/cloudflare_ddns/cloudflare.py#L90-L111 | def setup_zone(self):
"""
Setup zone for current domain.
It will also setup the dns records of the zone
:return:
"""
# Initialize current zone
zones_content = self.request(self.api_url, 'get')
try:
if len(self.domain.split('.')) == 3:
... | [
"def",
"setup_zone",
"(",
"self",
")",
":",
"# Initialize current zone",
"zones_content",
"=",
"self",
".",
"request",
"(",
"self",
".",
"api_url",
",",
"'get'",
")",
"try",
":",
"if",
"len",
"(",
"self",
".",
"domain",
".",
"split",
"(",
"'.'",
")",
"... | Setup zone for current domain.
It will also setup the dns records of the zone
:return: | [
"Setup",
"zone",
"for",
"current",
"domain",
".",
"It",
"will",
"also",
"setup",
"the",
"dns",
"records",
"of",
"the",
"zone",
":",
"return",
":"
] | python | train |
lsanomaly/lsanomaly | lsanomaly/__init__.py | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L30-L51 | def pair_distance_centile(X, centile, max_pairs=5000):
"""
Calculate centiles of distances between random pairs in a dataset.
This an alternative to the median kNN distance for setting the kernel
length scale.
"""
N = X.shape[0]
n_pairs = min(max_pairs, N**2)
# randorder1 = np.random.pe... | [
"def",
"pair_distance_centile",
"(",
"X",
",",
"centile",
",",
"max_pairs",
"=",
"5000",
")",
":",
"N",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"n_pairs",
"=",
"min",
"(",
"max_pairs",
",",
"N",
"**",
"2",
")",
"# randorder1 = np.random.permutation(N)",
"... | Calculate centiles of distances between random pairs in a dataset.
This an alternative to the median kNN distance for setting the kernel
length scale. | [
"Calculate",
"centiles",
"of",
"distances",
"between",
"random",
"pairs",
"in",
"a",
"dataset",
"."
] | python | train |
neelkamath/hclib | hclib.py | https://github.com/neelkamath/hclib/blob/8678e7abe619796af85f219e280417cfa9a703f2/hclib.py#L117-L123 | def _on_open(self, _):
"""Joins the hack.chat channel and starts pinging."""
nick = self._format_nick(self._nick, self._pwd)
data = {"cmd": "join", "channel": self._channel, "nick": nick}
self._send_packet(data)
self._thread = True
threading.Thread(target=self._ping).star... | [
"def",
"_on_open",
"(",
"self",
",",
"_",
")",
":",
"nick",
"=",
"self",
".",
"_format_nick",
"(",
"self",
".",
"_nick",
",",
"self",
".",
"_pwd",
")",
"data",
"=",
"{",
"\"cmd\"",
":",
"\"join\"",
",",
"\"channel\"",
":",
"self",
".",
"_channel",
... | Joins the hack.chat channel and starts pinging. | [
"Joins",
"the",
"hack",
".",
"chat",
"channel",
"and",
"starts",
"pinging",
"."
] | python | train |
greenbone/ospd | ospd/misc.py | https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L444-L462 | def target_to_ipv4_cidr(target):
""" Attempt to return a IPv4 CIDR list from a target string. """
splitted = target.split('/')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET, splitted[0])
block = int(splitted[1])
except (socket.error, ValueEr... | [
"def",
"target_to_ipv4_cidr",
"(",
"target",
")",
":",
"splitted",
"=",
"target",
".",
"split",
"(",
"'/'",
")",
"if",
"len",
"(",
"splitted",
")",
"!=",
"2",
":",
"return",
"None",
"try",
":",
"start_packed",
"=",
"inet_pton",
"(",
"socket",
".",
"AF_... | Attempt to return a IPv4 CIDR list from a target string. | [
"Attempt",
"to",
"return",
"a",
"IPv4",
"CIDR",
"list",
"from",
"a",
"target",
"string",
"."
] | python | train |
tensorflow/cleverhans | cleverhans/attacks/spsa.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L350-L371 | def _apply_gradients(self, grads, x, optim_state):
"""Refer to parent class documentation."""
new_x = [None] * len(x)
new_optim_state = {
"t": optim_state["t"] + 1.,
"m": [None] * len(x),
"u": [None] * len(x)
}
t = new_optim_state["t"]
for i in xrange(len(x)):
g = g... | [
"def",
"_apply_gradients",
"(",
"self",
",",
"grads",
",",
"x",
",",
"optim_state",
")",
":",
"new_x",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"x",
")",
"new_optim_state",
"=",
"{",
"\"t\"",
":",
"optim_state",
"[",
"\"t\"",
"]",
"+",
"1.",
",",
"\... | Refer to parent class documentation. | [
"Refer",
"to",
"parent",
"class",
"documentation",
"."
] | python | train |
briancappello/flask-unchained | flask_unchained/bundles/security/decorators/auth_required_same_user.py | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/decorators/auth_required_same_user.py#L9-L50 | def auth_required_same_user(*args, **kwargs):
"""
Decorator for requiring an authenticated user to be the same as the
user in the URL parameters. By default the user url parameter name to
lookup is ``id``, but this can be customized by passing an argument::
@auth_require_same_user('user_id')
... | [
"def",
"auth_required_same_user",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"auth_kwargs",
"=",
"{",
"}",
"user_id_parameter_name",
"=",
"'id'",
"if",
"not",
"(",
"args",
"and",
"callable",
"(",
"args",
"[",
"0",
"]",
")",
")",
":",
"auth_kw... | Decorator for requiring an authenticated user to be the same as the
user in the URL parameters. By default the user url parameter name to
lookup is ``id``, but this can be customized by passing an argument::
@auth_require_same_user('user_id')
@bp.route('/users/<int:user_id>/foo/<int:id>')
... | [
"Decorator",
"for",
"requiring",
"an",
"authenticated",
"user",
"to",
"be",
"the",
"same",
"as",
"the",
"user",
"in",
"the",
"URL",
"parameters",
".",
"By",
"default",
"the",
"user",
"url",
"parameter",
"name",
"to",
"lookup",
"is",
"id",
"but",
"this",
... | python | train |
crm416/semantic | semantic/numbers.py | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/numbers.py#L124-L192 | def parseFloat(self, words):
"""Convert a floating-point number described in words to a double.
Supports two kinds of descriptions: those with a 'point' (e.g.,
"one point two five") and those with a fraction (e.g., "one and
a quarter").
Args:
words (str): Descriptio... | [
"def",
"parseFloat",
"(",
"self",
",",
"words",
")",
":",
"def",
"pointFloat",
"(",
"words",
")",
":",
"m",
"=",
"re",
".",
"search",
"(",
"r'(.*) point (.*)'",
",",
"words",
")",
"if",
"m",
":",
"whole",
"=",
"m",
".",
"group",
"(",
"1",
")",
"f... | Convert a floating-point number described in words to a double.
Supports two kinds of descriptions: those with a 'point' (e.g.,
"one point two five") and those with a fraction (e.g., "one and
a quarter").
Args:
words (str): Description of the floating-point number.
... | [
"Convert",
"a",
"floating",
"-",
"point",
"number",
"described",
"in",
"words",
"to",
"a",
"double",
"."
] | python | train |
saltstack/salt | salt/modules/boto_lambda.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L448-L495 | def update_function_code(FunctionName, ZipFile=None, S3Bucket=None, S3Key=None,
S3ObjectVersion=None, Publish=False,
region=None, key=None, keyid=None, profile=None):
'''
Upload the given code to the named lambda function.
Returns {updated: true} if the fun... | [
"def",
"update_function_code",
"(",
"FunctionName",
",",
"ZipFile",
"=",
"None",
",",
"S3Bucket",
"=",
"None",
",",
"S3Key",
"=",
"None",
",",
"S3ObjectVersion",
"=",
"None",
",",
"Publish",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"Non... | Upload the given code to the named lambda function.
Returns {updated: true} if the function was updated and returns
{updated: False} if the function was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_lamba.update_function_code my_function ZipFile=function.zip | [
"Upload",
"the",
"given",
"code",
"to",
"the",
"named",
"lambda",
"function",
"."
] | python | train |
chengsoonong/wib | wib/cli.py | https://github.com/chengsoonong/wib/blob/ca701ed72cd9f23a8e887f72f36c0fb0af42ef70/wib/cli.py#L12-L29 | def call(self, args, devnull=False):
"""Call other processes.
args - list of command args
devnull - whether to pipe stdout to /dev/null (or equivalent)
"""
if self.debug:
click.echo(subprocess.list2cmdline(args))
click.confirm('Continue?', default=True, ab... | [
"def",
"call",
"(",
"self",
",",
"args",
",",
"devnull",
"=",
"False",
")",
":",
"if",
"self",
".",
"debug",
":",
"click",
".",
"echo",
"(",
"subprocess",
".",
"list2cmdline",
"(",
"args",
")",
")",
"click",
".",
"confirm",
"(",
"'Continue?'",
",",
... | Call other processes.
args - list of command args
devnull - whether to pipe stdout to /dev/null (or equivalent) | [
"Call",
"other",
"processes",
".",
"args",
"-",
"list",
"of",
"command",
"args",
"devnull",
"-",
"whether",
"to",
"pipe",
"stdout",
"to",
"/",
"dev",
"/",
"null",
"(",
"or",
"equivalent",
")"
] | python | train |
jaywink/federation | federation/protocols/activitypub/protocol.py | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/protocol.py#L69-L88 | def receive(
self,
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False) -> Tuple[str, dict]:
"""
Receive a request.
For testing purposes, `skip_author_ver... | [
"def",
"receive",
"(",
"self",
",",
"request",
":",
"RequestType",
",",
"user",
":",
"UserType",
"=",
"None",
",",
"sender_key_fetcher",
":",
"Callable",
"[",
"[",
"str",
"]",
",",
"str",
"]",
"=",
"None",
",",
"skip_author_verification",
":",
"bool",
"=... | Receive a request.
For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified. | [
"Receive",
"a",
"request",
"."
] | python | train |
ajslater/picopt | picopt/formats/comic.py | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/comic.py#L117-L149 | def comic_archive_compress(args):
"""
Called back by every optimization inside a comic archive.
When they're all done it creates the new archive and cleans up.
"""
try:
filename, old_format, settings, nag_about_gifs = args
Settings.update(settings)
tmp_dir = _get_archive_tmp... | [
"def",
"comic_archive_compress",
"(",
"args",
")",
":",
"try",
":",
"filename",
",",
"old_format",
",",
"settings",
",",
"nag_about_gifs",
"=",
"args",
"Settings",
".",
"update",
"(",
"settings",
")",
"tmp_dir",
"=",
"_get_archive_tmp_dir",
"(",
"filename",
")... | Called back by every optimization inside a comic archive.
When they're all done it creates the new archive and cleans up. | [
"Called",
"back",
"by",
"every",
"optimization",
"inside",
"a",
"comic",
"archive",
"."
] | python | train |
iclab/centinel | centinel/primitives/headless_browser.py | https://github.com/iclab/centinel/blob/9a25dcf30c6a1db3c046f7ccb8ab8873e455c1a4/centinel/primitives/headless_browser.py#L281-L329 | def run(self, input_files, url=None, verbose=0):
"""
run the headless browser with given input
if url given, the proc will only run hlb with given url and ignore input_list.
:param url:
:param input_files: the name of the file in "index url" format. i.e.
1, www.fa... | [
"def",
"run",
"(",
"self",
",",
"input_files",
",",
"url",
"=",
"None",
",",
"verbose",
"=",
"0",
")",
":",
"if",
"not",
"url",
"and",
"not",
"input_files",
":",
"logging",
".",
"warning",
"(",
"\"No input file\"",
")",
"return",
"{",
"\"error\"",
":",... | run the headless browser with given input
if url given, the proc will only run hlb with given url and ignore input_list.
:param url:
:param input_files: the name of the file in "index url" format. i.e.
1, www.facebook.com
1, www.google.com
...
... | [
"run",
"the",
"headless",
"browser",
"with",
"given",
"input",
"if",
"url",
"given",
"the",
"proc",
"will",
"only",
"run",
"hlb",
"with",
"given",
"url",
"and",
"ignore",
"input_list",
".",
":",
"param",
"url",
":",
":",
"param",
"input_files",
":",
"the... | python | train |
apacha/OMR-Datasets | omrdatasettools/image_generators/HomusSymbol.py | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/HomusSymbol.py#L64-L76 | def draw_into_bitmap(self, export_path: ExportPath, stroke_thickness: int, margin: int = 0) -> None:
"""
Draws the symbol in the original size that it has plus an optional margin
:param export_path: The path, where the symbols should be created on disk
:param stroke_thickness: Pen-thick... | [
"def",
"draw_into_bitmap",
"(",
"self",
",",
"export_path",
":",
"ExportPath",
",",
"stroke_thickness",
":",
"int",
",",
"margin",
":",
"int",
"=",
"0",
")",
"->",
"None",
":",
"self",
".",
"draw_onto_canvas",
"(",
"export_path",
",",
"stroke_thickness",
","... | Draws the symbol in the original size that it has plus an optional margin
:param export_path: The path, where the symbols should be created on disk
:param stroke_thickness: Pen-thickness for drawing the symbol in pixels
:param margin: An optional margin for each symbol | [
"Draws",
"the",
"symbol",
"in",
"the",
"original",
"size",
"that",
"it",
"has",
"plus",
"an",
"optional",
"margin"
] | python | train |
pletzer/pnumpy | src/pnDistArray.py | https://github.com/pletzer/pnumpy/blob/9e6d308be94a42637466b91ab1a7b4d64b4c29ae/src/pnDistArray.py#L15-L208 | def distArrayFactory(BaseClass):
"""
Returns a distributed array class that derives from BaseClass
@param BaseClass base class, e.g. numpy.ndarray or numpy.ma.masked_array
@return dist array class
"""
class DistArrayAny(BaseClass):
"""
Distributed array. Each process owns data a... | [
"def",
"distArrayFactory",
"(",
"BaseClass",
")",
":",
"class",
"DistArrayAny",
"(",
"BaseClass",
")",
":",
"\"\"\"\n Distributed array. Each process owns data and can expose a subset\n of the data to other processes. These are known as windows. Any\n number of windows c... | Returns a distributed array class that derives from BaseClass
@param BaseClass base class, e.g. numpy.ndarray or numpy.ma.masked_array
@return dist array class | [
"Returns",
"a",
"distributed",
"array",
"class",
"that",
"derives",
"from",
"BaseClass"
] | python | train |
pycontribs/pyrax | pyrax/cloudloadbalancers.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudloadbalancers.py#L564-L572 | def delete_virtualip(self, loadbalancer, vip):
"""Deletes the VirtualIP from its load balancer."""
lb = vip.parent
if not lb:
raise exc.UnattachedVirtualIP("No parent Load Balancer for this "
"VirtualIP could be determined.")
resp, body = self.api.method_d... | [
"def",
"delete_virtualip",
"(",
"self",
",",
"loadbalancer",
",",
"vip",
")",
":",
"lb",
"=",
"vip",
".",
"parent",
"if",
"not",
"lb",
":",
"raise",
"exc",
".",
"UnattachedVirtualIP",
"(",
"\"No parent Load Balancer for this \"",
"\"VirtualIP could be determined.\""... | Deletes the VirtualIP from its load balancer. | [
"Deletes",
"the",
"VirtualIP",
"from",
"its",
"load",
"balancer",
"."
] | python | train |
senaite/senaite.core | bika/lims/exportimport/instruments/abbott/m2000rt/m2000rt.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/exportimport/instruments/abbott/m2000rt/m2000rt.py#L206-L219 | def _date_to_bika_date(self, date_time, only_date):
"""
Convert a string containing a date from results file to bika format
:param date_time: str with Date to convert
:param only_date: boolean value that specifies if there is only a date
to parse (true) or date plus time (false)
... | [
"def",
"_date_to_bika_date",
"(",
"self",
",",
"date_time",
",",
"only_date",
")",
":",
"# if only date the input date format is: 2017/01/26",
"# else: 2017/01/26 12:47:09 PM",
"if",
"only_date",
":",
"return",
"datetime",
".",
"strptime",
"(",
"date_time",
",",
"'%Y/%m/%... | Convert a string containing a date from results file to bika format
:param date_time: str with Date to convert
:param only_date: boolean value that specifies if there is only a date
to parse (true) or date plus time (false)
:return: datetime in bika format | [
"Convert",
"a",
"string",
"containing",
"a",
"date",
"from",
"results",
"file",
"to",
"bika",
"format",
":",
"param",
"date_time",
":",
"str",
"with",
"Date",
"to",
"convert",
":",
"param",
"only_date",
":",
"boolean",
"value",
"that",
"specifies",
"if",
"... | python | train |
automl/HpBandSter | hpbandster/optimizers/config_generators/kde.py | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/config_generators/kde.py#L84-L147 | def new_result(self, job):
"""
function to register finished runs
Every time a run has finished, this function should be called
to register it with the result logger. If overwritten, make
sure to call this method from the base class to ensure proper
logging.
Parameters:
-----------
job_id: ... | [
"def",
"new_result",
"(",
"self",
",",
"job",
")",
":",
"super",
"(",
"KernelDensityEstimator",
",",
"self",
")",
".",
"new_result",
"(",
"job",
")",
"budget",
"=",
"job",
".",
"kwargs",
"[",
"\"budget\"",
"]",
"if",
"budget",
"not",
"in",
"self",
".",... | function to register finished runs
Every time a run has finished, this function should be called
to register it with the result logger. If overwritten, make
sure to call this method from the base class to ensure proper
logging.
Parameters:
-----------
job_id: dict
a dictionary containing all... | [
"function",
"to",
"register",
"finished",
"runs"
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_common_def.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_common_def.py#L620-L636 | def ip_rtm_config_route_static_route_nh_vrf_next_hop_vrf(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
rtm_config = ET.SubElement(ip, "rtm-config", xmlns="urn:brocade.com... | [
"def",
"ip_rtm_config_route_static_route_nh_vrf_next_hop_vrf",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"ip",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ip\"",
",",
"xmlns",
"=",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
iclab/centinel | centinel/primitives/tcpdump.py | https://github.com/iclab/centinel/blob/9a25dcf30c6a1db3c046f7ccb8ab8873e455c1a4/centinel/primitives/tcpdump.py#L78-L88 | def _tcpdump_callback(self, line, kill_switch):
"""Callback function to handle tcpdump"""
line = line.lower()
if ("listening" in line) or ("reading" in line):
self.started = True
if ("no suitable device" in line):
self.error = True
self.kill_switch()
if "by kernel" in line:
... | [
"def",
"_tcpdump_callback",
"(",
"self",
",",
"line",
",",
"kill_switch",
")",
":",
"line",
"=",
"line",
".",
"lower",
"(",
")",
"if",
"(",
"\"listening\"",
"in",
"line",
")",
"or",
"(",
"\"reading\"",
"in",
"line",
")",
":",
"self",
".",
"started",
... | Callback function to handle tcpdump | [
"Callback",
"function",
"to",
"handle",
"tcpdump"
] | python | train |
fastai/fastai | fastai/callbacks/loss_metrics.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/loss_metrics.py#L30-L34 | def on_epoch_end(self, last_metrics, **kwargs):
"Finish the computation and sends the result to the Recorder."
if not self.nums: return
metrics = [self.metrics[name]/self.nums for name in self.names]
return {'last_metrics': last_metrics+metrics} | [
"def",
"on_epoch_end",
"(",
"self",
",",
"last_metrics",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"nums",
":",
"return",
"metrics",
"=",
"[",
"self",
".",
"metrics",
"[",
"name",
"]",
"/",
"self",
".",
"nums",
"for",
"name",
"in... | Finish the computation and sends the result to the Recorder. | [
"Finish",
"the",
"computation",
"and",
"sends",
"the",
"result",
"to",
"the",
"Recorder",
"."
] | python | train |
DataBiosphere/toil | src/toil/common.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/common.py#L870-L900 | def createBatchSystem(config):
"""
Creates an instance of the batch system specified in the given config.
:param toil.common.Config config: the current configuration
:rtype: batchSystems.abstractBatchSystem.AbstractBatchSystem
:return: an instance of a concrete subclass of Abs... | [
"def",
"createBatchSystem",
"(",
"config",
")",
":",
"kwargs",
"=",
"dict",
"(",
"config",
"=",
"config",
",",
"maxCores",
"=",
"config",
".",
"maxCores",
",",
"maxMemory",
"=",
"config",
".",
"maxMemory",
",",
"maxDisk",
"=",
"config",
".",
"maxDisk",
"... | Creates an instance of the batch system specified in the given config.
:param toil.common.Config config: the current configuration
:rtype: batchSystems.abstractBatchSystem.AbstractBatchSystem
:return: an instance of a concrete subclass of AbstractBatchSystem | [
"Creates",
"an",
"instance",
"of",
"the",
"batch",
"system",
"specified",
"in",
"the",
"given",
"config",
"."
] | python | train |
halcy/Mastodon.py | mastodon/Mastodon.py | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1034-L1042 | def filter(self, id):
"""
Fetches information about the filter with the specified `id`.
Returns a `filter dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/filters/{0}'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"filter",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/filters/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
... | Fetches information about the filter with the specified `id`.
Returns a `filter dict`_. | [
"Fetches",
"information",
"about",
"the",
"filter",
"with",
"the",
"specified",
"id",
".",
"Returns",
"a",
"filter",
"dict",
"_",
"."
] | python | train |
iotile/coretools | iotileemulate/iotile/emulate/transport/emulatedadapter.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/transport/emulatedadapter.py#L43-L58 | async def send_rpc(self, conn_id, address, rpc_id, payload, timeout):
"""Asynchronously send an RPC to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
address (int): the address of the tile that we wish to send the RPC to
... | [
"async",
"def",
"send_rpc",
"(",
"self",
",",
"conn_id",
",",
"address",
",",
"rpc_id",
",",
"payload",
",",
"timeout",
")",
":",
"try",
":",
"return",
"await",
"super",
"(",
"EmulatedDeviceAdapter",
",",
"self",
")",
".",
"send_rpc",
"(",
"conn_id",
","... | Asynchronously send an RPC to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
address (int): the address of the tile that we wish to send the RPC to
rpc_id (int): the 16-bit id of the RPC we want to call
payload (byt... | [
"Asynchronously",
"send",
"an",
"RPC",
"to",
"this",
"IOTile",
"device"
] | python | train |
KnuVerse/knuverse-sdk-python | knuverse/knufactor.py | https://github.com/KnuVerse/knuverse-sdk-python/blob/00f1275a452a4dcf9bc92ef345f6985504226d8e/knuverse/knufactor.py#L821-L860 | def verification_start(
self,
client,
mode=None,
verification_speed=None,
row_doubling="off",
phone_number=None,
):
"""
Start a verification. Uses POST to /verifications interface.
:Args:
* *client*: (str) Client's Name
... | [
"def",
"verification_start",
"(",
"self",
",",
"client",
",",
"mode",
"=",
"None",
",",
"verification_speed",
"=",
"None",
",",
"row_doubling",
"=",
"\"off\"",
",",
"phone_number",
"=",
"None",
",",
")",
":",
"data",
"=",
"{",
"\"name\"",
":",
"client",
... | Start a verification. Uses POST to /verifications interface.
:Args:
* *client*: (str) Client's Name
* *mode*: (str) Verification Mode. Allowed values: "audiopin", "audiopass"
* *verification_speed*: (int) Allowed values: 0, 25, 50, 75, 100
* *row_doubling*: (str... | [
"Start",
"a",
"verification",
".",
"Uses",
"POST",
"to",
"/",
"verifications",
"interface",
"."
] | python | train |
6809/dragonlib | dragonlib/api.py | https://github.com/6809/dragonlib/blob/faa4011e76c5857db96efdb4199e2fd49711e999/dragonlib/api.py#L100-L109 | def pformat_program_dump(self, program_dump, program_start=None):
"""
format a BASIC program dump. Useful for debugging.
returns a list of formated string lines.
"""
assert isinstance(program_dump, bytearray)
if program_start is None:
program_start = self.DEF... | [
"def",
"pformat_program_dump",
"(",
"self",
",",
"program_dump",
",",
"program_start",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"program_dump",
",",
"bytearray",
")",
"if",
"program_start",
"is",
"None",
":",
"program_start",
"=",
"self",
".",
"DEFA... | format a BASIC program dump. Useful for debugging.
returns a list of formated string lines. | [
"format",
"a",
"BASIC",
"program",
"dump",
".",
"Useful",
"for",
"debugging",
".",
"returns",
"a",
"list",
"of",
"formated",
"string",
"lines",
"."
] | python | train |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py#L68-L89 | def _parse_book_links(dom):
"""
Parse links to the details about publications from page with book list.
Args:
dom (obj): HTMLElement container of the page with book list.
Returns:
list: List of strings / absolute links to book details.
"""
links = []
picker = lambda x: x.pa... | [
"def",
"_parse_book_links",
"(",
"dom",
")",
":",
"links",
"=",
"[",
"]",
"picker",
"=",
"lambda",
"x",
":",
"x",
".",
"params",
".",
"get",
"(",
"\"class\"",
",",
"\"\"",
")",
".",
"startswith",
"(",
"\"boxProKnihy\"",
")",
"for",
"el",
"in",
"dom",... | Parse links to the details about publications from page with book list.
Args:
dom (obj): HTMLElement container of the page with book list.
Returns:
list: List of strings / absolute links to book details. | [
"Parse",
"links",
"to",
"the",
"details",
"about",
"publications",
"from",
"page",
"with",
"book",
"list",
"."
] | python | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L236-L248 | def _is_ready(self, as_of):
"""Is the RecurringCost ready to be enacted as of the date `as_of`
This determines if `as_of` precedes the start of `initial_billing_cycle`. If so,
we should not be enacting this RecurringCost yet.
Args:
as_of (Date):
"""
if self.... | [
"def",
"_is_ready",
"(",
"self",
",",
"as_of",
")",
":",
"if",
"self",
".",
"is_one_off",
"(",
")",
":",
"return",
"self",
".",
"initial_billing_cycle",
".",
"date_range",
".",
"lower",
"<=",
"as_of",
"else",
":",
"return",
"True"
] | Is the RecurringCost ready to be enacted as of the date `as_of`
This determines if `as_of` precedes the start of `initial_billing_cycle`. If so,
we should not be enacting this RecurringCost yet.
Args:
as_of (Date): | [
"Is",
"the",
"RecurringCost",
"ready",
"to",
"be",
"enacted",
"as",
"of",
"the",
"date",
"as_of"
] | python | train |
aiogram/aiogram | aiogram/utils/helper.py | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/helper.py#L59-L74 | def _screaming_snake_case(cls, text):
"""
Transform text to SCREAMING_SNAKE_CASE
:param text:
:return:
"""
if text.isupper():
return text
result = ''
for pos, symbol in enumerate(text):
if symbol.isupper() and pos > 0:
... | [
"def",
"_screaming_snake_case",
"(",
"cls",
",",
"text",
")",
":",
"if",
"text",
".",
"isupper",
"(",
")",
":",
"return",
"text",
"result",
"=",
"''",
"for",
"pos",
",",
"symbol",
"in",
"enumerate",
"(",
"text",
")",
":",
"if",
"symbol",
".",
"isuppe... | Transform text to SCREAMING_SNAKE_CASE
:param text:
:return: | [
"Transform",
"text",
"to",
"SCREAMING_SNAKE_CASE"
] | python | train |
satellogic/telluric | telluric/georaster.py | https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1611-L1613 | def to_raster(self, vector):
"""Return the vector in pixel coordinates, as shapely.Geometry."""
return transform(vector.get_shape(vector.crs), vector.crs, self.crs, dst_affine=~self.affine) | [
"def",
"to_raster",
"(",
"self",
",",
"vector",
")",
":",
"return",
"transform",
"(",
"vector",
".",
"get_shape",
"(",
"vector",
".",
"crs",
")",
",",
"vector",
".",
"crs",
",",
"self",
".",
"crs",
",",
"dst_affine",
"=",
"~",
"self",
".",
"affine",
... | Return the vector in pixel coordinates, as shapely.Geometry. | [
"Return",
"the",
"vector",
"in",
"pixel",
"coordinates",
"as",
"shapely",
".",
"Geometry",
"."
] | python | train |
LuminosoInsight/python-ftfy | ftfy/fixes.py | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/fixes.py#L133-L158 | def fix_encoding_and_explain(text):
"""
Re-decodes text that has been decoded incorrectly, and also return a
"plan" indicating all the steps required to fix it.
The resulting plan could be used with :func:`ftfy.fixes.apply_plan`
to fix additional strings that are broken in the same way.
"""
... | [
"def",
"fix_encoding_and_explain",
"(",
"text",
")",
":",
"best_version",
"=",
"text",
"best_cost",
"=",
"text_cost",
"(",
"text",
")",
"best_plan",
"=",
"[",
"]",
"plan_so_far",
"=",
"[",
"]",
"while",
"True",
":",
"prevtext",
"=",
"text",
"text",
",",
... | Re-decodes text that has been decoded incorrectly, and also return a
"plan" indicating all the steps required to fix it.
The resulting plan could be used with :func:`ftfy.fixes.apply_plan`
to fix additional strings that are broken in the same way. | [
"Re",
"-",
"decodes",
"text",
"that",
"has",
"been",
"decoded",
"incorrectly",
"and",
"also",
"return",
"a",
"plan",
"indicating",
"all",
"the",
"steps",
"required",
"to",
"fix",
"it",
"."
] | python | train |
hactar-is/frink | frink/orm.py | https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L33-L90 | def save(self):
"""
Save the current instance to the DB
"""
with rconnect() as conn:
try:
self.validate()
except ValidationError as e:
log.warn(e.messages)
raise
except ModelValidationError as e:
... | [
"def",
"save",
"(",
"self",
")",
":",
"with",
"rconnect",
"(",
")",
"as",
"conn",
":",
"try",
":",
"self",
".",
"validate",
"(",
")",
"except",
"ValidationError",
"as",
"e",
":",
"log",
".",
"warn",
"(",
"e",
".",
"messages",
")",
"raise",
"except"... | Save the current instance to the DB | [
"Save",
"the",
"current",
"instance",
"to",
"the",
"DB"
] | python | train |
gunthercox/ChatterBot | chatterbot/storage/mongodb.py | https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/mongodb.py#L44-L54 | def get_statement_model(self):
"""
Return the class for the statement model.
"""
from chatterbot.conversation import Statement
# Create a storage-aware statement
statement = Statement
statement.storage = self
return statement | [
"def",
"get_statement_model",
"(",
"self",
")",
":",
"from",
"chatterbot",
".",
"conversation",
"import",
"Statement",
"# Create a storage-aware statement",
"statement",
"=",
"Statement",
"statement",
".",
"storage",
"=",
"self",
"return",
"statement"
] | Return the class for the statement model. | [
"Return",
"the",
"class",
"for",
"the",
"statement",
"model",
"."
] | python | train |
inveniosoftware/dcxml | dcxml/xmlutils.py | https://github.com/inveniosoftware/dcxml/blob/9fed6123ec0f3f2e2f645ff91653a7e86a39138d/dcxml/xmlutils.py#L18-L33 | def dump_etree_helper(container_name, data, rules, nsmap, attrib):
"""Convert DataCite JSON format to DataCite XML.
JSON should be validated before it is given to to_xml.
"""
output = etree.Element(container_name, nsmap=nsmap, attrib=attrib)
for rule in rules:
if rule not in data:
... | [
"def",
"dump_etree_helper",
"(",
"container_name",
",",
"data",
",",
"rules",
",",
"nsmap",
",",
"attrib",
")",
":",
"output",
"=",
"etree",
".",
"Element",
"(",
"container_name",
",",
"nsmap",
"=",
"nsmap",
",",
"attrib",
"=",
"attrib",
")",
"for",
"rul... | Convert DataCite JSON format to DataCite XML.
JSON should be validated before it is given to to_xml. | [
"Convert",
"DataCite",
"JSON",
"format",
"to",
"DataCite",
"XML",
"."
] | python | train |
CxAalto/gtfspy | gtfspy/import_validator.py | https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/import_validator.py#L229-L243 | def _validate_danglers(self):
"""
Checks for rows that are not referenced in the the tables that should be linked
stops <> stop_times using stop_I
stop_times <> trips <> days, using trip_I
trips <> routes, using route_I
:return:
"""
for query, warning in ... | [
"def",
"_validate_danglers",
"(",
"self",
")",
":",
"for",
"query",
",",
"warning",
"in",
"zip",
"(",
"DANGLER_QUERIES",
",",
"DANGLER_WARNINGS",
")",
":",
"dangler_count",
"=",
"self",
".",
"gtfs",
".",
"execute_custom_query",
"(",
"query",
")",
".",
"fetch... | Checks for rows that are not referenced in the the tables that should be linked
stops <> stop_times using stop_I
stop_times <> trips <> days, using trip_I
trips <> routes, using route_I
:return: | [
"Checks",
"for",
"rows",
"that",
"are",
"not",
"referenced",
"in",
"the",
"the",
"tables",
"that",
"should",
"be",
"linked"
] | python | valid |
StackStorm/pybind | pybind/slxos/v17s_1_02/routing_system/evpn_config/evpn/evpn_instance/bridge_domain/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/routing_system/evpn_config/evpn/evpn_instance/bridge_domain/__init__.py#L94-L115 | def _set_bd_add(self, v, load=False):
"""
Setter method for bd_add, mapped from YANG variable /routing_system/evpn_config/evpn/evpn_instance/bridge_domain/bd_add (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bd_add is considered as a private
method. Bac... | [
"def",
"_set_bd_add",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | Setter method for bd_add, mapped from YANG variable /routing_system/evpn_config/evpn/evpn_instance/bridge_domain/bd_add (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bd_add is considered as a private
method. Backends looking to populate this variable should
... | [
"Setter",
"method",
"for",
"bd_add",
"mapped",
"from",
"YANG",
"variable",
"/",
"routing_system",
"/",
"evpn_config",
"/",
"evpn",
"/",
"evpn_instance",
"/",
"bridge_domain",
"/",
"bd_add",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
... | python | train |
6809/MC6809 | MC6809/components/mc6809_base.py | https://github.com/6809/MC6809/blob/6ba2f5106df46689017b5d0b6d84d43b7ee6a240/MC6809/components/mc6809_base.py#L144-L165 | def get_state(self):
"""
used in unittests
"""
return {
REG_X: self.index_x.value,
REG_Y: self.index_y.value,
REG_U: self.user_stack_pointer.value,
REG_S: self.system_stack_pointer.value,
REG_PC: self.program_counter.value,
... | [
"def",
"get_state",
"(",
"self",
")",
":",
"return",
"{",
"REG_X",
":",
"self",
".",
"index_x",
".",
"value",
",",
"REG_Y",
":",
"self",
".",
"index_y",
".",
"value",
",",
"REG_U",
":",
"self",
".",
"user_stack_pointer",
".",
"value",
",",
"REG_S",
"... | used in unittests | [
"used",
"in",
"unittests"
] | python | train |
PyThaiNLP/pythainlp | pythainlp/tokenize/multi_cut.py | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tokenize/multi_cut.py#L121-L128 | def segment(text: str, custom_dict: Trie = None) -> List[str]:
"""
ใช้ในการหา list ที่สามารถตัดคำได้ทั้งหมด
"""
if not text or not isinstance(text, str):
return []
return list(_multicut(text, custom_dict=custom_dict)) | [
"def",
"segment",
"(",
"text",
":",
"str",
",",
"custom_dict",
":",
"Trie",
"=",
"None",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"not",
"text",
"or",
"not",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"return",
"[",
"]",
"return",
"li... | ใช้ในการหา list ที่สามารถตัดคำได้ทั้งหมด | [
"ใช้ในการหา",
"list",
"ที่สามารถตัดคำได้ทั้งหมด"
] | python | train |
pkgw/pwkit | pwkit/environments/casa/tasks.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/environments/casa/tasks.py#L658-L701 | def concat(invises, outvis, timesort=False):
"""Concatenate visibility measurement sets.
invises (list of str)
Paths to the input measurement sets
outvis (str)
Path to the output measurement set.
timesort (boolean)
If true, sort the output in time after concatenation.
Example::
... | [
"def",
"concat",
"(",
"invises",
",",
"outvis",
",",
"timesort",
"=",
"False",
")",
":",
"tb",
"=",
"util",
".",
"tools",
".",
"table",
"(",
")",
"ms",
"=",
"util",
".",
"tools",
".",
"ms",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",... | Concatenate visibility measurement sets.
invises (list of str)
Paths to the input measurement sets
outvis (str)
Path to the output measurement set.
timesort (boolean)
If true, sort the output in time after concatenation.
Example::
from pwkit.environments.casa import tasks
... | [
"Concatenate",
"visibility",
"measurement",
"sets",
"."
] | python | train |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/flows/action_flows.py | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/flows/action_flows.py#L109-L139 | def execute_flow(self, custom_command="", is_config=False):
""" Execute flow which run custom command on device
:param custom_command: the command to execute on device
:param is_config: if True then run command in configuration mode
:return: command execution output
"""
... | [
"def",
"execute_flow",
"(",
"self",
",",
"custom_command",
"=",
"\"\"",
",",
"is_config",
"=",
"False",
")",
":",
"responses",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"custom_command",
",",
"str",
")",
":",
"commands",
"=",
"[",
"custom_command",
"]",
"e... | Execute flow which run custom command on device
:param custom_command: the command to execute on device
:param is_config: if True then run command in configuration mode
:return: command execution output | [
"Execute",
"flow",
"which",
"run",
"custom",
"command",
"on",
"device"
] | python | train |
voyages-sncf-technologies/nexus_uploader | nexus_uploader/utils.py | https://github.com/voyages-sncf-technologies/nexus_uploader/blob/dca654f9080264b1dcaabfc2fd19f26b1c4f59fe/nexus_uploader/utils.py#L17-L21 | def aslist(generator):
'Function decorator to transform a generator into a list'
def wrapper(*args, **kwargs):
return list(generator(*args, **kwargs))
return wrapper | [
"def",
"aslist",
"(",
"generator",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"list",
"(",
"generator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"wrapper"
] | Function decorator to transform a generator into a list | [
"Function",
"decorator",
"to",
"transform",
"a",
"generator",
"into",
"a",
"list"
] | python | train |
pypa/pipenv | pipenv/vendor/requests/adapters.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/adapters.py#L319-L327 | def close(self):
"""Disposes of any internal state.
Currently, this closes the PoolManager and any active ProxyManager,
which closes any pooled connections.
"""
self.poolmanager.clear()
for proxy in self.proxy_manager.values():
proxy.clear() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"poolmanager",
".",
"clear",
"(",
")",
"for",
"proxy",
"in",
"self",
".",
"proxy_manager",
".",
"values",
"(",
")",
":",
"proxy",
".",
"clear",
"(",
")"
] | Disposes of any internal state.
Currently, this closes the PoolManager and any active ProxyManager,
which closes any pooled connections. | [
"Disposes",
"of",
"any",
"internal",
"state",
"."
] | python | train |
globocom/GloboNetworkAPI-client-python | networkapiclient/ClientFactory.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ClientFactory.py#L505-L511 | def create_option_vip(self):
"""Get an instance of option_vip services facade."""
return OptionVIP(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | [
"def",
"create_option_vip",
"(",
"self",
")",
":",
"return",
"OptionVIP",
"(",
"self",
".",
"networkapi_url",
",",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"self",
".",
"user_ldap",
")"
] | Get an instance of option_vip services facade. | [
"Get",
"an",
"instance",
"of",
"option_vip",
"services",
"facade",
"."
] | python | train |
KelSolaar/Foundations | foundations/environment.py | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/environment.py#L237-L260 | def get_system_application_data_directory():
"""
Returns the system Application data directory.
Examples directories::
- 'C:\\Users\\$USER\\AppData\\Roaming' on Windows 7.
- 'C:\\Documents and Settings\\$USER\\Application Data' on Windows XP.
- '/Users/$USER/Library/Preferences' on... | [
"def",
"get_system_application_data_directory",
"(",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"\"Windows\"",
"or",
"platform",
".",
"system",
"(",
")",
"==",
"\"Microsoft\"",
":",
"environment",
"=",
"Environment",
"(",
"\"APPDATA\"",
")",
"r... | Returns the system Application data directory.
Examples directories::
- 'C:\\Users\\$USER\\AppData\\Roaming' on Windows 7.
- 'C:\\Documents and Settings\\$USER\\Application Data' on Windows XP.
- '/Users/$USER/Library/Preferences' on Mac Os X.
- '/home/$USER' on Linux.
:return... | [
"Returns",
"the",
"system",
"Application",
"data",
"directory",
"."
] | python | train |
cisco-sas/kitty | kitty/remote/actor.py | https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/remote/actor.py#L36-L42 | def get_report(self):
'''
need to wrap get_report, since we need to parse the report
'''
report_dict = self._meta_get_report()
report = Report.from_dict(report_dict)
return report | [
"def",
"get_report",
"(",
"self",
")",
":",
"report_dict",
"=",
"self",
".",
"_meta_get_report",
"(",
")",
"report",
"=",
"Report",
".",
"from_dict",
"(",
"report_dict",
")",
"return",
"report"
] | need to wrap get_report, since we need to parse the report | [
"need",
"to",
"wrap",
"get_report",
"since",
"we",
"need",
"to",
"parse",
"the",
"report"
] | python | train |
Jajcus/pyxmpp2 | pyxmpp2/error.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/error.py#L399-L410 | def _from_xml(self, element):
"""Initialize an ErrorElement object from an XML element.
:Parameters:
- `element`: XML element to be decoded.
:Types:
- `element`: :etree:`ElementTree.Element`
"""
ErrorElement._from_xml(self, element)
error_type = e... | [
"def",
"_from_xml",
"(",
"self",
",",
"element",
")",
":",
"ErrorElement",
".",
"_from_xml",
"(",
"self",
",",
"element",
")",
"error_type",
"=",
"element",
".",
"get",
"(",
"u\"type\"",
")",
"if",
"error_type",
":",
"self",
".",
"error_type",
"=",
"erro... | Initialize an ErrorElement object from an XML element.
:Parameters:
- `element`: XML element to be decoded.
:Types:
- `element`: :etree:`ElementTree.Element` | [
"Initialize",
"an",
"ErrorElement",
"object",
"from",
"an",
"XML",
"element",
"."
] | python | valid |
noahbenson/neuropythy | neuropythy/hcp/files.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/hcp/files.py#L1761-L1820 | def download(sid, credentials=None, subjects_path=None, overwrite=False, release='HCP_1200',
database='hcp-openaccess', file_list=None):
'''
download(sid) downloads the data for subject with the given subject id. By default, the subject
will be placed in the first HCP subject directory in the... | [
"def",
"download",
"(",
"sid",
",",
"credentials",
"=",
"None",
",",
"subjects_path",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"release",
"=",
"'HCP_1200'",
",",
"database",
"=",
"'hcp-openaccess'",
",",
"file_list",
"=",
"None",
")",
":",
"if",
... | download(sid) downloads the data for subject with the given subject id. By default, the subject
will be placed in the first HCP subject directory in the subjects directories list.
Note: In order for downloading to work, you must have s3fs installed. This is not a requirement
for the neuropythy library an... | [
"download",
"(",
"sid",
")",
"downloads",
"the",
"data",
"for",
"subject",
"with",
"the",
"given",
"subject",
"id",
".",
"By",
"default",
"the",
"subject",
"will",
"be",
"placed",
"in",
"the",
"first",
"HCP",
"subject",
"directory",
"in",
"the",
"subjects"... | python | train |
cgarciae/phi | phi/dsl.py | https://github.com/cgarciae/phi/blob/87fd7100a76f823232f4fd8360498b4b80675265/phi/dsl.py#L661-L666 | def Then3(self, f, arg1, arg2, *args, **kwargs):
"""
`Then3(f, ...)` is equivalent to `ThenAt(3, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
"""
args = (arg1, arg2) + args
return self.ThenAt(3, f, *args, **kwargs) | [
"def",
"Then3",
"(",
"self",
",",
"f",
",",
"arg1",
",",
"arg2",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"arg1",
",",
"arg2",
")",
"+",
"args",
"return",
"self",
".",
"ThenAt",
"(",
"3",
",",
"f",
",",
"*",
"a... | `Then3(f, ...)` is equivalent to `ThenAt(3, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information. | [
"Then3",
"(",
"f",
"...",
")",
"is",
"equivalent",
"to",
"ThenAt",
"(",
"3",
"f",
"...",
")",
".",
"Checkout",
"phi",
".",
"builder",
".",
"Builder",
".",
"ThenAt",
"for",
"more",
"information",
"."
] | python | train |
saltstack/salt | salt/pillar/file_tree.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/file_tree.py#L174-L192 | def _check_newline(prefix, file_name, keep_newline):
'''
Return a boolean stating whether or not a file's trailing newline should be
removed. To figure this out, first check if keep_newline is a boolean and
if so, return its opposite. Otherwise, iterate over keep_newline and check
if any of the patt... | [
"def",
"_check_newline",
"(",
"prefix",
",",
"file_name",
",",
"keep_newline",
")",
":",
"if",
"isinstance",
"(",
"keep_newline",
",",
"bool",
")",
":",
"return",
"not",
"keep_newline",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
... | Return a boolean stating whether or not a file's trailing newline should be
removed. To figure this out, first check if keep_newline is a boolean and
if so, return its opposite. Otherwise, iterate over keep_newline and check
if any of the patterns match the file path. If a match is found, return
False, ... | [
"Return",
"a",
"boolean",
"stating",
"whether",
"or",
"not",
"a",
"file",
"s",
"trailing",
"newline",
"should",
"be",
"removed",
".",
"To",
"figure",
"this",
"out",
"first",
"check",
"if",
"keep_newline",
"is",
"a",
"boolean",
"and",
"if",
"so",
"return",
... | python | train |
bitesofcode/projexui | projexui/widgets/xcombobox.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcombobox.py#L568-L583 | def toggleModelIndex(self, modelIndex):
"""
Toggles the index's check state.
:param modelIndex | <QModelIndex>
"""
if not self.isCheckable():
return
item = self.model().item(modelIndex.row())
if item.checkState() == Qt.Checke... | [
"def",
"toggleModelIndex",
"(",
"self",
",",
"modelIndex",
")",
":",
"if",
"not",
"self",
".",
"isCheckable",
"(",
")",
":",
"return",
"item",
"=",
"self",
".",
"model",
"(",
")",
".",
"item",
"(",
"modelIndex",
".",
"row",
"(",
")",
")",
"if",
"it... | Toggles the index's check state.
:param modelIndex | <QModelIndex> | [
"Toggles",
"the",
"index",
"s",
"check",
"state",
".",
":",
"param",
"modelIndex",
"|",
"<QModelIndex",
">"
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L666-L672 | def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]:
"""
Gets column names (that is, database column names) from an SQLAlchemy
ORM class.
"""
colnames = [col.name for col in get_orm_columns(cls)]
return sorted(colnames) if sort else colnames | [
"def",
"get_orm_column_names",
"(",
"cls",
":",
"Type",
",",
"sort",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"str",
"]",
":",
"colnames",
"=",
"[",
"col",
".",
"name",
"for",
"col",
"in",
"get_orm_columns",
"(",
"cls",
")",
"]",
"return",
... | Gets column names (that is, database column names) from an SQLAlchemy
ORM class. | [
"Gets",
"column",
"names",
"(",
"that",
"is",
"database",
"column",
"names",
")",
"from",
"an",
"SQLAlchemy",
"ORM",
"class",
"."
] | python | train |
bram85/topydo | topydo/lib/ChangeSet.py | https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ChangeSet.py#L36-L41 | def get_backup_path():
""" Returns full path and filename of backup file """
dirname, filename = path.split(path.splitext(config().todotxt())[0])
filename = '.' + filename + '.bak'
return path.join(dirname, filename) | [
"def",
"get_backup_path",
"(",
")",
":",
"dirname",
",",
"filename",
"=",
"path",
".",
"split",
"(",
"path",
".",
"splitext",
"(",
"config",
"(",
")",
".",
"todotxt",
"(",
")",
")",
"[",
"0",
"]",
")",
"filename",
"=",
"'.'",
"+",
"filename",
"+",
... | Returns full path and filename of backup file | [
"Returns",
"full",
"path",
"and",
"filename",
"of",
"backup",
"file"
] | python | train |
OpenKMIP/PyKMIP | kmip/core/messages/payloads/sign.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/messages/payloads/sign.py#L311-L355 | def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the Sign response payload and decode it.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
... | [
"def",
"read",
"(",
"self",
",",
"input_stream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"super",
"(",
"SignResponsePayload",
",",
"self",
")",
".",
"read",
"(",
"input_stream",
",",
"kmip_version",
"=",
"kmip_versio... | Read the data encoding the Sign response payload and decode it.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the ... | [
"Read",
"the",
"data",
"encoding",
"the",
"Sign",
"response",
"payload",
"and",
"decode",
"it",
"."
] | python | test |
6809/dragonlib | dragonlib/core/basic.py | https://github.com/6809/dragonlib/blob/faa4011e76c5857db96efdb4199e2fd49711e999/dragonlib/core/basic.py#L169-L192 | def token_load(self, line_number, tokens):
self.line_number = line_number
assert tokens[-1] == 0x00, "line code %s doesn't ends with \\x00: %s" % (
repr(tokens), repr(tokens[-1])
)
"""
NOTE: The BASIC interpreter changed REM shortcut and ELSE
internaly:
... | [
"def",
"token_load",
"(",
"self",
",",
"line_number",
",",
"tokens",
")",
":",
"self",
".",
"line_number",
"=",
"line_number",
"assert",
"tokens",
"[",
"-",
"1",
"]",
"==",
"0x00",
",",
"\"line code %s doesn't ends with \\\\x00: %s\"",
"%",
"(",
"repr",
"(",
... | NOTE: The BASIC interpreter changed REM shortcut and ELSE
internaly:
"'" <-> ":'"
"ELSE" <-> ":ELSE"
See also:
http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4310&p=11632#p11630 | [
"NOTE",
":",
"The",
"BASIC",
"interpreter",
"changed",
"REM",
"shortcut",
"and",
"ELSE",
"internaly",
":",
"<",
"-",
">",
":",
"ELSE",
"<",
"-",
">",
":",
"ELSE"
] | python | train |
frawau/aiolifx | aiolifx/aiolifx.py | https://github.com/frawau/aiolifx/blob/9bd8c5e6d291f4c79314989402f7e2c6476d5851/aiolifx/aiolifx.py#L1248-L1259 | def cleanup(self):
"""Method to call to cleanly terminate the connection to the device.
"""
if self.transport:
self.transport.close()
self.transport = None
if self.task:
self.task.cancel()
self.task = None
for light in self.lights.v... | [
"def",
"cleanup",
"(",
"self",
")",
":",
"if",
"self",
".",
"transport",
":",
"self",
".",
"transport",
".",
"close",
"(",
")",
"self",
".",
"transport",
"=",
"None",
"if",
"self",
".",
"task",
":",
"self",
".",
"task",
".",
"cancel",
"(",
")",
"... | Method to call to cleanly terminate the connection to the device. | [
"Method",
"to",
"call",
"to",
"cleanly",
"terminate",
"the",
"connection",
"to",
"the",
"device",
"."
] | python | train |
angr/angr | angr/analyses/cfg/cfg_fast.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/cfg/cfg_fast.py#L1404-L1498 | def _scan_irsb(self, cfg_job, current_func_addr):
"""
Generate a list of successors (generating them each as entries) to IRSB.
Updates previous CFG nodes with edges.
:param CFGJob cfg_job: The CFGJob instance.
:param int current_func_addr: Address of the current function
... | [
"def",
"_scan_irsb",
"(",
"self",
",",
"cfg_job",
",",
"current_func_addr",
")",
":",
"addr",
",",
"function_addr",
",",
"cfg_node",
",",
"irsb",
"=",
"self",
".",
"_generate_cfgnode",
"(",
"cfg_job",
",",
"current_func_addr",
")",
"# Add edges going to this node ... | Generate a list of successors (generating them each as entries) to IRSB.
Updates previous CFG nodes with edges.
:param CFGJob cfg_job: The CFGJob instance.
:param int current_func_addr: Address of the current function
:return: a list of successors
:rtype: list | [
"Generate",
"a",
"list",
"of",
"successors",
"(",
"generating",
"them",
"each",
"as",
"entries",
")",
"to",
"IRSB",
".",
"Updates",
"previous",
"CFG",
"nodes",
"with",
"edges",
"."
] | python | train |
trailofbits/manticore | manticore/ethereum/detectors.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/detectors.py#L675-L712 | def _in_user_func(state):
"""
:param state: current state
:return: whether the current execution is in a user-defined function or not.
NOTE / TODO / FIXME: As this may produce false postives, this is not in the base `Detector` class.
It should be fixed at some point and moved th... | [
"def",
"_in_user_func",
"(",
"state",
")",
":",
"# If we are already in user function (we cached it) let's just return True",
"in_function",
"=",
"state",
".",
"context",
".",
"get",
"(",
"'in_function'",
",",
"False",
")",
"prev_tx_count",
"=",
"state",
".",
"context",... | :param state: current state
:return: whether the current execution is in a user-defined function or not.
NOTE / TODO / FIXME: As this may produce false postives, this is not in the base `Detector` class.
It should be fixed at some point and moved there. See below.
The first 4 bytes of ... | [
":",
"param",
"state",
":",
"current",
"state",
":",
"return",
":",
"whether",
"the",
"current",
"execution",
"is",
"in",
"a",
"user",
"-",
"defined",
"function",
"or",
"not",
"."
] | python | valid |
Yelp/kafka-utils | kafka_utils/kafka_check/main.py | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_check/main.py#L123-L171 | def run():
"""Verify command-line arguments and run commands"""
args = parse_args()
logging.basicConfig(level=logging.WARN)
# to prevent flooding for sensu-check.
logging.getLogger('kafka').setLevel(logging.CRITICAL)
if args.controller_only and args.first_broker_only:
terminate(
... | [
"def",
"run",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"WARN",
")",
"# to prevent flooding for sensu-check.",
"logging",
".",
"getLogger",
"(",
"'kafka'",
")",
".",
"setLevel",
"(",... | Verify command-line arguments and run commands | [
"Verify",
"command",
"-",
"line",
"arguments",
"and",
"run",
"commands"
] | python | train |
Jammy2211/PyAutoLens | autolens/data/array/scaled_array.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/scaled_array.py#L122-L137 | def grid_pixels_to_grid_arcsec(self, grid_pixels):
"""Convert a grid of (y,x) pixel coordinates to a grid of (y,x) arc second values.
The pixel coordinate origin is at the top left corner of the grid, such that the pixel [0,0] corresponds to \
higher y arc-second coordinate value and lowest x a... | [
"def",
"grid_pixels_to_grid_arcsec",
"(",
"self",
",",
"grid_pixels",
")",
":",
"return",
"grid_util",
".",
"grid_pixels_1d_to_grid_arcsec_1d",
"(",
"grid_pixels_1d",
"=",
"grid_pixels",
",",
"shape",
"=",
"self",
".",
"shape",
",",
"pixel_scales",
"=",
"self",
".... | Convert a grid of (y,x) pixel coordinates to a grid of (y,x) arc second values.
The pixel coordinate origin is at the top left corner of the grid, such that the pixel [0,0] corresponds to \
higher y arc-second coordinate value and lowest x arc-second coordinate.
The arc-second coordinate origi... | [
"Convert",
"a",
"grid",
"of",
"(",
"y",
"x",
")",
"pixel",
"coordinates",
"to",
"a",
"grid",
"of",
"(",
"y",
"x",
")",
"arc",
"second",
"values",
"."
] | python | valid |
dnanexus/dx-toolkit | src/python/dxpy/cli/exec_io.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/cli/exec_io.py#L486-L495 | def update(self, new_inputs, strip_prefix=True):
"""
Updates the inputs dictionary with the key/value pairs from new_inputs, overwriting existing keys.
"""
if strip_prefix and self.input_name_prefix is not None:
for i in new_inputs:
if i.startswith(self.input_... | [
"def",
"update",
"(",
"self",
",",
"new_inputs",
",",
"strip_prefix",
"=",
"True",
")",
":",
"if",
"strip_prefix",
"and",
"self",
".",
"input_name_prefix",
"is",
"not",
"None",
":",
"for",
"i",
"in",
"new_inputs",
":",
"if",
"i",
".",
"startswith",
"(",
... | Updates the inputs dictionary with the key/value pairs from new_inputs, overwriting existing keys. | [
"Updates",
"the",
"inputs",
"dictionary",
"with",
"the",
"key",
"/",
"value",
"pairs",
"from",
"new_inputs",
"overwriting",
"existing",
"keys",
"."
] | python | train |
yvesalexandre/bandicoot | bandicoot/helper/tools.py | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/tools.py#L237-L243 | def antennas_missing_locations(user, Method=None):
"""
Return the number of antennas missing locations in the records of a given user.
"""
unique_antennas = set([record.position.antenna for record in user.records
if record.position.antenna is not None])
return sum([1 for a... | [
"def",
"antennas_missing_locations",
"(",
"user",
",",
"Method",
"=",
"None",
")",
":",
"unique_antennas",
"=",
"set",
"(",
"[",
"record",
".",
"position",
".",
"antenna",
"for",
"record",
"in",
"user",
".",
"records",
"if",
"record",
".",
"position",
".",... | Return the number of antennas missing locations in the records of a given user. | [
"Return",
"the",
"number",
"of",
"antennas",
"missing",
"locations",
"in",
"the",
"records",
"of",
"a",
"given",
"user",
"."
] | python | train |
daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumberutil.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L914-L925 | def is_number_type_geographical(num_type, country_code):
"""Tests whether a phone number has a geographical association,
as represented by its type and the country it belongs to.
This version of isNumberGeographical exists since calculating the phone
number type is expensive; if we have already done th... | [
"def",
"is_number_type_geographical",
"(",
"num_type",
",",
"country_code",
")",
":",
"return",
"(",
"num_type",
"==",
"PhoneNumberType",
".",
"FIXED_LINE",
"or",
"num_type",
"==",
"PhoneNumberType",
".",
"FIXED_LINE_OR_MOBILE",
"or",
"(",
"(",
"country_code",
"in",... | Tests whether a phone number has a geographical association,
as represented by its type and the country it belongs to.
This version of isNumberGeographical exists since calculating the phone
number type is expensive; if we have already done this, we don't want to
do it again. | [
"Tests",
"whether",
"a",
"phone",
"number",
"has",
"a",
"geographical",
"association",
"as",
"represented",
"by",
"its",
"type",
"and",
"the",
"country",
"it",
"belongs",
"to",
"."
] | python | train |
alberanid/python-iplib | iplib.py | https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L99-L111 | def is_dot(ip):
"""Return true if the IP address is in dotted decimal notation."""
octets = str(ip).split('.')
if len(octets) != 4:
return False
for i in octets:
try:
val = int(i)
except ValueError:
return False
if val > 255 or val < 0:
... | [
"def",
"is_dot",
"(",
"ip",
")",
":",
"octets",
"=",
"str",
"(",
"ip",
")",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"octets",
")",
"!=",
"4",
":",
"return",
"False",
"for",
"i",
"in",
"octets",
":",
"try",
":",
"val",
"=",
"int",
"("... | Return true if the IP address is in dotted decimal notation. | [
"Return",
"true",
"if",
"the",
"IP",
"address",
"is",
"in",
"dotted",
"decimal",
"notation",
"."
] | python | valid |
raamana/hiwenet | hiwenet/pairwise_dist.py | https://github.com/raamana/hiwenet/blob/b12699b3722fd0a6a835e7d7ca4baf58fb181809/hiwenet/pairwise_dist.py#L674-L700 | def parse_args():
"""Parser/validator for the cmd line args."""
parser = get_parser()
if len(sys.argv) < 2:
parser.print_help()
warnings.warn('Too few arguments!', UserWarning)
parser.exit(1)
# parsing
try:
params = parser.parse_args()
except Exception as exc:
... | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"get_parser",
"(",
")",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"<",
"2",
":",
"parser",
".",
"print_help",
"(",
")",
"warnings",
".",
"warn",
"(",
"'Too few arguments!'",
",",
"UserWarning",
")",
... | Parser/validator for the cmd line args. | [
"Parser",
"/",
"validator",
"for",
"the",
"cmd",
"line",
"args",
"."
] | python | train |
marshmallow-code/webargs | src/webargs/tornadoparser.py | https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/tornadoparser.py#L34-L47 | def parse_json_body(req):
"""Return the decoded JSON body from the request."""
content_type = req.headers.get("Content-Type")
if content_type and core.is_json(content_type):
try:
return core.parse_json(req.body)
except TypeError:
pass
except json.JSONDecodeErr... | [
"def",
"parse_json_body",
"(",
"req",
")",
":",
"content_type",
"=",
"req",
".",
"headers",
".",
"get",
"(",
"\"Content-Type\"",
")",
"if",
"content_type",
"and",
"core",
".",
"is_json",
"(",
"content_type",
")",
":",
"try",
":",
"return",
"core",
".",
"... | Return the decoded JSON body from the request. | [
"Return",
"the",
"decoded",
"JSON",
"body",
"from",
"the",
"request",
"."
] | python | train |
box/flaky | flaky/_flaky_plugin.py | https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L495-L512 | def _get_flaky_attributes(cls, test_item):
"""
Get all the flaky related attributes from the test.
:param test_item:
The test callable from which to get the flaky related attributes.
:type test_item:
`callable` or :class:`nose.case.Test` or :class:`Function`
... | [
"def",
"_get_flaky_attributes",
"(",
"cls",
",",
"test_item",
")",
":",
"return",
"{",
"attr",
":",
"cls",
".",
"_get_flaky_attribute",
"(",
"test_item",
",",
"attr",
",",
")",
"for",
"attr",
"in",
"FlakyNames",
"(",
")",
"}"
] | Get all the flaky related attributes from the test.
:param test_item:
The test callable from which to get the flaky related attributes.
:type test_item:
`callable` or :class:`nose.case.Test` or :class:`Function`
:return:
:rtype:
`dict` of `unicode` to... | [
"Get",
"all",
"the",
"flaky",
"related",
"attributes",
"from",
"the",
"test",
"."
] | python | train |
kubernetes-client/python | kubernetes/client/apis/apps_v1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/apps_v1_api.py#L4963-L4984 | def read_namespaced_daemon_set_status(self, name, namespace, **kwargs):
"""
read status of the specified DaemonSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_daemon_set... | [
"def",
"read_namespaced_daemon_set_status",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self"... | read status of the specified DaemonSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_daemon_set_status(name, namespace, async_req=True)
>>> result = thread.get()
:param a... | [
"read",
"status",
"of",
"the",
"specified",
"DaemonSet",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
">>>",
"thread",... | python | train |
dddomodossola/remi | remi/gui.py | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L143-L158 | def decorate_set_on_listener(prototype):
""" Private decorator for use in the editor.
Allows the Editor to create listener methods.
Args:
params (str): The list of parameters for the listener
method (es. "(self, new_value)")
"""
# noinspection PyDictCreation,PyP... | [
"def",
"decorate_set_on_listener",
"(",
"prototype",
")",
":",
"# noinspection PyDictCreation,PyProtectedMember",
"def",
"add_annotation",
"(",
"method",
")",
":",
"method",
".",
"_event_info",
"=",
"{",
"}",
"method",
".",
"_event_info",
"[",
"'name'",
"]",
"=",
... | Private decorator for use in the editor.
Allows the Editor to create listener methods.
Args:
params (str): The list of parameters for the listener
method (es. "(self, new_value)") | [
"Private",
"decorator",
"for",
"use",
"in",
"the",
"editor",
".",
"Allows",
"the",
"Editor",
"to",
"create",
"listener",
"methods",
"."
] | python | train |
erikrose/peep | peep.py | https://github.com/erikrose/peep/blob/c16f08c7f61e2f2afecb7cd1c93752bdd96c4968/peep.py#L935-L947 | def main():
"""Be the top-level entrypoint. Return a shell status code."""
commands = {'hash': peep_hash,
'install': peep_install,
'port': peep_port}
try:
if len(argv) >= 2 and argv[1] in commands:
return commands[argv[1]](argv[2:])
else:
... | [
"def",
"main",
"(",
")",
":",
"commands",
"=",
"{",
"'hash'",
":",
"peep_hash",
",",
"'install'",
":",
"peep_install",
",",
"'port'",
":",
"peep_port",
"}",
"try",
":",
"if",
"len",
"(",
"argv",
")",
">=",
"2",
"and",
"argv",
"[",
"1",
"]",
"in",
... | Be the top-level entrypoint. Return a shell status code. | [
"Be",
"the",
"top",
"-",
"level",
"entrypoint",
".",
"Return",
"a",
"shell",
"status",
"code",
"."
] | python | train |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/issuer.py | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/issuer.py#L34-L44 | async def genSchema(self, name, version, attrNames) -> Schema:
"""
Generates and submits Schema.
:param name: schema name
:param version: schema version
:param attrNames: a list of attributes the schema contains
:return: submitted Schema
"""
schema = Sche... | [
"async",
"def",
"genSchema",
"(",
"self",
",",
"name",
",",
"version",
",",
"attrNames",
")",
"->",
"Schema",
":",
"schema",
"=",
"Schema",
"(",
"name",
",",
"version",
",",
"attrNames",
",",
"self",
".",
"issuerId",
")",
"return",
"await",
"self",
"."... | Generates and submits Schema.
:param name: schema name
:param version: schema version
:param attrNames: a list of attributes the schema contains
:return: submitted Schema | [
"Generates",
"and",
"submits",
"Schema",
"."
] | python | train |
projectshift/shift-schema | shiftschema/schema.py | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/schema.py#L328-L352 | def validate_properties(self, model, context=None):
"""
Validate simple properties
Performs validation on simple properties to return a result object.
:param model: object or dict
:param context: object, dict or None
:return: shiftschema.result.Result
"""
... | [
"def",
"validate_properties",
"(",
"self",
",",
"model",
",",
"context",
"=",
"None",
")",
":",
"result",
"=",
"Result",
"(",
")",
"for",
"property_name",
"in",
"self",
".",
"properties",
":",
"prop",
"=",
"self",
".",
"properties",
"[",
"property_name",
... | Validate simple properties
Performs validation on simple properties to return a result object.
:param model: object or dict
:param context: object, dict or None
:return: shiftschema.result.Result | [
"Validate",
"simple",
"properties",
"Performs",
"validation",
"on",
"simple",
"properties",
"to",
"return",
"a",
"result",
"object",
".",
":",
"param",
"model",
":",
"object",
"or",
"dict",
":",
"param",
"context",
":",
"object",
"dict",
"or",
"None",
":",
... | python | train |
angr/pyvex | pyvex/block.py | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L399-L404 | def constants(self):
"""
The constants (excluding updates of the program counter) in the IRSB as :class:`pyvex.const.IRConst`.
"""
return sum(
(s.constants for s in self.statements if not (type(s) is stmt.Put and s.offset == self.offsIP)), []) | [
"def",
"constants",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"(",
"s",
".",
"constants",
"for",
"s",
"in",
"self",
".",
"statements",
"if",
"not",
"(",
"type",
"(",
"s",
")",
"is",
"stmt",
".",
"Put",
"and",
"s",
".",
"offset",
"==",
"self",
... | The constants (excluding updates of the program counter) in the IRSB as :class:`pyvex.const.IRConst`. | [
"The",
"constants",
"(",
"excluding",
"updates",
"of",
"the",
"program",
"counter",
")",
"in",
"the",
"IRSB",
"as",
":",
"class",
":",
"pyvex",
".",
"const",
".",
"IRConst",
"."
] | python | train |
ejeschke/ginga | ginga/gtk3w/Widgets.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/gtk3w/Widgets.py#L1446-L1449 | def index_to_widget(self, idx):
"""Returns child corresponding to `idx`"""
nchild = self.mdi_w.get_nth_page(idx)
return self._native_to_child(nchild) | [
"def",
"index_to_widget",
"(",
"self",
",",
"idx",
")",
":",
"nchild",
"=",
"self",
".",
"mdi_w",
".",
"get_nth_page",
"(",
"idx",
")",
"return",
"self",
".",
"_native_to_child",
"(",
"nchild",
")"
] | Returns child corresponding to `idx` | [
"Returns",
"child",
"corresponding",
"to",
"idx"
] | python | train |
osfclient/osfclient | osfclient/models/file.py | https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/file.py#L71-L92 | def update(self, fp):
"""Update the remote file from a local file.
Pass in a filepointer `fp` that has been opened for writing in
binary mode.
"""
if 'b' not in fp.mode:
raise ValueError("File has to be opened in binary mode.")
url = self._upload_url
... | [
"def",
"update",
"(",
"self",
",",
"fp",
")",
":",
"if",
"'b'",
"not",
"in",
"fp",
".",
"mode",
":",
"raise",
"ValueError",
"(",
"\"File has to be opened in binary mode.\"",
")",
"url",
"=",
"self",
".",
"_upload_url",
"# peek at the file to check if it is an ampt... | Update the remote file from a local file.
Pass in a filepointer `fp` that has been opened for writing in
binary mode. | [
"Update",
"the",
"remote",
"file",
"from",
"a",
"local",
"file",
"."
] | python | valid |
Qiskit/qiskit-terra | qiskit/qasm/qasmparser.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/qasmparser.py#L75-L89 | def verify_declared_bit(self, obj):
"""Verify a qubit id against the gate prototype."""
# We are verifying gate args against the formal parameters of a
# gate prototype.
if obj.name not in self.current_symtab:
raise QasmError("Cannot find symbol '" + obj.name
... | [
"def",
"verify_declared_bit",
"(",
"self",
",",
"obj",
")",
":",
"# We are verifying gate args against the formal parameters of a",
"# gate prototype.",
"if",
"obj",
".",
"name",
"not",
"in",
"self",
".",
"current_symtab",
":",
"raise",
"QasmError",
"(",
"\"Cannot find ... | Verify a qubit id against the gate prototype. | [
"Verify",
"a",
"qubit",
"id",
"against",
"the",
"gate",
"prototype",
"."
] | python | test |
gophish/api-client-python | gophish/api/campaigns.py | https://github.com/gophish/api-client-python/blob/28a7790f19e13c92ef0fb7bde8cd89389df5c155/gophish/api/campaigns.py#L38-L51 | def summary(self, campaign_id=None):
""" Returns the campaign summary """
resource_cls = CampaignSummary
single_resource = False
if not campaign_id:
resource_cls = CampaignSummaries
single_resource = True
return super(API, self).get(
resource... | [
"def",
"summary",
"(",
"self",
",",
"campaign_id",
"=",
"None",
")",
":",
"resource_cls",
"=",
"CampaignSummary",
"single_resource",
"=",
"False",
"if",
"not",
"campaign_id",
":",
"resource_cls",
"=",
"CampaignSummaries",
"single_resource",
"=",
"True",
"return",
... | Returns the campaign summary | [
"Returns",
"the",
"campaign",
"summary"
] | python | train |
PlaidWeb/Publ | publ/index.py | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/index.py#L198-L206 | def prune_missing(table):
""" Prune any files which are missing from the specified table """
try:
for item in table.select():
if not os.path.isfile(item.file_path):
logger.info("File disappeared: %s", item.file_path)
item.delete()
except: # pylint:disable... | [
"def",
"prune_missing",
"(",
"table",
")",
":",
"try",
":",
"for",
"item",
"in",
"table",
".",
"select",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"item",
".",
"file_path",
")",
":",
"logger",
".",
"info",
"(",
"\"File disa... | Prune any files which are missing from the specified table | [
"Prune",
"any",
"files",
"which",
"are",
"missing",
"from",
"the",
"specified",
"table"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.